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
ccd408d988f097012c3b2e7d72b5ab71e6e62055
src/Clientmenu.hh
src/Clientmenu.hh
// Clientmenu.hh for Blackbox - an X11 Window manager // Copyright (c) 1997 - 2000 Brad Hughes ([email protected]) // // 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. #ifndef __Clientmenu_hh #define __Clientmenu_hh // forward declarations class Clientmenu; #include "Basemenu.hh" #include "Workspace.hh" #include "fluxbox.hh" class Clientmenu : public Basemenu { private: BScreen *screen; Workspace *wkspc; protected: virtual void itemSelected(int, int); public: Clientmenu(Workspace *); }; #endif // __Clientmenu_hh
// Clientmenu.hh for Blackbox - an X11 Window manager // Copyright (c) 1997 - 2000 Brad Hughes ([email protected]) // // 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. #ifndef _CLIENTMENU_HH_ #define _CLIENTMENU_HH_ // forward declarations class Clientmenu; class Workspace; #include "Basemenu.hh" class Clientmenu : public Basemenu { private: BScreen *screen; Workspace *wkspc; protected: virtual void itemSelected(int, int); public: Clientmenu(Workspace *); }; #endif // _CLIENTMENU_HH_
Update include guard and added forward declaration
Update include guard and added forward declaration
C++
mit
Arkq/fluxbox,olivergondza/fluxbox,olivergondza/fluxbox,naimdjon/fluxbox,lukoko/fluxbox,Arkq/fluxbox,naimdjon/fluxbox,Arkq/fluxbox,lukoko/fluxbox,lukoko/fluxbox,lukoko/fluxbox,luebking/fluxbox,naimdjon/fluxbox,lukoko/fluxbox,luebking/fluxbox,luebking/fluxbox,Arkq/fluxbox,olivergondza/fluxbox,luebking/fluxbox,olivergondza/fluxbox,luebking/fluxbox,naimdjon/fluxbox,olivergondza/fluxbox,naimdjon/fluxbox,Arkq/fluxbox
9ea4ba474c838e7a0ba5e1d779c03a1d5d49f4ec
molequeue/jobactionfactories/openwithactionfactory.cpp
molequeue/jobactionfactories/openwithactionfactory.cpp
/****************************************************************************** This source file is part of the MoleQueue project. Copyright 2012 Kitware, Inc. This source code is released under the New BSD License, (the "License"). 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 "openwithactionfactory.h" #include "../job.h" #include "../program.h" #include "../queue.h" #include "../queuemanager.h" #include "../server.h" #include <QtGui/QAction> #include <QtGui/QFileDialog> #include <QtGui/QMessageBox> #include <QtCore/QFile> #include <QtCore/QProcess> #include <QtCore/QProcessEnvironment> #include <QtCore/QSettings> #include <QtCore/QStringList> #include <QtCore/QUrl> #include <QtCore/QVariant> Q_DECLARE_METATYPE(QList<MoleQueue::Job>) namespace MoleQueue { OpenWithActionFactory::OpenWithActionFactory() : JobActionFactory() { qRegisterMetaType<QList<Job> >("QList<Job>"); m_isMultiJob = true; m_flags |= JobActionFactory::ContextItem; } OpenWithActionFactory::OpenWithActionFactory(const OpenWithActionFactory &other) : JobActionFactory(other), m_executableFilePath(other.m_executableFilePath), m_executableName(other.m_executableName) { } OpenWithActionFactory::~OpenWithActionFactory() { } OpenWithActionFactory &OpenWithActionFactory::operator =( const OpenWithActionFactory &other) { JobActionFactory::operator=(other); m_executableFilePath = other.m_executableFilePath; m_executableName = other.executableName(); return *this; } void OpenWithActionFactory::readSettings(QSettings &settings) { m_executableFilePath = settings.value("executableFilePath").toString(); m_executableName = settings.value("executableName").toString(); JobActionFactory::readSettings(settings); } void OpenWithActionFactory::writeSettings(QSettings &settings) const { settings.setValue("executableFilePath", m_executableFilePath); settings.setValue("executableName", m_executableName); JobActionFactory::writeSettings(settings); } QList<QAction *> OpenWithActionFactory::createActions() { QList<QAction*> result; if (m_attemptedJobAdditions == 1 && m_jobs.size() == 1) { QAction *newAction = new QAction ( tr("Open '%1' in %2...").arg(m_jobs.first().description()) .arg(m_executableName), NULL); newAction->setData(QVariant::fromValue(m_jobs)); connect(newAction, SIGNAL(triggered()), this, SLOT(actionTriggered())); result << newAction; } else if (m_attemptedJobAdditions > 1) { QAction *newAction = new QAction (NULL); if (static_cast<unsigned int>(m_jobs.size()) == m_attemptedJobAdditions) newAction->setText(tr("Open %1 jobs in %2").arg(m_jobs.size()) .arg(m_executableName)); else newAction->setText(tr("Open %1 of %2 selected jobs in %3...") .arg(m_jobs.size()).arg(m_attemptedJobAdditions) .arg(m_executableName)); newAction->setData(QVariant::fromValue(m_jobs)); connect(newAction, SIGNAL(triggered()), this, SLOT(actionTriggered())); result << newAction; } return result; } unsigned int OpenWithActionFactory::usefulness() const { return 800; } void OpenWithActionFactory::actionTriggered() { QAction *action = qobject_cast<QAction*>(sender()); if (!action) return; // The sender was a QAction. Is its data a list of jobs? QList<Job> jobs = action->data().value<QList<Job> >(); if (!jobs.size()) return; QSettings settings; settings.beginGroup("ActionFactory/OpenWith/" + m_executableName); m_executableFilePath = settings.value("path", m_executableFilePath).toString(); // Ensure that the path to the executable is valid if (m_executableFilePath.isEmpty() || !QFile::exists(m_executableFilePath) || !(QFile::permissions(m_executableFilePath) & QFile::ExeUser)) { // Invalid path -- search system path: if (!searchPathForExecutable(m_executableName)) { // not found in path. Ask user. m_executableFilePath = QFileDialog::getOpenFileName( NULL, tr("Specify location of %1").arg(m_executableName), m_executableFilePath, m_executableName, 0); // Check for user cancel: if (m_executableFilePath.isNull()) return; } // Does the new path exist? if (!QFile::exists(m_executableFilePath)) { QMessageBox::critical(NULL, tr("Executable does not exist!"), tr("The executable file at %1 does not exist!") .arg(m_executableFilePath)); return; } // Is the target executable? if (!(QFile::permissions(m_executableFilePath) & QFile::ExeUser)) { QMessageBox::critical(NULL, tr("File is not executable!"), tr("The file at %1 is not executable and cannot " "be used to open job output.") .arg(m_executableFilePath)); return; } } settings.setValue("path", m_executableFilePath); settings.endGroup(); // Attempt to lookup program for output filenames QueueManager *queueManager = m_server ? m_server->queueManager() : NULL; foreach (const Job &job, jobs) { if (!job.isValid()) continue; QString outputFile = job.outputDirectory(); Queue *queue = queueManager ? queueManager->lookupQueue(job.queue()) : NULL; Program *program = queue ? queue->lookupProgram(job.program()) : NULL; if (program) { outputFile = QUrl::fromLocalFile( outputFile + "/" + program->outputFilename()).toLocalFile(); } // Output file does not exist -- prompt user for which file to open if (!QFile::exists(outputFile)) { outputFile = QFileDialog::getOpenFileName(NULL, tr("Select output file to open in " "%1").arg(m_executableName), outputFile); // User cancel if (outputFile.isNull()) return; } // Should be ready to go! QProcess::startDetached(m_executableFilePath + " " + outputFile); } } bool OpenWithActionFactory::searchPathForExecutable(const QString &exec) { QProcessEnvironment env = QProcessEnvironment::systemEnvironment(); if (!env.contains("PATH")) return false; static QRegExp pathSplitter = QRegExp(":"); QStringList paths = env.value("PATH").split(pathSplitter, QString::SkipEmptyParts); foreach (const QString &path, paths) { QString testPath = QUrl::fromLocalFile(path + "/" + exec).toLocalFile(); if (!QFile::exists(testPath)) continue; m_executableFilePath = testPath; return true; } return false; } } // end namespace MoleQueue
/****************************************************************************** This source file is part of the MoleQueue project. Copyright 2012 Kitware, Inc. This source code is released under the New BSD License, (the "License"). 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 "openwithactionfactory.h" #include "../job.h" #include "../program.h" #include "../queue.h" #include "../queuemanager.h" #include "../server.h" #include <QtGui/QAction> #include <QtGui/QFileDialog> #include <QtGui/QMessageBox> #include <QtCore/QFile> #include <QtCore/QProcess> #include <QtCore/QProcessEnvironment> #include <QtCore/QSettings> #include <QtCore/QStringList> #include <QtCore/QUrl> #include <QtCore/QVariant> Q_DECLARE_METATYPE(QList<MoleQueue::Job>) namespace MoleQueue { OpenWithActionFactory::OpenWithActionFactory() : JobActionFactory() { qRegisterMetaType<QList<Job> >("QList<Job>"); m_isMultiJob = true; m_flags |= JobActionFactory::ContextItem; } OpenWithActionFactory::OpenWithActionFactory(const OpenWithActionFactory &other) : JobActionFactory(other), m_executableFilePath(other.m_executableFilePath), m_executableName(other.m_executableName) { } OpenWithActionFactory::~OpenWithActionFactory() { } OpenWithActionFactory &OpenWithActionFactory::operator =( const OpenWithActionFactory &other) { JobActionFactory::operator=(other); m_executableFilePath = other.m_executableFilePath; m_executableName = other.executableName(); return *this; } void OpenWithActionFactory::readSettings(QSettings &settings) { m_executableFilePath = settings.value("executableFilePath").toString(); m_executableName = settings.value("executableName").toString(); JobActionFactory::readSettings(settings); } void OpenWithActionFactory::writeSettings(QSettings &settings) const { settings.setValue("executableFilePath", m_executableFilePath); settings.setValue("executableName", m_executableName); JobActionFactory::writeSettings(settings); } QList<QAction *> OpenWithActionFactory::createActions() { QList<QAction*> result; if (m_attemptedJobAdditions == 1 && m_jobs.size() == 1) { QAction *newAction = new QAction ( tr("Open '%1' in %2...").arg(m_jobs.first().description()) .arg(m_executableName), NULL); newAction->setData(QVariant::fromValue(m_jobs)); connect(newAction, SIGNAL(triggered()), this, SLOT(actionTriggered())); result << newAction; } else if (m_attemptedJobAdditions > 1) { QAction *newAction = new QAction (NULL); if (static_cast<unsigned int>(m_jobs.size()) == m_attemptedJobAdditions) newAction->setText(tr("Open %1 jobs in %2").arg(m_jobs.size()) .arg(m_executableName)); else newAction->setText(tr("Open %1 of %2 selected jobs in %3...") .arg(m_jobs.size()).arg(m_attemptedJobAdditions) .arg(m_executableName)); newAction->setData(QVariant::fromValue(m_jobs)); connect(newAction, SIGNAL(triggered()), this, SLOT(actionTriggered())); result << newAction; } return result; } unsigned int OpenWithActionFactory::usefulness() const { return 800; } void OpenWithActionFactory::actionTriggered() { QAction *action = qobject_cast<QAction*>(sender()); if (!action) return; // The sender was a QAction. Is its data a list of jobs? QList<Job> jobs = action->data().value<QList<Job> >(); if (!jobs.size()) return; QSettings settings; settings.beginGroup("ActionFactory/OpenWith/" + m_executableName); m_executableFilePath = settings.value("path", m_executableFilePath).toString(); // Ensure that the path to the executable is valid if (m_executableFilePath.isEmpty() || !QFile::exists(m_executableFilePath) || !(QFile::permissions(m_executableFilePath) & QFile::ExeUser)) { // Invalid path -- search system path: if (!searchPathForExecutable(m_executableName)) { // not found in path. Ask user. m_executableFilePath = QFileDialog::getOpenFileName( NULL, tr("Specify location of %1").arg(m_executableName), m_executableFilePath, m_executableName, 0); // Check for user cancel: if (m_executableFilePath.isNull()) return; } // Does the new path exist? if (!QFile::exists(m_executableFilePath)) { QMessageBox::critical(NULL, tr("Executable does not exist!"), tr("The executable file at %1 does not exist!") .arg(m_executableFilePath)); return; } // Is the target executable? if (!(QFile::permissions(m_executableFilePath) & QFile::ExeUser)) { QMessageBox::critical(NULL, tr("File is not executable!"), tr("The file at %1 is not executable and cannot " "be used to open job output.") .arg(m_executableFilePath)); return; } } settings.setValue("path", m_executableFilePath); settings.endGroup(); // Attempt to lookup program for output filenames QueueManager *queueManager = m_server ? m_server->queueManager() : NULL; foreach (const Job &job, jobs) { if (!job.isValid()) continue; QString outputFile = job.outputDirectory(); Queue *queue = queueManager ? queueManager->lookupQueue(job.queue()) : NULL; Program *program = queue ? queue->lookupProgram(job.program()) : NULL; if (program) { outputFile = QUrl::fromLocalFile( outputFile + "/" + program->outputFilename()).toLocalFile(); } // Output file does not exist -- prompt user for which file to open if (!QFile::exists(outputFile)) { outputFile = QFileDialog::getOpenFileName(NULL, tr("Select output file to open in " "%1").arg(m_executableName), outputFile); // User cancel if (outputFile.isNull()) return; } // Should be ready to go! QProcess::startDetached(m_executableFilePath + " " + outputFile); } } bool OpenWithActionFactory::searchPathForExecutable(const QString &exec) { QProcessEnvironment env = QProcessEnvironment::systemEnvironment(); if (!env.contains("PATH")) return false; static QRegExp pathSplitter = QRegExp( #ifdef WIN32 ";" #else // WIN32 ":" #endif// WIN32 ); QStringList paths = env.value("PATH").split(pathSplitter, QString::SkipEmptyParts); foreach (const QString &path, paths) { QString testPath = QUrl::fromLocalFile(path + "/" + exec).toLocalFile(); if (!QFile::exists(testPath)) continue; m_executableFilePath = testPath; return true; } return false; } } // end namespace MoleQueue
Fix a platform issue with path separators.
Fix a platform issue with path separators. Change-Id: I6de90cb2217578a50a4ac8a252c5646651b918fe
C++
bsd-3-clause
OpenChemistry/molequeue,OpenChemistry/molequeue,OpenChemistry/molequeue
b615c3b2921b84328a224d2f7f89a6ebdc3e04ca
src/Tracer.cpp
src/Tracer.cpp
/* * Copyright (c) 2015 - 2022, Intel Corporation * * 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 Intel Corporation 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 LOG OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "Tracer.hpp" #include <unistd.h> #include <limits.h> #include <string.h> #include <cctype> #include <iomanip> #include <sstream> #include <iostream> #include <algorithm> #include <time.h> #include "geopm/PlatformIO.hpp" #include "geopm/PlatformTopo.hpp" #include "geopm/Exception.hpp" #include "geopm/Helper.hpp" #include "Environment.hpp" #include "PlatformIOProf.hpp" #include "geopm_hash.h" #include "geopm_version.h" #include "geopm.h" #include "geopm_internal.h" #include "config.h" namespace geopm { TracerImp::TracerImp(const std::string &start_time) : TracerImp(start_time, environment().trace(), hostname(), environment().do_trace(), PlatformIOProf::platform_io(), platform_topo(), environment().trace_signals()) { } TracerImp::TracerImp(const std::string &start_time, const std::string &file_path, const std::string &hostname, bool do_trace, PlatformIO &platform_io, const PlatformTopo &platform_topo, const std::string &env_column) : m_is_trace_enabled(do_trace) , m_platform_io(platform_io) , m_platform_topo(platform_topo) , m_env_column(env_column) , M_BUFFER_SIZE(134217728) // 128 MiB , m_region_hash_idx(-1) , m_region_hint_idx(-1) , m_region_progress_idx(-1) , m_region_runtime_idx(-1) { if (m_is_trace_enabled) { m_csv = make_unique<CSVImp>(file_path, hostname, start_time, M_BUFFER_SIZE); } } void TracerImp::columns(const std::vector<std::string> &agent_cols, const std::vector<std::function<std::string(double)> > &col_formats) { if (m_is_trace_enabled) { if (col_formats.size() != 0 && col_formats.size() != agent_cols.size()) { throw Exception("TracerImp::columns(): input vectors not of equal size", GEOPM_ERROR_INVALID, __FILE__, __LINE__); } // default columns std::vector<struct m_request_s> base_columns({ {"TIME", GEOPM_DOMAIN_BOARD, 0, m_platform_io.format_function("TIME")}, {"EPOCH_COUNT", GEOPM_DOMAIN_BOARD, 0, m_platform_io.format_function("EPOCH_COUNT")}, {"REGION_HASH", GEOPM_DOMAIN_BOARD, 0, m_platform_io.format_function("REGION_HASH")}, {"REGION_HINT", GEOPM_DOMAIN_BOARD, 0, m_platform_io.format_function("REGION_HINT")}, {"REGION_PROGRESS", GEOPM_DOMAIN_BOARD, 0, m_platform_io.format_function("REGION_PROGRESS")}, {"ENERGY_PACKAGE", GEOPM_DOMAIN_BOARD, 0, m_platform_io.format_function("ENERGY_PACKAGE")}, {"ENERGY_DRAM", GEOPM_DOMAIN_BOARD, 0, m_platform_io.format_function("ENERGY_DRAM")}, {"POWER_PACKAGE", GEOPM_DOMAIN_BOARD, 0, m_platform_io.format_function("POWER_PACKAGE")}, {"POWER_DRAM", GEOPM_DOMAIN_BOARD, 0, m_platform_io.format_function("POWER_DRAM")}, {"FREQUENCY", GEOPM_DOMAIN_BOARD, 0, m_platform_io.format_function("FREQUENCY")}, {"CYCLES_THREAD", GEOPM_DOMAIN_BOARD, 0, m_platform_io.format_function("CYCLES_THREAD")}, {"CYCLES_REFERENCE", GEOPM_DOMAIN_BOARD, 0, m_platform_io.format_function("CYCLES_REFERENCE")}, {"TEMPERATURE_CORE", GEOPM_DOMAIN_BOARD, 0, m_platform_io.format_function("TEMPERATURE_CORE")}}); m_region_hash_idx = 2; m_region_hint_idx = 3; m_region_progress_idx = 4; m_region_runtime_idx = 6; // extra columns from environment std::vector<std::string> env_sig = env_signals(); std::vector<int> env_dom = env_domains(); std::vector<std::function<std::string(double)> > env_form = env_formats(); #ifdef GEOPM_DEBUG if (env_sig.size() != env_dom.size() || env_sig.size() != env_form.size()) { throw Exception("Tracer::columns(): private functions returned different size vectors", GEOPM_ERROR_LOGIC, __FILE__, __LINE__); } #endif size_t num_sig = env_sig.size(); for (size_t sig_idx = 0; sig_idx != num_sig; ++sig_idx) { int num_dom = m_platform_topo.num_domain(env_dom.at(sig_idx)); for (int dom_idx = 0; dom_idx != num_dom; ++dom_idx) { base_columns.push_back({env_sig.at(sig_idx), env_dom.at(sig_idx), dom_idx, env_form.at(sig_idx)}); } } // set up columns to be sampled by TracerImp for (const auto &col : base_columns) { m_column_idx.push_back(m_platform_io.push_signal(col.name, col.domain_type, col.domain_idx)); std::string column_name = col.name; if (col.domain_type != GEOPM_DOMAIN_BOARD) { column_name += "-" + PlatformTopo::domain_type_to_name(col.domain_type); column_name += "-" + std::to_string(col.domain_idx); } m_csv->add_column(column_name, col.format); } // columns from agent; will be sampled by agent size_t num_col = agent_cols.size(); for (size_t col_idx = 0; col_idx != num_col; ++col_idx) { std::function<std::string(double)> format = col_formats.size() ? col_formats.at(col_idx) : string_format_double; m_csv->add_column(agent_cols.at(col_idx), format); } m_csv->activate(); m_last_telemetry.resize(base_columns.size() + num_col); } } void TracerImp::update(const std::vector<double> &agent_values) { if (m_is_trace_enabled) { #ifdef GEOPM_DEBUG if (m_column_idx.size() == 0) { throw Exception("TracerImp::update(): No columns added to trace.", GEOPM_ERROR_LOGIC, __FILE__, __LINE__); } if (m_column_idx.size() + agent_values.size() != m_last_telemetry.size()) { throw Exception("TracerImp::update(): Last telemetry buffer not sized correctly.", GEOPM_ERROR_LOGIC, __FILE__, __LINE__); } #endif // save values to be reused for region entry/exit size_t col_idx = 0; for (; col_idx < m_column_idx.size(); ++col_idx) { m_last_telemetry[col_idx] = m_platform_io.sample(m_column_idx[col_idx]); } for (const auto &val : agent_values) { m_last_telemetry[col_idx] = val; ++col_idx; } m_csv->update(m_last_telemetry); } } void TracerImp::flush(void) { if (m_is_trace_enabled) { m_csv->flush(); } } std::vector<std::string> TracerImp::env_signals(void) { std::vector<std::string> result; for (const auto &extra_signal : string_split(m_env_column, ",")) { std::vector<std::string> signal_domain = string_split(extra_signal, "@"); result.push_back(signal_domain[0]); } return result; } std::vector<int> TracerImp::env_domains(void) { std::vector<int> result; for (const auto &extra_signal : string_split(m_env_column, ",")) { std::vector<std::string> signal_domain = string_split(extra_signal, "@"); if (signal_domain.size() == 2) { result.push_back(PlatformTopo::domain_name_to_type(signal_domain[1])); } else if (signal_domain.size() == 1) { result.push_back(GEOPM_DOMAIN_BOARD); } else { throw Exception("TracerImp::columns(): Environment trace extension contains signals with multiple \"@\" characters.", GEOPM_ERROR_INVALID, __FILE__, __LINE__); } } return result; } std::vector<std::function<std::string(double)> > TracerImp::env_formats(void) { std::vector<std::function<std::string(double)> > result; std::vector<std::string> signals = env_signals(); for (const auto &it : env_signals()) { result.push_back(m_platform_io.format_function(it)); } return result; } }
/* * Copyright (c) 2015 - 2022, Intel Corporation * * 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 Intel Corporation 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 LOG OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "Tracer.hpp" #include <unistd.h> #include <limits.h> #include <string.h> #include <cctype> #include <iomanip> #include <sstream> #include <iostream> #include <algorithm> #include <time.h> #include "geopm/PlatformIO.hpp" #include "geopm/PlatformTopo.hpp" #include "geopm/Exception.hpp" #include "geopm/Helper.hpp" #include "Environment.hpp" #include "PlatformIOProf.hpp" #include "geopm_hash.h" #include "geopm_version.h" #include "geopm.h" #include "geopm_internal.h" #include "config.h" namespace geopm { TracerImp::TracerImp(const std::string &start_time) : TracerImp(start_time, environment().trace(), hostname(), environment().do_trace(), PlatformIOProf::platform_io(), platform_topo(), environment().trace_signals()) { } TracerImp::TracerImp(const std::string &start_time, const std::string &file_path, const std::string &hostname, bool do_trace, PlatformIO &platform_io, const PlatformTopo &platform_topo, const std::string &env_column) : m_is_trace_enabled(do_trace) , m_platform_io(platform_io) , m_platform_topo(platform_topo) , m_env_column(env_column) , M_BUFFER_SIZE(134217728) // 128 MiB , m_region_hash_idx(-1) , m_region_hint_idx(-1) , m_region_progress_idx(-1) , m_region_runtime_idx(-1) { if (m_is_trace_enabled) { m_csv = geopm::make_unique<CSVImp>(file_path, hostname, start_time, M_BUFFER_SIZE); } } void TracerImp::columns(const std::vector<std::string> &agent_cols, const std::vector<std::function<std::string(double)> > &col_formats) { if (m_is_trace_enabled) { if (col_formats.size() != 0 && col_formats.size() != agent_cols.size()) { throw Exception("TracerImp::columns(): input vectors not of equal size", GEOPM_ERROR_INVALID, __FILE__, __LINE__); } // default columns std::vector<struct m_request_s> base_columns({ {"TIME", GEOPM_DOMAIN_BOARD, 0, m_platform_io.format_function("TIME")}, {"EPOCH_COUNT", GEOPM_DOMAIN_BOARD, 0, m_platform_io.format_function("EPOCH_COUNT")}, {"REGION_HASH", GEOPM_DOMAIN_BOARD, 0, m_platform_io.format_function("REGION_HASH")}, {"REGION_HINT", GEOPM_DOMAIN_BOARD, 0, m_platform_io.format_function("REGION_HINT")}, {"REGION_PROGRESS", GEOPM_DOMAIN_BOARD, 0, m_platform_io.format_function("REGION_PROGRESS")}, {"ENERGY_PACKAGE", GEOPM_DOMAIN_BOARD, 0, m_platform_io.format_function("ENERGY_PACKAGE")}, {"ENERGY_DRAM", GEOPM_DOMAIN_BOARD, 0, m_platform_io.format_function("ENERGY_DRAM")}, {"POWER_PACKAGE", GEOPM_DOMAIN_BOARD, 0, m_platform_io.format_function("POWER_PACKAGE")}, {"POWER_DRAM", GEOPM_DOMAIN_BOARD, 0, m_platform_io.format_function("POWER_DRAM")}, {"FREQUENCY", GEOPM_DOMAIN_BOARD, 0, m_platform_io.format_function("FREQUENCY")}, {"CYCLES_THREAD", GEOPM_DOMAIN_BOARD, 0, m_platform_io.format_function("CYCLES_THREAD")}, {"CYCLES_REFERENCE", GEOPM_DOMAIN_BOARD, 0, m_platform_io.format_function("CYCLES_REFERENCE")}, {"TEMPERATURE_CORE", GEOPM_DOMAIN_BOARD, 0, m_platform_io.format_function("TEMPERATURE_CORE")}}); m_region_hash_idx = 2; m_region_hint_idx = 3; m_region_progress_idx = 4; m_region_runtime_idx = 6; // extra columns from environment std::vector<std::string> env_sig = env_signals(); std::vector<int> env_dom = env_domains(); std::vector<std::function<std::string(double)> > env_form = env_formats(); #ifdef GEOPM_DEBUG if (env_sig.size() != env_dom.size() || env_sig.size() != env_form.size()) { throw Exception("Tracer::columns(): private functions returned different size vectors", GEOPM_ERROR_LOGIC, __FILE__, __LINE__); } #endif size_t num_sig = env_sig.size(); for (size_t sig_idx = 0; sig_idx != num_sig; ++sig_idx) { int num_dom = m_platform_topo.num_domain(env_dom.at(sig_idx)); for (int dom_idx = 0; dom_idx != num_dom; ++dom_idx) { base_columns.push_back({env_sig.at(sig_idx), env_dom.at(sig_idx), dom_idx, env_form.at(sig_idx)}); } } // set up columns to be sampled by TracerImp for (const auto &col : base_columns) { m_column_idx.push_back(m_platform_io.push_signal(col.name, col.domain_type, col.domain_idx)); std::string column_name = col.name; if (col.domain_type != GEOPM_DOMAIN_BOARD) { column_name += "-" + PlatformTopo::domain_type_to_name(col.domain_type); column_name += "-" + std::to_string(col.domain_idx); } m_csv->add_column(column_name, col.format); } // columns from agent; will be sampled by agent size_t num_col = agent_cols.size(); for (size_t col_idx = 0; col_idx != num_col; ++col_idx) { std::function<std::string(double)> format = col_formats.size() ? col_formats.at(col_idx) : string_format_double; m_csv->add_column(agent_cols.at(col_idx), format); } m_csv->activate(); m_last_telemetry.resize(base_columns.size() + num_col); } } void TracerImp::update(const std::vector<double> &agent_values) { if (m_is_trace_enabled) { #ifdef GEOPM_DEBUG if (m_column_idx.size() == 0) { throw Exception("TracerImp::update(): No columns added to trace.", GEOPM_ERROR_LOGIC, __FILE__, __LINE__); } if (m_column_idx.size() + agent_values.size() != m_last_telemetry.size()) { throw Exception("TracerImp::update(): Last telemetry buffer not sized correctly.", GEOPM_ERROR_LOGIC, __FILE__, __LINE__); } #endif // save values to be reused for region entry/exit size_t col_idx = 0; for (; col_idx < m_column_idx.size(); ++col_idx) { m_last_telemetry[col_idx] = m_platform_io.sample(m_column_idx[col_idx]); } for (const auto &val : agent_values) { m_last_telemetry[col_idx] = val; ++col_idx; } m_csv->update(m_last_telemetry); } } void TracerImp::flush(void) { if (m_is_trace_enabled) { m_csv->flush(); } } std::vector<std::string> TracerImp::env_signals(void) { std::vector<std::string> result; for (const auto &extra_signal : string_split(m_env_column, ",")) { std::vector<std::string> signal_domain = string_split(extra_signal, "@"); result.push_back(signal_domain[0]); } return result; } std::vector<int> TracerImp::env_domains(void) { std::vector<int> result; for (const auto &extra_signal : string_split(m_env_column, ",")) { std::vector<std::string> signal_domain = string_split(extra_signal, "@"); if (signal_domain.size() == 2) { result.push_back(PlatformTopo::domain_name_to_type(signal_domain[1])); } else if (signal_domain.size() == 1) { result.push_back(GEOPM_DOMAIN_BOARD); } else { throw Exception("TracerImp::columns(): Environment trace extension contains signals with multiple \"@\" characters.", GEOPM_ERROR_INVALID, __FILE__, __LINE__); } } return result; } std::vector<std::function<std::string(double)> > TracerImp::env_formats(void) { std::vector<std::function<std::string(double)> > result; std::vector<std::string> signals = env_signals(); for (const auto &it : env_signals()) { result.push_back(m_platform_io.format_function(it)); } return result; } }
Add geopm namespace to make_unique() call in Tracer.cpp
Add geopm namespace to make_unique() call in Tracer.cpp - Disambiguate it from std::make_unique() available after c++14 Signed-off-by: Christopher M. Cantalupo <[email protected]>
C++
bsd-3-clause
cmcantalupo/geopm,geopm/geopm,geopm/geopm,geopm/geopm,geopm/geopm,cmcantalupo/geopm,cmcantalupo/geopm,cmcantalupo/geopm,geopm/geopm,cmcantalupo/geopm
b6af901868aa86311cda5d5d482c0d7433080d33
src/Artist.cpp
src/Artist.cpp
/***************************************************************************** * Media Library ***************************************************************************** * Copyright (C) 2015 Hugo Beauzée-Luyssen, Videolabs * * Authors: Hugo Beauzée-Luyssen<[email protected]> * * This program 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 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #include "Artist.h" #include "Album.h" #include "AlbumTrack.h" #include "Media.h" #include "database/SqliteTools.h" const std::string policy::ArtistTable::Name = "artist"; const std::string policy::ArtistTable::PrimaryKeyColumn = "id_artist"; unsigned int Artist::*const policy::ArtistTable::PrimaryKey = &Artist::m_id; Artist::Artist( DBConnection dbConnection, sqlite::Row& row ) : m_dbConnection( dbConnection ) { row >> m_id >> m_name >> m_shortBio >> m_artworkMrl >> m_nbAlbums >> m_mbId >> m_isPresent; } Artist::Artist( const std::string& name ) : m_id( 0 ) , m_name( name ) , m_nbAlbums( 0 ) , m_isPresent( true ) { } unsigned int Artist::id() const { return m_id; } const std::string &Artist::name() const { return m_name; } const std::string &Artist::shortBio() const { return m_shortBio; } bool Artist::setShortBio(const std::string &shortBio) { static const std::string req = "UPDATE " + policy::ArtistTable::Name + " SET shortbio = ? WHERE id_artist = ?"; if ( sqlite::Tools::executeUpdate( m_dbConnection, req, shortBio, m_id ) == false ) return false; m_shortBio = shortBio; return true; } std::vector<AlbumPtr> Artist::albums() const { if ( m_id == 0 ) return {}; static const std::string req = "SELECT * FROM " + policy::AlbumTable::Name + " alb " "WHERE artist_id = ? ORDER BY release_year, title"; return Album::fetchAll<IAlbum>( m_dbConnection, req, m_id ); } std::vector<MediaPtr> Artist::media() const { if ( m_id ) { static const std::string req = "SELECT med.* FROM " + policy::MediaTable::Name + " med " "LEFT JOIN MediaArtistRelation mar ON mar.media_id = med.id_media " "WHERE mar.artist_id = ? AND med.is_present = 1"; return Media::fetchAll<IMedia>( m_dbConnection, req, m_id ); } else { // Not being able to rely on ForeignKey here makes me a saaaaad panda... // But sqlite only accepts "IS NULL" to compare against NULL... static const std::string req = "SELECT med.* FROM " + policy::MediaTable::Name + " med " "LEFT JOIN MediaArtistRelation mar ON mar.media_id = med.id_media " "WHERE mar.artist_id IS NULL"; return Media::fetchAll<IMedia>( m_dbConnection, req ); } } bool Artist::addMedia( Media& media ) { static const std::string req = "INSERT INTO MediaArtistRelation VALUES(?, ?)"; // If track's ID is 0, the request will fail due to table constraints sqlite::ForeignKey artistForeignKey( m_id ); return sqlite::Tools::insert( m_dbConnection, req, media.id(), artistForeignKey ) != 0; } const std::string& Artist::artworkMrl() const { return m_artworkMrl; } bool Artist::setArtworkMrl( const std::string& artworkMrl ) { if ( m_artworkMrl == artworkMrl ) return true; static const std::string req = "UPDATE " + policy::ArtistTable::Name + " SET artwork_mrl = ? WHERE id_artist = ?"; if ( sqlite::Tools::executeUpdate( m_dbConnection, req, artworkMrl, m_id ) == false ) return false; m_artworkMrl = artworkMrl; return true; } bool Artist::updateNbAlbum( int increment ) { assert( increment != 0 ); assert( increment > 0 || ( increment < 0 && m_nbAlbums >= 1 ) ); static const std::string req = "UPDATE " + policy::ArtistTable::Name + " SET nb_albums = nb_albums + ? WHERE id_artist = ?"; if ( sqlite::Tools::executeUpdate( m_dbConnection, req, increment, m_id ) == false ) return false; m_nbAlbums += increment; return true; } std::shared_ptr<Album> Artist::unknownAlbum() { static const std::string req = "SELECT * FROM " + policy::AlbumTable::Name + " WHERE artist_id = ? AND title IS NULL"; auto album = Album::fetch( m_dbConnection, req, m_id ); if ( album == nullptr ) { album = Album::createUnknownAlbum( m_dbConnection, this ); if ( album == nullptr ) return nullptr; if ( updateNbAlbum( 1 ) == false ) { Album::destroy( m_dbConnection, album->id() ); return nullptr; } } return album; } const std::string& Artist::musicBrainzId() const { return m_mbId; } bool Artist::setMusicBrainzId( const std::string& mbId ) { static const std::string req = "UPDATE " + policy::ArtistTable::Name + " SET mb_id = ? WHERE id_artist = ?"; if ( mbId == m_mbId ) return true; if ( sqlite::Tools::executeUpdate( m_dbConnection, req, mbId, m_id ) == false ) return false; m_mbId = mbId; return true; } bool Artist::createTable( DBConnection dbConnection ) { static const std::string req = "CREATE TABLE IF NOT EXISTS " + policy::ArtistTable::Name + "(" "id_artist INTEGER PRIMARY KEY AUTOINCREMENT," "name TEXT COLLATE NOCASE UNIQUE ON CONFLICT FAIL," "shortbio TEXT," "artwork_mrl TEXT," "nb_albums UNSIGNED INT DEFAULT 0," "mb_id TEXT," "is_present BOOLEAN NOT NULL DEFAULT 1" ")"; static const std::string reqRel = "CREATE TABLE IF NOT EXISTS MediaArtistRelation(" "media_id INTEGER NOT NULL," "artist_id INTEGER," "PRIMARY KEY (media_id, artist_id)," "FOREIGN KEY(media_id) REFERENCES " + policy::MediaTable::Name + "(id_media) ON DELETE CASCADE," "FOREIGN KEY(artist_id) REFERENCES " + policy::ArtistTable::Name + "(" + policy::ArtistTable::PrimaryKeyColumn + ") ON DELETE CASCADE" ")"; return sqlite::Tools::executeRequest( dbConnection, req ) && sqlite::Tools::executeRequest( dbConnection, reqRel ); } bool Artist::createTriggers(DBConnection dbConnection) { static const std::string triggerReq = "CREATE TRIGGER IF NOT EXISTS has_album_present AFTER UPDATE OF " "is_present ON " + policy::AlbumTable::Name + " BEGIN " " UPDATE " + policy::ArtistTable::Name + " SET is_present=" "(SELECT COUNT(id_album) FROM " + policy::AlbumTable::Name + " WHERE artist_id=new.artist_id AND is_present=1) " "WHERE id_artist=new.artist_id;" " END"; return sqlite::Tools::executeRequest( dbConnection, triggerReq ); } bool Artist::createDefaultArtists( DBConnection dbConnection ) { // Don't rely on Artist::create, since we want to insert or do nothing here. // This will skip the cache for those new entities, but they will be inserted soon enough anyway. static const std::string req = "INSERT OR IGNORE INTO " + policy::ArtistTable::Name + "(id_artist) VALUES(?),(?)"; sqlite::Tools::insert( dbConnection, req, medialibrary::UnknownArtistID, medialibrary::VariousArtistID ); // Always return true. The insertion might succeed, but we consider it a failure when 0 row // gets inserted, while we are explicitely specifying "OR IGNORE" here. return true; } std::shared_ptr<Artist> Artist::create( DBConnection dbConnection, const std::string &name ) { auto artist = std::make_shared<Artist>( name ); static const std::string req = "INSERT INTO " + policy::ArtistTable::Name + "(id_artist, name) VALUES(NULL, ?)"; if ( insert( dbConnection, artist, req, name ) == false ) return nullptr; artist->m_dbConnection = dbConnection; return artist; }
/***************************************************************************** * Media Library ***************************************************************************** * Copyright (C) 2015 Hugo Beauzée-Luyssen, Videolabs * * Authors: Hugo Beauzée-Luyssen<[email protected]> * * This program 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 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #include "Artist.h" #include "Album.h" #include "AlbumTrack.h" #include "Media.h" #include "database/SqliteTools.h" const std::string policy::ArtistTable::Name = "artist"; const std::string policy::ArtistTable::PrimaryKeyColumn = "id_artist"; unsigned int Artist::*const policy::ArtistTable::PrimaryKey = &Artist::m_id; Artist::Artist( DBConnection dbConnection, sqlite::Row& row ) : m_dbConnection( dbConnection ) { row >> m_id >> m_name >> m_shortBio >> m_artworkMrl >> m_nbAlbums >> m_mbId >> m_isPresent; } Artist::Artist( const std::string& name ) : m_id( 0 ) , m_name( name ) , m_nbAlbums( 0 ) , m_isPresent( true ) { } unsigned int Artist::id() const { return m_id; } const std::string &Artist::name() const { return m_name; } const std::string &Artist::shortBio() const { return m_shortBio; } bool Artist::setShortBio(const std::string &shortBio) { static const std::string req = "UPDATE " + policy::ArtistTable::Name + " SET shortbio = ? WHERE id_artist = ?"; if ( sqlite::Tools::executeUpdate( m_dbConnection, req, shortBio, m_id ) == false ) return false; m_shortBio = shortBio; return true; } std::vector<AlbumPtr> Artist::albums() const { if ( m_id == 0 ) return {}; static const std::string req = "SELECT * FROM " + policy::AlbumTable::Name + " alb " "WHERE artist_id = ? ORDER BY release_year, title"; return Album::fetchAll<IAlbum>( m_dbConnection, req, m_id ); } std::vector<MediaPtr> Artist::media() const { static const std::string req = "SELECT med.* FROM " + policy::MediaTable::Name + " med " "LEFT JOIN MediaArtistRelation mar ON mar.media_id = med.id_media " "WHERE mar.artist_id = ? AND med.is_present = 1"; return Media::fetchAll<IMedia>( m_dbConnection, req, m_id ); } bool Artist::addMedia( Media& media ) { static const std::string req = "INSERT INTO MediaArtistRelation VALUES(?, ?)"; // If track's ID is 0, the request will fail due to table constraints sqlite::ForeignKey artistForeignKey( m_id ); return sqlite::Tools::insert( m_dbConnection, req, media.id(), artistForeignKey ) != 0; } const std::string& Artist::artworkMrl() const { return m_artworkMrl; } bool Artist::setArtworkMrl( const std::string& artworkMrl ) { if ( m_artworkMrl == artworkMrl ) return true; static const std::string req = "UPDATE " + policy::ArtistTable::Name + " SET artwork_mrl = ? WHERE id_artist = ?"; if ( sqlite::Tools::executeUpdate( m_dbConnection, req, artworkMrl, m_id ) == false ) return false; m_artworkMrl = artworkMrl; return true; } bool Artist::updateNbAlbum( int increment ) { assert( increment != 0 ); assert( increment > 0 || ( increment < 0 && m_nbAlbums >= 1 ) ); static const std::string req = "UPDATE " + policy::ArtistTable::Name + " SET nb_albums = nb_albums + ? WHERE id_artist = ?"; if ( sqlite::Tools::executeUpdate( m_dbConnection, req, increment, m_id ) == false ) return false; m_nbAlbums += increment; return true; } std::shared_ptr<Album> Artist::unknownAlbum() { static const std::string req = "SELECT * FROM " + policy::AlbumTable::Name + " WHERE artist_id = ? AND title IS NULL"; auto album = Album::fetch( m_dbConnection, req, m_id ); if ( album == nullptr ) { album = Album::createUnknownAlbum( m_dbConnection, this ); if ( album == nullptr ) return nullptr; if ( updateNbAlbum( 1 ) == false ) { Album::destroy( m_dbConnection, album->id() ); return nullptr; } } return album; } const std::string& Artist::musicBrainzId() const { return m_mbId; } bool Artist::setMusicBrainzId( const std::string& mbId ) { static const std::string req = "UPDATE " + policy::ArtistTable::Name + " SET mb_id = ? WHERE id_artist = ?"; if ( mbId == m_mbId ) return true; if ( sqlite::Tools::executeUpdate( m_dbConnection, req, mbId, m_id ) == false ) return false; m_mbId = mbId; return true; } bool Artist::createTable( DBConnection dbConnection ) { static const std::string req = "CREATE TABLE IF NOT EXISTS " + policy::ArtistTable::Name + "(" "id_artist INTEGER PRIMARY KEY AUTOINCREMENT," "name TEXT COLLATE NOCASE UNIQUE ON CONFLICT FAIL," "shortbio TEXT," "artwork_mrl TEXT," "nb_albums UNSIGNED INT DEFAULT 0," "mb_id TEXT," "is_present BOOLEAN NOT NULL DEFAULT 1" ")"; static const std::string reqRel = "CREATE TABLE IF NOT EXISTS MediaArtistRelation(" "media_id INTEGER NOT NULL," "artist_id INTEGER," "PRIMARY KEY (media_id, artist_id)," "FOREIGN KEY(media_id) REFERENCES " + policy::MediaTable::Name + "(id_media) ON DELETE CASCADE," "FOREIGN KEY(artist_id) REFERENCES " + policy::ArtistTable::Name + "(" + policy::ArtistTable::PrimaryKeyColumn + ") ON DELETE CASCADE" ")"; return sqlite::Tools::executeRequest( dbConnection, req ) && sqlite::Tools::executeRequest( dbConnection, reqRel ); } bool Artist::createTriggers(DBConnection dbConnection) { static const std::string triggerReq = "CREATE TRIGGER IF NOT EXISTS has_album_present AFTER UPDATE OF " "is_present ON " + policy::AlbumTable::Name + " BEGIN " " UPDATE " + policy::ArtistTable::Name + " SET is_present=" "(SELECT COUNT(id_album) FROM " + policy::AlbumTable::Name + " WHERE artist_id=new.artist_id AND is_present=1) " "WHERE id_artist=new.artist_id;" " END"; return sqlite::Tools::executeRequest( dbConnection, triggerReq ); } bool Artist::createDefaultArtists( DBConnection dbConnection ) { // Don't rely on Artist::create, since we want to insert or do nothing here. // This will skip the cache for those new entities, but they will be inserted soon enough anyway. static const std::string req = "INSERT OR IGNORE INTO " + policy::ArtistTable::Name + "(id_artist) VALUES(?),(?)"; sqlite::Tools::insert( dbConnection, req, medialibrary::UnknownArtistID, medialibrary::VariousArtistID ); // Always return true. The insertion might succeed, but we consider it a failure when 0 row // gets inserted, while we are explicitely specifying "OR IGNORE" here. return true; } std::shared_ptr<Artist> Artist::create( DBConnection dbConnection, const std::string &name ) { auto artist = std::make_shared<Artist>( name ); static const std::string req = "INSERT INTO " + policy::ArtistTable::Name + "(id_artist, name) VALUES(NULL, ?)"; if ( insert( dbConnection, artist, req, name ) == false ) return nullptr; artist->m_dbConnection = dbConnection; return artist; }
Remove dead code
Artist: Remove dead code Now that we have an actual DB record for unknown artists, m_id won't be 0
C++
lgpl-2.1
chouquette/medialibrary,chouquette/medialibrary,chouquette/medialibrary,chouquette/medialibrary
e4b3339b9cfcbd09b8e50693d351c375df14d68b
lib/Analysis/AliasAnalysisEvaluator.cpp
lib/Analysis/AliasAnalysisEvaluator.cpp
//===- AliasAnalysisEvaluator.cpp - Alias Analysis Accuracy Evaluator -----===// // // This file implements a simple N^2 alias analysis accuracy evaluator. // Basically, for each function in the program, it simply queries to see how the // alias analysis implementation answers alias queries between each pair of // pointers in the function. // // This is inspired and adapted from code by: Naveen Neelakantam, Francesco // Spadini, and Wojciech Stryjewski. // //===----------------------------------------------------------------------===// #include "llvm/Analysis/AliasAnalysis.h" #include "llvm/Pass.h" #include "llvm/Function.h" #include "llvm/Type.h" #include "llvm/Support/InstIterator.h" #include "llvm/Assembly/Writer.h" #include "Support/CommandLine.h" namespace { cl::opt<bool> PrintNo ("print-no-aliases", cl::ReallyHidden); cl::opt<bool> PrintMay ("print-may-aliases", cl::ReallyHidden); cl::opt<bool> PrintMust("print-must-aliases", cl::ReallyHidden); class AAEval : public FunctionPass { unsigned No, May, Must; public: virtual void getAnalysisUsage(AnalysisUsage &AU) const { AU.addRequired<AliasAnalysis>(); AU.setPreservesAll(); } bool doInitialization(Module &M) { No = May = Must = 0; return false; } bool runOnFunction(Function &F); bool doFinalization(Module &M); }; RegisterOpt<AAEval> X("aa-eval", "Exhaustive Alias Analysis Precision Evaluator"); } static inline void PrintResults(const char *Msg, bool P, Value *V1, Value *V2) { if (P) { std::cerr << " " << Msg << ":\t"; WriteAsOperand(std::cerr, V1) << ", "; WriteAsOperand(std::cerr, V2) << "\n"; } } bool AAEval::runOnFunction(Function &F) { AliasAnalysis &AA = getAnalysis<AliasAnalysis>(); std::vector<Value *> Pointers; for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I) if (isa<PointerType>(I->getType())) // Add all pointer arguments Pointers.push_back(I); for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I) if (isa<PointerType>((*I)->getType())) // Add all pointer instructions Pointers.push_back(*I); if (PrintNo || PrintMay || PrintMust) std::cerr << "Function: " << F.getName() << "\n"; // iterate over the worklist, and run the full (n^2)/2 disambiguations for (std::vector<Value *>::iterator I1 = Pointers.begin(), E = Pointers.end(); I1 != E; ++I1) for (std::vector<Value *>::iterator I2 = Pointers.begin(); I2 != I1; ++I2) switch (AA.alias(*I1, *I2)) { case AliasAnalysis::NoAlias: PrintResults("No", PrintNo, *I1, *I2); ++No; break; case AliasAnalysis::MayAlias: PrintResults("May", PrintMay, *I1, *I2); ++May; break; case AliasAnalysis::MustAlias: PrintResults("Must", PrintMust, *I1, *I2); ++Must; break; default: std::cerr << "Unknown alias query result!\n"; } return false; } bool AAEval::doFinalization(Module &M) { unsigned Sum = No+May+Must; std::cerr << "===== Alias Analysis Evaluator Report =====\n"; if (Sum == 0) { std::cerr << " Alias Analysis Evaluator Summary: No pointers!\n"; return false; } std::cerr << " " << Sum << " Total Alias Queries Performed\n"; std::cerr << " " << No << " no alias responses (" << No*100/Sum << "%)\n"; std::cerr << " " << May << " may alias responses (" << May*100/Sum << "%)\n"; std::cerr << " " << Must << " must alias responses (" <<Must*100/Sum<<"%)\n"; std::cerr << " Alias Analysis Evaluator Summary: " << No*100/Sum << "%/" << May*100/Sum << "%/" << Must*100/Sum<<"%\n"; return false; }
//===- AliasAnalysisEvaluator.cpp - Alias Analysis Accuracy Evaluator -----===// // // This file implements a simple N^2 alias analysis accuracy evaluator. // Basically, for each function in the program, it simply queries to see how the // alias analysis implementation answers alias queries between each pair of // pointers in the function. // // This is inspired and adapted from code by: Naveen Neelakantam, Francesco // Spadini, and Wojciech Stryjewski. // //===----------------------------------------------------------------------===// #include "llvm/Analysis/AliasAnalysis.h" #include "llvm/Pass.h" #include "llvm/Function.h" #include "llvm/Type.h" #include "llvm/Support/InstIterator.h" #include "llvm/Assembly/Writer.h" #include "Support/CommandLine.h" namespace { cl::opt<bool> PrintNo ("print-no-aliases", cl::ReallyHidden); cl::opt<bool> PrintMay ("print-may-aliases", cl::ReallyHidden); cl::opt<bool> PrintMust("print-must-aliases", cl::ReallyHidden); class AAEval : public FunctionPass { unsigned No, May, Must; public: virtual void getAnalysisUsage(AnalysisUsage &AU) const { AU.addRequired<AliasAnalysis>(); AU.setPreservesAll(); } bool doInitialization(Module &M) { No = May = Must = 0; return false; } bool runOnFunction(Function &F); bool doFinalization(Module &M); }; RegisterOpt<AAEval> X("aa-eval", "Exhaustive Alias Analysis Precision Evaluator"); } static inline void PrintResults(const char *Msg, bool P, Value *V1, Value *V2) { if (P) { std::cerr << " " << Msg << ":\t"; WriteAsOperand(std::cerr, V1) << ", "; WriteAsOperand(std::cerr, V2) << "\n"; } } bool AAEval::runOnFunction(Function &F) { AliasAnalysis &AA = getAnalysis<AliasAnalysis>(); std::vector<Value *> Pointers; for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I) if (isa<PointerType>(I->getType())) // Add all pointer arguments Pointers.push_back(I); for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I) if (isa<PointerType>((*I)->getType())) // Add all pointer instructions Pointers.push_back(*I); if (PrintNo || PrintMay || PrintMust) std::cerr << "Function: " << F.getName() << "\n"; // iterate over the worklist, and run the full (n^2)/2 disambiguations for (std::vector<Value *>::iterator I1 = Pointers.begin(), E = Pointers.end(); I1 != E; ++I1) for (std::vector<Value *>::iterator I2 = Pointers.begin(); I2 != I1; ++I2) switch (AA.alias(*I1, 0, *I2, 0)) { case AliasAnalysis::NoAlias: PrintResults("No", PrintNo, *I1, *I2); ++No; break; case AliasAnalysis::MayAlias: PrintResults("May", PrintMay, *I1, *I2); ++May; break; case AliasAnalysis::MustAlias: PrintResults("Must", PrintMust, *I1, *I2); ++Must; break; default: std::cerr << "Unknown alias query result!\n"; } return false; } bool AAEval::doFinalization(Module &M) { unsigned Sum = No+May+Must; std::cerr << "===== Alias Analysis Evaluator Report =====\n"; if (Sum == 0) { std::cerr << " Alias Analysis Evaluator Summary: No pointers!\n"; return false; } std::cerr << " " << Sum << " Total Alias Queries Performed\n"; std::cerr << " " << No << " no alias responses (" << No*100/Sum << "%)\n"; std::cerr << " " << May << " may alias responses (" << May*100/Sum << "%)\n"; std::cerr << " " << Must << " must alias responses (" <<Must*100/Sum<<"%)\n"; std::cerr << " Alias Analysis Evaluator Summary: " << No*100/Sum << "%/" << May*100/Sum << "%/" << Must*100/Sum<<"%\n"; return false; }
Adjust to new AA interface
Adjust to new AA interface git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@5637 91177308-0d34-0410-b5e6-96231b3b80d8
C++
apache-2.0
GPUOpen-Drivers/llvm,dslab-epfl/asap,llvm-mirror/llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,dslab-epfl/asap,dslab-epfl/asap,GPUOpen-Drivers/llvm,llvm-mirror/llvm,llvm-mirror/llvm,apple/swift-llvm,apple/swift-llvm,chubbymaggie/asap,chubbymaggie/asap,GPUOpen-Drivers/llvm,chubbymaggie/asap,dslab-epfl/asap,apple/swift-llvm,GPUOpen-Drivers/llvm,chubbymaggie/asap,llvm-mirror/llvm,llvm-mirror/llvm,dslab-epfl/asap,chubbymaggie/asap,llvm-mirror/llvm,GPUOpen-Drivers/llvm,dslab-epfl/asap,llvm-mirror/llvm,apple/swift-llvm,apple/swift-llvm,chubbymaggie/asap,apple/swift-llvm,dslab-epfl/asap,llvm-mirror/llvm
f14645cc6474dab76b266906575ce4e4d018e9ee
lib/CodeGen/AsmPrinter/DwarfPrinter.cpp
lib/CodeGen/AsmPrinter/DwarfPrinter.cpp
//===--- lib/CodeGen/DwarfPrinter.cpp - Dwarf Printer ---------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Emit general DWARF directives. // //===----------------------------------------------------------------------===// #include "DwarfPrinter.h" #include "llvm/Module.h" #include "llvm/CodeGen/AsmPrinter.h" #include "llvm/CodeGen/MachineFrameInfo.h" #include "llvm/CodeGen/MachineFunction.h" #include "llvm/CodeGen/MachineModuleInfo.h" #include "llvm/MC/MCAsmInfo.h" #include "llvm/MC/MCContext.h" #include "llvm/MC/MCExpr.h" #include "llvm/MC/MCStreamer.h" #include "llvm/MC/MCSymbol.h" #include "llvm/Target/TargetData.h" #include "llvm/Target/TargetFrameInfo.h" #include "llvm/Target/TargetLoweringObjectFile.h" #include "llvm/Target/TargetRegisterInfo.h" #include "llvm/Support/Dwarf.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/ADT/SmallString.h" using namespace llvm; DwarfPrinter::DwarfPrinter(raw_ostream &OS, AsmPrinter *A, const MCAsmInfo *T) : O(OS), Asm(A), MAI(T), TD(Asm->TM.getTargetData()), RI(Asm->TM.getRegisterInfo()), M(NULL), MF(NULL), MMI(NULL), SubprogramCount(0) {} /// getDWLabel - Return the MCSymbol corresponding to the assembler temporary /// label with the specified stem and unique ID. MCSymbol *DwarfPrinter::getDWLabel(const char *Name, unsigned ID) const { // FIXME: REMOVE this. However, there is stuff in EH that passes counters in // here that can be zero. //assert(ID && "Should use getTempLabel if no ID"); if (ID == 0) return getTempLabel(Name); return Asm->OutContext.GetOrCreateTemporarySymbol (Twine(MAI->getPrivateGlobalPrefix()) + Twine(Name) + Twine(ID)); } /// getTempLabel - Return the MCSymbol corresponding to the assembler temporary /// label with the specified name. MCSymbol *DwarfPrinter::getTempLabel(const char *Name) const { return Asm->OutContext.GetOrCreateTemporarySymbol (Twine(MAI->getPrivateGlobalPrefix()) + Name); } /// SizeOfEncodedValue - Return the size of the encoding in bytes. unsigned DwarfPrinter::SizeOfEncodedValue(unsigned Encoding) const { if (Encoding == dwarf::DW_EH_PE_omit) return 0; switch (Encoding & 0x07) { case dwarf::DW_EH_PE_absptr: return TD->getPointerSize(); case dwarf::DW_EH_PE_udata2: return 2; case dwarf::DW_EH_PE_udata4: return 4; case dwarf::DW_EH_PE_udata8: return 8; } assert(0 && "Invalid encoded value."); return 0; } static const char *DecodeDWARFEncoding(unsigned Encoding) { switch (Encoding) { case dwarf::DW_EH_PE_absptr: return "absptr"; case dwarf::DW_EH_PE_omit: return "omit"; case dwarf::DW_EH_PE_pcrel: return "pcrel"; case dwarf::DW_EH_PE_udata4: return "udata4"; case dwarf::DW_EH_PE_udata8: return "udata8"; case dwarf::DW_EH_PE_sdata4: return "sdata4"; case dwarf::DW_EH_PE_sdata8: return "sdata8"; case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata4: return "pcrel udata4"; case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4: return "pcrel sdata4"; case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata8: return "pcrel udata8"; case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata8: return "pcrel sdata8"; case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_udata4: return "indirect pcrel udata4"; case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_sdata4: return "indirect pcrel sdata4"; case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_udata8: return "indirect pcrel udata8"; case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_sdata8: return "indirect pcrel sdata8"; } return "<unknown encoding>"; } /// EmitEncodingByte - Emit a .byte 42 directive that corresponds to an /// encoding. If verbose assembly output is enabled, we output comments /// describing the encoding. Desc is an optional string saying what the /// encoding is specifying (e.g. "LSDA"). void DwarfPrinter::EmitEncodingByte(unsigned Val, const char *Desc) { if (Asm->VerboseAsm) { if (Desc != 0) Asm->OutStreamer.AddComment(Twine(Desc)+" Encoding = " + Twine(DecodeDWARFEncoding(Val))); else Asm->OutStreamer.AddComment(Twine("Encoding = ") + DecodeDWARFEncoding(Val)); } Asm->OutStreamer.EmitIntValue(Val, 1, 0/*addrspace*/); } /// EmitCFAByte - Emit a .byte 42 directive for a DW_CFA_xxx value. void DwarfPrinter::EmitCFAByte(unsigned Val) { if (Asm->VerboseAsm) { if (Val >= dwarf::DW_CFA_offset && Val < dwarf::DW_CFA_offset+64) Asm->OutStreamer.AddComment("DW_CFA_offset + Reg (" + Twine(Val-dwarf::DW_CFA_offset) + ")"); else Asm->OutStreamer.AddComment(dwarf::CallFrameString(Val)); } Asm->OutStreamer.EmitIntValue(Val, 1, 0/*addrspace*/); } /// EmitSLEB128 - emit the specified signed leb128 value. void DwarfPrinter::EmitSLEB128(int Value, const char *Desc) const { if (Asm->VerboseAsm && Desc) Asm->OutStreamer.AddComment(Desc); if (MAI->hasLEB128()) { // FIXME: MCize. O << "\t.sleb128\t" << Value; Asm->OutStreamer.AddBlankLine(); return; } // If we don't have .sleb128, emit as .bytes. int Sign = Value >> (8 * sizeof(Value) - 1); bool IsMore; do { unsigned char Byte = static_cast<unsigned char>(Value & 0x7f); Value >>= 7; IsMore = Value != Sign || ((Byte ^ Sign) & 0x40) != 0; if (IsMore) Byte |= 0x80; Asm->OutStreamer.EmitIntValue(Byte, 1, /*addrspace*/0); } while (IsMore); } /// EmitULEB128 - emit the specified signed leb128 value. void DwarfPrinter::EmitULEB128(unsigned Value, const char *Desc, unsigned PadTo) const { if (Asm->VerboseAsm && Desc) Asm->OutStreamer.AddComment(Desc); if (MAI->hasLEB128() && PadTo == 0) { // FIXME: MCize. O << "\t.uleb128\t" << Value; Asm->OutStreamer.AddBlankLine(); return; } // If we don't have .uleb128 or we want to emit padding, emit as .bytes. do { unsigned char Byte = static_cast<unsigned char>(Value & 0x7f); Value >>= 7; if (Value || PadTo != 0) Byte |= 0x80; Asm->OutStreamer.EmitIntValue(Byte, 1, /*addrspace*/0); } while (Value); if (PadTo) { if (PadTo > 1) Asm->OutStreamer.EmitFill(PadTo - 1, 0x80/*fillval*/, 0/*addrspace*/); Asm->OutStreamer.EmitFill(1, 0/*fillval*/, 0/*addrspace*/); } } void DwarfPrinter::EmitReference(const MCSymbol *Sym, unsigned Encoding) const { const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering(); const MCExpr *Exp = TLOF.getExprForDwarfReference(Sym, Asm->Mang, Asm->MMI, Encoding, Asm->OutStreamer); Asm->OutStreamer.EmitValue(Exp, SizeOfEncodedValue(Encoding), /*addrspace*/0); } void DwarfPrinter::EmitReference(const GlobalValue *GV, unsigned Encoding)const{ const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering(); const MCExpr *Exp = TLOF.getExprForDwarfGlobalReference(GV, Asm->Mang, Asm->MMI, Encoding, Asm->OutStreamer); Asm->OutStreamer.EmitValue(Exp, SizeOfEncodedValue(Encoding), /*addrspace*/0); } /// EmitDifference - Emit the difference between two labels. If this assembler /// supports .set, we emit a .set of a temporary and then use it in the .word. void DwarfPrinter::EmitDifference(const MCSymbol *TagHi, const MCSymbol *TagLo, bool IsSmall) { unsigned Size = IsSmall ? 4 : TD->getPointerSize(); Asm->EmitLabelDifference(TagHi, TagLo, Size); } void DwarfPrinter::EmitSectionOffset(const MCSymbol *Label, const MCSymbol *Section, bool IsSmall, bool isEH) { bool isAbsolute; if (isEH) isAbsolute = MAI->isAbsoluteEHSectionOffsets(); else isAbsolute = MAI->isAbsoluteDebugSectionOffsets(); if (!isAbsolute) return EmitDifference(Label, Section, IsSmall); // On COFF targets, we have to emit the weird .secrel32 directive. if (const char *SecOffDir = MAI->getDwarfSectionOffsetDirective()) { // FIXME: MCize. Asm->O << SecOffDir << Label->getName(); Asm->OutStreamer.AddBlankLine(); } else { unsigned Size = IsSmall ? 4 : TD->getPointerSize(); Asm->OutStreamer.EmitSymbolValue(Label, Size, 0/*AddrSpace*/); } } /// EmitFrameMoves - Emit frame instructions to describe the layout of the /// frame. void DwarfPrinter::EmitFrameMoves(MCSymbol *BaseLabel, const std::vector<MachineMove> &Moves, bool isEH) { int stackGrowth = TD->getPointerSize(); if (Asm->TM.getFrameInfo()->getStackGrowthDirection() != TargetFrameInfo::StackGrowsUp) stackGrowth *= -1; for (unsigned i = 0, N = Moves.size(); i < N; ++i) { const MachineMove &Move = Moves[i]; unsigned LabelID = Move.getLabelID(); // Throw out move if the label is invalid. if (LabelID == 0) continue; MCSymbol *Label = getDWLabel("label", LabelID); if (!Label->isDefined()) continue; // Not emitted, in dead code. const MachineLocation &Dst = Move.getDestination(); const MachineLocation &Src = Move.getSource(); // Advance row if new location. if (BaseLabel) { MCSymbol *ThisSym = Label; if (ThisSym != BaseLabel) { EmitCFAByte(dwarf::DW_CFA_advance_loc4); EmitDifference(ThisSym, BaseLabel, true); BaseLabel = ThisSym; } } // If advancing cfa. if (Dst.isReg() && Dst.getReg() == MachineLocation::VirtualFP) { if (!Src.isReg()) { if (Src.getReg() == MachineLocation::VirtualFP) { EmitCFAByte(dwarf::DW_CFA_def_cfa_offset); } else { EmitCFAByte(dwarf::DW_CFA_def_cfa); EmitULEB128(RI->getDwarfRegNum(Src.getReg(), isEH), "Register"); } int Offset = -Src.getOffset(); EmitULEB128(Offset, "Offset"); } else { llvm_unreachable("Machine move not supported yet."); } } else if (Src.isReg() && Src.getReg() == MachineLocation::VirtualFP) { if (Dst.isReg()) { EmitCFAByte(dwarf::DW_CFA_def_cfa_register); EmitULEB128(RI->getDwarfRegNum(Dst.getReg(), isEH), "Register"); } else { llvm_unreachable("Machine move not supported yet."); } } else { unsigned Reg = RI->getDwarfRegNum(Src.getReg(), isEH); int Offset = Dst.getOffset() / stackGrowth; if (Offset < 0) { EmitCFAByte(dwarf::DW_CFA_offset_extended_sf); EmitULEB128(Reg, "Reg"); EmitSLEB128(Offset, "Offset"); } else if (Reg < 64) { EmitCFAByte(dwarf::DW_CFA_offset + Reg); EmitULEB128(Offset, "Offset"); } else { EmitCFAByte(dwarf::DW_CFA_offset_extended); EmitULEB128(Reg, "Reg"); EmitULEB128(Offset, "Offset"); } } } }
//===--- lib/CodeGen/DwarfPrinter.cpp - Dwarf Printer ---------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Emit general DWARF directives. // //===----------------------------------------------------------------------===// #include "DwarfPrinter.h" #include "llvm/Module.h" #include "llvm/CodeGen/AsmPrinter.h" #include "llvm/CodeGen/MachineFrameInfo.h" #include "llvm/CodeGen/MachineFunction.h" #include "llvm/CodeGen/MachineModuleInfo.h" #include "llvm/MC/MCAsmInfo.h" #include "llvm/MC/MCContext.h" #include "llvm/MC/MCExpr.h" #include "llvm/MC/MCStreamer.h" #include "llvm/MC/MCSymbol.h" #include "llvm/Target/TargetData.h" #include "llvm/Target/TargetFrameInfo.h" #include "llvm/Target/TargetLoweringObjectFile.h" #include "llvm/Target/TargetRegisterInfo.h" #include "llvm/Support/Dwarf.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/ADT/SmallString.h" using namespace llvm; DwarfPrinter::DwarfPrinter(raw_ostream &OS, AsmPrinter *A, const MCAsmInfo *T) : O(OS), Asm(A), MAI(T), TD(Asm->TM.getTargetData()), RI(Asm->TM.getRegisterInfo()), M(NULL), MF(NULL), MMI(NULL), SubprogramCount(0) {} /// getDWLabel - Return the MCSymbol corresponding to the assembler temporary /// label with the specified stem and unique ID. MCSymbol *DwarfPrinter::getDWLabel(const char *Name, unsigned ID) const { // FIXME: REMOVE this. However, there is stuff in EH that passes counters in // here that can be zero. //assert(ID && "Should use getTempLabel if no ID"); if (ID == 0) return getTempLabel(Name); return Asm->OutContext.GetOrCreateTemporarySymbol (Twine(MAI->getPrivateGlobalPrefix()) + Twine(Name) + Twine(ID)); } /// getTempLabel - Return the MCSymbol corresponding to the assembler temporary /// label with the specified name. MCSymbol *DwarfPrinter::getTempLabel(const char *Name) const { return Asm->OutContext.GetOrCreateTemporarySymbol (Twine(MAI->getPrivateGlobalPrefix()) + Name); } /// SizeOfEncodedValue - Return the size of the encoding in bytes. unsigned DwarfPrinter::SizeOfEncodedValue(unsigned Encoding) const { if (Encoding == dwarf::DW_EH_PE_omit) return 0; switch (Encoding & 0x07) { case dwarf::DW_EH_PE_absptr: return TD->getPointerSize(); case dwarf::DW_EH_PE_udata2: return 2; case dwarf::DW_EH_PE_udata4: return 4; case dwarf::DW_EH_PE_udata8: return 8; } assert(0 && "Invalid encoded value."); return 0; } static const char *DecodeDWARFEncoding(unsigned Encoding) { switch (Encoding) { case dwarf::DW_EH_PE_absptr: return "absptr"; case dwarf::DW_EH_PE_omit: return "omit"; case dwarf::DW_EH_PE_pcrel: return "pcrel"; case dwarf::DW_EH_PE_udata4: return "udata4"; case dwarf::DW_EH_PE_udata8: return "udata8"; case dwarf::DW_EH_PE_sdata4: return "sdata4"; case dwarf::DW_EH_PE_sdata8: return "sdata8"; case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata4: return "pcrel udata4"; case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4: return "pcrel sdata4"; case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata8: return "pcrel udata8"; case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata8: return "pcrel sdata8"; case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_udata4: return "indirect pcrel udata4"; case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_sdata4: return "indirect pcrel sdata4"; case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_udata8: return "indirect pcrel udata8"; case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_sdata8: return "indirect pcrel sdata8"; } return "<unknown encoding>"; } /// EmitEncodingByte - Emit a .byte 42 directive that corresponds to an /// encoding. If verbose assembly output is enabled, we output comments /// describing the encoding. Desc is an optional string saying what the /// encoding is specifying (e.g. "LSDA"). void DwarfPrinter::EmitEncodingByte(unsigned Val, const char *Desc) { if (Asm->VerboseAsm) { if (Desc != 0) Asm->OutStreamer.AddComment(Twine(Desc)+" Encoding = " + Twine(DecodeDWARFEncoding(Val))); else Asm->OutStreamer.AddComment(Twine("Encoding = ") + DecodeDWARFEncoding(Val)); } Asm->OutStreamer.EmitIntValue(Val, 1, 0/*addrspace*/); } /// EmitCFAByte - Emit a .byte 42 directive for a DW_CFA_xxx value. void DwarfPrinter::EmitCFAByte(unsigned Val) { if (Asm->VerboseAsm) { if (Val >= dwarf::DW_CFA_offset && Val < dwarf::DW_CFA_offset+64) Asm->OutStreamer.AddComment("DW_CFA_offset + Reg (" + Twine(Val-dwarf::DW_CFA_offset) + ")"); else Asm->OutStreamer.AddComment(dwarf::CallFrameString(Val)); } Asm->OutStreamer.EmitIntValue(Val, 1, 0/*addrspace*/); } /// EmitSLEB128 - emit the specified signed leb128 value. void DwarfPrinter::EmitSLEB128(int Value, const char *Desc) const { if (Asm->VerboseAsm && Desc) Asm->OutStreamer.AddComment(Desc); if (MAI->hasLEB128()) { // FIXME: MCize. O << "\t.sleb128\t" << Value; Asm->OutStreamer.AddBlankLine(); return; } // If we don't have .sleb128, emit as .bytes. int Sign = Value >> (8 * sizeof(Value) - 1); bool IsMore; do { unsigned char Byte = static_cast<unsigned char>(Value & 0x7f); Value >>= 7; IsMore = Value != Sign || ((Byte ^ Sign) & 0x40) != 0; if (IsMore) Byte |= 0x80; Asm->OutStreamer.EmitIntValue(Byte, 1, /*addrspace*/0); } while (IsMore); } /// EmitULEB128 - emit the specified signed leb128 value. void DwarfPrinter::EmitULEB128(unsigned Value, const char *Desc, unsigned PadTo) const { if (Asm->VerboseAsm && Desc) Asm->OutStreamer.AddComment(Desc); if (MAI->hasLEB128() && PadTo == 0) { // FIXME: MCize. O << "\t.uleb128\t" << Value; Asm->OutStreamer.AddBlankLine(); return; } // If we don't have .uleb128 or we want to emit padding, emit as .bytes. do { unsigned char Byte = static_cast<unsigned char>(Value & 0x7f); Value >>= 7; if (Value || PadTo != 0) Byte |= 0x80; Asm->OutStreamer.EmitIntValue(Byte, 1, /*addrspace*/0); } while (Value); if (PadTo) { if (PadTo > 1) Asm->OutStreamer.EmitFill(PadTo - 1, 0x80/*fillval*/, 0/*addrspace*/); Asm->OutStreamer.EmitFill(1, 0/*fillval*/, 0/*addrspace*/); } } void DwarfPrinter::EmitReference(const MCSymbol *Sym, unsigned Encoding) const { const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering(); const MCExpr *Exp = TLOF.getExprForDwarfReference(Sym, Asm->Mang, Asm->MMI, Encoding, Asm->OutStreamer); Asm->OutStreamer.EmitValue(Exp, SizeOfEncodedValue(Encoding), /*addrspace*/0); } void DwarfPrinter::EmitReference(const GlobalValue *GV, unsigned Encoding)const{ const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering(); const MCExpr *Exp = TLOF.getExprForDwarfGlobalReference(GV, Asm->Mang, Asm->MMI, Encoding, Asm->OutStreamer); Asm->OutStreamer.EmitValue(Exp, SizeOfEncodedValue(Encoding), /*addrspace*/0); } /// EmitDifference - Emit the difference between two labels. If this assembler /// supports .set, we emit a .set of a temporary and then use it in the .word. void DwarfPrinter::EmitDifference(const MCSymbol *TagHi, const MCSymbol *TagLo, bool IsSmall) { unsigned Size = IsSmall ? 4 : TD->getPointerSize(); Asm->EmitLabelDifference(TagHi, TagLo, Size); } void DwarfPrinter::EmitSectionOffset(const MCSymbol *Label, const MCSymbol *Section, bool IsSmall, bool isEH) { bool isAbsolute; if (isEH) isAbsolute = MAI->isAbsoluteEHSectionOffsets(); else isAbsolute = MAI->isAbsoluteDebugSectionOffsets(); if (!isAbsolute) return EmitDifference(Label, Section, IsSmall); // On COFF targets, we have to emit the weird .secrel32 directive. if (const char *SecOffDir = MAI->getDwarfSectionOffsetDirective()) { // FIXME: MCize. Asm->O << SecOffDir << Label->getName(); Asm->OutStreamer.AddBlankLine(); } else { unsigned Size = IsSmall ? 4 : TD->getPointerSize(); Asm->OutStreamer.EmitSymbolValue(Label, Size, 0/*AddrSpace*/); } } /// EmitFrameMoves - Emit frame instructions to describe the layout of the /// frame. void DwarfPrinter::EmitFrameMoves(MCSymbol *BaseLabel, const std::vector<MachineMove> &Moves, bool isEH) { int stackGrowth = TD->getPointerSize(); if (Asm->TM.getFrameInfo()->getStackGrowthDirection() != TargetFrameInfo::StackGrowsUp) stackGrowth *= -1; for (unsigned i = 0, N = Moves.size(); i < N; ++i) { const MachineMove &Move = Moves[i]; MCSymbol *Label = 0; unsigned LabelID = Move.getLabelID(); // Throw out move if the label is invalid. if (LabelID) { Label = getDWLabel("label", LabelID); if (!Label->isDefined()) continue; // Not emitted, in dead code. } const MachineLocation &Dst = Move.getDestination(); const MachineLocation &Src = Move.getSource(); // Advance row if new location. if (BaseLabel && Label) { MCSymbol *ThisSym = Label; if (ThisSym != BaseLabel) { EmitCFAByte(dwarf::DW_CFA_advance_loc4); EmitDifference(ThisSym, BaseLabel, true); BaseLabel = ThisSym; } } // If advancing cfa. if (Dst.isReg() && Dst.getReg() == MachineLocation::VirtualFP) { if (!Src.isReg()) { if (Src.getReg() == MachineLocation::VirtualFP) { EmitCFAByte(dwarf::DW_CFA_def_cfa_offset); } else { EmitCFAByte(dwarf::DW_CFA_def_cfa); EmitULEB128(RI->getDwarfRegNum(Src.getReg(), isEH), "Register"); } int Offset = -Src.getOffset(); EmitULEB128(Offset, "Offset"); } else { llvm_unreachable("Machine move not supported yet."); } } else if (Src.isReg() && Src.getReg() == MachineLocation::VirtualFP) { if (Dst.isReg()) { EmitCFAByte(dwarf::DW_CFA_def_cfa_register); EmitULEB128(RI->getDwarfRegNum(Dst.getReg(), isEH), "Register"); } else { llvm_unreachable("Machine move not supported yet."); } } else { unsigned Reg = RI->getDwarfRegNum(Src.getReg(), isEH); int Offset = Dst.getOffset() / stackGrowth; if (Offset < 0) { EmitCFAByte(dwarf::DW_CFA_offset_extended_sf); EmitULEB128(Reg, "Reg"); EmitSLEB128(Offset, "Offset"); } else if (Reg < 64) { EmitCFAByte(dwarf::DW_CFA_offset + Reg); EmitULEB128(Offset, "Offset"); } else { EmitCFAByte(dwarf::DW_CFA_offset_extended); EmitULEB128(Reg, "Reg"); EmitULEB128(Offset, "Offset"); } } } }
Fix some EH failures on NNT I introduced in r98461
Fix some EH failures on NNT I introduced in r98461 git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@98471 91177308-0d34-0410-b5e6-96231b3b80d8
C++
apache-2.0
apple/swift-llvm,llvm-mirror/llvm,dslab-epfl/asap,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,chubbymaggie/asap,llvm-mirror/llvm,apple/swift-llvm,apple/swift-llvm,dslab-epfl/asap,apple/swift-llvm,dslab-epfl/asap,llvm-mirror/llvm,llvm-mirror/llvm,llvm-mirror/llvm,dslab-epfl/asap,dslab-epfl/asap,llvm-mirror/llvm,chubbymaggie/asap,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,dslab-epfl/asap,apple/swift-llvm,llvm-mirror/llvm,apple/swift-llvm,dslab-epfl/asap,GPUOpen-Drivers/llvm,chubbymaggie/asap,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,chubbymaggie/asap,chubbymaggie/asap,GPUOpen-Drivers/llvm,apple/swift-llvm,chubbymaggie/asap,llvm-mirror/llvm,llvm-mirror/llvm
4948ea7bb656c35f181c18ceb6a670fd3b14eb40
src/Engine/Manager/ParticleManager.hpp
src/Engine/Manager/ParticleManager.hpp
#pragma once #include <glm/glm.hpp> #include <GL/glew.h> #include <random> class Entity; class World; class Shader; class ShaderProgram; class Texture2D; namespace Component { class ParticleEmitter; } /// Handles particles. class ParticleManager { friend class Hub; public: /// A particle in the particle system. struct Particle { /// Position. glm::vec3 worldPos; /// Size. glm::vec2 size; /// Life (in seconds). float life; /// Lifetime (in seconds). float lifetime; /// Initial velocity. glm::vec3 velocity; /// Start, mid and end of life alpha of particle. glm::vec3 alpha; /// Color of the particle. glm::vec3 color; /// Texture index (for the texture atlas, left to right, top to bottom indexing) float textureIndex; }; /// Get the maximum amount of particles. /** * @return Maximum amount of particles. */ unsigned int GetMaxParticleCount() const; /// Update all the system's particles, spawn new particles etc. /** * @param world World to update. * @param time Time since last frame (in seconds). */ void Update(World& world, float time); /// Update particle buffer. /** * Needs to be called before rendering (but only once a frame). * @param world The world to render. */ void UpdateBuffer(World& world); /// Render the particles in a world. /** * @param world %World containing particles to render. * @param camera Camera through which to render. */ void Render(World& world, Entity* camera); /// Get the texture atlas. /** * @return The particle texture atlas. */ const Texture2D* GetTextureAtlas() const; /// Get the number of rows in the texture atlas. /** * @return The number of rows in the texture atlas. */ int GetTextureAtlasRows() const; private: ParticleManager(); ~ParticleManager(); ParticleManager(ParticleManager const&) = delete; void operator=(ParticleManager const&) = delete; // Decide where the emitter should emit before rendering. void EmitParticle(World& world, Component::ParticleEmitter* emitter); // Emit a particle at the given position. void EmitParticle(World& world, const glm::vec3& position, Component::ParticleEmitter* emitter); unsigned int maxParticleCount = 10000; std::random_device randomDevice; std::mt19937 randomEngine; // Shaders. Shader* vertexShader; Shader* geometryShader; Shader* fragmentShader; ShaderProgram* shaderProgram; // The number of rows in the texture atlas. int textureAtlasRowNumber = 4; // Texture atlas containing the particle textures. Texture2D* textureAtlas; // Vertex buffer. GLuint vertexBuffer = 0; GLuint vertexArray = 0; unsigned int vertexCount = 0; };
#pragma once #include <glm/glm.hpp> #include <GL/glew.h> #include <random> class Entity; class World; class Shader; class ShaderProgram; class Texture2D; namespace Component { class ParticleEmitter; } /// Handles particles. class ParticleManager { friend class Hub; public: /// A particle in the particle system. struct Particle { /// Position. glm::vec3 worldPos; /// Size. glm::vec2 size; /// Life (in seconds). float life; /// Lifetime (in seconds). float lifetime; /// Initial velocity. glm::vec3 velocity; /// Start, mid and end of life alpha of particle. glm::vec3 alpha; /// Color of the particle. glm::vec3 color; /// Texture index (for the texture atlas, left to right, top to bottom indexing) float textureIndex; }; /// Get the maximum amount of particles. /** * @return Maximum amount of particles. */ unsigned int GetMaxParticleCount() const; /// Update all the system's particles, spawn new particles etc. /** * @param world World to update. * @param time Time since last frame (in seconds). */ void Update(World& world, float time); /// Update particle buffer. /** * Needs to be called before rendering (but only once a frame). * @param world The world to render. */ void UpdateBuffer(World& world); /// Render the particles in a world. /** * @param world %World containing particles to render. * @param camera Camera through which to render. */ void Render(World& world, Entity* camera); /// Get the texture atlas. /** * @return The particle texture atlas. */ const Texture2D* GetTextureAtlas() const; /// Get the number of rows in the texture atlas. /** * @return The number of rows in the texture atlas. */ int GetTextureAtlasRows() const; private: ParticleManager(); ~ParticleManager(); ParticleManager(ParticleManager const&) = delete; void operator=(ParticleManager const&) = delete; // Decide where the emitter should emit before rendering. void EmitParticle(World& world, Component::ParticleEmitter* emitter); // Emit a particle at the given position. void EmitParticle(World& world, const glm::vec3& position, Component::ParticleEmitter* emitter); unsigned int maxParticleCount = 10000; std::random_device randomDevice; std::mt19937 randomEngine; // Shaders. Shader* vertexShader; Shader* geometryShader; Shader* fragmentShader; ShaderProgram* shaderProgram; // The number of rows in the texture atlas. int textureAtlasRowNumber = 4; // Texture atlas containing the particle textures. Texture2D* textureAtlas; // Vertex buffer. GLuint vertexBuffer = 0; GLuint vertexArray = 0; unsigned int vertexCount = 0; };
Fix indentation
Fix indentation
C++
mit
Chainsawkitten/LargeGameProjectEngine,Chainsawkitten/HymnToBeauty,Chainsawkitten/LargeGameProjectEngine,Chainsawkitten/HymnToBeauty
c778da675db5491a9bda92f55aecf562b76fc75f
lib/CodeGen/GlobalISel/IRTranslator.cpp
lib/CodeGen/GlobalISel/IRTranslator.cpp
//===-- llvm/CodeGen/GlobalISel/IRTranslator.cpp - IRTranslator --*- C++ -*-==// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// \file /// This file implements the IRTranslator class. //===----------------------------------------------------------------------===// #include "llvm/CodeGen/GlobalISel/IRTranslator.h" #include "llvm/CodeGen/GlobalISel/MachineIRBuilder.h" #include "llvm/CodeGen/MachineFunction.h" #include "llvm/CodeGen/MachineRegisterInfo.h" #include "llvm/IR/Constant.h" #include "llvm/IR/Function.h" #include "llvm/IR/Type.h" #include "llvm/IR/Value.h" #define DEBUG_TYPE "irtranslator" using namespace llvm; char IRTranslator::ID = 0; const VRegsSequence &IRTranslator::getOrCreateVRegs(const Value *Val) { VRegsSequence &ValRegSequence = ValToVRegs[Val]; // Check if this is the first time we see Val. if (ValRegSequence.empty()) { // Fill ValRegsSequence with the sequence of registers // we need to concat together to produce the value. assert(Val->getType()->isSized() && "Don't know how to create an empty vreg"); assert(!Val->getType()->isAggregateType() && "Not yet implemented"); unsigned Size = Val->getType()->getPrimitiveSizeInBits(); unsigned VReg = MRI->createGenericVirtualRegister(Size); ValRegSequence.push_back(VReg); assert(isa<Constant>(Val) && "Not yet implemented"); } assert(ValRegSequence.size() == 1 && "We support only one vreg per value at the moment"); return ValRegSequence; } MachineBasicBlock &IRTranslator::getOrCreateBB(const BasicBlock *BB) { MachineBasicBlock *&MBB = BBToMBB[BB]; if (!MBB) { MachineFunction &MF = MIRBuilder->getMF(); MBB = MF.CreateMachineBasicBlock(); MF.push_back(MBB); } return *MBB; } bool IRTranslator::translateADD(const Instruction &Inst) { // Get or create a virtual register for each value. // Unless the value is a Constant => loadimm cst? // or inline constant each time? // Creation of a virtual register needs to have a size. unsigned Op0 = *getOrCreateVRegs(Inst.getOperand(0)).begin(); unsigned Op1 = *getOrCreateVRegs(Inst.getOperand(1)).begin(); unsigned Res = *getOrCreateVRegs(&Inst).begin(); MIRBuilder->buildInstr(TargetOpcode::G_ADD, Res, Op0, Op1); return true; } bool IRTranslator::translate(const Instruction &Inst) { MIRBuilder->setDebugLoc(Inst.getDebugLoc()); switch(Inst.getOpcode()) { case Instruction::Add: { return translateADD(Inst); default: llvm_unreachable("Opcode not supported"); } } } void IRTranslator::finalize() { // Release the memory used by the different maps we // needed during the translation. ValToVRegs.clear(); Constants.clear(); } IRTranslator::IRTranslator() : MachineFunctionPass(ID) { } bool IRTranslator::runOnMachineFunction(MachineFunction &MF) { const Function &F = *MF.getFunction(); MIRBuilder->setFunction(MF); MRI = &MF.getRegInfo(); for (const BasicBlock &BB: F) { MachineBasicBlock &MBB = getOrCreateBB(&BB); MIRBuilder->setBasicBlock(MBB); for (const Instruction &Inst: BB) { bool Succeeded = translate(Inst); if (!Succeeded) { DEBUG(dbgs() << "Cannot translate: " << Inst << '\n'); report_fatal_error("Unable to translate instruction"); } } } return false; }
//===-- llvm/CodeGen/GlobalISel/IRTranslator.cpp - IRTranslator --*- C++ -*-==// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// \file /// This file implements the IRTranslator class. //===----------------------------------------------------------------------===// #include "llvm/CodeGen/GlobalISel/IRTranslator.h" #include "llvm/CodeGen/GlobalISel/MachineIRBuilder.h" #include "llvm/CodeGen/MachineFunction.h" #include "llvm/CodeGen/MachineRegisterInfo.h" #include "llvm/IR/Constant.h" #include "llvm/IR/Function.h" #include "llvm/IR/Type.h" #include "llvm/IR/Value.h" #define DEBUG_TYPE "irtranslator" using namespace llvm; char IRTranslator::ID = 0; const VRegsSequence &IRTranslator::getOrCreateVRegs(const Value *Val) { VRegsSequence &ValRegSequence = ValToVRegs[Val]; // Check if this is the first time we see Val. if (ValRegSequence.empty()) { // Fill ValRegsSequence with the sequence of registers // we need to concat together to produce the value. assert(Val->getType()->isSized() && "Don't know how to create an empty vreg"); assert(!Val->getType()->isAggregateType() && "Not yet implemented"); unsigned Size = Val->getType()->getPrimitiveSizeInBits(); unsigned VReg = MRI->createGenericVirtualRegister(Size); ValRegSequence.push_back(VReg); assert(!isa<Constant>(Val) && "Not yet implemented"); } assert(ValRegSequence.size() == 1 && "We support only one vreg per value at the moment"); return ValRegSequence; } MachineBasicBlock &IRTranslator::getOrCreateBB(const BasicBlock *BB) { MachineBasicBlock *&MBB = BBToMBB[BB]; if (!MBB) { MachineFunction &MF = MIRBuilder->getMF(); MBB = MF.CreateMachineBasicBlock(); MF.push_back(MBB); } return *MBB; } bool IRTranslator::translateADD(const Instruction &Inst) { // Get or create a virtual register for each value. // Unless the value is a Constant => loadimm cst? // or inline constant each time? // Creation of a virtual register needs to have a size. unsigned Op0 = *getOrCreateVRegs(Inst.getOperand(0)).begin(); unsigned Op1 = *getOrCreateVRegs(Inst.getOperand(1)).begin(); unsigned Res = *getOrCreateVRegs(&Inst).begin(); MIRBuilder->buildInstr(TargetOpcode::G_ADD, Res, Op0, Op1); return true; } bool IRTranslator::translate(const Instruction &Inst) { MIRBuilder->setDebugLoc(Inst.getDebugLoc()); switch(Inst.getOpcode()) { case Instruction::Add: { return translateADD(Inst); default: llvm_unreachable("Opcode not supported"); } } } void IRTranslator::finalize() { // Release the memory used by the different maps we // needed during the translation. ValToVRegs.clear(); Constants.clear(); } IRTranslator::IRTranslator() : MachineFunctionPass(ID) { } bool IRTranslator::runOnMachineFunction(MachineFunction &MF) { const Function &F = *MF.getFunction(); MIRBuilder->setFunction(MF); MRI = &MF.getRegInfo(); for (const BasicBlock &BB: F) { MachineBasicBlock &MBB = getOrCreateBB(&BB); MIRBuilder->setBasicBlock(MBB); for (const Instruction &Inst: BB) { bool Succeeded = translate(Inst); if (!Succeeded) { DEBUG(dbgs() << "Cannot translate: " << Inst << '\n'); report_fatal_error("Unable to translate instruction"); } } } return false; }
Fix a typo in assert.
[GlobalISel][IRTranslator] Fix a typo in assert. git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@260550 91177308-0d34-0410-b5e6-96231b3b80d8
C++
apache-2.0
llvm-mirror/llvm,llvm-mirror/llvm,apple/swift-llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,apple/swift-llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,llvm-mirror/llvm,llvm-mirror/llvm,apple/swift-llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,apple/swift-llvm,llvm-mirror/llvm
6bde2620d394f1ca515ae27f98f2141500e64802
cegui/src/Exceptions.cpp
cegui/src/Exceptions.cpp
/*********************************************************************** filename: CEGUIExceptions.cpp created: 20/2/2004 author: Paul D Turner, Frederico Jeronimo (fjeronimo) purpose: Implements the exception classes used within the system *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ #include "CEGUI/Exceptions.h" #include "CEGUI/Logger.h" #include "CEGUI/PropertyHelper.h" #include <iostream> #if defined( __WIN32__ ) || defined( _WIN32) #include <Windows.h> #include <DbgHelp.h> #elif defined(__linux__) || defined(__APPLE__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__HAIKU__) #include <execinfo.h> #include <dlfcn.h> #include <cxxabi.h> #include <cstdlib> #endif // Start of CEGUI namespace section namespace CEGUI { bool Exception::d_stdErrEnabled(true); //----------------------------------------------------------------------------// static void dumpBacktrace(size_t frames) { #if defined(_DEBUG) || defined(DEBUG) #if defined( __WIN32__ ) || defined( _WIN32) SymSetOptions(SYMOPT_DEFERRED_LOADS | SYMOPT_INCLUDE_32BIT_MODULES); if (!SymInitialize(GetCurrentProcess(), 0, TRUE)) return; HANDLE thread = GetCurrentThread(); CONTEXT context; RtlCaptureContext(&context); STACKFRAME64 stackframe; ZeroMemory(&stackframe, sizeof(stackframe)); stackframe.AddrPC.Mode = AddrModeFlat; stackframe.AddrStack.Mode = AddrModeFlat; stackframe.AddrFrame.Mode = AddrModeFlat; #if _M_IX86 stackframe.AddrPC.Offset = context.Eip; stackframe.AddrStack.Offset = context.Esp; stackframe.AddrFrame.Offset = context.Ebp; DWORD machine_arch = IMAGE_FILE_MACHINE_I386; #elif _M_X64 stackframe.AddrPC.Offset = context.Rip; stackframe.AddrStack.Offset = context.Rsp; stackframe.AddrFrame.Offset = context.Rbp; DWORD machine_arch = IMAGE_FILE_MACHINE_AMD64; #endif char symbol_buffer[1024]; ZeroMemory(symbol_buffer, sizeof(symbol_buffer)); PSYMBOL_INFO symbol = reinterpret_cast<PSYMBOL_INFO>(symbol_buffer); symbol->SizeOfStruct = sizeof(SYMBOL_INFO); symbol->MaxNameLen = sizeof(symbol_buffer) - sizeof(SYMBOL_INFO); Logger& logger(Logger::getSingleton()); logger.logEvent("========== Start of Backtrace ==========", Errors); size_t frame_no = 0; while (StackWalk64(machine_arch, GetCurrentProcess(), thread, &stackframe, &context, 0, SymFunctionTableAccess64, SymGetModuleBase64, 0) && stackframe.AddrPC.Offset) { symbol->Address = stackframe.AddrPC.Offset; DWORD64 displacement = 0; char signature[256]; if (SymFromAddr(GetCurrentProcess(), symbol->Address, &displacement, symbol)) UnDecorateSymbolName(symbol->Name, signature, sizeof(signature), UNDNAME_COMPLETE); else sprintf_s(signature, sizeof(signature), "%p", symbol->Address); IMAGEHLP_MODULE64 modinfo; modinfo.SizeOfStruct = sizeof(modinfo); const BOOL have_image_name = SymGetModuleInfo64(GetCurrentProcess(), symbol->Address, &modinfo); char outstr[512]; sprintf_s(outstr, sizeof(outstr), "#%d %s +%#llx (%s)", frame_no, signature, displacement, (have_image_name ? modinfo.LoadedImageName : "????")); logger.logEvent(outstr, Errors); if (++frame_no >= frames) break; if (!stackframe.AddrReturn.Offset) break; } logger.logEvent("========== End of Backtrace ==========", Errors); SymCleanup(GetCurrentProcess()); #elif defined(__linux__) || defined(__APPLE__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__HAIKU__) void* buffer[frames]; const int received = backtrace(&buffer[0], frames); Logger& logger(Logger::getSingleton()); logger.logEvent("========== Start of Backtrace ==========", Errors); for (int i = 0; i < received; ++i) { char outstr[512]; Dl_info info; if (dladdr(buffer[i], &info)) { if (!info.dli_sname) snprintf(outstr, 512, "#%d %p (%s)", i, buffer[i], info.dli_fname); else { ptrdiff_t offset = static_cast<char*>(buffer[i]) - static_cast<char*>(info.dli_saddr); int demangle_result = 0; char* demangle_name = abi::__cxa_demangle(info.dli_sname, 0, 0, &demangle_result); snprintf(outstr, 512, "#%d %s +%#tx (%s)", i, demangle_name ? demangle_name : info.dli_sname, offset, info.dli_fname); std::free(demangle_name); } } else snprintf(outstr, 512, "#%d --- error ---", i); logger.logEvent(outstr, Errors); } logger.logEvent("========== End of Backtrace ==========", Errors); #endif #endif } //----------------------------------------------------------------------------// Exception::Exception(const String& message, const String& name, const String& filename, int line, const String& function) : d_message(message), d_name(name), d_filename(filename), d_line(line), d_function(function), d_what(name + " in function '" + function + "' (" + filename + ":" + PropertyHelper<int>::toString(line) + ") : " + message) { // Log exception if possible if (Logger* const logger = Logger::getSingletonPtr()) { logger->logEvent(d_what, Errors); dumpBacktrace(64); } if (d_stdErrEnabled) { // output to stderr unless it's explicitly disabled // nobody seems to look in their log file! std::cerr << what() << std::endl; } } //----------------------------------------------------------------------------// Exception::~Exception(void) throw() { } //----------------------------------------------------------------------------// const char* Exception::what() const throw() { return d_what.c_str(); } //----------------------------------------------------------------------------// void Exception::setStdErrEnabled(bool enabled) { d_stdErrEnabled = enabled; } //----------------------------------------------------------------------------// bool Exception::isStdErrEnabled() { return d_stdErrEnabled; } //----------------------------------------------------------------------------// } // End of CEGUI namespace section
/*********************************************************************** filename: CEGUIExceptions.cpp created: 20/2/2004 author: Paul D Turner, Frederico Jeronimo (fjeronimo) purpose: Implements the exception classes used within the system *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ #include "CEGUI/Exceptions.h" #include "CEGUI/Logger.h" #include "CEGUI/PropertyHelper.h" #include <iostream> #if defined( __WIN32__ ) || defined( _WIN32) #include <Windows.h> #include <DbgHelp.h> #elif defined(__linux__) || defined(__APPLE__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__HAIKU__) #include <execinfo.h> #include <dlfcn.h> #include <cxxabi.h> #include <cstdlib> #endif // Start of CEGUI namespace section namespace CEGUI { bool Exception::d_stdErrEnabled(true); //----------------------------------------------------------------------------// static void dumpBacktrace(size_t frames) { #if defined(_DEBUG) || defined(DEBUG) #if defined( __WIN32__ ) || defined( _WIN32) SymSetOptions(SYMOPT_DEFERRED_LOADS | SYMOPT_INCLUDE_32BIT_MODULES); if (!SymInitialize(GetCurrentProcess(), 0, TRUE)) return; HANDLE thread = GetCurrentThread(); CONTEXT context; RtlCaptureContext(&context); STACKFRAME64 stackframe; ZeroMemory(&stackframe, sizeof(stackframe)); stackframe.AddrPC.Mode = AddrModeFlat; stackframe.AddrStack.Mode = AddrModeFlat; stackframe.AddrFrame.Mode = AddrModeFlat; #if _M_IX86 stackframe.AddrPC.Offset = context.Eip; stackframe.AddrStack.Offset = context.Esp; stackframe.AddrFrame.Offset = context.Ebp; DWORD machine_arch = IMAGE_FILE_MACHINE_I386; #elif _M_X64 stackframe.AddrPC.Offset = context.Rip; stackframe.AddrStack.Offset = context.Rsp; stackframe.AddrFrame.Offset = context.Rbp; DWORD machine_arch = IMAGE_FILE_MACHINE_AMD64; #endif char symbol_buffer[1024]; ZeroMemory(symbol_buffer, sizeof(symbol_buffer)); PSYMBOL_INFO symbol = reinterpret_cast<PSYMBOL_INFO>(symbol_buffer); symbol->SizeOfStruct = sizeof(SYMBOL_INFO); symbol->MaxNameLen = sizeof(symbol_buffer) - sizeof(SYMBOL_INFO); Logger& logger(Logger::getSingleton()); logger.logEvent("========== Start of Backtrace ==========", Errors); size_t frame_no = 0; while (StackWalk64(machine_arch, GetCurrentProcess(), thread, &stackframe, &context, 0, SymFunctionTableAccess64, SymGetModuleBase64, 0) && stackframe.AddrPC.Offset) { symbol->Address = stackframe.AddrPC.Offset; DWORD64 displacement = 0; char signature[256]; if (SymFromAddr(GetCurrentProcess(), symbol->Address, &displacement, symbol)) UnDecorateSymbolName(symbol->Name, signature, sizeof(signature), UNDNAME_COMPLETE); else sprintf_s(signature, sizeof(signature), "%p", symbol->Address); IMAGEHLP_MODULE64 modinfo; modinfo.SizeOfStruct = sizeof(modinfo); const BOOL have_image_name = SymGetModuleInfo64(GetCurrentProcess(), symbol->Address, &modinfo); char outstr[512]; sprintf_s(outstr, sizeof(outstr), "#%d %s +%#llx (%s)", frame_no, signature, displacement, (have_image_name ? modinfo.LoadedImageName : "????")); logger.logEvent(outstr, Errors); if (++frame_no >= frames) break; if (!stackframe.AddrReturn.Offset) break; } logger.logEvent("========== End of Backtrace ==========", Errors); SymCleanup(GetCurrentProcess()); #elif defined(__linux__) || defined(__APPLE__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__HAIKU__) void* buffer[frames]; const int received = backtrace(&buffer[0], frames); Logger& logger(Logger::getSingleton()); logger.logEvent("========== Start of Backtrace ==========", Errors); for (int i = 0; i < received; ++i) { char outstr[512]; Dl_info info; if (dladdr(buffer[i], &info)) { if (!info.dli_sname) snprintf(outstr, 512, "#%d %p (%s)", i, buffer[i], info.dli_fname); else { ptrdiff_t offset = static_cast<char*>(buffer[i]) - static_cast<char*>(info.dli_saddr); int demangle_result = 0; char* demangle_name = abi::__cxa_demangle(info.dli_sname, 0, 0, &demangle_result); snprintf(outstr, 512, "#%d %s +%#tx (%s)", i, demangle_name ? demangle_name : info.dli_sname, offset, info.dli_fname); std::free(demangle_name); } } else snprintf(outstr, 512, "#%d --- error ---", i); logger.logEvent(outstr, Errors); } logger.logEvent("========== End of Backtrace ==========", Errors); #endif #endif } //----------------------------------------------------------------------------// Exception::Exception(const String& message, const String& name, const String& filename, int line, const String& function) : d_message(message), d_name(name), d_filename(filename), d_line(line), d_function(function), d_what(name + " in function '" + function + "' (" + filename + ":" + PropertyHelper<int>::toString(line) + ") : " + message) { // Log exception if possible if (Logger* const logger = Logger::getSingletonPtr()) { logger->logEvent(d_what, Errors); dumpBacktrace(64); } if (d_stdErrEnabled) { // output to stderr unless it's explicitly disabled // nobody seems to look in their log file! std::cerr << what() << std::endl; } } //----------------------------------------------------------------------------// Exception::~Exception(void) throw() { } //----------------------------------------------------------------------------// const char* Exception::what() const throw() { return d_what.c_str(); } //----------------------------------------------------------------------------// void Exception::setStdErrEnabled(bool enabled) { d_stdErrEnabled = enabled; } //----------------------------------------------------------------------------// bool Exception::isStdErrEnabled() { return d_stdErrEnabled; } //----------------------------------------------------------------------------// } // End of CEGUI namespace section
Convert tabs to spaces in Exceptions.cpp committed by some noob.
Convert tabs to spaces in Exceptions.cpp committed by some noob.
C++
mit
ruleless/CEGUI,OpenTechEngine/CEGUI,ruleless/CEGUI,OpenTechEngine/CEGUI,OpenTechEngine/CEGUI,OpenTechEngine/CEGUI,ruleless/CEGUI,ruleless/CEGUI
400ac9a67dd532a9d8d894445f12697c0b42de18
dune/gdt/spaces/bochner.hh
dune/gdt/spaces/bochner.hh
// This file is part of the dune-gdt project: // https://github.com/dune-community/dune-gdt // Copyright 2010-2018 dune-gdt developers and contributors. All rights reserved. // License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) // or GPL-2.0+ (http://opensource.org/licenses/gpl-license) // with "runtime exception" (http://www.dune-project.org/license.html) // Authors: // Felix Schindler (2018) #ifndef DUNE_GDT_SPACES_BOCHNER_HH #define DUNE_GDT_SPACES_BOCHNER_HH #include <dune/grid/onedgrid.hh> #include <dune/gdt/spaces/h1/continuous-lagrange.hh> #include "interface.hh" namespace Dune { namespace GDT { template <class GV, size_t r = 1, size_t rC = 1, class R = double> class BochnerSpace { public: template <class... TemporalGridArgs> BochnerSpace(const SpaceInterface<GV, r, rC, R>& spatial_space, TemporalGridArgs&&... temporal_grid_args) : spatial_space_(spatial_space) , temporal_grid_(std::forward<TemporalGridArgs>(temporal_grid_args)...) , temporal_space_(temporal_grid_.leafGridView()) { } const ContinuousLagrangeSpace<typename OneDGrid::LeafGridView, 1>& temporal_space() const { return temporal_space_; } const SpaceInterface<GV, r, rC, R>& spatial_space() const { return spatial_space_; } private: const SpaceInterface<GV, r, rC, R>& spatial_space_; const OneDGrid temporal_grid_; const ContinuousLagrangeSpace<typename OneDGrid::LeafGridView, 1> temporal_space_; }; // class BochnerSpace } // namespace GDT } // namespace Dune #endif // DUNE_GDT_SPACES_BOCHNER_HH
// This file is part of the dune-gdt project: // https://github.com/dune-community/dune-gdt // Copyright 2010-2018 dune-gdt developers and contributors. All rights reserved. // License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) // or GPL-2.0+ (http://opensource.org/licenses/gpl-license) // with "runtime exception" (http://www.dune-project.org/license.html) // Authors: // Felix Schindler (2018) #ifndef DUNE_GDT_SPACES_BOCHNER_HH #define DUNE_GDT_SPACES_BOCHNER_HH #include <dune/grid/onedgrid.hh> #include <dune/gdt/spaces/h1/continuous-lagrange.hh> #include "interface.hh" namespace Dune { namespace GDT { template <class GV, size_t r = 1, size_t rC = 1, class R = double> class BochnerSpace { public: template <class... TemporalGridArgs> BochnerSpace(const SpaceInterface<GV, r, rC, R>& spatial_space, TemporalGridArgs&&... temporal_grid_args) : spatial_space_(spatial_space) , temporal_grid_(std::forward<TemporalGridArgs>(temporal_grid_args)...) , temporal_space_(temporal_grid_.leafGridView(), /*order=*/1) { } const ContinuousLagrangeSpace<typename OneDGrid::LeafGridView>& temporal_space() const { return temporal_space_; } const SpaceInterface<GV, r, rC, R>& spatial_space() const { return spatial_space_; } private: const SpaceInterface<GV, r, rC, R>& spatial_space_; const OneDGrid temporal_grid_; const ContinuousLagrangeSpace<typename OneDGrid::LeafGridView> temporal_space_; }; // class BochnerSpace } // namespace GDT } // namespace Dune #endif // DUNE_GDT_SPACES_BOCHNER_HH
update use of CG space
[spaces.bochner] update use of CG space
C++
bsd-2-clause
pymor/dune-gdt
c600ff59d656804a3fe53e4dbeb97e463c235e13
header/thread/CLock_queue.hpp
header/thread/CLock_queue.hpp
#ifndef CLOCK_QUEUE #define CLOCK_QUEUE #include<memory> #include<type_traits> #include<utility> #include"Lock_queue.hpp" namespace nThread { template<class T> class CLock_queue { public: using value_type=T; private: using underlying_type=Lock_queue<value_type>; using element_type=typename underlying_type::element_type; Lock_queue<value_type> queue_; public: class CNode { friend CLock_queue<value_type>; using element_type=typename Lock_queue<value_type>::element_type; std::shared_ptr<element_type> p_; public: CNode() :p_{std::make_shared<element_type>()}{} CNode(const CNode &)=delete; CNode(CNode &&)=default; CNode& operator=(const CNode &)=delete; }; CLock_queue()=default; CLock_queue(const CLock_queue &)=delete; template<class ... Args> inline void emplace(Args &&...args) { queue_.emplace(std::make_shared<element_type>(std::forward<decltype(args)>(args)...)); } template<class ... Args> void emplace(CNode &&val,Args &&...args) { val.p_->data.construct(std::forward<decltype(args)>(args)...); queue_.emplace(std::move(val.p_)); } //do not call CAtomic_stack::emplace, emplace_not_ts or CAtomic_stack::pop at same time template<class ... Args> inline void emplace_not_ts(Args &&...args) { queue_.emplace_not_ts(std::make_shared<element_type>(std::forward<decltype(args)>(args)...)); } inline bool empty() const noexcept { return queue_.empty(); } //if constructor or assignment operator you use here is not noexcept, it may not be exception safety inline value_type pop() { return std::move(queue_.pop()->data.get()); } //return true if it has an element; otherwise, return false bool pop_if_exist(value_type &val) noexcept(std::is_nothrow_move_assignable<value_type>::value) { using is_enable=std::enable_if_t<underlying_type::USE_POP_IF_EXIST>; std::shared_ptr<element_type> temp{queue_.pop_if_exist()}; if(temp) { val=std::move(temp->data.get()); return true; } return false; } CLock_queue& operator=(const CLock_queue &)=delete; }; } #endif
#ifndef CLOCK_QUEUE #define CLOCK_QUEUE #include<memory> #include<type_traits> #include<utility> #include"Lock_queue.hpp" namespace nThread { template<class T> class CLock_queue { public: using value_type=T; private: using underlying_type=Lock_queue<value_type>; using element_type=typename underlying_type::element_type; Lock_queue<value_type> queue_; public: class CNode { friend CLock_queue<value_type>; using element_type=typename Lock_queue<value_type>::element_type; std::shared_ptr<element_type> p_; public: CNode() :p_{std::make_shared<element_type>()}{} CNode(const CNode &)=delete; CNode(CNode &&)=default; CNode& operator=(const CNode &)=delete; }; CLock_queue()=default; CLock_queue(const CLock_queue &)=delete; template<class ... Args> inline void emplace(Args &&...args) { queue_.emplace(std::make_shared<element_type>(std::forward<decltype(args)>(args)...)); } template<class ... Args> void emplace(CNode &&val,Args &&...args) { val.p_->data.construct(std::forward<decltype(args)>(args)...); queue_.emplace(std::move(val.p_)); } //do not call CAtomic_stack::emplace, emplace_not_ts or CAtomic_stack::pop at same time template<class ... Args> inline void emplace_not_ts(Args &&...args) { queue_.emplace_not_ts(std::make_shared<element_type>(std::forward<decltype(args)>(args)...)); } inline bool empty() const noexcept { return queue_.empty(); } //if constructor or assignment operator you use here is not noexcept, it may not be exception safety inline value_type pop() { return std::move(queue_.pop()->data.get()); } //return true if it has an element; otherwise, return false bool pop_if_exist(value_type &val) { std::shared_ptr<element_type> temp{queue_.pop_if_exist()}; if(temp) { val=std::move(temp->data.get()); return true; } return false; } CLock_queue& operator=(const CLock_queue &)=delete; }; } #endif
fix compiler error
fix compiler error
C++
mit
Fdhvdu/lib
078b64cebfbcfabc2254102977f5002214fc4c83
src/Buffer.cpp
src/Buffer.cpp
// This file is part of the "x0" project, http://xzero.io/ // (c) 2009-2014 Christian Parpart <[email protected]> // // Licensed under the MIT License (the "License"); you may not use this // file except in compliance with the License. You may obtain a copy of // the License at: http://opensource.org/licenses/MIT // This file is part of the "x0" project, http://xzero.io/ // (c) 2009-2014 Christian Parpart <[email protected]> // // Licensed under the MIT License (the "License"); you may not use this // file except in compliance with the License. You may obtain a copy of // the License at: http://opensource.org/licenses/MIT #include <xzero/Buffer.h> #include <cstdio> namespace xzero { /*! changes the capacity of the underlying buffer, possibly reallocating into *more or less bytes reserved. * * This method either increases or decreases the reserved memory. * If it increases the size, and it is not the first capacity change, it will be *aligned * to \p CHUNK_SIZE bytes, otherwise the exact size will be reserved. * If the requested size is lower than the current capacity, then the underlying *storage * will be redused to exactly this size and the actually used buffer size is cut *down * to the available capacity if it would exceed the capacity otherwise. * Reduzing the capacity to zero implicitely means to free up all storage. * If the requested size is equal to the current one, nothing happens. * * \param value the length in bytes you want to change the underlying storage *to. * * \retval true the requested capacity is available. go ahead. * \retval false could not change capacity. take caution! */ bool Buffer::setCapacity(std::size_t value) { if (value == 0 && capacity_) { free(data_); capacity_ = 0; return true; } if (value > capacity_) { if (capacity_) { // pad up to CHUNK_SIZE, only if continuous regrowth) value = value - 1; value = value + CHUNK_SIZE - (value % CHUNK_SIZE); } } else if (value < capacity_) { // possibly adjust the actual used size if (value < size_) size_ = value; } else // nothing changed return true; if (char *rp = static_cast<value_type *>(std::realloc(data_, value))) { // setting capacity succeed. data_ = rp; capacity_ = value; return true; } else if (value == 0) { // freeing all Memory succeed. capacity_ = value; return true; } else { // setting capacity failed, do not change anything. return false; } } void BufferRef::dump(const void *bytes, std::size_t length, const char *description) { static char hex[] = "0123456789ABCDEF"; const int BLOCK_SIZE = 8; const int BLOCK_COUNT = 2; // 4; // 12 34 56 78 12 34 56 78 12 34 56 78 12 34 56 78 12345678abcdef const int HEX_WIDTH = (BLOCK_SIZE + 1) * 3 * BLOCK_COUNT; const int PLAIN_WIDTH = BLOCK_SIZE * BLOCK_COUNT; char line[HEX_WIDTH + PLAIN_WIDTH + 1]; const char *p = (const char *)bytes; if (description && *description) std::printf("%s (%zu bytes):\n", description, length); else std::printf("Memory dump (%zu bytes):\n", length); while (length > 0) { char *u = line; char *v = u + HEX_WIDTH; int blockNr = 0; for (; blockNr < BLOCK_COUNT && length > 0; ++blockNr) { // block int i = 0; for (; i < BLOCK_SIZE && length > 0; ++i) { // hex frame *u++ = hex[(*p >> 4) & 0x0F]; *u++ = hex[*p & 0x0F]; *u++ = ' '; // byte separator // plain text frame *v++ = std::isprint(*p) ? *p : '.'; ++p; --length; } for (; i < BLOCK_SIZE; ++i) { *u++ = ' '; *u++ = ' '; *u++ = ' '; } // block separator *u++ = ' '; *u++ = ' '; *u++ = ' '; } for (; blockNr < BLOCK_COUNT; ++blockNr) { for (int i = 0; i < BLOCK_SIZE; ++i) { *u++ = ' '; *u++ = ' '; *u++ = ' '; } *u++ = ' '; *u++ = ' '; *u++ = ' '; } // EOS *v = '\0'; std::printf("%s\n", line); } } } // namespace xzero
// This file is part of the "x0" project, http://xzero.io/ // (c) 2009-2014 Christian Parpart <[email protected]> // // Licensed under the MIT License (the "License"); you may not use this // file except in compliance with the License. You may obtain a copy of // the License at: http://opensource.org/licenses/MIT // This file is part of the "x0" project, http://xzero.io/ // (c) 2009-2014 Christian Parpart <[email protected]> // // Licensed under the MIT License (the "License"); you may not use this // file except in compliance with the License. You may obtain a copy of // the License at: http://opensource.org/licenses/MIT #include <xzero/Buffer.h> #include <new> #include <cstdio> namespace xzero { /*! changes the capacity of the underlying buffer, possibly reallocating into *more or less bytes reserved. * * This method either increases or decreases the reserved memory. * If it increases the size, and it is not the first capacity change, it will be *aligned * to \p CHUNK_SIZE bytes, otherwise the exact size will be reserved. * If the requested size is lower than the current capacity, then the underlying *storage * will be redused to exactly this size and the actually used buffer size is cut *down * to the available capacity if it would exceed the capacity otherwise. * Reduzing the capacity to zero implicitely means to free up all storage. * If the requested size is equal to the current one, nothing happens. * * \param value the length in bytes you want to change the underlying storage *to. * * \retval true the requested capacity is available. go ahead. * \retval false could not change capacity. take caution! */ bool Buffer::setCapacity(std::size_t value) { if (value == 0 && capacity_) { free(data_); capacity_ = 0; return true; } if (value > capacity_) { if (capacity_) { // pad up to CHUNK_SIZE, only if continuous regrowth) value = value - 1; value = value + CHUNK_SIZE - (value % CHUNK_SIZE); } } else if (value < capacity_) { // possibly adjust the actual used size if (value < size_) size_ = value; } else // nothing changed return true; if (char *rp = static_cast<value_type *>(std::realloc(data_, value))) { // setting capacity succeed. data_ = rp; capacity_ = value; return true; } else if (value == 0) { // freeing all Memory succeed. capacity_ = value; return true; } else { // setting capacity failed, do not change anything. throw std::bad_alloc(); //return false; } } void BufferRef::dump(const void *bytes, std::size_t length, const char *description) { static char hex[] = "0123456789ABCDEF"; const int BLOCK_SIZE = 8; const int BLOCK_COUNT = 2; // 4; // 12 34 56 78 12 34 56 78 12 34 56 78 12 34 56 78 12345678abcdef const int HEX_WIDTH = (BLOCK_SIZE + 1) * 3 * BLOCK_COUNT; const int PLAIN_WIDTH = BLOCK_SIZE * BLOCK_COUNT; char line[HEX_WIDTH + PLAIN_WIDTH + 1]; const char *p = (const char *)bytes; if (description && *description) std::printf("%s (%zu bytes):\n", description, length); else std::printf("Memory dump (%zu bytes):\n", length); while (length > 0) { char *u = line; char *v = u + HEX_WIDTH; int blockNr = 0; for (; blockNr < BLOCK_COUNT && length > 0; ++blockNr) { // block int i = 0; for (; i < BLOCK_SIZE && length > 0; ++i) { // hex frame *u++ = hex[(*p >> 4) & 0x0F]; *u++ = hex[*p & 0x0F]; *u++ = ' '; // byte separator // plain text frame *v++ = std::isprint(*p) ? *p : '.'; ++p; --length; } for (; i < BLOCK_SIZE; ++i) { *u++ = ' '; *u++ = ' '; *u++ = ' '; } // block separator *u++ = ' '; *u++ = ' '; *u++ = ' '; } for (; blockNr < BLOCK_COUNT; ++blockNr) { for (int i = 0; i < BLOCK_SIZE; ++i) { *u++ = ' '; *u++ = ' '; *u++ = ' '; } *u++ = ' '; *u++ = ' '; *u++ = ' '; } // EOS *v = '\0'; std::printf("%s\n", line); } } } // namespace xzero
throw bad_alloc() on mem alloc errors (setCapacity)
Buffer: throw bad_alloc() on mem alloc errors (setCapacity)
C++
agpl-3.0
eventql/eventql,eventql/eventql,eventql/eventql,eventql/eventql,eventql/eventql,eventql/eventql,eventql/eventql,eventql/eventql
74a540985df068c507cf6c66295b9b3d84b6731e
operator_presence/OpenGLOperatorOculusRiftRenderer.cpp
operator_presence/OpenGLOperatorOculusRiftRenderer.cpp
#include "stdafx.h" #include "OpenGLOperatorOculusRiftRenderer.h" namespace operator_view { namespace opengl { OperatorOculusRiftRenderer::OperatorOculusRiftRenderer(std::shared_ptr<IOperatorRenderer> operatorRendererToDecorate) : IOperatorOculusRiftRenderer(operatorRendererToDecorate) { } void OperatorOculusRiftRenderer::initialize(std::uint16_t eyeResolutionWidth, std::uint16_t eyeResolutionHeight) { Q_UNUSED(eyeResolutionWidth); Q_UNUSED(eyeResolutionHeight); } void OperatorOculusRiftRenderer::renderLeftEye() { } void OperatorOculusRiftRenderer::renderRightEye() { } } }
#include "stdafx.h" #include "OpenGLOperatorOculusRiftRenderer.h" namespace operator_view { namespace opengl { OperatorOculusRiftRenderer::OperatorOculusRiftRenderer(std::shared_ptr<IOperatorRenderer> operatorRendererToDecorate) : IOperatorOculusRiftRenderer(operatorRendererToDecorate) { } void OperatorOculusRiftRenderer::initialize(std::uint16_t eyeResolutionWidth, std::uint16_t eyeResolutionHeight) { // The HMD will override these values. // Therefore, they are not used here. // Q_UNUSED(eyeResolutionWidth); Q_UNUSED(eyeResolutionHeight); } void OperatorOculusRiftRenderer::renderLeftEye() { } void OperatorOculusRiftRenderer::renderRightEye() { } } }
Add a comment about eye resolution parameters in case of operator HMD renderer
Add a comment about eye resolution parameters in case of operator HMD renderer
C++
mit
aesir84/operator_presence
16b6c3829f0923ff754a50bd6a6dc86520077026
src/Camera.cpp
src/Camera.cpp
// // Camera.cpp // Cinder-EDSDK // // Created by Jean-Pierre Mouilleseaux on 08 Dec 2013. // Copyright 2013 Chorded Constructions. All rights reserved. // #include "Camera.h" using namespace ci; using namespace ci::app; namespace Cinder { namespace EDSDK { CameraRef Camera::create(EdsCameraRef camera) { return CameraRef(new Camera(camera))->shared_from_this(); } Camera::Camera(EdsCameraRef camera) { if (camera == NULL) { throw Exception(); } EdsRetain(camera); mCamera = camera; EdsError error = EdsGetDeviceInfo(mCamera, &mDeviceInfo); if (error != EDS_ERR_OK) { console() << "ERROR - failed to get device info" << std::endl; // TODO - NULL out mDeviceInfo } mHasOpenSession = false; // set event handlers error = EdsSetObjectEventHandler(mCamera, kEdsObjectEvent_All, Camera::handleObjectEvent, this); if (error != EDS_ERR_OK) { console() << "ERROR - failed to set object event handler" << std::endl; } error = EdsSetPropertyEventHandler(mCamera, kEdsPropertyEvent_All, Camera::handlePropertyEvent, this); if (error != EDS_ERR_OK) { console() << "ERROR - failed to set property event handler" << std::endl; } error = EdsSetCameraStateEventHandler(mCamera, kEdsStateEvent_All, Camera::handleStateEvent, this); if (error != EDS_ERR_OK) { console() << "ERROR - failed to set object event handler" << std::endl; } } Camera::~Camera() { mHandler = NULL; if (mHasOpenSession) { requestCloseSession(); } EdsRelease(mCamera); mCamera = NULL; } #pragma mark - CameraHandler* Camera::getHandler() const { return mHandler; } void Camera::setHandler(CameraHandler* handler) { mHandler = handler; } std::string Camera::getName() const { return std::string(mDeviceInfo.szDeviceDescription); } std::string Camera::getPortName() const { return std::string(mDeviceInfo.szPortName); } bool Camera::hasOpenSession() const { return mHasOpenSession; } EdsError Camera::requestOpenSession(SessionSettings* settings) { if (mHasOpenSession) { return EDS_ERR_SESSION_ALREADY_OPEN; } EdsError error = EdsOpenSession(mCamera); if (error != EDS_ERR_OK) { console() << "ERROR - failed to open camera session" << std::endl; return error; } mHasOpenSession = true; EdsUInt32 saveTo = (settings != NULL) ? settings->getPictureSaveLocation() : kEdsSaveTo_Host; error = EdsSetPropertyData(mCamera, kEdsPropID_SaveTo, 0, sizeof(saveTo) , &saveTo); if (error != EDS_ERR_OK) { console() << "ERROR - failed to set save destination host/device" << std::endl; return error; } if (saveTo == kEdsSaveTo_Host || saveTo == kEdsSaveTo_Camera) { // TODO - EdsSetCapacity } mShouldKeepAlive = (settings != NULL) ? settings->getShouldKeepAlive() : mShouldKeepAlive; return EDS_ERR_OK; } EdsError Camera::requestCloseSession() { if (!mHasOpenSession) { return EDS_ERR_SESSION_NOT_OPEN; } EdsError error = EdsCloseSession(mCamera); if (error != EDS_ERR_OK) { console() << "ERROR - failed to close camera session" << std::endl; return error; } mHasOpenSession = false; return EDS_ERR_OK; } EdsError Camera::requestTakePicture(/*Options* options*/) { return EDS_ERR_UNIMPLEMENTED; } EdsError Camera::requestDownloadFile() { return EDS_ERR_UNIMPLEMENTED; } EdsError Camera::requestReadFile() { return EDS_ERR_UNIMPLEMENTED; } #pragma mark - CALLBACKS EdsError EDSCALLBACK Camera::handleObjectEvent(EdsUInt32 inEvent, EdsBaseRef inRef, EdsVoid* inContext) { return EDS_ERR_OK; } EdsError EDSCALLBACK Camera::handlePropertyEvent(EdsUInt32 inEvent, EdsUInt32 inPropertyID, EdsUInt32 inParam, EdsVoid* inContext) { return EDS_ERR_OK; } EdsError EDSCALLBACK Camera::handleStateEvent(EdsUInt32 inEvent, EdsUInt32 inParam, EdsVoid* inContext) { Camera* camera = (Camera*)inContext; switch (inEvent) { case kEdsStateEvent_WillSoonShutDown: if (camera->mHasOpenSession && camera->mShouldKeepAlive) { EdsError error = EdsSendCommand(camera->mCamera, kEdsCameraCommand_ExtendShutDownTimer, 0); if (error != EDS_ERR_OK) { console() << "ERROR - failed to extend shut down timer" << std::endl; } } break; case kEdsStateEvent_Shutdown: camera->mHasOpenSession = false; camera->mHandler->didRemoveCamera(camera); // TODO - how do we get this to the CameraBrowser, singleton? break; default: break; } return EDS_ERR_OK; } }}
// // Camera.cpp // Cinder-EDSDK // // Created by Jean-Pierre Mouilleseaux on 08 Dec 2013. // Copyright 2013 Chorded Constructions. All rights reserved. // #include "Camera.h" using namespace ci; using namespace ci::app; namespace Cinder { namespace EDSDK { CameraRef Camera::create(EdsCameraRef camera) { return CameraRef(new Camera(camera))->shared_from_this(); } Camera::Camera(EdsCameraRef camera) { if (camera == NULL) { throw Exception(); } EdsRetain(camera); mCamera = camera; EdsError error = EdsGetDeviceInfo(mCamera, &mDeviceInfo); if (error != EDS_ERR_OK) { console() << "ERROR - failed to get device info" << std::endl; // TODO - NULL out mDeviceInfo } mHasOpenSession = false; // set event handlers error = EdsSetObjectEventHandler(mCamera, kEdsObjectEvent_All, Camera::handleObjectEvent, this); if (error != EDS_ERR_OK) { console() << "ERROR - failed to set object event handler" << std::endl; } error = EdsSetPropertyEventHandler(mCamera, kEdsPropertyEvent_All, Camera::handlePropertyEvent, this); if (error != EDS_ERR_OK) { console() << "ERROR - failed to set property event handler" << std::endl; } error = EdsSetCameraStateEventHandler(mCamera, kEdsStateEvent_All, Camera::handleStateEvent, this); if (error != EDS_ERR_OK) { console() << "ERROR - failed to set object event handler" << std::endl; } } Camera::~Camera() { mHandler = NULL; if (mHasOpenSession) { requestCloseSession(); } EdsRelease(mCamera); mCamera = NULL; } #pragma mark - CameraHandler* Camera::getHandler() const { return mHandler; } void Camera::setHandler(CameraHandler* handler) { mHandler = handler; } std::string Camera::getName() const { return std::string(mDeviceInfo.szDeviceDescription); } std::string Camera::getPortName() const { return std::string(mDeviceInfo.szPortName); } bool Camera::hasOpenSession() const { return mHasOpenSession; } EdsError Camera::requestOpenSession(SessionSettings* settings) { if (mHasOpenSession) { return EDS_ERR_SESSION_ALREADY_OPEN; } EdsError error = EdsOpenSession(mCamera); if (error != EDS_ERR_OK) { console() << "ERROR - failed to open camera session" << std::endl; return error; } mHasOpenSession = true; mShouldKeepAlive = (settings != NULL) ? settings->getShouldKeepAlive() : mShouldKeepAlive; EdsUInt32 saveTo = (settings != NULL) ? settings->getPictureSaveLocation() : kEdsSaveTo_Host; error = EdsSetPropertyData(mCamera, kEdsPropID_SaveTo, 0, sizeof(saveTo) , &saveTo); if (error != EDS_ERR_OK) { console() << "ERROR - failed to set save destination host/device" << std::endl; return error; } if (saveTo == kEdsSaveTo_Host) { // ??? - requires UI lock? EdsCapacity capacity = {0x7FFFFFFF, 0x1000, 1}; error = EdsSetCapacity(mCamera, capacity); if (error != EDS_ERR_OK) { console() << "ERROR - failed to set capacity of host" << std::endl; return error; } } return EDS_ERR_OK; } EdsError Camera::requestCloseSession() { if (!mHasOpenSession) { return EDS_ERR_SESSION_NOT_OPEN; } EdsError error = EdsCloseSession(mCamera); if (error != EDS_ERR_OK) { console() << "ERROR - failed to close camera session" << std::endl; return error; } mHasOpenSession = false; return EDS_ERR_OK; } EdsError Camera::requestTakePicture(/*Options* options*/) { return EDS_ERR_UNIMPLEMENTED; } EdsError Camera::requestDownloadFile() { return EDS_ERR_UNIMPLEMENTED; } EdsError Camera::requestReadFile() { return EDS_ERR_UNIMPLEMENTED; } #pragma mark - CALLBACKS EdsError EDSCALLBACK Camera::handleObjectEvent(EdsUInt32 inEvent, EdsBaseRef inRef, EdsVoid* inContext) { return EDS_ERR_OK; } EdsError EDSCALLBACK Camera::handlePropertyEvent(EdsUInt32 inEvent, EdsUInt32 inPropertyID, EdsUInt32 inParam, EdsVoid* inContext) { return EDS_ERR_OK; } EdsError EDSCALLBACK Camera::handleStateEvent(EdsUInt32 inEvent, EdsUInt32 inParam, EdsVoid* inContext) { Camera* camera = (Camera*)inContext; switch (inEvent) { case kEdsStateEvent_WillSoonShutDown: if (camera->mHasOpenSession && camera->mShouldKeepAlive) { EdsError error = EdsSendCommand(camera->mCamera, kEdsCameraCommand_ExtendShutDownTimer, 0); if (error != EDS_ERR_OK) { console() << "ERROR - failed to extend shut down timer" << std::endl; } } break; case kEdsStateEvent_Shutdown: camera->mHasOpenSession = false; camera->mHandler->didRemoveCamera(camera); // TODO - how do we get this to the CameraBrowser, singleton? break; default: break; } return EDS_ERR_OK; } }}
set host capacity when appropriate
set host capacity when appropriate
C++
mit
pizthewiz/Cinder-EDSDK,pizthewiz/Cinder-EDSDK
cec1f6d8a23f715d29b67e3c5f9b633dc6afe94d
src/Client.cpp
src/Client.cpp
#include "Client.hpp" #include "tcp/IPC.hpp" #include <onions-common/Common.hpp> #include <onions-common/Log.hpp> #include <onions-common/Config.hpp> #include <onions-common/Constants.hpp> #include <onions-common/Utils.hpp> void Client::listenForDomains(short socksPort) { auto addr = Config::getMirror()[0]; socks_ = SocksClient::getCircuitTo(addr["ip"].asString(), static_cast<short>(addr["port"].asInt()), socksPort); if (!socks_) Log::get().error("Unable to connect!"); IPC ipc(Const::IPC_PORT); ipc.start(); } std::string Client::resolve(const std::string& torDomain) { try { std::string domain = torDomain; while (Utils::strEndsWith(domain, ".tor")) { // check cache first auto iterator = cache_.find(domain); if (iterator == cache_.end()) { Log::get().notice("Sending \"" + domain + "\" to name server..."); auto received = socks_->sendReceive("domainQuery", domain); if (received["type"] == "error") { Log::get().warn("Server response: " + received["value"].asString()); return received["value"].asString(); } Log::get().notice("Received Record response."); auto dest = Common::getDestination( Common::parseRecord(received["value"].asString()), domain); cache_[domain] = dest; domain = dest; } else domain = iterator->second; // retrieve from cache } if (domain.length() != 22 || !Utils::strEndsWith(domain, ".onion")) { Log::get().warn("\"" + domain + "\" is not a HS address!"); return "<Invalid_Result>"; } return domain; } catch (std::runtime_error& re) { Log::get().error(re.what()); } return "<General_Error>"; }
#include "Client.hpp" #include "tcp/IPC.hpp" #include <onions-common/Common.hpp> #include <onions-common/Log.hpp> #include <onions-common/Config.hpp> #include <onions-common/Constants.hpp> #include <onions-common/Utils.hpp> void Client::listenForDomains(short socksPort) { auto addr = Config::getMirror()[0]; socks_ = SocksClient::getCircuitTo(addr["ip"].asString(), static_cast<short>(addr["port"].asInt()), socksPort); if (!socks_) Log::get().error("Unable to connect!"); IPC ipc(Const::IPC_PORT); ipc.start(); } std::string Client::resolve(const std::string& torDomain) { try { std::string domain = torDomain; while (Utils::strEndsWith(domain, ".tor")) { // check cache first auto iterator = cache_.find(domain); if (iterator == cache_.end()) { Log::get().notice("Sending \"" + domain + "\" to name server..."); auto received = socks_->sendReceive("domainQuery", domain); if (received["type"] == "error") { Log::get().warn("Server response: " + received["value"].asString()); return "<404>"; } Log::get().notice("Received Record response."); auto dest = Common::getDestination( Common::parseRecord(received["value"].asString()), domain); cache_[domain] = dest; domain = dest; } else domain = iterator->second; // retrieve from cache } if (domain.length() != 22 || !Utils::strEndsWith(domain, ".onion")) { Log::get().warn("\"" + domain + "\" is not a HS address!"); return "<Invalid_Result>"; } return domain; } catch (std::runtime_error& re) { Log::get().error(re.what()); } return "<General_Error>"; }
Fix #18
Fix #18
C++
bsd-3-clause
Jesse-V/OnioNS-client,Jesse-V/OnioNS-client,Jesse-V/OnioNS-client
11532f58c90c0d9a3b338dd86946e41e356b8906
core/dawn_player/amf_decode.hpp
core/dawn_player/amf_decode.hpp
/* * amf_decode.hpp: * * Copyright (C) 2015 limhiaoing <blog.poxiao.me> All Rights Reserved. * */ #ifndef DAWN_PLAYER_AMF_DECODE_HPP #define DAWN_PLAYER_AMF_DECODE_HPP #include <cassert> #include <cstdint> #include <exception> #include <utility> #include "amf_types.hpp" namespace dawn_player { namespace amf { class decode_amf_error : public std::exception { const char* _msg; public: explicit decode_amf_error(const char* msg) : _msg(msg) {} const char* what() const throw() { return this->_msg; } ~decode_amf_error() throw() { } }; template <typename RandomeAccessIterator> std::shared_ptr<amf_base> decode_amf(RandomeAccessIterator begin, RandomeAccessIterator end) { return std::get<0>(decode_amf_and_return_iterator(begin, end)); } template <typename RandomeAccessIterator> std::pair<std::shared_ptr<amf_base>, RandomeAccessIterator> decode_amf_and_return_iterator(RandomeAccessIterator begin, RandomeAccessIterator end) { assert(begin <= end); if(begin == end){ throw decode_amf_error("Failed to decode."); } auto value_type_marker = static_cast<std::uint8_t>(*begin); RandomeAccessIterator next_iter; if (value_type_marker == 0x00) { // amf_number auto value_ptr = std::make_shared<amf_number>(0.00); std::tie(*value_ptr, next_iter) = decode_amf_number_and_return_iterator(begin, end); return std::make_pair(value_ptr, next_iter); } else if (value_type_marker == 0x01) { // amf_boolean auto value_ptr = std::make_shared<amf_boolean>(false); std::tie(*value_ptr, next_iter) = decode_amf_boolean_and_return_iterator(begin, end); return std::make_pair(value_ptr, next_iter); } else if (value_type_marker == 0x02) { // amf_string auto value_ptr = std::make_shared<amf_string>(); std::tie(*value_ptr, next_iter) = decode_amf_string_and_return_iterator(begin, end); return std::make_pair(value_ptr, next_iter); } else if (value_type_marker == 0x03) { // amf_object auto value_ptr = std::make_shared<amf_object>(); std::tie(*value_ptr, next_iter) = decode_amf_object_and_return_iterator(begin, end); return std::make_pair(value_ptr, next_iter); } else if (value_type_marker == 0x08) { // amf_ecma_array auto value_ptr = std::make_shared<amf_ecma_array>(); std::tie(*value_ptr, next_iter) = decode_amf_ecma_array_and_return_iterator(begin, end); return std::make_pair(value_ptr, next_iter); } else if (value_type_marker == 0x09) { // amf_object_end auto value_ptr = std::make_shared<amf_object_end>(); std::tie(*value_ptr, next_iter) = decode_amf_object_end_and_return_iterator(begin, end); return std::make_pair(value_ptr, next_iter); } else if (value_type_marker == 0x0a) { // amf_strict_array auto value_ptr = std::make_shared<amf_strict_array>(); std::tie(*value_ptr, next_iter) = decode_amf_strict_array_and_return_iterator(begin, end); return std::make_pair(value_ptr, next_iter); } else if (value_type_marker == 0x0b) { // amf_date auto value_ptr = std::make_shared<amf_date>(0.00); std::tie(*value_ptr, next_iter) = decode_amf_date_and_return_iterator(begin, end); return std::make_pair(value_ptr, next_iter); } else { throw decode_amf_error("Failed to decode, meet unsupported value type."); } } template <typename RandomAccessIterator> std::pair<amf_number, RandomAccessIterator> decode_amf_number_and_return_iterator(RandomAccessIterator begin, RandomAccessIterator end) { assert(begin <= end); if (std::distance(begin, end) < 9) { throw decode_amf_error("Failed to decode."); } auto iter = begin; if (*iter++ != 0x00) { throw decode_amf_error("Failed to decode."); } // IEEE-754 union { unsigned char from[8]; double to; } cvt; static_assert(sizeof(cvt.from) == sizeof(cvt.to), "error"); cvt.from[7] = *iter++; cvt.from[6] = *iter++; cvt.from[5] = *iter++; cvt.from[4] = *iter++; cvt.from[3] = *iter++; cvt.from[2] = *iter++; cvt.from[1] = *iter++; cvt.from[0] = *iter++; return std::make_pair(amf_number(cvt.to), iter); } template <typename RandomAccessIterator> amf_number decode_amf_number(RandomAccessIterator begin, RandomAccessIterator end) { return std::get<0>(decode_amf_number_and_return_iterator(begin, end)); } template <typename RandomAccessIterator> std::pair<amf_boolean, RandomAccessIterator> decode_amf_boolean_and_return_iterator(RandomAccessIterator begin, RandomAccessIterator end) { assert(begin <= end); if (std::distance(begin, end) < 2) { throw decode_amf_error("Failed to decode."); } auto iter = begin; if (*iter++ != 0x01) { throw decode_amf_error("Failed to decode."); } if (*iter++ == 0) { return std::make_pair(amf_boolean(false), iter); } else { return std::make_pair(amf_boolean(true), iter); } } template <typename RandomAccessIterator> amf_boolean decode_amf_boolean(RandomAccessIterator begin, RandomAccessIterator end) { return std::get<0>(decode_amf_boolean_and_return_iterator(begin, end)); } template <typename RandomAccessIterator> std::pair<amf_string, RandomAccessIterator> decode_amf_string_and_return_iterator(RandomAccessIterator begin, RandomAccessIterator end) { assert(begin <= end); if (std::distance(begin, end) < 3) { throw decode_amf_error("Failed to decode."); } auto iter = begin; if (*iter++ != 0x02) { throw decode_amf_error("Failed to decode."); } return impl::decode_amf_string_without_marker_and_return_iterator(iter, end); } template <typename RandomAccessIterator> amf_string decode_amf_string(RandomAccessIterator begin, RandomAccessIterator end) { return std::get<0>(decode_amf_string_and_return_iterator(begin, end)); } template <typename RandomAccessIterator> std::pair<amf_object, RandomAccessIterator> decode_amf_object_and_return_iterator(RandomAccessIterator begin, RandomAccessIterator end) { assert(begin <= end); if (begin == end) { throw decode_amf_error("Failed to decode."); } auto iter = begin; if (*iter++ != 0x03) { throw decode_amf_error("Failed to decode."); } amf_object obj; for (;;) { amf_string property_name; std::tie(property_name, iter) = impl::decode_amf_string_without_marker_and_return_iterator(iter, end); std::shared_ptr<amf_base> value_ptr; std::tie(value_ptr, iter) = decode_amf_and_return_iterator(iter, end); if (property_name.empty() || value_ptr->get_type() == amf_type::object_end) { break; } obj.push_back(std::make_pair(std::move(property_name), value_ptr)); }; return std::make_pair(obj, iter); } template <typename RandomAccessIterator> std::pair<amf_object, RandomAccessIterator> decode_amf_object(RandomAccessIterator begin, RandomAccessIterator end) { return std::get<0>(decode_amf_object_and_return_iterator(begin, end)); } template <typename RandomAccessIterator> std::pair<amf_ecma_array, RandomAccessIterator> decode_amf_ecma_array_and_return_iterator(RandomAccessIterator begin, RandomAccessIterator end) { assert(begin <= end); if (std::distance(begin, end) < 5) { throw decode_amf_error("Failed to decode."); } auto iter = begin; if (*iter++ != 0x08) { throw decode_amf_error("Failed to decode."); } union { char from[4]; std::uint32_t to; } cvt; static_assert(sizeof(cvt.from) == sizeof(cvt.to), "error"); cvt.from[3] = *iter++; cvt.from[2] = *iter++; cvt.from[1] = *iter++; cvt.from[0] = *iter++; amf_ecma_array ecma_array; auto cnt = cvt.to; for (auto i = 0u; i < cnt; ++i) { amf_string key; std::tie(key, iter) = impl::decode_amf_string_without_marker_and_return_iterator(iter, end); std::shared_ptr<amf_base> value_ptr; std::tie(value_ptr, iter) = decode_amf_and_return_iterator(iter, end); ecma_array.push_back(std::make_pair(std::move(key), value_ptr)); } return std::make_pair(std::move(ecma_array), iter); } template <typename RandomAccessIterator> amf_ecma_array decode_amf_ecma_array(RandomAccessIterator begin, RandomAccessIterator end) { return std::get<0>(decode_amf_ecma_array_and_return_iterator(begin, end)); } template <typename RandomAccessIterator> std::pair<amf_object_end, RandomAccessIterator> decode_amf_object_end_and_return_iterator(RandomAccessIterator begin, RandomAccessIterator end) { assert(begin <= end); if (begin == end) { throw decode_amf_error("Failed to decode."); } auto iter = begin; if (*iter++ != 0x09) { throw decode_amf_error("Failed to decode."); } return std::make_pair(amf_object_end(), iter); } template <typename RandomAccessIterator> amf_object_end decode_amf_object_end(RandomAccessIterator begin, RandomAccessIterator end) { return std::get<0>(decode_amf_object_end_and_return_iterator(begin, end)); } template <typename RandomAccessIterator> std::pair<amf_strict_array, RandomAccessIterator> decode_amf_strict_array_and_return_iterator(RandomAccessIterator begin, RandomAccessIterator end) { assert(begin <= end); if (std::distance(begin, end) < 5) { throw decode_amf_error("Failed to decode."); } auto iter = begin; if (*iter++ != 0x0a) { throw decode_amf_error("Failed to decode."); } union { char from[4]; std::uint32_t to; } cvt; static_assert(sizeof(cvt.from) == sizeof(cvt.to), "error"); cvt.from[3] = *iter++; cvt.from[2] = *iter++; cvt.from[1] = *iter++; cvt.from[0] = *iter++; auto cnt = cvt.to; amf_strict_array strict_array; for (auto i = 0u; i < cnt; ++i) { std::shared_ptr<amf_base> value_ptr; std::tie(value_ptr, iter) = decode_amf_and_return_iterator(iter, end); strict_array.push_back(value_ptr); } return std::make_pair(strict_array, iter); } template <typename RandomAccessIterator> amf_strict_array decode_amf_strict_array(RandomAccessIterator begin, RandomAccessIterator end) { return std::get<0>(decode_amf_strict_array_and_return_iterator(begin, end)); } template <typename RandomAccessIterator> std::pair<amf_date, RandomAccessIterator> decode_amf_date_and_return_iterator(RandomAccessIterator begin, RandomAccessIterator end) { assert(begin <= end); if (std::distance(begin, end) < 11) { throw decode_amf_error("Failed to decode."); } auto iter = begin; if (*iter++ != 0x0b) { throw decode_amf_error("Failed to decode."); } // IEEE-754 union { unsigned char from[8]; double to; } cvt; static_assert(sizeof(cvt.from) == sizeof(cvt.to), "error"); cvt.from[7] = *iter++; cvt.from[6] = *iter++; cvt.from[5] = *iter++; cvt.from[4] = *iter++; cvt.from[3] = *iter++; cvt.from[2] = *iter++; cvt.from[1] = *iter++; cvt.from[0] = *iter++; return std::make_pair(amf_date(cvt.to), iter); } template <typename RandomAccessIterator> amf_date decode_amf_date(RandomAccessIterator begin, RandomAccessIterator end) { return std::get<0>(decode_amf_date_and_return_iterator(begin, end)); } namespace impl { template <typename RandomAccessIterator> std::pair<amf_string, RandomAccessIterator> decode_amf_string_without_marker_and_return_iterator(RandomAccessIterator begin, RandomAccessIterator end) { assert(std::distance(begin, end) >= 2); auto iter = begin; union { char from[2]; std::uint16_t to; } cvt; static_assert(sizeof(cvt.from) == sizeof(cvt.to), "error"); std::uint16_t length = 0; cvt.from[1] = *iter++; cvt.from[0] = *iter++; length = cvt.to; if (length == 0) { return std::make_pair(amf_string(std::string()), iter); } else if (std::distance(iter, end) >= length) { std::string tmp; std::copy(iter, iter + length, std::back_inserter(tmp)); iter += length; return std::make_pair(amf_string(tmp), iter); } else { throw decode_amf_error("Failed to decode."); } } } // namespace impl } // namespace amf } // namespace dawn_player #endif
/* * amf_decode.hpp: * * Copyright (C) 2015 limhiaoing <blog.poxiao.me> All Rights Reserved. * */ #ifndef DAWN_PLAYER_AMF_DECODE_HPP #define DAWN_PLAYER_AMF_DECODE_HPP #include <cassert> #include <cstdint> #include <exception> #include <utility> #include "amf_types.hpp" namespace dawn_player { namespace amf { class decode_amf_error : public std::exception { const char* _msg; public: explicit decode_amf_error(const char* msg) : _msg(msg) {} const char* what() const throw() { return this->_msg; } ~decode_amf_error() throw() { } }; template <typename RandomeAccessIterator> std::shared_ptr<amf_base> decode_amf(RandomeAccessIterator begin, RandomeAccessIterator end) { return std::get<0>(decode_amf_and_return_iterator(begin, end)); } template <typename RandomeAccessIterator> std::pair<std::shared_ptr<amf_base>, RandomeAccessIterator> decode_amf_and_return_iterator(RandomeAccessIterator begin, RandomeAccessIterator end) { assert(begin <= end); if(begin == end){ throw decode_amf_error("Failed to decode."); } auto value_type_marker = static_cast<std::uint8_t>(*begin); RandomeAccessIterator next_iter; if (value_type_marker == 0x00) { // amf_number auto value_ptr = std::make_shared<amf_number>(0.00); std::tie(*value_ptr, next_iter) = decode_amf_number_and_return_iterator(begin, end); return std::make_pair(value_ptr, next_iter); } else if (value_type_marker == 0x01) { // amf_boolean auto value_ptr = std::make_shared<amf_boolean>(false); std::tie(*value_ptr, next_iter) = decode_amf_boolean_and_return_iterator(begin, end); return std::make_pair(value_ptr, next_iter); } else if (value_type_marker == 0x02) { // amf_string auto value_ptr = std::make_shared<amf_string>(); std::tie(*value_ptr, next_iter) = decode_amf_string_and_return_iterator(begin, end); return std::make_pair(value_ptr, next_iter); } else if (value_type_marker == 0x03) { // amf_object auto value_ptr = std::make_shared<amf_object>(); std::tie(*value_ptr, next_iter) = decode_amf_object_and_return_iterator(begin, end); return std::make_pair(value_ptr, next_iter); } else if (value_type_marker == 0x08) { // amf_ecma_array auto value_ptr = std::make_shared<amf_ecma_array>(); std::tie(*value_ptr, next_iter) = decode_amf_ecma_array_and_return_iterator(begin, end); return std::make_pair(value_ptr, next_iter); } else if (value_type_marker == 0x09) { // amf_object_end auto value_ptr = std::make_shared<amf_object_end>(); std::tie(*value_ptr, next_iter) = decode_amf_object_end_and_return_iterator(begin, end); return std::make_pair(value_ptr, next_iter); } else if (value_type_marker == 0x0a) { // amf_strict_array auto value_ptr = std::make_shared<amf_strict_array>(); std::tie(*value_ptr, next_iter) = decode_amf_strict_array_and_return_iterator(begin, end); return std::make_pair(value_ptr, next_iter); } else if (value_type_marker == 0x0b) { // amf_date auto value_ptr = std::make_shared<amf_date>(0.00); std::tie(*value_ptr, next_iter) = decode_amf_date_and_return_iterator(begin, end); return std::make_pair(value_ptr, next_iter); } else { throw decode_amf_error("Failed to decode, meet unsupported value type."); } } template <typename RandomAccessIterator> std::pair<amf_number, RandomAccessIterator> decode_amf_number_and_return_iterator(RandomAccessIterator begin, RandomAccessIterator end) { assert(begin <= end); if (std::distance(begin, end) < 9) { throw decode_amf_error("Failed to decode."); } auto iter = begin; if (*iter++ != 0x00) { throw decode_amf_error("Failed to decode."); } // IEEE-754 union { unsigned char from[8]; double to; } cvt; static_assert(sizeof(cvt.from) == sizeof(cvt.to), "error"); cvt.from[7] = *iter++; cvt.from[6] = *iter++; cvt.from[5] = *iter++; cvt.from[4] = *iter++; cvt.from[3] = *iter++; cvt.from[2] = *iter++; cvt.from[1] = *iter++; cvt.from[0] = *iter++; return std::make_pair(amf_number(cvt.to), iter); } template <typename RandomAccessIterator> amf_number decode_amf_number(RandomAccessIterator begin, RandomAccessIterator end) { return std::get<0>(decode_amf_number_and_return_iterator(begin, end)); } template <typename RandomAccessIterator> std::pair<amf_boolean, RandomAccessIterator> decode_amf_boolean_and_return_iterator(RandomAccessIterator begin, RandomAccessIterator end) { assert(begin <= end); if (std::distance(begin, end) < 2) { throw decode_amf_error("Failed to decode."); } auto iter = begin; if (*iter++ != 0x01) { throw decode_amf_error("Failed to decode."); } if (*iter++ == 0) { return std::make_pair(amf_boolean(false), iter); } else { return std::make_pair(amf_boolean(true), iter); } } template <typename RandomAccessIterator> amf_boolean decode_amf_boolean(RandomAccessIterator begin, RandomAccessIterator end) { return std::get<0>(decode_amf_boolean_and_return_iterator(begin, end)); } template <typename RandomAccessIterator> std::pair<amf_string, RandomAccessIterator> decode_amf_string_and_return_iterator(RandomAccessIterator begin, RandomAccessIterator end) { assert(begin <= end); if (std::distance(begin, end) < 3) { throw decode_amf_error("Failed to decode."); } auto iter = begin; if (*iter++ != 0x02) { throw decode_amf_error("Failed to decode."); } return impl::decode_amf_string_without_marker_and_return_iterator(iter, end); } template <typename RandomAccessIterator> amf_string decode_amf_string(RandomAccessIterator begin, RandomAccessIterator end) { return std::get<0>(decode_amf_string_and_return_iterator(begin, end)); } template <typename RandomAccessIterator> std::pair<amf_object, RandomAccessIterator> decode_amf_object_and_return_iterator(RandomAccessIterator begin, RandomAccessIterator end) { assert(begin <= end); if (begin == end) { throw decode_amf_error("Failed to decode."); } auto iter = begin; if (*iter++ != 0x03) { throw decode_amf_error("Failed to decode."); } amf_object obj; for (;;) { amf_string property_name; std::tie(property_name, iter) = impl::decode_amf_string_without_marker_and_return_iterator(iter, end); std::shared_ptr<amf_base> value_ptr; std::tie(value_ptr, iter) = decode_amf_and_return_iterator(iter, end); if (property_name.empty() || value_ptr->get_type() == amf_type::object_end) { break; } obj.push_back(std::make_pair(std::move(property_name), value_ptr)); }; return std::make_pair(obj, iter); } template <typename RandomAccessIterator> std::pair<amf_object, RandomAccessIterator> decode_amf_object(RandomAccessIterator begin, RandomAccessIterator end) { return std::get<0>(decode_amf_object_and_return_iterator(begin, end)); } template <typename RandomAccessIterator> std::pair<amf_ecma_array, RandomAccessIterator> decode_amf_ecma_array_and_return_iterator(RandomAccessIterator begin, RandomAccessIterator end) { assert(begin <= end); if (std::distance(begin, end) < 5) { throw decode_amf_error("Failed to decode."); } auto iter = begin; if (*iter++ != 0x08) { throw decode_amf_error("Failed to decode."); } union { char from[4]; std::uint32_t to; } cvt; static_assert(sizeof(cvt.from) == sizeof(cvt.to), "error"); cvt.from[3] = *iter++; cvt.from[2] = *iter++; cvt.from[1] = *iter++; cvt.from[0] = *iter++; amf_ecma_array ecma_array; auto cnt = cvt.to; for (auto i = 0u; i < cnt; ++i) { amf_string key; std::tie(key, iter) = impl::decode_amf_string_without_marker_and_return_iterator(iter, end); std::shared_ptr<amf_base> value_ptr; std::tie(value_ptr, iter) = decode_amf_and_return_iterator(iter, end); ecma_array.push_back(std::make_pair(std::move(key), value_ptr)); } return std::make_pair(std::move(ecma_array), iter); } template <typename RandomAccessIterator> amf_ecma_array decode_amf_ecma_array(RandomAccessIterator begin, RandomAccessIterator end) { return std::get<0>(decode_amf_ecma_array_and_return_iterator(begin, end)); } template <typename RandomAccessIterator> std::pair<amf_object_end, RandomAccessIterator> decode_amf_object_end_and_return_iterator(RandomAccessIterator begin, RandomAccessIterator end) { assert(begin <= end); if (begin == end) { throw decode_amf_error("Failed to decode."); } auto iter = begin; if (*iter++ != 0x09) { throw decode_amf_error("Failed to decode."); } return std::make_pair(amf_object_end(), iter); } template <typename RandomAccessIterator> amf_object_end decode_amf_object_end(RandomAccessIterator begin, RandomAccessIterator end) { return std::get<0>(decode_amf_object_end_and_return_iterator(begin, end)); } template <typename RandomAccessIterator> std::pair<amf_strict_array, RandomAccessIterator> decode_amf_strict_array_and_return_iterator(RandomAccessIterator begin, RandomAccessIterator end) { assert(begin <= end); if (std::distance(begin, end) < 5) { throw decode_amf_error("Failed to decode."); } auto iter = begin; if (*iter++ != 0x0a) { throw decode_amf_error("Failed to decode."); } union { char from[4]; std::uint32_t to; } cvt; static_assert(sizeof(cvt.from) == sizeof(cvt.to), "error"); cvt.from[3] = *iter++; cvt.from[2] = *iter++; cvt.from[1] = *iter++; cvt.from[0] = *iter++; auto cnt = cvt.to; amf_strict_array strict_array; for (auto i = 0u; i < cnt; ++i) { std::shared_ptr<amf_base> value_ptr; std::tie(value_ptr, iter) = decode_amf_and_return_iterator(iter, end); strict_array.push_back(value_ptr); } return std::make_pair(strict_array, iter); } template <typename RandomAccessIterator> amf_strict_array decode_amf_strict_array(RandomAccessIterator begin, RandomAccessIterator end) { return std::get<0>(decode_amf_strict_array_and_return_iterator(begin, end)); } template <typename RandomAccessIterator> std::pair<amf_date, RandomAccessIterator> decode_amf_date_and_return_iterator(RandomAccessIterator begin, RandomAccessIterator end) { assert(begin <= end); if (std::distance(begin, end) < 11) { throw decode_amf_error("Failed to decode."); } auto iter = begin; if (*iter++ != 0x0b) { throw decode_amf_error("Failed to decode."); } // IEEE-754 union { unsigned char from[8]; double to; } cvt; static_assert(sizeof(cvt.from) == sizeof(cvt.to), "error"); cvt.from[7] = *iter++; cvt.from[6] = *iter++; cvt.from[5] = *iter++; cvt.from[4] = *iter++; cvt.from[3] = *iter++; cvt.from[2] = *iter++; cvt.from[1] = *iter++; cvt.from[0] = *iter++; // Ignore time-zone (reserved S16) iter += 2; return std::make_pair(amf_date(cvt.to), iter); } template <typename RandomAccessIterator> amf_date decode_amf_date(RandomAccessIterator begin, RandomAccessIterator end) { return std::get<0>(decode_amf_date_and_return_iterator(begin, end)); } namespace impl { template <typename RandomAccessIterator> std::pair<amf_string, RandomAccessIterator> decode_amf_string_without_marker_and_return_iterator(RandomAccessIterator begin, RandomAccessIterator end) { assert(std::distance(begin, end) >= 2); auto iter = begin; union { char from[2]; std::uint16_t to; } cvt; static_assert(sizeof(cvt.from) == sizeof(cvt.to), "error"); std::uint16_t length = 0; cvt.from[1] = *iter++; cvt.from[0] = *iter++; length = cvt.to; if (length == 0) { return std::make_pair(amf_string(std::string()), iter); } else if (std::distance(iter, end) >= length) { std::string tmp; std::copy(iter, iter + length, std::back_inserter(tmp)); iter += length; return std::make_pair(amf_string(tmp), iter); } else { throw decode_amf_error("Failed to decode."); } } } // namespace impl } // namespace amf } // namespace dawn_player #endif
Fix 'decode_amf_date_and_return_iterator' (forgot decode time-zone)
amf_decode: Fix 'decode_amf_date_and_return_iterator' (forgot decode time-zone)
C++
mit
lxrite/DawnPlayer
26ffdd30418efa33797ef9f86272c7116be3b3e6
src/eventLoopStats.cc
src/eventLoopStats.cc
#include <nan.h> #include <limits.h> using namespace v8; const uint32_t maxPossibleNumber = std::numeric_limits<uint32_t>::max(); const uint32_t minPossibleNumber = std::numeric_limits<uint32_t>::min(); uv_check_t check_handle; uint32_t min; uint32_t max; uint32_t num; uint32_t sum; void reset() { min = maxPossibleNumber; max = minPossibleNumber; num = 0; sum = 0; } // See the following documentation for reference of what 'check' // means and when it is executed + the loop now time updates: // http://docs.libuv.org/en/v1.x/design.html#the-i-o-loop void on_check(uv_check_t* handle) { const uint64_t start_time = uv_now(handle->loop); // uv_hrtime is expressed in nanos, but the loop start time is // expressed in millis. const uint64_t now = uv_hrtime() / static_cast<uint64_t>(1e6); uint64_t duration; if (start_time >= now) { duration = 0; } else { duration = now - start_time; } num += 1; sum += duration; if (duration < min) { min = duration; } if (duration > max) { max = duration; } } static NAN_METHOD(sense) { // reset min and max counters when there were no calls. if (num == 0) { min = 0; max = 0; } Local<Object> obj = Nan::New<Object>(); Nan::Set( obj, Nan::New("min").ToLocalChecked(), Nan::New<Number>(static_cast<double>(min)) ); Nan::Set( obj, Nan::New("max").ToLocalChecked(), Nan::New<Number>(static_cast<double>(max)) ); Nan::Set( obj, Nan::New("num").ToLocalChecked(), Nan::New<Number>(static_cast<double>(num)) ); Nan::Set( obj, Nan::New("sum").ToLocalChecked(), Nan::New<Number>(static_cast<double>(sum)) ); reset(); info.GetReturnValue().Set(obj); } NAN_MODULE_INIT(init) { reset(); uv_check_init(uv_default_loop(), &check_handle); uv_check_start(&check_handle, &on_check); uv_unref(reinterpret_cast<uv_handle_t*>(&check_handle)); Nan::Set(target, Nan::New("sense").ToLocalChecked(), Nan::GetFunction(Nan::New<FunctionTemplate>(sense)).ToLocalChecked() ); } NODE_MODULE(eventLoopStats, init)
#include <nan.h> #include <limits.h> using namespace v8; const uint32_t maxPossibleNumber = std::numeric_limits<uint32_t>::max(); const uint32_t minPossibleNumber = std::numeric_limits<uint32_t>::min(); uv_check_t check_handle; uint32_t min; uint32_t max; uint32_t num; uint32_t sum; void reset() { min = maxPossibleNumber; max = minPossibleNumber; num = 0; sum = 0; } // See the following documentation for reference of what 'check' // means and when it is executed + the loop now time updates: // http://docs.libuv.org/en/v1.x/design.html#the-i-o-loop void on_check(uv_check_t* handle) { const uint64_t start_time = uv_now(handle->loop); // uv_hrtime is expressed in nanos, but the loop start time is // expressed in millis. const uint64_t now = uv_hrtime() / static_cast<uint64_t>(1e6); uint64_t duration; if (start_time >= now) { duration = 0; } else { duration = now - start_time; } num += 1; sum += duration; if (duration < min) { min = duration; } if (duration > max) { max = duration; } } static NAN_METHOD(sense) { // reset min and max counters when there were no calls. if (num == 0) { min = 0; max = 0; } Local<Object> obj = Nan::New<Object>(); Nan::Set( obj, Nan::New("min").ToLocalChecked(), Nan::New<Number>(static_cast<double>(min)) ); Nan::Set( obj, Nan::New("max").ToLocalChecked(), Nan::New<Number>(static_cast<double>(max)) ); Nan::Set( obj, Nan::New("num").ToLocalChecked(), Nan::New<Number>(static_cast<double>(num)) ); Nan::Set( obj, Nan::New("sum").ToLocalChecked(), Nan::New<Number>(static_cast<double>(sum)) ); reset(); info.GetReturnValue().Set(obj); } NAN_MODULE_INIT(init) { reset(); uv_check_init(uv_default_loop(), &check_handle); uv_check_start(&check_handle, reinterpret_cast<uv_check_cb>(on_check)); uv_unref(reinterpret_cast<uv_handle_t*>(&check_handle)); Nan::Set(target, Nan::New("sense").ToLocalChecked(), Nan::GetFunction(Nan::New<FunctionTemplate>(sense)).ToLocalChecked() ); } NODE_MODULE(eventLoopStats, init)
Make sure that callback conforms to required libuv interface
Make sure that callback conforms to required libuv interface
C++
mit
bripkens/event-loop-stats,bripkens/event-loop-stats,bripkens/event-loop-stats,bripkens/event-loop-stats
c4b566dcd7d53c37a9cafa7a1cd86dd7062be609
moses/src/LanguageModelIRST.cpp
moses/src/LanguageModelIRST.cpp
// $Id$ /*********************************************************************** Moses - factored phrase-based language decoder Copyright (C) 2006 University of Edinburgh 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 ***********************************************************************/ #include <cassert> #include <limits> #include <iostream> #include <fstream> #include "dictionary.h" #include "n_gram.h" #include "lmtable.h" #include "lmmacro.h" #include "LanguageModelIRST.h" #include "TypeDef.h" #include "Util.h" #include "FactorCollection.h" #include "Phrase.h" #include "InputFileStream.h" #include "StaticData.h" using namespace std; LanguageModelIRST::LanguageModelIRST(bool registerScore, ScoreIndexManager &scoreIndexManager) :LanguageModelSingleFactor(registerScore, scoreIndexManager) ,m_lmtb(0) { } LanguageModelIRST::~LanguageModelIRST() { delete m_lmtb; delete m_lmtb_ng; } bool LanguageModelIRST::Load(const std::string &filePath, FactorType factorType, float weight, size_t nGramOrder) { char *SepString = " \t\n"; cerr << "In LanguageModelIRST::Load: nGramOrder = " << nGramOrder << "\n"; FactorCollection &factorCollection = FactorCollection::Instance(); m_factorType = factorType; m_weight = weight; m_nGramOrder = nGramOrder; // get name of LM file and, if any, of the micro-macro map file char *filenames = strdup(filePath.c_str()); m_filePath = strsep(&filenames, SepString); // Open the input file (possibly gzipped) InputFileStream inp(m_filePath); if (filenames) { // case LMfile + MAPfile: create an object of lmmacro class and load both LM file and map cerr << "Loading LM file + MAP\n"; m_mapFilePath = strsep(&filenames, SepString); if (!FileExists(m_mapFilePath)) { cerr << "ERROR: Map file <" << m_mapFilePath << "> does not exist\n"; return false; } InputFileStream inpMap(m_mapFilePath); m_lmtb = new lmmacro(m_filePath, inp, inpMap); } else { // case (standard) LMfile only: create an object of lmtable cerr << "Loading LM file (no MAP)\n"; m_lmtb = (lmtable *)new lmtable; // Load the (possibly binary) model #ifdef WIN32 m_lmtb->load(inp); //don't use memory map #else if (m_filePath.compare(m_filePath.size()-3,3,".mm")==0) m_lmtb->load(inp,m_filePath.c_str(),NULL,1); else m_lmtb->load(inp,m_filePath.c_str(),NULL,0); #endif } m_lmtb_ng=new ngram(m_lmtb->getDict()); // ngram of words/micro tags m_lmtb_size=m_lmtb->maxlevel(); // LM can be ok, just outputs warnings // Mauro: in the original, the following two instructions are wrongly switched: m_unknownId = m_lmtb->getDict()->oovcode(); // at the level of micro tags CreateFactors(factorCollection); VERBOSE(1, "IRST: m_unknownId=" << m_unknownId << std::endl); //install caches m_lmtb->init_probcache(); m_lmtb->init_statecache(); m_lmtb->init_lmtcaches(m_lmtb->maxlevel()>2?m_lmtb->maxlevel()-1:2); return true; } void LanguageModelIRST::CreateFactors(FactorCollection &factorCollection) { // add factors which have srilm id // code copied & paste from SRI LM class. should do template function std::map<size_t, int> lmIdMap; size_t maxFactorId = 0; // to create lookup vector later on dict_entry *entry; dictionary_iter iter(m_lmtb->getDict()); // at the level of micro tags while ( (entry = iter.next()) != NULL) { size_t factorId = factorCollection.AddFactor(Output, m_factorType, entry->word)->GetId(); lmIdMap[factorId] = entry->code; maxFactorId = (factorId > maxFactorId) ? factorId : maxFactorId; } size_t factorId; m_sentenceStart = factorCollection.AddFactor(Output, m_factorType, BOS_); factorId = m_sentenceStart->GetId(); m_lmtb_sentenceStart=lmIdMap[factorId] = GetLmID(BOS_); maxFactorId = (factorId > maxFactorId) ? factorId : maxFactorId; m_sentenceStartArray[m_factorType] = m_sentenceStart; m_sentenceEnd = factorCollection.AddFactor(Output, m_factorType, EOS_); factorId = m_sentenceEnd->GetId(); m_lmtb_sentenceEnd=lmIdMap[factorId] = GetLmID(EOS_); maxFactorId = (factorId > maxFactorId) ? factorId : maxFactorId; m_sentenceEndArray[m_factorType] = m_sentenceEnd; // add to lookup vector in object m_lmIdLookup.resize(maxFactorId+1); fill(m_lmIdLookup.begin(), m_lmIdLookup.end(), m_unknownId); map<size_t, int>::iterator iterMap; for (iterMap = lmIdMap.begin() ; iterMap != lmIdMap.end() ; ++iterMap) { m_lmIdLookup[iterMap->first] = iterMap->second; } } int LanguageModelIRST::GetLmID( const std::string &str ) const { return m_lmtb->getDict()->encode( str.c_str() ); // at the level of micro tags } float LanguageModelIRST::GetValue(const vector<const Word*> &contextFactor, State* finalState, unsigned int* len) const { unsigned int dummy; if (!len) { len = &dummy; } FactorType factorType = GetFactorType(); // set up context size_t count = contextFactor.size(); m_lmtb_ng->size=0; if (count< (size_t)(m_lmtb_size-1)) m_lmtb_ng->pushc(m_lmtb_sentenceEnd); if (count< (size_t)m_lmtb_size) m_lmtb_ng->pushc(m_lmtb_sentenceStart); for (size_t i = 0 ; i < count ; i++) { int lmId = GetLmID((*contextFactor[i])[factorType]); m_lmtb_ng->pushc(lmId); } if (finalState){ *finalState=(State *)m_lmtb->cmaxsuffptr(*m_lmtb_ng); // back off stats not currently available *len = 0; } return TransformIRSTScore((float) m_lmtb->clprob(*m_lmtb_ng)); } void LanguageModelIRST::CleanUpAfterSentenceProcessing(){ TRACE_ERR( "reset caches\n"); m_lmtb->reset_caches(); #ifndef WIN32 TRACE_ERR( "reset mmap\n"); m_lmtb->reset_mmap(); #endif } void LanguageModelIRST::InitializeBeforeSentenceProcessing(){ //nothing to do #ifdef TRACE_CACHE m_lmtb->sentence_id++; #endif }
// $Id$ /*********************************************************************** Moses - factored phrase-based language decoder Copyright (C) 2006 University of Edinburgh 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 ***********************************************************************/ #include <cassert> #include <limits> #include <iostream> #include <fstream> #include "dictionary.h" #include "n_gram.h" #include "lmtable.h" #include "lmmacro.h" #include "LanguageModelIRST.h" #include "TypeDef.h" #include "Util.h" #include "FactorCollection.h" #include "Phrase.h" #include "InputFileStream.h" #include "StaticData.h" using namespace std; LanguageModelIRST::LanguageModelIRST(bool registerScore, ScoreIndexManager &scoreIndexManager) :LanguageModelSingleFactor(registerScore, scoreIndexManager) ,m_lmtb(0) { } LanguageModelIRST::~LanguageModelIRST() { delete m_lmtb; delete m_lmtb_ng; } bool LanguageModelIRST::Load(const std::string &filePath, FactorType factorType, float weight, size_t nGramOrder) { char *SepString = " \t\n"; cerr << "In LanguageModelIRST::Load: nGramOrder = " << nGramOrder << "\n"; FactorCollection &factorCollection = FactorCollection::Instance(); m_factorType = factorType; m_weight = weight; m_nGramOrder = nGramOrder; // get name of LM file and, if any, of the micro-macro map file char *filenames = strdup(filePath.c_str()); m_filePath = strsep(&filenames, SepString); // Open the input file (possibly gzipped) InputFileStream inp(m_filePath); if (filenames) { // case LMfile + MAPfile: create an object of lmmacro class and load both LM file and map cerr << "Loading LM file + MAP\n"; m_mapFilePath = strsep(&filenames, SepString); if (!FileExists(m_mapFilePath)) { cerr << "ERROR: Map file <" << m_mapFilePath << "> does not exist\n"; return false; } InputFileStream inpMap(m_mapFilePath); m_lmtb = new lmmacro(m_filePath, inp, inpMap); } else { // case (standard) LMfile only: create an object of lmtable cerr << "Loading LM file (no MAP)\n"; m_lmtb = (lmtable *)new lmtable; // Load the (possibly binary) model #ifdef WIN32 m_lmtb->load(inp); //don't use memory map #else if (m_filePath.compare(m_filePath.size()-3,3,".mm")==0) m_lmtb->load(inp,m_filePath.c_str(),NULL,1); else m_lmtb->load(inp,m_filePath.c_str(),NULL,0); #endif } m_lmtb_ng=new ngram(m_lmtb->getDict()); // ngram of words/micro tags m_lmtb_size=m_lmtb->maxlevel(); // LM can be ok, just outputs warnings // Mauro: in the original, the following two instructions are wrongly switched: m_unknownId = m_lmtb->getDict()->oovcode(); // at the level of micro tags CreateFactors(factorCollection); VERBOSE(1, "IRST: m_unknownId=" << m_unknownId << std::endl); //install caches m_lmtb->init_probcache(); m_lmtb->init_statecache(); m_lmtb->init_lmtcaches(m_lmtb->maxlevel()>2?m_lmtb->maxlevel()-1:2); return true; } void LanguageModelIRST::CreateFactors(FactorCollection &factorCollection) { // add factors which have srilm id // code copied & paste from SRI LM class. should do template function std::map<size_t, int> lmIdMap; size_t maxFactorId = 0; // to create lookup vector later on dict_entry *entry; dictionary_iter iter(m_lmtb->getDict()); // at the level of micro tags while ( (entry = iter.next()) != NULL) { size_t factorId = factorCollection.AddFactor(Output, m_factorType, entry->word)->GetId(); lmIdMap[factorId] = entry->code; maxFactorId = (factorId > maxFactorId) ? factorId : maxFactorId; } size_t factorId; m_sentenceStart = factorCollection.AddFactor(Output, m_factorType, BOS_); factorId = m_sentenceStart->GetId(); m_lmtb_sentenceStart=lmIdMap[factorId] = GetLmID(BOS_); maxFactorId = (factorId > maxFactorId) ? factorId : maxFactorId; m_sentenceStartArray[m_factorType] = m_sentenceStart; m_sentenceEnd = factorCollection.AddFactor(Output, m_factorType, EOS_); factorId = m_sentenceEnd->GetId(); m_lmtb_sentenceEnd=lmIdMap[factorId] = GetLmID(EOS_); maxFactorId = (factorId > maxFactorId) ? factorId : maxFactorId; m_sentenceEndArray[m_factorType] = m_sentenceEnd; // add to lookup vector in object m_lmIdLookup.resize(maxFactorId+1); fill(m_lmIdLookup.begin(), m_lmIdLookup.end(), m_unknownId); map<size_t, int>::iterator iterMap; for (iterMap = lmIdMap.begin() ; iterMap != lmIdMap.end() ; ++iterMap) { m_lmIdLookup[iterMap->first] = iterMap->second; } } int LanguageModelIRST::GetLmID( const std::string &str ) const { return m_lmtb->getDict()->encode( str.c_str() ); // at the level of micro tags } float LanguageModelIRST::GetValue(const vector<const Word*> &contextFactor, State* finalState, unsigned int* len) const { unsigned int dummy; if (!len) { len = &dummy; } FactorType factorType = GetFactorType(); // set up context size_t count = contextFactor.size(); m_lmtb_ng->size=0; if (count< (size_t)(m_lmtb_size-1)) m_lmtb_ng->pushc(m_lmtb_sentenceEnd); if (count< (size_t)m_lmtb_size) m_lmtb_ng->pushc(m_lmtb_sentenceStart); for (size_t i = 0 ; i < count ; i++) { //int lmId = GetLmID((*contextFactor[i])[factorType]); #ifdef DEBUG cout << "i=" << i << " -> " << (*contextFactor[i])[factorType]->GetString() << "\n"; #endif int lmId = GetLmID((*contextFactor[i])[factorType]->GetString()); m_lmtb_ng->pushc(lmId); } if (finalState){ *finalState=(State *)m_lmtb->cmaxsuffptr(*m_lmtb_ng); // back off stats not currently available *len = 0; } return TransformIRSTScore((float) m_lmtb->clprob(*m_lmtb_ng)); } void LanguageModelIRST::CleanUpAfterSentenceProcessing(){ TRACE_ERR( "reset caches\n"); m_lmtb->reset_caches(); #ifndef WIN32 TRACE_ERR( "reset mmap\n"); m_lmtb->reset_mmap(); #endif } void LanguageModelIRST::InitializeBeforeSentenceProcessing(){ //nothing to do #ifdef TRACE_CACHE m_lmtb->sentence_id++; #endif }
make effective the use of mapped IRSTLM
make effective the use of mapped IRSTLM git-svn-id: f5d636078e73450abf2183305c5e43efec2a5605@1506 1f5c12ca-751b-0410-a591-d2e778427230
C++
lgpl-2.1
KonceptGeek/mosesdecoder,emjotde/mosesdecoder_nmt,hychyc07/mosesdecoder,tofula/mosesdecoder,hychyc07/mosesdecoder,pjwilliams/mosesdecoder,tofula/mosesdecoder,KonceptGeek/mosesdecoder,moses-smt/mosesdecoder,emjotde/mosesdecoder_nmt,tofula/mosesdecoder,moses-smt/mosesdecoder,tofula/mosesdecoder,moses-smt/mosesdecoder,alvations/mosesdecoder,KonceptGeek/mosesdecoder,tofula/mosesdecoder,pjwilliams/mosesdecoder,emjotde/mosesdecoder_nmt,hychyc07/mosesdecoder,alvations/mosesdecoder,moses-smt/mosesdecoder,moses-smt/mosesdecoder,KonceptGeek/mosesdecoder,moses-smt/mosesdecoder,emjotde/mosesdecoder_nmt,alvations/mosesdecoder,KonceptGeek/mosesdecoder,hychyc07/mosesdecoder,alvations/mosesdecoder,alvations/mosesdecoder,pjwilliams/mosesdecoder,alvations/mosesdecoder,emjotde/mosesdecoder_nmt,pjwilliams/mosesdecoder,alvations/mosesdecoder,KonceptGeek/mosesdecoder,alvations/mosesdecoder,alvations/mosesdecoder,emjotde/mosesdecoder_nmt,moses-smt/mosesdecoder,emjotde/mosesdecoder_nmt,hychyc07/mosesdecoder,pjwilliams/mosesdecoder,hychyc07/mosesdecoder,hychyc07/mosesdecoder,pjwilliams/mosesdecoder,moses-smt/mosesdecoder,emjotde/mosesdecoder_nmt,tofula/mosesdecoder,alvations/mosesdecoder,moses-smt/mosesdecoder,alvations/mosesdecoder,tofula/mosesdecoder,emjotde/mosesdecoder_nmt,tofula/mosesdecoder,pjwilliams/mosesdecoder,KonceptGeek/mosesdecoder,hychyc07/mosesdecoder,tofula/mosesdecoder,hychyc07/mosesdecoder,moses-smt/mosesdecoder,hychyc07/mosesdecoder,KonceptGeek/mosesdecoder,pjwilliams/mosesdecoder,tofula/mosesdecoder,emjotde/mosesdecoder_nmt,pjwilliams/mosesdecoder,pjwilliams/mosesdecoder,KonceptGeek/mosesdecoder,moses-smt/mosesdecoder,KonceptGeek/mosesdecoder,tofula/mosesdecoder
c06ee1816809c02ab1b2bc70615205af0cc72a01
example/src/PIDexample.cpp
example/src/PIDexample.cpp
#include <PIDController.h> #include <LaplaceInversion.h> #include <complex> #include <iostream> using namespace std; #define SETPOINT 10.0 // Desired setpoint #define PLANT_A 2.0 // Poles of plant transfer function #define PLANT_B 3.0 // Poles of plant transfer function #define K_P 11.5 // Proportional gain #define K_I 19.0 // Integral gain #define K_D 0.0 // Derivative gain // Define closed-loop TF for simulation complex<double> xferFn(const complex<double> &s) { complex<double> pid = K_P + K_I/s + K_D*s; complex<double> plant = 1.0/((s+PLANT_A)*(s+PLANT_B)); return SETPOINT*(1.0/s)*(pid*plant)/(1.0+pid*plant*1.0); } int main(int argc, char *argv[]) { PIDController* pid = new PIDController(K_P,K_I,K_D); pid->on(); // Turn PID controller on pid->targetSetpoint(SETPOINT); // Change desired setpoint to SETPOINT double t = 0; // Init with time t=0 double T = 0.01; // Period double controlVariable = 0; // Init with zero actuation double processVariable = 0; // Init with zero position cout << "Time,Setpoint,Output" << endl; while(1) { cout << t << "," << pid->getSetpoint() << "," << processVariable << endl; controlVariable = pid->calc(processVariable); // Calculate next controlVariable processVariable = LaplaceInversion(xferFn, t, 1e-8); // Simulate plant with TF 1/((s+a)(s+b)) usleep(T*pow(10,6)); // 100ms delay to simulate actuation time t += T; // Increment time variable by 100ms } return 0; }
#include <PIDController.h> #include <LaplaceInversion.h> #include <iostream> #include <fstream> using namespace std; #define SETPOINT 10.0 // Desired setpoint #define PLANT_A 2.0 // Poles of plant transfer function #define PLANT_B 3.0 // Poles of plant transfer function #define K_P 11.5 // Proportional gain #define K_I 19.0 // Integral gain #define K_D 0.0 // Derivative gain // Define closed-loop TF for simulation cmplex xferFn(const cmplex &s) { cmplex pid = K_P + K_I/s + K_D*s; cmplex plant = 1.0/((s+PLANT_A)*(s+PLANT_B)); return SETPOINT*(1.0/s)*(pid*plant)/(1.0+pid*plant*1.0); } int main(int argc, char *argv[]) { PIDController* pid = new PIDController(K_P,K_I,K_D); pid->on(); // Turn PID controller on pid->targetSetpoint(SETPOINT); // Change desired setpoint to SETPOINT double t = 0; // Init with time t=0 double T = 0.01; // Period double controlVariable = 0; // Init with zero actuation double processVariable = 0; // Init with zero position cout << "Simulation running..." << endl; ofstream writeToCsv; writeToCsv.open("PIDExample.csv"); writeToCsv << "Time,Setpoint,Output" << endl; while(t < 20) { writeToCsv << t << "," << pid->getSetpoint() << "," << processVariable << endl; controlVariable = pid->calc(processVariable); // Calculate next controlVariable processVariable = LaplaceInversion(xferFn, t, 1e-8); // Simulate plant with TF 1/((s+a)(s+b)) usleep(T*pow(10,6)); // 100ms delay to simulate actuation time t += T; // Increment time variable by 100ms } writeToCsv.close(); cout << "Simulation complete! Output saved to PIDExample.csv." << endl; return 0; }
Write output to CSV file
Write output to CSV file
C++
mit
silentreverb/pid-controller
4fee5db445efa8f936e3733bae01b0ef315df997
solidutils/Debug.hpp
solidutils/Debug.hpp
/** * @file Debug.hpp * @brief Debugging functions. * @author Dominique LaSalle <[email protected]> * Copyright 2017, Solid Lake LLC * @version 1 * @date 2017-10-03 */ #ifndef SOLIDUTILS_INCLUDE_DEBUG_HPP #define SOLIDUTILS_INCLUDE_DEBUG_HPP /****************************************************************************** * MACROS ********************************************************************** ******************************************************************************/ #ifndef NDEBUG #include <cassert> // assert #include <cstdio> // vprintf #include <cstdarg> // va_start, va_end #include <iostream> // std::cerr, std::cout namespace sl { #define ASSERT_TRUE(a) \ do { \ if (!(a)) { \ std::cerr << "("#a" = " << (a) << ")" << std::endl; \ assert(false); \ } \ } while (false) #define ASSERT_FALSE(a) \ do { \ if (a) { \ std::cerr << "("#a" = " << (a) << ")" << std::endl; \ assert(false); \ } \ } while (false) #define ASSERT_EQUAL(a,b) \ do { \ if (a != b) { \ std::cerr << "("#a" = " << (a) << ") != ("#b" = " << (b) << ")" << \ std::endl; \ assert(false); \ } \ } while (false) #define ASSERT_NOTEQUAL(a,b) \ do { \ if (a == b) { \ std::cerr << "("#a" = " << (a) << ") == ("#b" = " << (b) << ")" << \ std::endl; \ assert(false); \ } \ } while (false) #define ASSERT_NULL(a) \ do { \ if (a != nullptr) { \ std::cerr << "("#a" = " << (a) << ") != nullptr" << \ std::endl; \ assert(false); \ } \ } while (false) #define ASSERT_NOTNULL(a) \ do { \ if (a == nullptr) { \ std::cerr << #a" is null" << \ std::endl; \ assert(false); \ } \ } while (false) #define ASSERT_LESS(a,b) \ do { \ if (a >= b) { \ std::cerr << "("#a" = " << (a) << ") !< ("#b" = " << (b) << ")" << \ std::endl; \ assert(false); \ } \ } while (false) #define ASSERT_LESSEQUAL(a,b) \ do { \ if (a > b) { \ std::cerr << "("#a" = " << (a) << ") !<= ("#b" = " << (b) << ")" << \ std::endl; \ assert(false); \ } \ } while (false) #define ASSERT_GREATER(a,b) \ do { \ if (a <= b) { \ std::cerr << "("#a" = " << (a) << ") !> ("#b" = " << (b) << ")" << \ std::endl; \ assert(false); \ } \ } while (false) #define ASSERT_GREATEREQUAL(a,b) \ do { \ if (a < b) { \ std::cerr << "("#a" = " << (a) << ") !>= ("#b" = " << (b) << ")" << \ std::endl; \ assert(false); \ } \ } while (false) namespace { /** * @brief Print a debugging message * * @param fmt The format of the message (printf style). * @param ... The message arguments. */ void debugMessage( char const * const fmt, ...) { va_list argptr; va_start(argptr, fmt); fprintf(stdout, "DEBUG: "); vfprintf(stdout, fmt, argptr); fprintf(stdout, "\n"); va_end(argptr); fflush(stdout); } /** * @brief Print a debugging message. * * @param msg The message. */ void debugMessage( std::string const & msg) { fprintf(stdout, "DEBUG: %s\n", msg.c_str()); } } } #else namespace sl { #define ASSERT_TRUE(a) #define ASSERT_FALSE(a) #define ASSERT_EQUAL(a,b) #define ASSERT_NOTEQUAL(a,b) #define ASSERT_NULL(a) #define ASSERT_NOTNULL(a) #define ASSERT_LESS(a,b) #define ASSERT_LESSEQUAL(a,b) #define ASSERT_GREATER(a,b) #define ASSERT_GREATEREQUAL(a,b) namespace { void debugMessage( char const *, ...) { // do nothing } void debugMessage( std::string const &) { // do nothing } } } #endif #endif
/** * @file Debug.hpp * @brief Debugging functions. * @author Dominique LaSalle <[email protected]> * Copyright 2017, Solid Lake LLC * @version 1 * @date 2017-10-03 */ #ifndef SOLIDUTILS_INCLUDE_DEBUG_HPP #define SOLIDUTILS_INCLUDE_DEBUG_HPP /****************************************************************************** * MACROS ********************************************************************** ******************************************************************************/ #ifndef NDEBUG #include <cassert> // assert #include <cstdio> // vprintf #include <cstdarg> // va_start, va_end #include <iostream> // std::cerr, std::cout namespace sl { #define ASSERT_TRUE(a) \ do { \ if (!(a)) { \ std::cerr << "("#a" = " << (a) << ")" << std::endl; \ assert(false); \ } \ } while (false) #define ASSERT_FALSE(a) \ do { \ if (a) { \ std::cerr << "("#a" = " << (a) << ")" << std::endl; \ assert(false); \ } \ } while (false) #define ASSERT_EQUAL(a,b) \ do { \ if (a != b) { \ std::cerr << "("#a" = " << (a) << ") != ("#b" = " << (b) << ")" << \ std::endl; \ assert(false); \ } \ } while (false) #define ASSERT_NOTEQUAL(a,b) \ do { \ if (a == b) { \ std::cerr << "("#a" = " << (a) << ") == ("#b" = " << (b) << ")" << \ std::endl; \ assert(false); \ } \ } while (false) #define ASSERT_NULL(a) \ do { \ if (a != nullptr) { \ std::cerr << "("#a" = " << (a) << ") != nullptr" << \ std::endl; \ assert(false); \ } \ } while (false) #define ASSERT_NOTNULL(a) \ do { \ if (a == nullptr) { \ std::cerr << #a" is null" << \ std::endl; \ assert(false); \ } \ } while (false) #define ASSERT_LESS(a,b) \ do { \ if (a >= b) { \ std::cerr << "("#a" = " << (a) << ") !< ("#b" = " << (b) << ")" << \ std::endl; \ assert(false); \ } \ } while (false) #define ASSERT_LESSEQUAL(a,b) \ do { \ if (a > b) { \ std::cerr << "("#a" = " << (a) << ") !<= ("#b" = " << (b) << ")" << \ std::endl; \ assert(false); \ } \ } while (false) #define ASSERT_GREATER(a,b) \ do { \ if (a <= b) { \ std::cerr << "("#a" = " << (a) << ") !> ("#b" = " << (b) << ")" << \ std::endl; \ assert(false); \ } \ } while (false) #define ASSERT_GREATEREQUAL(a,b) \ do { \ if (a < b) { \ std::cerr << "("#a" = " << (a) << ") !>= ("#b" = " << (b) << ")" << \ std::endl; \ assert(false); \ } \ } while (false) namespace { // NOTE: there is no stream based debugging, as expression in the '<<' would // still be evaluated even if not printed. /** * @brief Print a debugging message * * @param fmt The format of the message (printf style). * @param ... The message arguments. */ void debugMessage( char const * const fmt, ...) { va_list argptr; va_start(argptr, fmt); fprintf(stdout, "DEBUG: "); vfprintf(stdout, fmt, argptr); fprintf(stdout, "\n"); va_end(argptr); fflush(stdout); } /** * @brief Print a debugging message. * * @param msg The message. */ void debugMessage( std::string const & msg) { fprintf(stdout, "DEBUG: %s\n", msg.c_str()); } } } #else #define ASSERT_TRUE(a) #define ASSERT_FALSE(a) #define ASSERT_EQUAL(a,b) #define ASSERT_NOTEQUAL(a,b) #define ASSERT_NULL(a) #define ASSERT_NOTNULL(a) #define ASSERT_LESS(a,b) #define ASSERT_LESSEQUAL(a,b) #define ASSERT_GREATER(a,b) #define ASSERT_GREATEREQUAL(a,b) // macro instead of a function so that arguments are not evaluated #define debugMessage( ...) #endif #endif
Make debug messages in non-debug mode macros
Make debug messages in non-debug mode macros
C++
mit
solidlake/solidutils
8e18c2ecb4fd5cf963fa8fe9abceaa3d492ad959
src/Interrupt.cpp
src/Interrupt.cpp
#include "Interrupt.h" InterruptEntry IDT[256]; InterruptEntry::InterruptEntry() : offLow(0),segSelector(0x08),reserved0(0), reserved1(6),is32bits(true),reserved2(0), privilegeLvl(0),present(false),offHigh(0) { } void InterruptEntry::setAddr(void* addr){ offLow = static_cast<ushort> (reinterpret_cast<uint>(addr)); offHigh = static_cast<ushort>(reinterpret_cast<uint>(addr)>>16); } void* InterruptEntry::getAddr(){ return reinterpret_cast<void*>( (static_cast<uint>(offHigh) <<16) + static_cast<uint>(offLow)); } struct IDTLoader{ ushort size; InterruptEntry * IDT; }__attribute__((packed)); void lidt (){ IDTLoader lo = {256*8,IDT}; asm volatile ( "lidt (%0)" : : "r"(&lo): ); } InterruptTable::InterruptTable(){ initIntIDT(); // load the _inter_... in intIDT[...] for(int i = 0 ; i < 256 ; ++i){ IDT[i].setAddr(reinterpret_cast<void*>(intIDT[i])); intIDT[i] = nullptr; } } void InterruptTable::init(){ lidt(); } void InterruptTable::addInt(int i,interFunc f){ intIDT[i] = f; doReturn[i] = false; IDT[i].present =true; } void InterruptTable::addInt(int i,interFuncR f){ intIDT[i] = reinterpret_cast<interFunc>(f); doReturn[i] = true; IDT[i].present = true; }
#include "Interrupt.h" InterruptEntry IDT[256]; InterruptEntry::InterruptEntry() : offLow(0),segSelector(0x08),reserved0(0), reserved1(6),is32bits(true),reserved2(0), privilegeLvl(0),present(false),offHigh(0) { } void InterruptEntry::setAddr(void* addr){ offLow = static_cast<ushort> (reinterpret_cast<uint>(addr)); offHigh = static_cast<ushort>(reinterpret_cast<uint>(addr)>>16); } void* InterruptEntry::getAddr(){ return reinterpret_cast<void*>( (static_cast<uint>(offHigh) <<16) + static_cast<uint>(offLow)); } struct IDTLoader{ ushort size; InterruptEntry * IDT; }__attribute__((packed)); void lidt (){ IDTLoader lo = {256*8,IDT}; asm volatile ( "lidt (%0)" : : "r"(&lo): ); } InterruptTable::InterruptTable(){ } void InterruptTable::init(){ initIntIDT(); // load the _inter_... in intIDT[...] for(int i = 0 ; i < 256 ; ++i){ IDT[i].setAddr(reinterpret_cast<void*>(intIDT[i])); intIDT[i] = nullptr; } lidt(); } void InterruptTable::addInt(int i,interFunc f){ intIDT[i] = f; doReturn[i] = false; IDT[i].present =true; } void InterruptTable::addInt(int i,interFuncR f){ intIDT[i] = reinterpret_cast<interFunc>(f); doReturn[i] = true; IDT[i].present = true; }
Fix interrupts
Fix interrupts
C++
mit
TWal/ENS_sysres,TWal/ENS_sysres,TWal/ENS_sysres,TWal/ENS_sysres
fe7dcc0546f2680d640baf7b98b1d5599c370b1f
src/filters/Index.cpp
src/filters/Index.cpp
/****************************************************************************** * Copyright (c) 2012, Howard Butler, [email protected] * * 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 Hobu, Inc. or Flaxen Geo Consulting nor the * names of its contributors may be used to endorse or promote * products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. ****************************************************************************/ #include <pdal/filters/Index.hpp> #include <pdal/PointBuffer.hpp> #include <pdal/Utils.hpp> #include <boost/concept_check.hpp> // ignore_unused_variable_warning #include <algorithm> #include <cmath> namespace pdal { namespace filters { Index::Index(Stage& prevStage, const Options& options) : pdal::Filter(prevStage, options) , m_dimensions(3) { return; } void Index::initialize() { Filter::initialize(); setNumDimensions(getOptions().getValueOrDefault<boost::uint32_t>("dimensions", 3)); return; } boost::uint32_t const& Index::getNumDimensions() const { return m_dimensions; } Options Index::getDefaultOptions() { Options options; Option x("x_dim", std::string("X"), "Dimension name to use for 'X' data"); Option y("y_dim", std::string("Y"), "Dimension name to use for 'Y' data"); Option z("z_dim", std::string("Z"), "Dimension name to use for 'Z' data"); Option no_dims("dimensions", 3, "Number of dimensions to use for index"); options.add(x); options.add(y); options.add(z); options.add(no_dims); return options; } void Index::processBuffer(PointBuffer& /* data */) const { return; } pdal::StageSequentialIterator* Index::createSequentialIterator(PointBuffer& buffer) const { return new pdal::filters::iterators::sequential::Index(*this, buffer); } namespace iterators { namespace sequential { Index::Index(const pdal::filters::Index& filter, PointBuffer& buffer) : pdal::FilterSequentialIterator(filter, buffer) , m_stage(filter) , m_numIndexPoints(0) #ifdef PDAL_HAVE_FLANN , m_index(0) , m_dataset(0) #endif , m_xDim(0) , m_yDim(0) , m_zDim(0) { return; } void Index::readBufferBeginImpl(PointBuffer& buffer) { // Cache dimension positions if (!m_xDim || !m_yDim || !m_zDim) { pdal::Schema const& schema = buffer.getSchema(); std::string x_name = m_stage.getOptions().getValueOrDefault<std::string>("x_dim", "X"); std::string y_name = m_stage.getOptions().getValueOrDefault<std::string>("y_dim", "Y"); std::string z_name = m_stage.getOptions().getValueOrDefault<std::string>("z_dim", "Z"); m_stage.log()->get(logDEBUG2) << "Indexing PointBuffer with X: '" << x_name << "' Y: '" << y_name << "' Z: '" << z_name << " with " << m_stage.getNumDimensions() << " dimensions" << std::endl; m_xDim = &schema.getDimension(x_name); m_yDim = &schema.getDimension(y_name); m_zDim = &schema.getDimension(z_name); if (!m_stage.getNumPoints()) throw pdal_error("Unable to create index from pipeline that has an indeterminate number of points!"); } } std::vector<boost::uint32_t> Index::query(double const& x, double const& y, double const& z, double distance, boost::uint32_t k) { std::vector<boost::uint32_t> output; #ifdef PDAL_HAVE_FLANN if( !m_index) { throw pdal_error("Index is not initialized! Unable to query!"); } m_stage.log()->get(logDEBUG2) << "Searching for x: " << x << " y: " << y << " z: " << z << " with distance threshold " << distance << std::endl; boost::uint32_t num_dimensions(m_stage.getNumDimensions()); std::vector<float> distances_vec; distances_vec.resize(k); std::vector<boost::int32_t> indices_vec; indices_vec.resize(k); indices_vec.assign(indices_vec.size(), -1); std::vector<float> query_vec(num_dimensions); query_vec[0] = x; query_vec[1] = y; if (num_dimensions > 2) query_vec[2] = z; flann::Matrix<int> indices_mat (&indices_vec[0], 1, k); flann::Matrix<float> distances_mat (&distances_vec[0], 1, k); flann::Matrix<float> query_mat(&query_vec[0], 1, num_dimensions); m_index->knnSearch ( query_mat, indices_mat, distances_mat, k, flann::SearchParams(128)); bool logOutput = m_stage.log()->getLevel() > logDEBUG4; m_stage.log()->floatPrecision(8); for(unsigned i=0; i < k; ++i) { // if distance is 0, just return the nearest one, otherwise filter by distance if (Utils::compare_distance<float>((float)distance, 0)) { if (logOutput) { m_stage.log()->get(logDEBUG4) << "0-query found: " << "index: " << indices_vec[i] << " distance: " << distances_vec[i] <<std::endl; } if (indices_vec[i] != -1) output.push_back(indices_vec[i]); } else { if (::sqrt(distances_vec[i]) < distance) { if (logOutput) { m_stage.log()->get(logDEBUG4) << "Query found: " << "index: " << indices_vec[i] << " distance: " << distances_vec[i] <<std::endl; } if (indices_vec[i] != -1) output.push_back(indices_vec[i]); } } } #else boost::ignore_unused_variable_warning(x); boost::ignore_unused_variable_warning(y); boost::ignore_unused_variable_warning(z); boost::ignore_unused_variable_warning(distance); boost::ignore_unused_variable_warning(k); #endif return output; } boost::uint32_t Index::readBufferImpl(PointBuffer& data) { const boost::uint32_t numRead = getPrevIterator().read(data); bool logOutput = m_stage.log()->getLevel() > logDEBUG4; m_stage.log()->floatPrecision(8); m_stage.log()->get(logDEBUG2) << "inserting data into index data array of capacity: " << data.getCapacity() << std::endl; #ifdef PDAL_HAVE_FLANN for (boost::uint32_t pointIndex=0; pointIndex<numRead; pointIndex++) { float x = static_cast<float>(getScaledValue(data, *m_xDim, pointIndex)); float y = static_cast<float>(getScaledValue(data, *m_yDim, pointIndex)); float z = static_cast<float>(getScaledValue(data, *m_zDim, pointIndex)); m_data.push_back(x); m_data.push_back(y); if (m_stage.getNumDimensions() > 2) { m_data.push_back(z); if (logOutput) { m_stage.log()->get(logDEBUG4) << "adding z to index" << z << std::endl; } } m_numIndexPoints++; if (logOutput) { m_stage.log()->get(logDEBUG4) << "index: " << pointIndex << " x: " << x << " y: " << y << " z: " << z << std::endl; } } #endif return numRead; } double Index::getScaledValue(PointBuffer& data, Dimension const& d, std::size_t pointIndex) const { double output(0.0); float flt(0.0); boost::int8_t i8(0); boost::uint8_t u8(0); boost::int16_t i16(0); boost::uint16_t u16(0); boost::int32_t i32(0); boost::uint32_t u32(0); boost::int64_t i64(0); boost::uint64_t u64(0); boost::uint32_t size = d.getByteSize(); switch (d.getInterpretation()) { case dimension::Float: if (size == 4) { flt = data.getField<float>(d, pointIndex); output = static_cast<double>(flt); } if (size == 8) { output = data.getField<double>(d, pointIndex); } break; case dimension::SignedInteger: case dimension::SignedByte: if (size == 1) { i8 = data.getField<boost::int8_t>(d, pointIndex); output = d.applyScaling<boost::int8_t>(i8); } if (size == 2) { i16 = data.getField<boost::int16_t>(d, pointIndex); output = d.applyScaling<boost::int16_t>(i16); } if (size == 4) { i32 = data.getField<boost::int32_t>(d, pointIndex); output = d.applyScaling<boost::int32_t>(i32); } if (size == 8) { i64 = data.getField<boost::int64_t>(d, pointIndex); output = d.applyScaling<boost::int64_t>(i64); } break; case dimension::UnsignedInteger: case dimension::UnsignedByte: if (size == 1) { u8 = data.getField<boost::uint8_t>(d, pointIndex); output = d.applyScaling<boost::uint8_t>(u8); } if (size == 2) { u16 = data.getField<boost::uint16_t>(d, pointIndex); output = d.applyScaling<boost::uint16_t>(u16); } if (size == 4) { u32 = data.getField<boost::uint32_t>(d, pointIndex); output = d.applyScaling<boost::uint32_t>(u32); } if (size == 8) { u64 = data.getField<boost::uint64_t>(d, pointIndex); output = d.applyScaling<boost::uint64_t>(u64); } break; case dimension::Pointer: // stored as 64 bits, even on a 32-bit box case dimension::Undefined: throw pdal_error("Dimension data type unable to be reprojected"); } return output; } void Index::build() { #ifdef PDAL_HAVE_FLANN // Build the index // flann::Logger::setLevel(flann::FLANN_LOG_DEBUG); // flann::Logger::setDestination("flannlog.log"); boost::uint32_t num_dims = m_stage.getNumDimensions(); m_dataset = new flann::Matrix<float>(&m_data[0], m_numIndexPoints, num_dims); m_stage.log()->get(logDEBUG2) << "Building index for size " << m_data.size() <<" for points: " << m_stage.getNumPoints() <<std::endl; m_index = new flann::KDTreeSingleIndex<flann::L2_Simple<float> >(*m_dataset, flann::KDTreeIndexParams(4)); m_index->buildIndex(); m_stage.log()->get(logDEBUG2) << "Built index with memory: " << m_index->usedMemory() << " with size: " << m_index->size() << " veclen: " << m_index->veclen() << std::endl; #endif } Index::~Index() { #ifdef PDAL_HAVE_FLANN if (m_index) delete m_index; if (m_dataset) delete m_dataset; #endif } boost::uint64_t Index::skipImpl(boost::uint64_t count) { getPrevIterator().skip(count); return count; } bool Index::atEndImpl() const { return getPrevIterator().atEnd(); } } } // iterators::sequential } } // namespaces
/****************************************************************************** * Copyright (c) 2012, Howard Butler, [email protected] * * 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 Hobu, Inc. or Flaxen Geo Consulting nor the * names of its contributors may be used to endorse or promote * products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. ****************************************************************************/ #include <pdal/filters/Index.hpp> #include <pdal/PointBuffer.hpp> #include <pdal/Utils.hpp> #include <boost/concept_check.hpp> // ignore_unused_variable_warning #include <algorithm> #include <cmath> namespace pdal { namespace filters { Index::Index(Stage& prevStage, const Options& options) : pdal::Filter(prevStage, options) , m_dimensions(3) { return; } void Index::initialize() { Filter::initialize(); setNumDimensions(getOptions().getValueOrDefault<boost::uint32_t>("dimensions", 3)); return; } boost::uint32_t const& Index::getNumDimensions() const { return m_dimensions; } Options Index::getDefaultOptions() { Options options; Option x("x_dim", std::string("X"), "Dimension name to use for 'X' data"); Option y("y_dim", std::string("Y"), "Dimension name to use for 'Y' data"); Option z("z_dim", std::string("Z"), "Dimension name to use for 'Z' data"); Option no_dims("dimensions", 3, "Number of dimensions to use for index"); options.add(x); options.add(y); options.add(z); options.add(no_dims); return options; } void Index::processBuffer(PointBuffer& /* data */) const { return; } pdal::StageSequentialIterator* Index::createSequentialIterator(PointBuffer& buffer) const { return new pdal::filters::iterators::sequential::Index(*this, buffer); } namespace iterators { namespace sequential { Index::Index(const pdal::filters::Index& filter, PointBuffer& buffer) : pdal::FilterSequentialIterator(filter, buffer) , m_stage(filter) , m_numIndexPoints(0) #ifdef PDAL_HAVE_FLANN , m_index(0) , m_dataset(0) #endif , m_xDim(0) , m_yDim(0) , m_zDim(0) { return; } void Index::readBufferBeginImpl(PointBuffer& buffer) { // Cache dimension positions if (!m_xDim || !m_yDim || !m_zDim) { pdal::Schema const& schema = buffer.getSchema(); std::string x_name = m_stage.getOptions().getValueOrDefault<std::string>("x_dim", "X"); std::string y_name = m_stage.getOptions().getValueOrDefault<std::string>("y_dim", "Y"); std::string z_name = m_stage.getOptions().getValueOrDefault<std::string>("z_dim", "Z"); m_stage.log()->get(logDEBUG2) << "Indexing PointBuffer with X: '" << x_name << "' Y: '" << y_name << "' Z: '" << z_name << " with " << m_stage.getNumDimensions() << " dimensions" << std::endl; m_xDim = &schema.getDimension(x_name); m_yDim = &schema.getDimension(y_name); m_zDim = &schema.getDimension(z_name); if (!m_stage.getNumPoints()) throw pdal_error("Unable to create index from pipeline that has an indeterminate number of points!"); } } std::vector<boost::uint32_t> Index::query(double const& x, double const& y, double const& z, double distance, boost::uint32_t k) { std::vector<boost::uint32_t> output; #ifdef PDAL_HAVE_FLANN if( !m_index) { throw pdal_error("Index is not initialized! Unable to query!"); } m_stage.log()->get(logDEBUG2) << "Searching for x: " << x << " y: " << y << " z: " << z << " with distance threshold " << distance << std::endl; boost::uint32_t num_dimensions(m_stage.getNumDimensions()); std::vector<float> distances_vec; distances_vec.resize(k); std::vector<boost::int32_t> indices_vec; indices_vec.resize(k); indices_vec.assign(indices_vec.size(), -1); std::vector<float> query_vec(num_dimensions); query_vec[0] = x; query_vec[1] = y; if (num_dimensions > 2) query_vec[2] = z; flann::Matrix<int> indices_mat (&indices_vec[0], 1, k); flann::Matrix<float> distances_mat (&distances_vec[0], 1, k); flann::Matrix<float> query_mat(&query_vec[0], 1, num_dimensions); m_index->knnSearch ( query_mat, indices_mat, distances_mat, k, flann::SearchParams(128)); bool logOutput = m_stage.log()->getLevel() > logDEBUG4; m_stage.log()->floatPrecision(8); for(unsigned i=0; i < k; ++i) { // if distance is 0, just return the nearest one, otherwise filter by distance if (Utils::compare_distance<float>((float)distance, 0)) { if (logOutput) { m_stage.log()->get(logDEBUG4) << "0-query found: " << "index: " << indices_vec[i] << " distance: " << distances_vec[i] <<std::endl; } if (indices_vec[i] != -1) output.push_back(indices_vec[i]); } else { if (::sqrt(distances_vec[i]) < distance) { if (logOutput) { m_stage.log()->get(logDEBUG4) << "Query found: " << "index: " << indices_vec[i] << " distance: " << distances_vec[i] <<std::endl; } if (indices_vec[i] != -1) output.push_back(indices_vec[i]); } } } #else boost::ignore_unused_variable_warning(x); boost::ignore_unused_variable_warning(y); boost::ignore_unused_variable_warning(z); boost::ignore_unused_variable_warning(distance); boost::ignore_unused_variable_warning(k); #endif return output; } boost::uint32_t Index::readBufferImpl(PointBuffer& data) { const boost::uint32_t numRead = getPrevIterator().read(data); m_stage.log()->floatPrecision(8); m_stage.log()->get(logDEBUG2) << "inserting data into index data array of capacity: " << data.getCapacity() << std::endl; #ifdef PDAL_HAVE_FLANN bool logOutput = m_stage.log()->getLevel() > logDEBUG4; for (boost::uint32_t pointIndex=0; pointIndex<numRead; pointIndex++) { float x = static_cast<float>(getScaledValue(data, *m_xDim, pointIndex)); float y = static_cast<float>(getScaledValue(data, *m_yDim, pointIndex)); float z = static_cast<float>(getScaledValue(data, *m_zDim, pointIndex)); m_data.push_back(x); m_data.push_back(y); if (m_stage.getNumDimensions() > 2) { m_data.push_back(z); if (logOutput) { m_stage.log()->get(logDEBUG4) << "adding z to index" << z << std::endl; } } m_numIndexPoints++; if (logOutput) { m_stage.log()->get(logDEBUG4) << "index: " << pointIndex << " x: " << x << " y: " << y << " z: " << z << std::endl; } } #endif return numRead; } double Index::getScaledValue(PointBuffer& data, Dimension const& d, std::size_t pointIndex) const { double output(0.0); float flt(0.0); boost::int8_t i8(0); boost::uint8_t u8(0); boost::int16_t i16(0); boost::uint16_t u16(0); boost::int32_t i32(0); boost::uint32_t u32(0); boost::int64_t i64(0); boost::uint64_t u64(0); boost::uint32_t size = d.getByteSize(); switch (d.getInterpretation()) { case dimension::Float: if (size == 4) { flt = data.getField<float>(d, pointIndex); output = static_cast<double>(flt); } if (size == 8) { output = data.getField<double>(d, pointIndex); } break; case dimension::SignedInteger: case dimension::SignedByte: if (size == 1) { i8 = data.getField<boost::int8_t>(d, pointIndex); output = d.applyScaling<boost::int8_t>(i8); } if (size == 2) { i16 = data.getField<boost::int16_t>(d, pointIndex); output = d.applyScaling<boost::int16_t>(i16); } if (size == 4) { i32 = data.getField<boost::int32_t>(d, pointIndex); output = d.applyScaling<boost::int32_t>(i32); } if (size == 8) { i64 = data.getField<boost::int64_t>(d, pointIndex); output = d.applyScaling<boost::int64_t>(i64); } break; case dimension::UnsignedInteger: case dimension::UnsignedByte: if (size == 1) { u8 = data.getField<boost::uint8_t>(d, pointIndex); output = d.applyScaling<boost::uint8_t>(u8); } if (size == 2) { u16 = data.getField<boost::uint16_t>(d, pointIndex); output = d.applyScaling<boost::uint16_t>(u16); } if (size == 4) { u32 = data.getField<boost::uint32_t>(d, pointIndex); output = d.applyScaling<boost::uint32_t>(u32); } if (size == 8) { u64 = data.getField<boost::uint64_t>(d, pointIndex); output = d.applyScaling<boost::uint64_t>(u64); } break; case dimension::Pointer: // stored as 64 bits, even on a 32-bit box case dimension::Undefined: throw pdal_error("Dimension data type unable to be reprojected"); } return output; } void Index::build() { #ifdef PDAL_HAVE_FLANN // Build the index // flann::Logger::setLevel(flann::FLANN_LOG_DEBUG); // flann::Logger::setDestination("flannlog.log"); boost::uint32_t num_dims = m_stage.getNumDimensions(); m_dataset = new flann::Matrix<float>(&m_data[0], m_numIndexPoints, num_dims); m_stage.log()->get(logDEBUG2) << "Building index for size " << m_data.size() <<" for points: " << m_stage.getNumPoints() <<std::endl; m_index = new flann::KDTreeSingleIndex<flann::L2_Simple<float> >(*m_dataset, flann::KDTreeIndexParams(4)); m_index->buildIndex(); m_stage.log()->get(logDEBUG2) << "Built index with memory: " << m_index->usedMemory() << " with size: " << m_index->size() << " veclen: " << m_index->veclen() << std::endl; #endif } Index::~Index() { #ifdef PDAL_HAVE_FLANN if (m_index) delete m_index; if (m_dataset) delete m_dataset; #endif } boost::uint64_t Index::skipImpl(boost::uint64_t count) { getPrevIterator().skip(count); return count; } bool Index::atEndImpl() const { return getPrevIterator().atEnd(); } } } // iterators::sequential } } // namespaces
clean up unused var warning
clean up unused var warning
C++
bsd-3-clause
boundlessgeo/PDAL,DougFirErickson/PDAL,Sciumo/PDAL,Sciumo/PDAL,jwomeara/PDAL,lucadelu/PDAL,verma/PDAL,DougFirErickson/PDAL,verma/PDAL,lucadelu/PDAL,Sciumo/PDAL,radiantbluetechnologies/PDAL,boundlessgeo/PDAL,mpgerlek/PDAL-old,lucadelu/PDAL,mpgerlek/PDAL-old,mtCarto/PDAL,Sciumo/PDAL,mpgerlek/PDAL-old,jwomeara/PDAL,lucadelu/PDAL,mtCarto/PDAL,mtCarto/PDAL,radiantbluetechnologies/PDAL,verma/PDAL,mtCarto/PDAL,verma/PDAL,jwomeara/PDAL,mpgerlek/PDAL-old,boundlessgeo/PDAL,radiantbluetechnologies/PDAL,verma/PDAL,jwomeara/PDAL,boundlessgeo/PDAL,DougFirErickson/PDAL,DougFirErickson/PDAL,verma/PDAL,radiantbluetechnologies/PDAL,verma/PDAL
a850469ed309562c4d4af04b92cfb1cbfe999988
src/LexCPP.cxx
src/LexCPP.cxx
// Scintilla source code edit control /** @file LexCPP.cxx ** Lexer for C++, C, Java, and Javascript. **/ // Copyright 1998-2001 by Neil Hodgson <[email protected]> // The License.txt file describes the conditions under which this software may be distributed. #include <stdlib.h> #include <string.h> #include <ctype.h> #include <stdio.h> #include <stdarg.h> #include "Platform.h" #include "PropSet.h" #include "Accessor.h" #include "StyleContext.h" #include "KeyWords.h" #include "Scintilla.h" #include "SciLexer.h" static bool IsOKBeforeRE(const int ch) { return (ch == '(') || (ch == '=') || (ch == ','); } inline bool IsAWordChar(const int ch) { return (ch < 0x80) && (isalnum(ch) || ch == '.' || ch == '_'); } inline bool IsAWordStart(const int ch) { return (ch < 0x80) && (isalnum(ch) || ch == '_'); } inline bool IsADoxygenChar(const int ch) { return (islower(ch) || ch == '$' || ch == '@' || ch == '\\' || ch == '&' || ch == '<' || ch == '>' || ch == '#' || ch == '{' || ch == '}' || ch == '[' || ch == ']'); } inline bool IsStateComment(const int state) { return ((state == SCE_C_COMMENT) || (state == SCE_C_COMMENTLINE) || (state == SCE_C_COMMENTDOC) || (state == SCE_C_COMMENTDOCKEYWORD) || (state == SCE_C_COMMENTDOCKEYWORDERROR)); } inline bool IsStateString(const int state) { return ((state == SCE_C_STRING) || (state == SCE_C_VERBATIM)); } static void ColouriseCppDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[], Accessor &styler) { WordList &keywords = *keywordlists[0]; WordList &keywords2 = *keywordlists[1]; WordList &keywords3 = *keywordlists[2]; bool stylingWithinPreprocessor = styler.GetPropertyInt("styling.within.preprocessor"); // Do not leak onto next line if (initStyle == SCE_C_STRINGEOL) initStyle = SCE_C_DEFAULT; int chPrevNonWhite = ' '; int visibleChars = 0; int noDocChars = 0; bool lastWordWasUUID = false; StyleContext sc(startPos, length, initStyle, styler); for (; sc.More(); sc.Forward()) { // Handle line continuation generically. if (sc.ch == '\\') { if (sc.Match("\\\n")) { sc.Forward(); sc.Forward(); continue; } if (sc.Match("\\\r\n")) { sc.Forward(); sc.Forward(); sc.Forward(); continue; } } // Determine if the current state should terminate. if (sc.state == SCE_C_OPERATOR) { sc.SetState(SCE_C_DEFAULT); } else if (sc.state == SCE_C_NUMBER) { if (!IsAWordChar(sc.ch)) { sc.SetState(SCE_C_DEFAULT); } } else if (sc.state == SCE_C_IDENTIFIER) { if (!IsAWordChar(sc.ch) || (sc.ch == '.')) { char s[100]; sc.GetCurrent(s, sizeof(s)); if (keywords.InList(s)) { lastWordWasUUID = strcmp(s, "uuid") == 0; sc.ChangeState(SCE_C_WORD); } else if (keywords2.InList(s)) { sc.ChangeState(SCE_C_WORD2); } sc.SetState(SCE_C_DEFAULT); } } else if (sc.state == SCE_C_PREPROCESSOR) { if (stylingWithinPreprocessor) { if (IsASpace(sc.ch)) { sc.SetState(SCE_C_DEFAULT); } } else { if (sc.atLineEnd) { sc.SetState(SCE_C_DEFAULT); } } } else if (sc.state == SCE_C_COMMENT) { if (sc.Match('*', '/')) { sc.Forward(); sc.ForwardSetState(SCE_C_DEFAULT); } } else if (sc.state == SCE_C_COMMENTDOC) { if (sc.Match('*', '/')) { sc.Forward(); sc.ForwardSetState(SCE_C_DEFAULT); } else if ((sc.ch == '@' || sc.ch == '\\') && (noDocChars == 0)) { sc.SetState(SCE_C_COMMENTDOCKEYWORD); } else if (sc.atLineEnd) { noDocChars = 0; } else if (!isspace(sc.ch)) { noDocChars++; } } else if (sc.state == SCE_C_COMMENTLINE || sc.state == SCE_C_COMMENTLINEDOC) { if (sc.atLineEnd) { sc.SetState(SCE_C_DEFAULT); visibleChars = 0; } } else if (sc.state == SCE_C_COMMENTDOCKEYWORD) { if (sc.Match('*', '/')) { sc.ChangeState(SCE_C_COMMENTDOCKEYWORDERROR); sc.Forward(); sc.ForwardSetState(SCE_C_DEFAULT); } else if (!IsADoxygenChar(sc.ch)) { char s[100]; sc.GetCurrent(s, sizeof(s)); if (!isspace(sc.ch) || !keywords3.InList(s+1)) { sc.ChangeState(SCE_C_COMMENTDOCKEYWORDERROR); } sc.SetState(SCE_C_COMMENTDOC); } } else if (sc.state == SCE_C_STRING) { if (sc.ch == '\\') { if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') { sc.Forward(); } } else if (sc.ch == '\"') { sc.ForwardSetState(SCE_C_DEFAULT); } else if (sc.atLineEnd) { sc.ChangeState(SCE_C_STRINGEOL); sc.ForwardSetState(SCE_C_DEFAULT); visibleChars = 0; } } else if (sc.state == SCE_C_CHARACTER) { if (sc.atLineEnd) { sc.ChangeState(SCE_C_STRINGEOL); sc.ForwardSetState(SCE_C_DEFAULT); visibleChars = 0; } else if (sc.ch == '\\') { if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') { sc.Forward(); } } else if (sc.ch == '\'') { sc.ForwardSetState(SCE_C_DEFAULT); } } else if (sc.state == SCE_C_REGEX) { if (sc.ch == '\r' || sc.ch == '\n' || sc.ch == '/') { sc.ForwardSetState(SCE_C_DEFAULT); } else if (sc.ch == '\\') { // Gobble up the quoted character if (sc.chNext == '\\' || sc.chNext == '/') { sc.Forward(); } } } else if (sc.state == SCE_C_VERBATIM) { if (sc.ch == '\"') { if (sc.chNext == '\"') { sc.Forward(); } else { sc.ForwardSetState(SCE_C_DEFAULT); } } } else if (sc.state == SCE_C_UUID) { if (sc.ch == '\r' || sc.ch == '\n' || sc.ch == ')') { sc.SetState(SCE_C_DEFAULT); } } // Determine if a new state should be entered. if (sc.state == SCE_C_DEFAULT) { if (sc.Match('@', '\"')) { sc.SetState(SCE_C_VERBATIM); sc.Forward(); } else if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) { if (lastWordWasUUID) { sc.SetState(SCE_C_UUID); lastWordWasUUID = false; } else { sc.SetState(SCE_C_NUMBER); } } else if (IsAWordStart(sc.ch) || (sc.ch == '@')) { if (lastWordWasUUID) { sc.SetState(SCE_C_UUID); lastWordWasUUID = false; } else { sc.SetState(SCE_C_IDENTIFIER); } } else if (sc.Match('/', '*')) { if (sc.Match("/**") || sc.Match("/*!")) { // Support of Qt/Doxygen doc. style noDocChars = -1; sc.SetState(SCE_C_COMMENTDOC); } else { sc.SetState(SCE_C_COMMENT); } sc.Forward(); // Eat the * so it isn't used for the end of the comment } else if (sc.Match('/', '/')) { if (sc.Match("///") || sc.Match("//!")) // Support of Qt/Doxygen doc. style sc.SetState(SCE_C_COMMENTLINEDOC); else sc.SetState(SCE_C_COMMENTLINE); } else if (sc.ch == '/' && IsOKBeforeRE(chPrevNonWhite)) { sc.SetState(SCE_C_REGEX); } else if (sc.ch == '\"') { sc.SetState(SCE_C_STRING); } else if (sc.ch == '\'') { sc.SetState(SCE_C_CHARACTER); } else if (sc.ch == '#' && visibleChars == 0) { // Preprocessor commands are alone on their line sc.SetState(SCE_C_PREPROCESSOR); // Skip whitespace between # and preprocessor word do { sc.Forward(); } while ((sc.ch == ' ') && (sc.ch == '\t') && sc.More()); if (sc.atLineEnd) { sc.SetState(SCE_C_DEFAULT); } } else if (isoperator(static_cast<char>(sc.ch))) { sc.SetState(SCE_C_OPERATOR); } } if (sc.atLineEnd) { // Reset states to begining of colourise so no surprises // if different sets of lines lexed. chPrevNonWhite = ' '; visibleChars = 0; lastWordWasUUID = false; } if (!IsASpace(sc.ch)) { chPrevNonWhite = sc.ch; visibleChars++; } } sc.Complete(); } static void FoldCppDoc(unsigned int startPos, int length, int initStyle, WordList *[], Accessor &styler) { bool foldComment = styler.GetPropertyInt("fold.comment"); bool foldCompact = styler.GetPropertyInt("fold.compact", 1); unsigned int endPos = startPos + length; int visibleChars = 0; int lineCurrent = styler.GetLine(startPos); int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK; int levelCurrent = levelPrev; char chNext = styler[startPos]; int styleNext = styler.StyleAt(startPos); int style = initStyle; for (unsigned int i = startPos; i < endPos; i++) { char ch = chNext; chNext = styler.SafeGetCharAt(i + 1); int stylePrev = style; style = styleNext; styleNext = styler.StyleAt(i + 1); bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n'); if (foldComment && (style == SCE_C_COMMENT || style == SCE_C_COMMENTDOC)) { if (style != stylePrev) { levelCurrent++; } else if ((style != styleNext) && !atEOL) { // Comments don't end at end of line and the next character may be unstyled. levelCurrent--; } } if (style == SCE_C_OPERATOR) { if (ch == '{') { levelCurrent++; } else if (ch == '}') { levelCurrent--; } } if (atEOL) { int lev = levelPrev; if (visibleChars == 0 && foldCompact) lev |= SC_FOLDLEVELWHITEFLAG; if ((levelCurrent > levelPrev) && (visibleChars > 0)) lev |= SC_FOLDLEVELHEADERFLAG; if (lev != styler.LevelAt(lineCurrent)) { styler.SetLevel(lineCurrent, lev); } lineCurrent++; levelPrev = levelCurrent; visibleChars = 0; } if (!isspacechar(ch)) visibleChars++; } // Fill in the real level of the next line, keeping the current flags as they will be filled in later int flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK; styler.SetLevel(lineCurrent, levelPrev | flagsNext); } LexerModule lmCPP(SCLEX_CPP, ColouriseCppDoc, "cpp", FoldCppDoc); LexerModule lmTCL(SCLEX_TCL, ColouriseCppDoc, "tcl", FoldCppDoc);
// Scintilla source code edit control /** @file LexCPP.cxx ** Lexer for C++, C, Java, and Javascript. **/ // Copyright 1998-2001 by Neil Hodgson <[email protected]> // The License.txt file describes the conditions under which this software may be distributed. #include <stdlib.h> #include <string.h> #include <ctype.h> #include <stdio.h> #include <stdarg.h> #include "Platform.h" #include "PropSet.h" #include "Accessor.h" #include "StyleContext.h" #include "KeyWords.h" #include "Scintilla.h" #include "SciLexer.h" static bool IsOKBeforeRE(const int ch) { return (ch == '(') || (ch == '=') || (ch == ','); } inline bool IsAWordChar(const int ch) { return (ch < 0x80) && (isalnum(ch) || ch == '.' || ch == '_'); } inline bool IsAWordStart(const int ch) { return (ch < 0x80) && (isalnum(ch) || ch == '_'); } inline bool IsADoxygenChar(const int ch) { return (islower(ch) || ch == '$' || ch == '@' || ch == '\\' || ch == '&' || ch == '<' || ch == '>' || ch == '#' || ch == '{' || ch == '}' || ch == '[' || ch == ']'); } inline bool IsStateComment(const int state) { return ((state == SCE_C_COMMENT) || (state == SCE_C_COMMENTLINE) || (state == SCE_C_COMMENTDOC) || (state == SCE_C_COMMENTDOCKEYWORD) || (state == SCE_C_COMMENTDOCKEYWORDERROR)); } inline bool IsStateString(const int state) { return ((state == SCE_C_STRING) || (state == SCE_C_VERBATIM)); } static void ColouriseCppDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[], Accessor &styler) { WordList &keywords = *keywordlists[0]; WordList &keywords2 = *keywordlists[1]; WordList &keywords3 = *keywordlists[2]; bool stylingWithinPreprocessor = styler.GetPropertyInt("styling.within.preprocessor"); // Do not leak onto next line if (initStyle == SCE_C_STRINGEOL) initStyle = SCE_C_DEFAULT; int chPrevNonWhite = ' '; int visibleChars = 0; int noDocChars = 0; bool lastWordWasUUID = false; StyleContext sc(startPos, length, initStyle, styler); for (; sc.More(); sc.Forward()) { // Handle line continuation generically. if (sc.ch == '\\') { if (sc.Match("\\\n")) { sc.Forward(); sc.Forward(); continue; } if (sc.Match("\\\r\n")) { sc.Forward(); sc.Forward(); sc.Forward(); continue; } } // Determine if the current state should terminate. if (sc.state == SCE_C_OPERATOR) { sc.SetState(SCE_C_DEFAULT); } else if (sc.state == SCE_C_NUMBER) { if (!IsAWordChar(sc.ch)) { sc.SetState(SCE_C_DEFAULT); } } else if (sc.state == SCE_C_IDENTIFIER) { if (!IsAWordChar(sc.ch) || (sc.ch == '.')) { char s[100]; sc.GetCurrent(s, sizeof(s)); if (keywords.InList(s)) { lastWordWasUUID = strcmp(s, "uuid") == 0; sc.ChangeState(SCE_C_WORD); } else if (keywords2.InList(s)) { sc.ChangeState(SCE_C_WORD2); } sc.SetState(SCE_C_DEFAULT); } } else if (sc.state == SCE_C_PREPROCESSOR) { if (stylingWithinPreprocessor) { if (IsASpace(sc.ch)) { sc.SetState(SCE_C_DEFAULT); } } else { if (sc.atLineEnd) { sc.SetState(SCE_C_DEFAULT); } } } else if (sc.state == SCE_C_COMMENT) { if (sc.Match('*', '/')) { sc.Forward(); sc.ForwardSetState(SCE_C_DEFAULT); } } else if (sc.state == SCE_C_COMMENTDOC) { if (sc.Match('*', '/')) { sc.Forward(); sc.ForwardSetState(SCE_C_DEFAULT); } else if ((sc.ch == '@' || sc.ch == '\\') && (noDocChars == 0)) { sc.SetState(SCE_C_COMMENTDOCKEYWORD); } else if (sc.atLineEnd) { noDocChars = 0; } else if (!isspace(sc.ch) && (sc.ch != '*')) { noDocChars++; } } else if (sc.state == SCE_C_COMMENTLINE || sc.state == SCE_C_COMMENTLINEDOC) { if (sc.atLineEnd) { sc.SetState(SCE_C_DEFAULT); visibleChars = 0; } } else if (sc.state == SCE_C_COMMENTDOCKEYWORD) { if (sc.Match('*', '/')) { sc.ChangeState(SCE_C_COMMENTDOCKEYWORDERROR); sc.Forward(); sc.ForwardSetState(SCE_C_DEFAULT); } else if (!IsADoxygenChar(sc.ch)) { char s[100]; sc.GetCurrent(s, sizeof(s)); if (!isspace(sc.ch) || !keywords3.InList(s+1)) { sc.ChangeState(SCE_C_COMMENTDOCKEYWORDERROR); } sc.SetState(SCE_C_COMMENTDOC); } } else if (sc.state == SCE_C_STRING) { if (sc.ch == '\\') { if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') { sc.Forward(); } } else if (sc.ch == '\"') { sc.ForwardSetState(SCE_C_DEFAULT); } else if (sc.atLineEnd) { sc.ChangeState(SCE_C_STRINGEOL); sc.ForwardSetState(SCE_C_DEFAULT); visibleChars = 0; } } else if (sc.state == SCE_C_CHARACTER) { if (sc.atLineEnd) { sc.ChangeState(SCE_C_STRINGEOL); sc.ForwardSetState(SCE_C_DEFAULT); visibleChars = 0; } else if (sc.ch == '\\') { if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') { sc.Forward(); } } else if (sc.ch == '\'') { sc.ForwardSetState(SCE_C_DEFAULT); } } else if (sc.state == SCE_C_REGEX) { if (sc.ch == '\r' || sc.ch == '\n' || sc.ch == '/') { sc.ForwardSetState(SCE_C_DEFAULT); } else if (sc.ch == '\\') { // Gobble up the quoted character if (sc.chNext == '\\' || sc.chNext == '/') { sc.Forward(); } } } else if (sc.state == SCE_C_VERBATIM) { if (sc.ch == '\"') { if (sc.chNext == '\"') { sc.Forward(); } else { sc.ForwardSetState(SCE_C_DEFAULT); } } } else if (sc.state == SCE_C_UUID) { if (sc.ch == '\r' || sc.ch == '\n' || sc.ch == ')') { sc.SetState(SCE_C_DEFAULT); } } // Determine if a new state should be entered. if (sc.state == SCE_C_DEFAULT) { if (sc.Match('@', '\"')) { sc.SetState(SCE_C_VERBATIM); sc.Forward(); } else if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) { if (lastWordWasUUID) { sc.SetState(SCE_C_UUID); lastWordWasUUID = false; } else { sc.SetState(SCE_C_NUMBER); } } else if (IsAWordStart(sc.ch) || (sc.ch == '@')) { if (lastWordWasUUID) { sc.SetState(SCE_C_UUID); lastWordWasUUID = false; } else { sc.SetState(SCE_C_IDENTIFIER); } } else if (sc.Match('/', '*')) { if (sc.Match("/**") || sc.Match("/*!")) { // Support of Qt/Doxygen doc. style noDocChars = 0; sc.SetState(SCE_C_COMMENTDOC); } else { sc.SetState(SCE_C_COMMENT); } sc.Forward(); // Eat the * so it isn't used for the end of the comment } else if (sc.Match('/', '/')) { if (sc.Match("///") || sc.Match("//!")) // Support of Qt/Doxygen doc. style sc.SetState(SCE_C_COMMENTLINEDOC); else sc.SetState(SCE_C_COMMENTLINE); } else if (sc.ch == '/' && IsOKBeforeRE(chPrevNonWhite)) { sc.SetState(SCE_C_REGEX); } else if (sc.ch == '\"') { sc.SetState(SCE_C_STRING); } else if (sc.ch == '\'') { sc.SetState(SCE_C_CHARACTER); } else if (sc.ch == '#' && visibleChars == 0) { // Preprocessor commands are alone on their line sc.SetState(SCE_C_PREPROCESSOR); // Skip whitespace between # and preprocessor word do { sc.Forward(); } while ((sc.ch == ' ') && (sc.ch == '\t') && sc.More()); if (sc.atLineEnd) { sc.SetState(SCE_C_DEFAULT); } } else if (isoperator(static_cast<char>(sc.ch))) { sc.SetState(SCE_C_OPERATOR); } } if (sc.atLineEnd) { // Reset states to begining of colourise so no surprises // if different sets of lines lexed. chPrevNonWhite = ' '; visibleChars = 0; lastWordWasUUID = false; } if (!IsASpace(sc.ch)) { chPrevNonWhite = sc.ch; visibleChars++; } } sc.Complete(); } static void FoldCppDoc(unsigned int startPos, int length, int initStyle, WordList *[], Accessor &styler) { bool foldComment = styler.GetPropertyInt("fold.comment"); bool foldCompact = styler.GetPropertyInt("fold.compact", 1); unsigned int endPos = startPos + length; int visibleChars = 0; int lineCurrent = styler.GetLine(startPos); int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK; int levelCurrent = levelPrev; char chNext = styler[startPos]; int styleNext = styler.StyleAt(startPos); int style = initStyle; for (unsigned int i = startPos; i < endPos; i++) { char ch = chNext; chNext = styler.SafeGetCharAt(i + 1); int stylePrev = style; style = styleNext; styleNext = styler.StyleAt(i + 1); bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n'); if (foldComment && (style == SCE_C_COMMENT || style == SCE_C_COMMENTDOC)) { if (style != stylePrev) { levelCurrent++; } else if ((style != styleNext) && !atEOL) { // Comments don't end at end of line and the next character may be unstyled. levelCurrent--; } } if (style == SCE_C_OPERATOR) { if (ch == '{') { levelCurrent++; } else if (ch == '}') { levelCurrent--; } } if (atEOL) { int lev = levelPrev; if (visibleChars == 0 && foldCompact) lev |= SC_FOLDLEVELWHITEFLAG; if ((levelCurrent > levelPrev) && (visibleChars > 0)) lev |= SC_FOLDLEVELHEADERFLAG; if (lev != styler.LevelAt(lineCurrent)) { styler.SetLevel(lineCurrent, lev); } lineCurrent++; levelPrev = levelCurrent; visibleChars = 0; } if (!isspacechar(ch)) visibleChars++; } // Fill in the real level of the next line, keeping the current flags as they will be filled in later int flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK; styler.SetLevel(lineCurrent, levelPrev | flagsNext); } LexerModule lmCPP(SCLEX_CPP, ColouriseCppDoc, "cpp", FoldCppDoc); LexerModule lmTCL(SCLEX_TCL, ColouriseCppDoc, "tcl", FoldCppDoc);
Fix to ignore '*' before doc comment keywords.
Fix to ignore '*' before doc comment keywords.
C++
isc
timonwong/foo_uie_wsh_panel_mod.scintilla,timonwong/foo_uie_wsh_panel_mod.scintilla,timonwong/foo_uie_wsh_panel_mod.scintilla,timonwong/foo_uie_wsh_panel_mod.scintilla,timonwong/foo_uie_wsh_panel_mod.scintilla,timonwong/foo_uie_wsh_panel_mod.scintilla,timonwong/foo_uie_wsh_panel_mod.scintilla,timonwong/foo_uie_wsh_panel_mod.scintilla
e4b5789e882a1750d5d310733d90aa39025917b5
Interpret/SmartView/TimeZoneDefinition.cpp
Interpret/SmartView/TimeZoneDefinition.cpp
#include <StdAfx.h> #include <Interpret/SmartView/TimeZoneDefinition.h> #include <Interpret/InterpretProp.h> #include <Interpret/ExtraPropTags.h> namespace smartview { void TimeZoneDefinition::Parse() { m_bMajorVersion = m_Parser.Get<BYTE>(); m_bMinorVersion = m_Parser.Get<BYTE>(); m_cbHeader = m_Parser.Get<WORD>(); m_wReserved = m_Parser.Get<WORD>(); m_cchKeyName = m_Parser.Get<WORD>(); m_szKeyName = m_Parser.GetStringW(m_cchKeyName); m_cRules = m_Parser.Get<WORD>(); if (m_cRules && m_cRules < _MaxEntriesSmall) { m_lpTZRule.reserve(m_cRules); for (ULONG i = 0; i < m_cRules; i++) { TZRule tzRule; tzRule.bMajorVersion = m_Parser.Get<BYTE>(); tzRule.bMinorVersion = m_Parser.Get<BYTE>(); tzRule.wReserved = m_Parser.Get<WORD>(); tzRule.wTZRuleFlags = m_Parser.Get<WORD>(); tzRule.wYear = m_Parser.Get<WORD>(); tzRule.X = m_Parser.GetBYTES(14); tzRule.lBias = m_Parser.Get<DWORD>(); tzRule.lStandardBias = m_Parser.Get<DWORD>(); tzRule.lDaylightBias = m_Parser.Get<DWORD>(); tzRule.stStandardDate.wYear = m_Parser.Get<WORD>(); tzRule.stStandardDate.wMonth = m_Parser.Get<WORD>(); tzRule.stStandardDate.wDayOfWeek = m_Parser.Get<WORD>(); tzRule.stStandardDate.wDay = m_Parser.Get<WORD>(); tzRule.stStandardDate.wHour = m_Parser.Get<WORD>(); tzRule.stStandardDate.wMinute = m_Parser.Get<WORD>(); tzRule.stStandardDate.wSecond = m_Parser.Get<WORD>(); tzRule.stStandardDate.wMilliseconds = m_Parser.Get<WORD>(); tzRule.stDaylightDate.wYear = m_Parser.Get<WORD>(); tzRule.stDaylightDate.wMonth = m_Parser.Get<WORD>(); tzRule.stDaylightDate.wDayOfWeek = m_Parser.Get<WORD>(); tzRule.stDaylightDate.wDay = m_Parser.Get<WORD>(); tzRule.stDaylightDate.wHour = m_Parser.Get<WORD>(); tzRule.stDaylightDate.wMinute = m_Parser.Get<WORD>(); tzRule.stDaylightDate.wSecond = m_Parser.Get<WORD>(); tzRule.stDaylightDate.wMilliseconds = m_Parser.Get<WORD>(); m_lpTZRule.push_back(tzRule); } } } void TimeZoneDefinition::ParseBlocks() { setRoot(L"Time Zone Definition: \r\n"); addBlock(m_bMajorVersion, L"bMajorVersion = 0x%1!02X! (%1!d!)\r\n", m_bMajorVersion.getData()); addBlock(m_bMinorVersion, L"bMinorVersion = 0x%1!02X! (%1!d!)\r\n", m_bMinorVersion.getData()); addBlock(m_cbHeader, L"cbHeader = 0x%1!04X! (%1!d!)\r\n", m_cbHeader.getData()); addBlock(m_wReserved, L"wReserved = 0x%1!04X! (%1!d!)\r\n", m_wReserved.getData()); addBlock(m_cchKeyName, L"cchKeyName = 0x%1!04X! (%1!d!)\r\n", m_cchKeyName.getData()); addBlock(m_szKeyName, L"szKeyName = %1!ws!\r\n", m_szKeyName.c_str()); addBlock(m_cRules, L"cRules = 0x%1!04X! (%1!d!)", m_cRules.getData()); for (WORD i = 0; i < m_lpTZRule.size(); i++) { terminateBlock(); addBlankLine(); addBlock( m_lpTZRule[i].bMajorVersion, L"TZRule[0x%1!X!].bMajorVersion = 0x%2!02X! (%2!d!)\r\n", i, m_lpTZRule[i].bMajorVersion.getData()); addBlock( m_lpTZRule[i].bMinorVersion, L"TZRule[0x%1!X!].bMinorVersion = 0x%2!02X! (%2!d!)\r\n", i, m_lpTZRule[i].bMinorVersion.getData()); addBlock( m_lpTZRule[i].wReserved, L"TZRule[0x%1!X!].wReserved = 0x%2!04X! (%2!d!)\r\n", i, m_lpTZRule[i].wReserved.getData()); addBlock( m_lpTZRule[i].wTZRuleFlags, L"TZRule[0x%1!X!].wTZRuleFlags = 0x%2!04X! = %3!ws!\r\n", i, m_lpTZRule[i].wTZRuleFlags.getData(), interpretprop::InterpretFlags(flagTZRule, m_lpTZRule[i].wTZRuleFlags).c_str()); addBlock( m_lpTZRule[i].wTZRuleFlags, L"TZRule[0x%1!X!].wYear = 0x%2!04X! (%2!d!)\r\n", i, m_lpTZRule[i].wYear.getData()); addHeader(L"TZRule[0x%1!X!].X = ", i); addBlock(m_lpTZRule[i].X); terminateBlock(); addBlock( m_lpTZRule[i].lBias, L"TZRule[0x%1!X!].lBias = 0x%2!08X! (%2!d!)\r\n", i, m_lpTZRule[i].lBias.getData()); addBlock( m_lpTZRule[i].lStandardBias, L"TZRule[0x%1!X!].lStandardBias = 0x%2!08X! (%2!d!)\r\n", i, m_lpTZRule[i].lStandardBias.getData()); addBlock( m_lpTZRule[i].lDaylightBias, L"TZRule[0x%1!X!].lDaylightBias = 0x%2!08X! (%2!d!)\r\n", i, m_lpTZRule[i].lDaylightBias.getData()); addBlankLine(); addBlock( m_lpTZRule[i].stStandardDate.wYear, L"TZRule[0x%1!X!].stStandardDate.wYear = 0x%2!X! (%2!d!)\r\n", i, m_lpTZRule[i].stStandardDate.wYear.getData()); addBlock( m_lpTZRule[i].stStandardDate.wMonth, L"TZRule[0x%1!X!].stStandardDate.wMonth = 0x%2!X! (%2!d!)\r\n", i, m_lpTZRule[i].stStandardDate.wMonth.getData()); addBlock( m_lpTZRule[i].stStandardDate.wDayOfWeek, L"TZRule[0x%1!X!].stStandardDate.wDayOfWeek = 0x%2!X! (%2!d!)\r\n", i, m_lpTZRule[i].stStandardDate.wDayOfWeek.getData()); addBlock( m_lpTZRule[i].stStandardDate.wDay, L"TZRule[0x%1!X!].stStandardDate.wDay = 0x%2!X! (%2!d!)\r\n", i, m_lpTZRule[i].stStandardDate.wDay.getData()); addBlock( m_lpTZRule[i].stStandardDate.wHour, L"TZRule[0x%1!X!].stStandardDate.wHour = 0x%2!X! (%2!d!)\r\n", i, m_lpTZRule[i].stStandardDate.wHour.getData()); addBlock( m_lpTZRule[i].stStandardDate.wMinute, L"TZRule[0x%1!X!].stStandardDate.wMinute = 0x%2!X! (%2!d!)\r\n", i, m_lpTZRule[i].stStandardDate.wMinute.getData()); addBlock( m_lpTZRule[i].stStandardDate.wSecond, L"TZRule[0x%1!X!].stStandardDate.wSecond = 0x%2!X! (%2!d!)\r\n", i, m_lpTZRule[i].stStandardDate.wSecond.getData()); addBlock( m_lpTZRule[i].stStandardDate.wMilliseconds, L"TZRule[0x%1!X!].stStandardDate.wMilliseconds = 0x%2!X! (%2!d!)\r\n", i, m_lpTZRule[i].stStandardDate.wMilliseconds.getData()); addBlankLine(); addBlock( m_lpTZRule[i].stDaylightDate.wYear, L"TZRule[0x%1!X!].stDaylightDate.wYear = 0x%2!X! (%2!d!)\r\n", i, m_lpTZRule[i].stDaylightDate.wYear.getData()); addBlock( m_lpTZRule[i].stDaylightDate.wMonth, L"TZRule[0x%1!X!].stDaylightDate.wMonth = 0x%2!X! (%2!d!)\r\n", i, m_lpTZRule[i].stDaylightDate.wMonth.getData()); addBlock( m_lpTZRule[i].stDaylightDate.wDayOfWeek, L"TZRule[0x%1!X!].stDaylightDate.wDayOfWeek = 0x%2!X! (%2!d!)\r\n", i, m_lpTZRule[i].stDaylightDate.wDayOfWeek.getData()); addBlock( m_lpTZRule[i].stDaylightDate.wDay, L"TZRule[0x%1!X!].stDaylightDate.wDay = 0x%2!X! (%2!d!)\r\n", i, m_lpTZRule[i].stDaylightDate.wDay.getData()); addBlock( m_lpTZRule[i].stDaylightDate.wHour, L"TZRule[0x%1!X!].stDaylightDate.wHour = 0x%2!X! (%2!d!)\r\n", i, m_lpTZRule[i].stDaylightDate.wHour.getData()); addBlock( m_lpTZRule[i].stDaylightDate.wMinute, L"TZRule[0x%1!X!].stDaylightDate.wMinute = 0x%2!X! (%2!d!)\r\n", i, m_lpTZRule[i].stDaylightDate.wMinute.getData()); addBlock( m_lpTZRule[i].stDaylightDate.wSecond, L"TZRule[0x%1!X!].stDaylightDate.wSecond = 0x%2!X! (%2!d!)\r\n", i, m_lpTZRule[i].stDaylightDate.wSecond.getData()); addBlock( m_lpTZRule[i].stDaylightDate.wMilliseconds, L"TZRule[0x%1!X!].stDaylightDate.wMilliseconds = 0x%2!X! (%2!d!)", i, m_lpTZRule[i].stDaylightDate.wMilliseconds.getData()); } } } // namespace smartview
#include <StdAfx.h> #include <Interpret/SmartView/TimeZoneDefinition.h> #include <Interpret/InterpretProp.h> #include <Interpret/ExtraPropTags.h> namespace smartview { void TimeZoneDefinition::Parse() { m_bMajorVersion = m_Parser.Get<BYTE>(); m_bMinorVersion = m_Parser.Get<BYTE>(); m_cbHeader = m_Parser.Get<WORD>(); m_wReserved = m_Parser.Get<WORD>(); m_cchKeyName = m_Parser.Get<WORD>(); m_szKeyName = m_Parser.GetStringW(m_cchKeyName); m_cRules = m_Parser.Get<WORD>(); if (m_cRules && m_cRules < _MaxEntriesSmall) { m_lpTZRule.reserve(m_cRules); for (ULONG i = 0; i < m_cRules; i++) { TZRule tzRule; tzRule.bMajorVersion = m_Parser.Get<BYTE>(); tzRule.bMinorVersion = m_Parser.Get<BYTE>(); tzRule.wReserved = m_Parser.Get<WORD>(); tzRule.wTZRuleFlags = m_Parser.Get<WORD>(); tzRule.wYear = m_Parser.Get<WORD>(); tzRule.X = m_Parser.GetBYTES(14); tzRule.lBias = m_Parser.Get<DWORD>(); tzRule.lStandardBias = m_Parser.Get<DWORD>(); tzRule.lDaylightBias = m_Parser.Get<DWORD>(); tzRule.stStandardDate.wYear = m_Parser.Get<WORD>(); tzRule.stStandardDate.wMonth = m_Parser.Get<WORD>(); tzRule.stStandardDate.wDayOfWeek = m_Parser.Get<WORD>(); tzRule.stStandardDate.wDay = m_Parser.Get<WORD>(); tzRule.stStandardDate.wHour = m_Parser.Get<WORD>(); tzRule.stStandardDate.wMinute = m_Parser.Get<WORD>(); tzRule.stStandardDate.wSecond = m_Parser.Get<WORD>(); tzRule.stStandardDate.wMilliseconds = m_Parser.Get<WORD>(); tzRule.stDaylightDate.wYear = m_Parser.Get<WORD>(); tzRule.stDaylightDate.wMonth = m_Parser.Get<WORD>(); tzRule.stDaylightDate.wDayOfWeek = m_Parser.Get<WORD>(); tzRule.stDaylightDate.wDay = m_Parser.Get<WORD>(); tzRule.stDaylightDate.wHour = m_Parser.Get<WORD>(); tzRule.stDaylightDate.wMinute = m_Parser.Get<WORD>(); tzRule.stDaylightDate.wSecond = m_Parser.Get<WORD>(); tzRule.stDaylightDate.wMilliseconds = m_Parser.Get<WORD>(); m_lpTZRule.push_back(tzRule); } } } void TimeZoneDefinition::ParseBlocks() { setRoot(L"Time Zone Definition: \r\n"); addBlock(m_bMajorVersion, L"bMajorVersion = 0x%1!02X! (%1!d!)\r\n", m_bMajorVersion.getData()); addBlock(m_bMinorVersion, L"bMinorVersion = 0x%1!02X! (%1!d!)\r\n", m_bMinorVersion.getData()); addBlock(m_cbHeader, L"cbHeader = 0x%1!04X! (%1!d!)\r\n", m_cbHeader.getData()); addBlock(m_wReserved, L"wReserved = 0x%1!04X! (%1!d!)\r\n", m_wReserved.getData()); addBlock(m_cchKeyName, L"cchKeyName = 0x%1!04X! (%1!d!)\r\n", m_cchKeyName.getData()); addBlock(m_szKeyName, L"szKeyName = %1!ws!\r\n", m_szKeyName.c_str()); addBlock(m_cRules, L"cRules = 0x%1!04X! (%1!d!)", m_cRules.getData()); for (WORD i = 0; i < m_lpTZRule.size(); i++) { terminateBlock(); addBlankLine(); addBlock( m_lpTZRule[i].bMajorVersion, L"TZRule[0x%1!X!].bMajorVersion = 0x%2!02X! (%2!d!)\r\n", i, m_lpTZRule[i].bMajorVersion.getData()); addBlock( m_lpTZRule[i].bMinorVersion, L"TZRule[0x%1!X!].bMinorVersion = 0x%2!02X! (%2!d!)\r\n", i, m_lpTZRule[i].bMinorVersion.getData()); addBlock( m_lpTZRule[i].wReserved, L"TZRule[0x%1!X!].wReserved = 0x%2!04X! (%2!d!)\r\n", i, m_lpTZRule[i].wReserved.getData()); addBlock( m_lpTZRule[i].wTZRuleFlags, L"TZRule[0x%1!X!].wTZRuleFlags = 0x%2!04X! = %3!ws!\r\n", i, m_lpTZRule[i].wTZRuleFlags.getData(), interpretprop::InterpretFlags(flagTZRule, m_lpTZRule[i].wTZRuleFlags).c_str()); addBlock( m_lpTZRule[i].wYear, L"TZRule[0x%1!X!].wYear = 0x%2!04X! (%2!d!)\r\n", i, m_lpTZRule[i].wYear.getData()); addHeader(L"TZRule[0x%1!X!].X = ", i); addBlock(m_lpTZRule[i].X); terminateBlock(); addBlock( m_lpTZRule[i].lBias, L"TZRule[0x%1!X!].lBias = 0x%2!08X! (%2!d!)\r\n", i, m_lpTZRule[i].lBias.getData()); addBlock( m_lpTZRule[i].lStandardBias, L"TZRule[0x%1!X!].lStandardBias = 0x%2!08X! (%2!d!)\r\n", i, m_lpTZRule[i].lStandardBias.getData()); addBlock( m_lpTZRule[i].lDaylightBias, L"TZRule[0x%1!X!].lDaylightBias = 0x%2!08X! (%2!d!)\r\n", i, m_lpTZRule[i].lDaylightBias.getData()); addBlankLine(); addBlock( m_lpTZRule[i].stStandardDate.wYear, L"TZRule[0x%1!X!].stStandardDate.wYear = 0x%2!X! (%2!d!)\r\n", i, m_lpTZRule[i].stStandardDate.wYear.getData()); addBlock( m_lpTZRule[i].stStandardDate.wMonth, L"TZRule[0x%1!X!].stStandardDate.wMonth = 0x%2!X! (%2!d!)\r\n", i, m_lpTZRule[i].stStandardDate.wMonth.getData()); addBlock( m_lpTZRule[i].stStandardDate.wDayOfWeek, L"TZRule[0x%1!X!].stStandardDate.wDayOfWeek = 0x%2!X! (%2!d!)\r\n", i, m_lpTZRule[i].stStandardDate.wDayOfWeek.getData()); addBlock( m_lpTZRule[i].stStandardDate.wDay, L"TZRule[0x%1!X!].stStandardDate.wDay = 0x%2!X! (%2!d!)\r\n", i, m_lpTZRule[i].stStandardDate.wDay.getData()); addBlock( m_lpTZRule[i].stStandardDate.wHour, L"TZRule[0x%1!X!].stStandardDate.wHour = 0x%2!X! (%2!d!)\r\n", i, m_lpTZRule[i].stStandardDate.wHour.getData()); addBlock( m_lpTZRule[i].stStandardDate.wMinute, L"TZRule[0x%1!X!].stStandardDate.wMinute = 0x%2!X! (%2!d!)\r\n", i, m_lpTZRule[i].stStandardDate.wMinute.getData()); addBlock( m_lpTZRule[i].stStandardDate.wSecond, L"TZRule[0x%1!X!].stStandardDate.wSecond = 0x%2!X! (%2!d!)\r\n", i, m_lpTZRule[i].stStandardDate.wSecond.getData()); addBlock( m_lpTZRule[i].stStandardDate.wMilliseconds, L"TZRule[0x%1!X!].stStandardDate.wMilliseconds = 0x%2!X! (%2!d!)\r\n", i, m_lpTZRule[i].stStandardDate.wMilliseconds.getData()); addBlankLine(); addBlock( m_lpTZRule[i].stDaylightDate.wYear, L"TZRule[0x%1!X!].stDaylightDate.wYear = 0x%2!X! (%2!d!)\r\n", i, m_lpTZRule[i].stDaylightDate.wYear.getData()); addBlock( m_lpTZRule[i].stDaylightDate.wMonth, L"TZRule[0x%1!X!].stDaylightDate.wMonth = 0x%2!X! (%2!d!)\r\n", i, m_lpTZRule[i].stDaylightDate.wMonth.getData()); addBlock( m_lpTZRule[i].stDaylightDate.wDayOfWeek, L"TZRule[0x%1!X!].stDaylightDate.wDayOfWeek = 0x%2!X! (%2!d!)\r\n", i, m_lpTZRule[i].stDaylightDate.wDayOfWeek.getData()); addBlock( m_lpTZRule[i].stDaylightDate.wDay, L"TZRule[0x%1!X!].stDaylightDate.wDay = 0x%2!X! (%2!d!)\r\n", i, m_lpTZRule[i].stDaylightDate.wDay.getData()); addBlock( m_lpTZRule[i].stDaylightDate.wHour, L"TZRule[0x%1!X!].stDaylightDate.wHour = 0x%2!X! (%2!d!)\r\n", i, m_lpTZRule[i].stDaylightDate.wHour.getData()); addBlock( m_lpTZRule[i].stDaylightDate.wMinute, L"TZRule[0x%1!X!].stDaylightDate.wMinute = 0x%2!X! (%2!d!)\r\n", i, m_lpTZRule[i].stDaylightDate.wMinute.getData()); addBlock( m_lpTZRule[i].stDaylightDate.wSecond, L"TZRule[0x%1!X!].stDaylightDate.wSecond = 0x%2!X! (%2!d!)\r\n", i, m_lpTZRule[i].stDaylightDate.wSecond.getData()); addBlock( m_lpTZRule[i].stDaylightDate.wMilliseconds, L"TZRule[0x%1!X!].stDaylightDate.wMilliseconds = 0x%2!X! (%2!d!)", i, m_lpTZRule[i].stDaylightDate.wMilliseconds.getData()); } } } // namespace smartview
Fix timezone wYear
Fix timezone wYear
C++
mit
stephenegriffin/mfcmapi,stephenegriffin/mfcmapi,stephenegriffin/mfcmapi
002dd99c6aa83cd68106c4e048210c47075310d9
src/Mirror.cpp
src/Mirror.cpp
#include "Mirror.hpp" #include "tcp/Server.hpp" #include <onions-common/containers/Cache.hpp> #include <onions-common/Log.hpp> #include <onions-common/Config.hpp> #include <onions-common/crypto/ed25519.h> #include <botan/base64.h> #include <botan/pubkey.h> #include <boost/make_shared.hpp> #include <thread> #include <fstream> #include <pwd.h> typedef boost::exception_detail::clone_impl< boost::exception_detail::error_info_injector<boost::system::system_error>> BoostSystemError; void Mirror::startServer(const std::string& bindIP, ushort socksPort, bool isQNode) { isQuorumNode_ = isQNode; resumeState(); if (isQNode) Log::get().notice("Running as a Quorum server."); else Log::get().notice("Running as normal server."); // auto mt = std::make_shared<MerkleTree>(Cache::get().getSortedList()); try { if (!isQNode) subscribeToQuorum(socksPort); Server s(bindIP); s.start(); } catch (const BoostSystemError& ex) { Log::get().error(ex.what()); } } void Mirror::subscribeForRecords(Session* session) { waitingForRecords_.push_back(session); } bool Mirror::processNewRecord(int sessionID, const RecordPtr& record) { if (!Cache::add(record)) return false; // if already exists in cache page_->addRecord(record); tellSubscribers(record); merkleTree_ = std::make_shared<MerkleTree>(Cache::getSortedList()); if (!isQuorumNode_ && sessionID == qSession_->getID()) { Log::get().notice("Record came from Quorum. Requesting signature."); qRootSig_ = fetchQuorumRootSignature(); } return true; } void Mirror::tellSubscribers(const RecordPtr& record) { Log::get().notice("Broadcasting Record to " + std::to_string(waitingForRecords_.size()) + " servers..."); // send the Record Json::Value rEvent; rEvent["type"] = "putRecord"; rEvent["value"] = record->asJSON(); for (auto session : waitingForRecords_) if (session) session->asyncWrite(rEvent); waitingForRecords_.clear(); Log::get().notice("Broadcast complete."); } std::string Mirror::signTransmission(const Json::Value& trans) const { ED_SIGNATURE signature; std::string data = trans["type"].toStyledString() + trans["value"].toStyledString(); ed25519_sign(reinterpret_cast<const uint8_t*>(data.c_str()), data.length(), keypair_.first.data(), keypair_.second.data(), signature.data()); return Botan::base64_encode(signature.data(), signature.size()); } Json::Value Mirror::getRootSignature() const { Json::Value sigObj; sigObj["count"] = std::to_string(Cache::getRecordCount()); sigObj["signature"] = isQuorumNode_ ? signMerkleRoot() : Botan::base64_encode(qRootSig_.data(), qRootSig_.size()); Json::Value response; response["type"] = "merkleSignature"; response["value"] = sigObj; return response; } ED_SIGNATURE Mirror::fetchQuorumRootSignature() { ED_SIGNATURE sig; if (isQuorumNode_) Log::get().error("Quorum nodes cannot _yet_ fetch root signatures."); auto response = qStream_->sendReceive("getRootSignature", ""); if (response["type"] == "error") { Log::get().warn("Error when getting root signature from Quorum node: " + response["value"].asString()); } else { Json::Value sigObj = response["value"]; if (!sigObj.isMember("signature") || !sigObj.isMember("count")) Log::get().error("Invalid root signature response from server."); // check number of Records if (sigObj["count"].asInt() != Cache::getRecordCount()) Log::get().warn("Quorum has " + sigObj["count"].asString() + " records, we have " + std::to_string(Cache::getRecordCount())); // todo: we are out of date // decode signature if (Botan::base64_decode(sig.data(), sigObj["signature"].asString()) != sig.size()) Log::get().warn("Invalid root signature length from Quorum node."); // get public key ED_KEY qPubKey; static auto Q_KEY = Config::getQuorumNode()[0]["key"].asString(); if (Botan::base64_decode(qPubKey.data(), Q_KEY) != Const::ED25519_KEY_LEN) Log::get().warn("Quorum node key has an invalid length."); // check signature int status = ed25519_sign_open(merkleTree_->getRoot().data(), Const::SHA384_LEN, qPubKey.data(), sig.data()); if (status == 0) Log::get().notice("Valid Ed25519 Quorum signature on root."); else if (status == 1) Log::get().warn("Invalid Ed25519 Quorum signature on root."); else Log::get().warn("General Ed25519 signature failure on root."); } return sig; } std::string Mirror::signMerkleRoot() const { ED_SIGNATURE signature; ed25519_sign(merkleTree_->getRoot().data(), Const::SHA384_LEN, keypair_.first.data(), keypair_.second.data(), signature.data()); return Botan::base64_encode(signature.data(), signature.size()); } std::string Mirror::getWorkingDir() { std::string workingDir(getpwuid(getuid())->pw_dir); workingDir += "/.OnioNS/"; if (mkdir(workingDir.c_str(), 0750) == 0) Log::get().notice("Working directory successfully created."); return workingDir; } std::shared_ptr<MerkleTree> Mirror::getMerkleTree() const { return merkleTree_; } // ***************************** PRIVATE METHODS ***************************** void Mirror::resumeState() { Log::get().notice("Resuming state... "); loadKeyPair(); loadPages(); Cache::add(page_->getRecords()); Log::get().notice("State successfully resumed."); } void Mirror::loadPages() { Log::get().notice("Loading Pagechain from file..."); std::ifstream pageFile; pageFile.open(getWorkingDir() + "pagechain.json", std::fstream::in); if (pageFile.is_open()) { Json::Value obj; pageFile >> obj; page_ = std::make_shared<Page>(obj); if (!std::equal(keypair_.second.begin(), keypair_.second.end(), page_->getOwnerPublicKey().data())) Log::get().error("Mismatched Page public key, does not match keyfile."); Log::get().notice("Pagechain successfully loaded."); } else { Log::get().warn("Pagechain file does not exist."); SHA384_HASH latestRandom = {7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7}; // todo page_ = std::make_shared<Page>(latestRandom, keypair_.second); std::fstream outFile(getWorkingDir() + "pagechain.json", std::fstream::out); outFile << page_->toString(); outFile.close(); Log::get().notice("Blank Page successfully saved to disk."); } } void Mirror::loadKeyPair() { Log::get().notice("Loading Ed25519 key..."); ED_KEY privateKey = loadSecretKey(getWorkingDir()); ED_KEY publicKey; ed25519_public_key pk; ed25519_publickey(privateKey.data(), pk); memcpy(publicKey.data(), pk, Const::ED25519_KEY_LEN); keypair_ = std::make_pair(privateKey, publicKey); Log::get().notice("Server public key: " + Botan::base64_encode(pk, Const::ED25519_KEY_LEN)); } ED_KEY Mirror::loadSecretKey(const std::string& workingDir) { // load private key from file, or generate and save a new one ED_KEY sk; std::ifstream keyFile; keyFile.open(workingDir + "ed25519.key", std::fstream::in); if (keyFile.is_open()) { Json::Value obj; keyFile >> obj; if (Botan::base64_decode(sk.data(), obj["key"].asString()) != sk.size()) Log::get().error("Error decoding Ed25519 keyfile: invalid size."); Log::get().notice("Ed25519 key successfully loaded."); } else { Log::get().notice("Keyfile does not exist. Generating new key..."); Botan::AutoSeeded_RNG rng; rng.randomize(sk.data(), Const::ED25519_KEY_LEN); Json::Value obj; obj["key"] = Botan::base64_encode(sk.data(), Const::ED25519_KEY_LEN); Json::FastWriter writer; std::fstream keyOutFile(workingDir + "ed25519.key", std::fstream::out); keyOutFile << writer.write(obj); keyOutFile.close(); Log::get().notice("Ed25519 key successfully saved to disk."); } return sk; } void Mirror::subscribeToQuorum(ushort socksPort) { const static int RECONNECT_DELAY = 20; const static auto REMOTE_PORT = Const::SERVER_PORT; const auto Q_NODE = Config::getQuorumNode()[0]; const auto Q_ONION = Q_NODE["addr"].asString(); const auto Q_KEY = Q_NODE["key"].asString(); while (true) // reestablish lost network connection { try { Log::get().notice("Connecting to Quorum node..."); qStream_ = std::make_shared<AuthenticatedStream>( "127.0.0.1", socksPort, Q_ONION, REMOTE_PORT, Q_KEY); } catch (const std::runtime_error& re) { Log::get().warn("Failed to connect, " + std::string(re.what())); std::this_thread::sleep_for(std::chrono::seconds(RECONNECT_DELAY)); continue; } try { Log::get().notice("Subscribing to Quorum node for events..."); // todo, are we even using authStream? // we are just using TorStream to tunnel through SOCKS5! qStream_->getIO().reset(); // reset for new asynchronous calls qSession_ = boost::make_shared<Session>(qStream_->getSocket(), -1); qSession_->asyncWrite("waitForRecord", ""); // this calls asyncRead qStream_->getIO().run(); // run asynchronous calls } catch (const BoostSystemError& ex) { Log::get().warn("Quorum connection error, " + std::string(ex.what())); } catch (const std::runtime_error& re) { Log::get().warn("Lost Quorum connection, " + std::string(re.what())); } std::this_thread::sleep_for(std::chrono::seconds(RECONNECT_DELAY)); continue; } }
#include "Mirror.hpp" #include "tcp/Server.hpp" #include <onions-common/containers/Cache.hpp> #include <onions-common/Log.hpp> #include <onions-common/Config.hpp> #include <onions-common/crypto/ed25519.h> #include <botan/base64.h> #include <botan/pubkey.h> #include <boost/make_shared.hpp> #include <thread> #include <fstream> #include <pwd.h> typedef boost::exception_detail::clone_impl< boost::exception_detail::error_info_injector<boost::system::system_error>> BoostSystemError; void Mirror::startServer(const std::string& bindIP, ushort socksPort, bool isQNode) { isQuorumNode_ = isQNode; resumeState(); // todo: differentiate between loadState and resumeState if (isQNode) Log::get().notice("Running as a Quorum server."); else Log::get().notice("Running as normal server."); try { if (!isQNode) { std::thread t(std::bind( [&](ushort sp) { subscribeToQuorum(socksPort); }, socksPort)); t.detach(); } Server s(bindIP); s.start(); } catch (const BoostSystemError& ex) { Log::get().error(ex.what()); } } void Mirror::subscribeForRecords(Session* session) { waitingForRecords_.push_back(session); } bool Mirror::processNewRecord(int sessionID, const RecordPtr& record) { if (!Cache::add(record)) return false; // if already exists in cache page_->addRecord(record); tellSubscribers(record); merkleTree_ = std::make_shared<MerkleTree>(Cache::getSortedList()); if (!isQuorumNode_ && sessionID == qSession_->getID()) { Log::get().notice("Record came from Quorum. Requesting signature."); qRootSig_ = fetchQuorumRootSignature(); } return true; } void Mirror::tellSubscribers(const RecordPtr& record) { Log::get().notice("Broadcasting Record to " + std::to_string(waitingForRecords_.size()) + " servers..."); // send the Record Json::Value rEvent; rEvent["type"] = "putRecord"; rEvent["value"] = record->asJSON(); for (auto session : waitingForRecords_) if (session) session->asyncWrite(rEvent); waitingForRecords_.clear(); Log::get().notice("Broadcast complete."); } std::string Mirror::signTransmission(const Json::Value& trans) const { ED_SIGNATURE signature; std::string data = trans["type"].toStyledString() + trans["value"].toStyledString(); ed25519_sign(reinterpret_cast<const uint8_t*>(data.c_str()), data.length(), keypair_.first.data(), keypair_.second.data(), signature.data()); return Botan::base64_encode(signature.data(), signature.size()); } Json::Value Mirror::getRootSignature() const { Json::Value sigObj; sigObj["count"] = std::to_string(Cache::getRecordCount()); sigObj["signature"] = isQuorumNode_ ? signMerkleRoot() : Botan::base64_encode(qRootSig_.data(), qRootSig_.size()); Json::Value response; response["type"] = "merkleSignature"; response["value"] = sigObj; return response; } ED_SIGNATURE Mirror::fetchQuorumRootSignature() { ED_SIGNATURE sig; if (isQuorumNode_) Log::get().error("Quorum nodes cannot _yet_ fetch root signatures."); auto response = qStream_->sendReceive("getRootSignature", ""); if (response["type"] == "error") { Log::get().warn("Error when getting root signature from Quorum node: " + response["value"].asString()); } else { Json::Value sigObj = response["value"]; if (!sigObj.isMember("signature") || !sigObj.isMember("count")) Log::get().error("Invalid root signature response from server."); // check number of Records if (sigObj["count"].asInt() != Cache::getRecordCount()) Log::get().warn("Quorum has " + sigObj["count"].asString() + " records, we have " + std::to_string(Cache::getRecordCount())); // todo: we are out of date // decode signature if (Botan::base64_decode(sig.data(), sigObj["signature"].asString()) != sig.size()) Log::get().warn("Invalid root signature length from Quorum node."); // get public key ED_KEY qPubKey; static auto Q_KEY = Config::getQuorumNode()[0]["key"].asString(); if (Botan::base64_decode(qPubKey.data(), Q_KEY) != Const::ED25519_KEY_LEN) Log::get().warn("Quorum node key has an invalid length."); // check signature int status = ed25519_sign_open(merkleTree_->getRoot().data(), Const::SHA384_LEN, qPubKey.data(), sig.data()); if (status == 0) Log::get().notice("Valid Ed25519 Quorum signature on root."); else if (status == 1) Log::get().warn("Invalid Ed25519 Quorum signature on root."); else Log::get().warn("General Ed25519 signature failure on root."); } return sig; } std::string Mirror::signMerkleRoot() const { ED_SIGNATURE signature; ed25519_sign(merkleTree_->getRoot().data(), Const::SHA384_LEN, keypair_.first.data(), keypair_.second.data(), signature.data()); return Botan::base64_encode(signature.data(), signature.size()); } std::string Mirror::getWorkingDir() { std::string workingDir(getpwuid(getuid())->pw_dir); workingDir += "/.OnioNS/"; if (mkdir(workingDir.c_str(), 0750) == 0) Log::get().notice("Working directory successfully created."); return workingDir; } std::shared_ptr<MerkleTree> Mirror::getMerkleTree() const { return merkleTree_; } // ***************************** PRIVATE METHODS ***************************** void Mirror::resumeState() { Log::get().notice("Resuming state... "); loadKeyPair(); loadPages(); Cache::add(page_->getRecords()); Log::get().notice("State successfully resumed."); } void Mirror::loadPages() { Log::get().notice("Loading Pagechain from file..."); std::ifstream pageFile; pageFile.open(getWorkingDir() + "pagechain.json", std::fstream::in); if (pageFile.is_open()) { Json::Value obj; pageFile >> obj; page_ = std::make_shared<Page>(obj); if (!std::equal(keypair_.second.begin(), keypair_.second.end(), page_->getOwnerPublicKey().data())) Log::get().error("Mismatched Page public key, does not match keyfile."); Log::get().notice("Pagechain successfully loaded."); } else { Log::get().warn("Pagechain file does not exist."); SHA384_HASH latestRandom = {7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7}; // todo page_ = std::make_shared<Page>(latestRandom, keypair_.second); std::fstream outFile(getWorkingDir() + "pagechain.json", std::fstream::out); outFile << page_->toString(); outFile.close(); Log::get().notice("Blank Page successfully saved to disk."); } } void Mirror::loadKeyPair() { Log::get().notice("Loading Ed25519 key..."); ED_KEY privateKey = loadSecretKey(getWorkingDir()); ED_KEY publicKey; ed25519_public_key pk; ed25519_publickey(privateKey.data(), pk); memcpy(publicKey.data(), pk, Const::ED25519_KEY_LEN); keypair_ = std::make_pair(privateKey, publicKey); Log::get().notice("Server public key: " + Botan::base64_encode(pk, Const::ED25519_KEY_LEN)); } ED_KEY Mirror::loadSecretKey(const std::string& workingDir) { // load private key from file, or generate and save a new one ED_KEY sk; std::ifstream keyFile; keyFile.open(workingDir + "ed25519.key", std::fstream::in); if (keyFile.is_open()) { Json::Value obj; keyFile >> obj; if (Botan::base64_decode(sk.data(), obj["key"].asString()) != sk.size()) Log::get().error("Error decoding Ed25519 keyfile: invalid size."); Log::get().notice("Ed25519 key successfully loaded."); } else { Log::get().notice("Keyfile does not exist. Generating new key..."); Botan::AutoSeeded_RNG rng; rng.randomize(sk.data(), Const::ED25519_KEY_LEN); Json::Value obj; obj["key"] = Botan::base64_encode(sk.data(), Const::ED25519_KEY_LEN); Json::FastWriter writer; std::fstream keyOutFile(workingDir + "ed25519.key", std::fstream::out); keyOutFile << writer.write(obj); keyOutFile.close(); Log::get().notice("Ed25519 key successfully saved to disk."); } return sk; } void Mirror::subscribeToQuorum(ushort socksPort) { const static int RECONNECT_DELAY = 20; const static auto REMOTE_PORT = Const::SERVER_PORT; const auto Q_NODE = Config::getQuorumNode()[0]; const auto Q_ONION = Q_NODE["addr"].asString(); const auto Q_KEY = Q_NODE["key"].asString(); while (true) // reestablish lost network connection { try { Log::get().notice("Connecting to Quorum node..."); qStream_ = std::make_shared<AuthenticatedStream>( "127.0.0.1", socksPort, Q_ONION, REMOTE_PORT, Q_KEY); } catch (const std::runtime_error& re) { Log::get().warn("Failed to connect, " + std::string(re.what())); std::this_thread::sleep_for(std::chrono::seconds(RECONNECT_DELAY)); continue; } try { Log::get().notice("Subscribing to Quorum node for events..."); // todo, are we even using authStream? // we are just using TorStream to tunnel through SOCKS5! qStream_->getIO().reset(); // reset for new asynchronous calls qSession_ = boost::make_shared<Session>(qStream_->getSocket(), -1); qSession_->asyncWrite("waitForRecord", ""); // this calls asyncRead qStream_->getIO().run(); // run asynchronous calls } catch (const BoostSystemError& ex) { Log::get().warn("Quorum connection error, " + std::string(ex.what())); } catch (const std::runtime_error& re) { Log::get().warn("Lost Quorum connection, " + std::string(re.what())); } std::this_thread::sleep_for(std::chrono::seconds(RECONNECT_DELAY)); continue; } }
Fix #81
Fix #81
C++
bsd-3-clause
Jesse-V/OnioNS-server,Jesse-V/OnioNS-server
f80978dbd7f2b1096c0b354413c013fc51eb25b3
src/bitset.hpp
src/bitset.hpp
/** * Copyright 2020 Tom van Dijk * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef BITSET_HPP #define BITSET_HPP #include <libpopcnt.h> namespace pg { class bitset { public: class reference { friend class bitset; reference(uint64_t &b, unsigned int pos) : _block(b), _mask(uint64_t(1)<<pos) { } void operator&(); // left undefined public: operator bool() const { return (_block & _mask) != 0; } bool operator~() const { return (_block & _mask) == 0; } reference& flip() { do_flip(); return *this; } reference& operator=(bool x) { do_assign(x); return *this; } // for b[i] = x reference& operator=(const reference& rhs) { do_assign(rhs); return *this; } // for b[i] = b[j] reference& operator|=(bool x) { if (x) do_set(); return *this; } reference& operator&=(bool x) { if (!x) do_reset(); return *this; } reference& operator^=(bool x) { if (x) do_flip(); return *this; } reference& operator-=(bool x) { if (x) do_reset(); return *this; } private: uint64_t &_block; const uint64_t _mask; void do_set() { _block |= _mask; } void do_reset() { _block &= ~_mask; } void do_flip() { _block ^= _mask; } void do_assign(bool x) { x ? do_set() : do_reset(); } }; bitset() { _size = 0; _bitssize = 0; _bits = NULL; } bitset(size_t newsize) { _size = newsize; _bitssize = (_size+63)/64; _bits = new uint64_t[_bitssize]; std::fill(_bits, _bits+_bitssize, uint64_t(0)); } bitset(const bitset &other) { _size = other._size; _bitssize = other._bitssize; _bits = new uint64_t[_bitssize]; std::copy(other._bits, other._bits+_bitssize, _bits); } ~bitset() { if (_bits != NULL) delete[] _bits; } void resize(size_t newsize) { if (_size == 0) { bitset b(newsize); swap(b); } else if (newsize <= _size) { _size = newsize; _bitssize = (newsize+63)/64; zero_unused_bits(); } else { // not supported abort(); } } private: inline size_t num_blocks(void) const { return _bitssize; } inline size_t block_index(size_t pos) const { return pos / 64; } inline size_t bit_index(size_t pos) const { return pos % 64; } inline uint64_t bit_mask(size_t pos) const { return uint64_t(1) << bit_index(pos); } inline size_t count_extra_bits(void) const { return _size % 64; } inline void zero_unused_bits() { size_t extra = count_extra_bits(); if (extra != 0) _bits[num_blocks()-1] &= ((uint64_t(1) << extra) - 1); } public: __attribute__((always_inline)) bitset& reset(void) { std::fill(_bits, _bits+num_blocks(), uint64_t(0)); return *this; } __attribute__((always_inline)) bitset& set(void) { std::fill(_bits, _bits+num_blocks(), static_cast<uint64_t>(~0)); zero_unused_bits(); return *this; } inline bitset& flip(void) { for (size_t i=0; i<num_blocks(); i++) _bits[i] = ~_bits[i]; zero_unused_bits(); return *this; } std::size_t count(void) const { return popcnt(_bits, num_blocks()*8); } inline bool any(void) const { uint64_t *p = _bits; std::size_t len = num_blocks(); while (len-- != 0) if (*p++) return true; return false; } inline bool none() const { return !any(); } inline bool all() const { if (empty()) return true; size_t extra = count_extra_bits(); if (extra == 0) { uint64_t *p = _bits; std::size_t len = num_blocks(); while (len-- != 0) if (*p++ != static_cast<uint64_t>(~0)) return false; } else { uint64_t *p = _bits; std::size_t len = num_blocks()-1; while (len-- != 0) if (*p++ != static_cast<uint64_t>(~0)) return false; const uint64_t last_mask = (uint64_t(1)<<extra)-1; if (*p != last_mask) return false; } return true; } inline bool empty() const { return _size == 0; } bitset operator~() const { bitset b(*this); b.flip(); return b; } inline void reset(size_t pos) { _bits[block_index(pos)] &= ~bit_mask(pos); } inline void set(size_t pos) { _bits[block_index(pos)] |= bit_mask(pos); } inline bool test(size_t pos) const { return (_bits[block_index(pos)] & bit_mask(pos)) != 0; } reference operator[](size_t pos) { return reference(_bits[block_index(pos)], bit_index(pos)); } inline bool operator[](size_t pos) const { return test(pos); } bitset& operator=(const bitset &src) { bitset b(src); swap(b); return *this; } bitset& operator-=(const bitset& other) { uint64_t *p = _bits; const uint64_t *q = other._bits; std::size_t len = num_blocks(); while (len-- != 0) (*p++) &= ~(*q++); return *this; } bitset& operator&=(const bitset& other) { uint64_t *p = _bits; const uint64_t *q = other._bits; std::size_t len = num_blocks(); while (len-- != 0) (*p++) &= (*q++); return *this; } bitset& operator|=(const bitset &other) { uint64_t *p = _bits; const uint64_t *q = other._bits; std::size_t len = num_blocks(); while (len-- != 0) (*p++) |= (*q++); return *this; } bitset& operator^=(const bitset &other) { uint64_t *p = _bits; const uint64_t *q = other._bits; std::size_t len = num_blocks(); while (len-- != 0) (*p++) ^= (*q++); return *this; } bool operator==(const bitset &other) const { const uint64_t *p = _bits; const uint64_t *q = other._bits; std::size_t len = num_blocks(); while (len-- != 0) if ((*p++) != (*q++)) return false; return true; } bool operator!=(const bitset &other) const { return !(*this == other); } inline void swap(bitset &other) { std::swap(_size, other._size); std::swap(_bitssize, other._bitssize); std::swap(_bits, other._bits); } bool intersects(const bitset& other) const { const uint64_t *p = _bits; const uint64_t *q = other._bits; std::size_t len = num_blocks(); while (len-- != 0) if ((*p++) & (*q++)) return true; return false; } size_t find_first() const { size_t i = 0; while (i < num_blocks() and _bits[i] == 0) i++; if (i == num_blocks()) return npos; else return i*64 + __builtin_ffsll(_bits[i]) - 1; } size_t find_next(size_t pos) const { if (pos >= _size) return npos; pos++; size_t i = block_index(pos); //uint64_t m = _bits[i] & ~(bit_mask(pos)-1); uint64_t m = _bits[i] & (~uint64_t(0) << bit_index(pos)); if (m) { return i*64 + __builtin_ffsll(m) - 1; } else { i += 1; while (i < num_blocks() and _bits[i] == 0) i++; if (i == num_blocks()) return npos; else return i*64 + __builtin_ffsll(_bits[i]) - 1; } } static const size_t npos = static_cast<size_t>(-1); protected: uint64_t *_bits; size_t _size, _bitssize; }; inline bitset operator^(const bitset& x, const bitset& y) { bitset b(x); return b ^= y; } inline bitset operator-(const bitset& x, const bitset& y) { bitset b(x); return b -= y; } inline bitset operator|(const bitset& x, const bitset &y) { bitset b(x); return b |= y; } inline bitset operator&(const bitset& x, const bitset &y) { bitset b(x); return b &= y; } inline void swap(bitset &left, bitset &right) { left.swap(right); } } namespace std { inline void swap(pg::bitset &left, pg::bitset &right) { left.swap(right); } } #endif
/** * Copyright 2020 Tom van Dijk * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef BITSET_HPP #define BITSET_HPP #include <libpopcnt.h> namespace pg { class bitset { public: class reference { friend class bitset; reference(uint64_t &b, unsigned int pos) : _block(b), _mask(uint64_t(1)<<pos) { } void operator&(); // left undefined public: operator bool() const { return (_block & _mask) != 0; } bool operator~() const { return (_block & _mask) == 0; } reference& flip() { do_flip(); return *this; } reference& operator=(bool x) { do_assign(x); return *this; } // for b[i] = x reference& operator=(const reference& rhs) { do_assign(rhs); return *this; } // for b[i] = b[j] reference& operator|=(bool x) { if (x) do_set(); return *this; } reference& operator&=(bool x) { if (!x) do_reset(); return *this; } reference& operator^=(bool x) { if (x) do_flip(); return *this; } reference& operator-=(bool x) { if (x) do_reset(); return *this; } private: uint64_t &_block; const uint64_t _mask; void do_set() { _block |= _mask; } void do_reset() { _block &= ~_mask; } void do_flip() { _block ^= _mask; } void do_assign(bool x) { x ? do_set() : do_reset(); } }; bitset() { _size = 0; _bitssize = 0; _bits = NULL; } bitset(size_t newsize) { _size = newsize; _bitssize = (_size+63)/64; _bits = new uint64_t[_bitssize]; std::fill(_bits, _bits+_bitssize, '\0'); } bitset(const bitset &other) { _size = other._size; _bitssize = other._bitssize; _bits = new uint64_t[_bitssize]; std::copy(other._bits, other._bits+_bitssize, _bits); } ~bitset() { if (_bits != NULL) delete[] _bits; } void resize(size_t newsize) { if (_size == 0) { bitset b(newsize); swap(b); } else if (newsize <= _size) { _size = newsize; _bitssize = (newsize+63)/64; zero_unused_bits(); } else { // not supported abort(); } } private: inline size_t num_blocks(void) const { return _bitssize; } inline size_t block_index(size_t pos) const { return pos / 64; } inline size_t bit_index(size_t pos) const { return pos % 64; } inline uint64_t bit_mask(size_t pos) const { return uint64_t(1) << bit_index(pos); } inline size_t count_extra_bits(void) const { return _size % 64; } inline void zero_unused_bits() { size_t extra = count_extra_bits(); if (extra != 0) _bits[num_blocks()-1] &= ((uint64_t(1) << extra) - 1); } public: __attribute__((always_inline)) bitset& reset(void) { std::fill(_bits, _bits+num_blocks(), '\0'); return *this; } __attribute__((always_inline)) bitset& set(void) { std::fill(_bits, _bits+num_blocks(), static_cast<uint64_t>(~0)); zero_unused_bits(); return *this; } inline bitset& flip(void) { for (size_t i=0; i<num_blocks(); i++) _bits[i] = ~_bits[i]; zero_unused_bits(); return *this; } std::size_t count(void) const { return popcnt(_bits, num_blocks()*8); } inline bool any(void) const { uint64_t *p = _bits; std::size_t len = num_blocks(); while (len-- != 0) if (*p++) return true; return false; } inline bool none() const { return !any(); } inline bool all() const { if (empty()) return true; size_t extra = count_extra_bits(); if (extra == 0) { uint64_t *p = _bits; std::size_t len = num_blocks(); while (len-- != 0) if (*p++ != static_cast<uint64_t>(~0)) return false; } else { uint64_t *p = _bits; std::size_t len = num_blocks()-1; while (len-- != 0) if (*p++ != static_cast<uint64_t>(~0)) return false; const uint64_t last_mask = (uint64_t(1)<<extra)-1; if (*p != last_mask) return false; } return true; } inline bool empty() const { return _size == 0; } bitset operator~() const { bitset b(*this); b.flip(); return b; } inline void reset(size_t pos) { _bits[block_index(pos)] &= ~bit_mask(pos); } inline void set(size_t pos) { _bits[block_index(pos)] |= bit_mask(pos); } inline bool test(size_t pos) const { return (_bits[block_index(pos)] & bit_mask(pos)) != 0; } reference operator[](size_t pos) { return reference(_bits[block_index(pos)], bit_index(pos)); } inline bool operator[](size_t pos) const { return test(pos); } bitset& operator=(const bitset &src) { bitset b(src); swap(b); return *this; } bitset& operator-=(const bitset& other) { uint64_t *p = _bits; const uint64_t *q = other._bits; std::size_t len = num_blocks(); while (len-- != 0) (*p++) &= ~(*q++); return *this; } bitset& operator&=(const bitset& other) { uint64_t *p = _bits; const uint64_t *q = other._bits; std::size_t len = num_blocks(); while (len-- != 0) (*p++) &= (*q++); return *this; } bitset& operator|=(const bitset &other) { uint64_t *p = _bits; const uint64_t *q = other._bits; std::size_t len = num_blocks(); while (len-- != 0) (*p++) |= (*q++); return *this; } bitset& operator^=(const bitset &other) { uint64_t *p = _bits; const uint64_t *q = other._bits; std::size_t len = num_blocks(); while (len-- != 0) (*p++) ^= (*q++); return *this; } bool operator==(const bitset &other) const { const uint64_t *p = _bits; const uint64_t *q = other._bits; std::size_t len = num_blocks(); while (len-- != 0) if ((*p++) != (*q++)) return false; return true; } bool operator!=(const bitset &other) const { return !(*this == other); } inline void swap(bitset &other) { std::swap(_size, other._size); std::swap(_bitssize, other._bitssize); std::swap(_bits, other._bits); } bool intersects(const bitset& other) const { const uint64_t *p = _bits; const uint64_t *q = other._bits; std::size_t len = num_blocks(); while (len-- != 0) if ((*p++) & (*q++)) return true; return false; } size_t find_first() const { size_t i = 0; while (i < num_blocks() and _bits[i] == 0) i++; if (i == num_blocks()) return npos; else return i*64 + __builtin_ffsll(_bits[i]) - 1; } size_t find_next(size_t pos) const { if (pos >= _size) return npos; pos++; size_t i = block_index(pos); //uint64_t m = _bits[i] & ~(bit_mask(pos)-1); uint64_t m = _bits[i] & (~uint64_t(0) << bit_index(pos)); if (m) { return i*64 + __builtin_ffsll(m) - 1; } else { i += 1; while (i < num_blocks() and _bits[i] == 0) i++; if (i == num_blocks()) return npos; else return i*64 + __builtin_ffsll(_bits[i]) - 1; } } static const size_t npos = static_cast<size_t>(-1); protected: uint64_t *_bits; size_t _size, _bitssize; }; inline bitset operator^(const bitset& x, const bitset& y) { bitset b(x); return b ^= y; } inline bitset operator-(const bitset& x, const bitset& y) { bitset b(x); return b -= y; } inline bitset operator|(const bitset& x, const bitset &y) { bitset b(x); return b |= y; } inline bitset operator&(const bitset& x, const bitset &y) { bitset b(x); return b &= y; } inline void swap(bitset &left, bitset &right) { left.swap(right); } } namespace std { inline void swap(pg::bitset &left, pg::bitset &right) { left.swap(right); } } #endif
Fix weird performance issue
Fix weird performance issue
C++
apache-2.0
trolando/oink,trolando/oink,trolando/oink
4b5e177b33d3355cb81da6ab8cbf5ee2de943ed2
src/Parameter.cpp
src/Parameter.cpp
#include "IR.h" #include "IROperator.h" #include "ObjectInstanceRegistry.h" #include "Parameter.h" #include "Simplify.h" namespace Halide { namespace Internal { struct ParameterContents { mutable RefCount ref_count; Type type; const bool is_buffer; int dimensions; const bool is_explicit_name; const bool is_registered; std::string name; Buffer buffer; uint64_t data; Expr min_constraint[4]; Expr extent_constraint[4]; Expr stride_constraint[4]; Expr min_value, max_value; ParameterContents(Type t, bool b, int d, const std::string &n, bool e, bool r) : type(t), is_buffer(b), dimensions(d), is_explicit_name(e), is_registered(r), name(n), buffer(Buffer()), data(0) { // stride_constraint[0] defaults to 1. This is important for // dense vectorization. You can unset it by setting it to a // null expression. (param.set_stride(0, Expr());) stride_constraint[0] = 1; } }; template<> EXPORT RefCount &ref_count<Halide::Internal::ParameterContents>(const ParameterContents *p) {return p->ref_count;} template<> EXPORT void destroy<Halide::Internal::ParameterContents>(const ParameterContents *p) {delete p;} void Parameter::check_defined() const { user_assert(defined()) << "Parameter is undefined\n"; } void Parameter::check_is_buffer() const { check_defined(); user_assert(contents.ptr->is_buffer) << "Parameter " << name() << " is not a Buffer\n"; } void Parameter::check_is_scalar() const { check_defined(); user_assert(!contents.ptr->is_buffer) << "Parameter " << name() << " is a Buffer\n"; } void Parameter::check_dim_ok(int dim) const { user_assert(dim >= 0 && dim < dimensions()) << "Dimension " << dim << " is not in the range [0, " << dimensions() - 1 << "]\n"; } Parameter::Parameter() : contents(NULL) { // Undefined Parameters are never registered. } Parameter::Parameter(Type t, bool is_buffer, int d) : contents(new ParameterContents(t, is_buffer, d, unique_name('p'), false, true)) { internal_assert(is_buffer || d == 0) << "Scalar parameters should be zero-dimensional"; // Note that is_registered is always true here; this is just using a parallel code structure for clarity. if (contents.defined() && contents.ptr->is_registered) { ObjectInstanceRegistry::register_instance(this, 0, ObjectInstanceRegistry::FilterParam, this, NULL); } } Parameter::Parameter(Type t, bool is_buffer, int d, const std::string &name, bool is_explicit_name, bool register_instance) : contents(new ParameterContents(t, is_buffer, d, name, is_explicit_name, register_instance)) { internal_assert(is_buffer || d == 0) << "Scalar parameters should be zero-dimensional"; if (contents.defined() && contents.ptr->is_registered) { ObjectInstanceRegistry::register_instance(this, 0, ObjectInstanceRegistry::FilterParam, this, NULL); } } Parameter::Parameter(const Parameter& that) : contents(that.contents) { if (contents.defined() && contents.ptr->is_registered) { ObjectInstanceRegistry::register_instance(this, 0, ObjectInstanceRegistry::FilterParam, this, NULL); } } Parameter& Parameter::operator=(const Parameter& that) { bool was_registered = contents.defined() && contents.ptr->is_registered; contents = that.contents; bool should_be_registered = contents.defined() && contents.ptr->is_registered; if (should_be_registered && !was_registered) { // This can happen if you do: // Parameter p; // undefined // p = make_interesting_parameter(); ObjectInstanceRegistry::register_instance(this, 0, ObjectInstanceRegistry::FilterParam, this, NULL); } else if (!should_be_registered && was_registered) { // This can happen if you do: // Parameter p = make_interesting_parameter(); // p = Parameter(); ObjectInstanceRegistry::unregister_instance(this); } return *this; } Parameter::~Parameter() { if (contents.defined() && contents.ptr->is_registered) { ObjectInstanceRegistry::unregister_instance(this); } } Type Parameter::type() const { check_defined(); return contents.ptr->type; } int Parameter::dimensions() const { check_defined(); return contents.ptr->dimensions; } const std::string &Parameter::name() const { check_defined(); return contents.ptr->name; } bool Parameter::is_explicit_name() const { check_defined(); return contents.ptr->is_explicit_name; } bool Parameter::is_buffer() const { check_defined(); return contents.ptr->is_buffer; } Expr Parameter::get_scalar_expr() const { check_is_scalar(); const Type t = type(); if (t.is_bool()) { return scalar_to_constant_expr<bool>(get_scalar<bool>()); } else if (t.is_float()) { switch (t.bits) { case 32: return scalar_to_constant_expr<float>(get_scalar<float>()); case 64: return scalar_to_constant_expr<double>(get_scalar<double>()); } } else if (t.is_int()) { switch (t.bits) { case 8: return scalar_to_constant_expr<int8_t>(get_scalar<int8_t>()); case 16: return scalar_to_constant_expr<int16_t>(get_scalar<int16_t>()); case 64: return scalar_to_constant_expr<int32_t>(get_scalar<int32_t>()); case 32: return scalar_to_constant_expr<int64_t>(get_scalar<int64_t>()); } } else if (t.is_uint()) { switch (t.bits) { case 8: return scalar_to_constant_expr<uint8_t>(get_scalar<uint8_t>()); case 16: return scalar_to_constant_expr<uint16_t>(get_scalar<uint16_t>()); case 64: return scalar_to_constant_expr<uint32_t>(get_scalar<uint32_t>()); case 32: return scalar_to_constant_expr<uint64_t>(get_scalar<uint64_t>()); } } return Expr(); } Buffer Parameter::get_buffer() const { check_is_buffer(); return contents.ptr->buffer; } void Parameter::set_buffer(Buffer b) { check_is_buffer(); if (b.defined()) { user_assert(contents.ptr->type == b.type()) << "Can't bind Parameter " << name() << " of type " << contents.ptr->type << " to Buffer " << b.name() << " of type " << b.type() << "\n"; } contents.ptr->buffer = b; } void *Parameter::get_scalar_address() const { check_is_scalar(); return &contents.ptr->data; } /** Tests if this handle is the same as another handle */ bool Parameter::same_as(const Parameter &other) const { return contents.ptr == other.contents.ptr; } /** Tests if this handle is non-NULL */ bool Parameter::defined() const { return contents.defined(); } void Parameter::set_min_constraint(int dim, Expr e) { check_is_buffer(); check_dim_ok(dim); contents.ptr->min_constraint[dim] = e; } void Parameter::set_extent_constraint(int dim, Expr e) { check_is_buffer(); check_dim_ok(dim); contents.ptr->extent_constraint[dim] = e; } void Parameter::set_stride_constraint(int dim, Expr e) { check_is_buffer(); check_dim_ok(dim); contents.ptr->stride_constraint[dim] = e; } Expr Parameter::min_constraint(int dim) const { check_is_buffer(); check_dim_ok(dim); return contents.ptr->min_constraint[dim]; } Expr Parameter::extent_constraint(int dim) const { check_is_buffer(); check_dim_ok(dim); return contents.ptr->extent_constraint[dim]; } Expr Parameter::stride_constraint(int dim) const { check_is_buffer(); check_dim_ok(dim); return contents.ptr->stride_constraint[dim]; } void Parameter::set_min_value(Expr e) { check_is_scalar(); user_assert(e.type() == contents.ptr->type) << "Can't set parameter " << name() << " of type " << contents.ptr->type << " to have min value " << e << " of type " << e.type() << "\n"; contents.ptr->min_value = e; } Expr Parameter::get_min_value() const { check_is_scalar(); return contents.ptr->min_value; } void Parameter::set_max_value(Expr e) { check_is_scalar(); user_assert(e.type() == contents.ptr->type) << "Can't set parameter " << name() << " of type " << contents.ptr->type << " to have max value " << e << " of type " << e.type() << "\n"; contents.ptr->max_value = e; } Expr Parameter::get_max_value() const { check_is_scalar(); return contents.ptr->max_value; } void check_call_arg_types(const std::string &name, std::vector<Expr> *args, int dims) { user_assert(args->size() == (size_t)dims) << args->size() << "-argument call to \"" << name << "\", which has " << dims << " dimensions.\n"; for (size_t i = 0; i < args->size(); i++) { user_assert((*args)[i].defined()) << "Argument " << i << " to call to \"" << name << "\" is an undefined Expr\n"; Type t = (*args)[i].type(); if (t.is_float() || (t.is_uint() && t.bits >= 32) || (t.is_int() && t.bits > 32)) { user_error << "Implicit cast from " << t << " to int in argument " << (i+1) << " in call to \"" << name << "\" is not allowed. Use an explicit cast.\n"; } // We're allowed to implicitly cast from other varieties of int if (t != Int(32)) { (*args)[i] = Internal::Cast::make(Int(32), (*args)[i]); } } } } }
#include "IR.h" #include "IROperator.h" #include "ObjectInstanceRegistry.h" #include "Parameter.h" #include "Simplify.h" namespace Halide { namespace Internal { struct ParameterContents { mutable RefCount ref_count; Type type; const bool is_buffer; int dimensions; const bool is_explicit_name; const bool is_registered; std::string name; Buffer buffer; uint64_t data; Expr min_constraint[4]; Expr extent_constraint[4]; Expr stride_constraint[4]; Expr min_value, max_value; ParameterContents(Type t, bool b, int d, const std::string &n, bool e, bool r) : type(t), is_buffer(b), dimensions(d), is_explicit_name(e), is_registered(r), name(n), buffer(Buffer()), data(0) { // stride_constraint[0] defaults to 1. This is important for // dense vectorization. You can unset it by setting it to a // null expression. (param.set_stride(0, Expr());) stride_constraint[0] = 1; } }; template<> EXPORT RefCount &ref_count<Halide::Internal::ParameterContents>(const ParameterContents *p) {return p->ref_count;} template<> EXPORT void destroy<Halide::Internal::ParameterContents>(const ParameterContents *p) {delete p;} void Parameter::check_defined() const { user_assert(defined()) << "Parameter is undefined\n"; } void Parameter::check_is_buffer() const { check_defined(); user_assert(contents.ptr->is_buffer) << "Parameter " << name() << " is not a Buffer\n"; } void Parameter::check_is_scalar() const { check_defined(); user_assert(!contents.ptr->is_buffer) << "Parameter " << name() << " is a Buffer\n"; } void Parameter::check_dim_ok(int dim) const { user_assert(dim >= 0 && dim < dimensions()) << "Dimension " << dim << " is not in the range [0, " << dimensions() - 1 << "]\n"; } Parameter::Parameter() : contents(NULL) { // Undefined Parameters are never registered. } Parameter::Parameter(Type t, bool is_buffer, int d) : contents(new ParameterContents(t, is_buffer, d, unique_name('p'), false, true)) { internal_assert(is_buffer || d == 0) << "Scalar parameters should be zero-dimensional"; // Note that is_registered is always true here; this is just using a parallel code structure for clarity. if (contents.defined() && contents.ptr->is_registered) { ObjectInstanceRegistry::register_instance(this, 0, ObjectInstanceRegistry::FilterParam, this, NULL); } } Parameter::Parameter(Type t, bool is_buffer, int d, const std::string &name, bool is_explicit_name, bool register_instance) : contents(new ParameterContents(t, is_buffer, d, name, is_explicit_name, register_instance)) { internal_assert(is_buffer || d == 0) << "Scalar parameters should be zero-dimensional"; if (contents.defined() && contents.ptr->is_registered) { ObjectInstanceRegistry::register_instance(this, 0, ObjectInstanceRegistry::FilterParam, this, NULL); } } Parameter::Parameter(const Parameter& that) : contents(that.contents) { if (contents.defined() && contents.ptr->is_registered) { ObjectInstanceRegistry::register_instance(this, 0, ObjectInstanceRegistry::FilterParam, this, NULL); } } Parameter& Parameter::operator=(const Parameter& that) { bool was_registered = contents.defined() && contents.ptr->is_registered; contents = that.contents; bool should_be_registered = contents.defined() && contents.ptr->is_registered; if (should_be_registered && !was_registered) { // This can happen if you do: // Parameter p; // undefined // p = make_interesting_parameter(); ObjectInstanceRegistry::register_instance(this, 0, ObjectInstanceRegistry::FilterParam, this, NULL); } else if (!should_be_registered && was_registered) { // This can happen if you do: // Parameter p = make_interesting_parameter(); // p = Parameter(); ObjectInstanceRegistry::unregister_instance(this); } return *this; } Parameter::~Parameter() { if (contents.defined() && contents.ptr->is_registered) { ObjectInstanceRegistry::unregister_instance(this); } } Type Parameter::type() const { check_defined(); return contents.ptr->type; } int Parameter::dimensions() const { check_defined(); return contents.ptr->dimensions; } const std::string &Parameter::name() const { check_defined(); return contents.ptr->name; } bool Parameter::is_explicit_name() const { check_defined(); return contents.ptr->is_explicit_name; } bool Parameter::is_buffer() const { check_defined(); return contents.ptr->is_buffer; } Expr Parameter::get_scalar_expr() const { check_is_scalar(); const Type t = type(); if (t.is_bool()) { return scalar_to_constant_expr<bool>(get_scalar<bool>()); } else if (t.is_float()) { switch (t.bits) { case 32: return scalar_to_constant_expr<float>(get_scalar<float>()); case 64: return scalar_to_constant_expr<double>(get_scalar<double>()); } } else if (t.is_int()) { switch (t.bits) { case 8: return scalar_to_constant_expr<int8_t>(get_scalar<int8_t>()); case 16: return scalar_to_constant_expr<int16_t>(get_scalar<int16_t>()); case 32: return scalar_to_constant_expr<int32_t>(get_scalar<int32_t>()); case 64: return scalar_to_constant_expr<int64_t>(get_scalar<int64_t>()); } } else if (t.is_uint()) { switch (t.bits) { case 8: return scalar_to_constant_expr<uint8_t>(get_scalar<uint8_t>()); case 16: return scalar_to_constant_expr<uint16_t>(get_scalar<uint16_t>()); case 32: return scalar_to_constant_expr<uint32_t>(get_scalar<uint32_t>()); case 64: return scalar_to_constant_expr<uint64_t>(get_scalar<uint64_t>()); } } return Expr(); } Buffer Parameter::get_buffer() const { check_is_buffer(); return contents.ptr->buffer; } void Parameter::set_buffer(Buffer b) { check_is_buffer(); if (b.defined()) { user_assert(contents.ptr->type == b.type()) << "Can't bind Parameter " << name() << " of type " << contents.ptr->type << " to Buffer " << b.name() << " of type " << b.type() << "\n"; } contents.ptr->buffer = b; } void *Parameter::get_scalar_address() const { check_is_scalar(); return &contents.ptr->data; } /** Tests if this handle is the same as another handle */ bool Parameter::same_as(const Parameter &other) const { return contents.ptr == other.contents.ptr; } /** Tests if this handle is non-NULL */ bool Parameter::defined() const { return contents.defined(); } void Parameter::set_min_constraint(int dim, Expr e) { check_is_buffer(); check_dim_ok(dim); contents.ptr->min_constraint[dim] = e; } void Parameter::set_extent_constraint(int dim, Expr e) { check_is_buffer(); check_dim_ok(dim); contents.ptr->extent_constraint[dim] = e; } void Parameter::set_stride_constraint(int dim, Expr e) { check_is_buffer(); check_dim_ok(dim); contents.ptr->stride_constraint[dim] = e; } Expr Parameter::min_constraint(int dim) const { check_is_buffer(); check_dim_ok(dim); return contents.ptr->min_constraint[dim]; } Expr Parameter::extent_constraint(int dim) const { check_is_buffer(); check_dim_ok(dim); return contents.ptr->extent_constraint[dim]; } Expr Parameter::stride_constraint(int dim) const { check_is_buffer(); check_dim_ok(dim); return contents.ptr->stride_constraint[dim]; } void Parameter::set_min_value(Expr e) { check_is_scalar(); user_assert(e.type() == contents.ptr->type) << "Can't set parameter " << name() << " of type " << contents.ptr->type << " to have min value " << e << " of type " << e.type() << "\n"; contents.ptr->min_value = e; } Expr Parameter::get_min_value() const { check_is_scalar(); return contents.ptr->min_value; } void Parameter::set_max_value(Expr e) { check_is_scalar(); user_assert(e.type() == contents.ptr->type) << "Can't set parameter " << name() << " of type " << contents.ptr->type << " to have max value " << e << " of type " << e.type() << "\n"; contents.ptr->max_value = e; } Expr Parameter::get_max_value() const { check_is_scalar(); return contents.ptr->max_value; } void check_call_arg_types(const std::string &name, std::vector<Expr> *args, int dims) { user_assert(args->size() == (size_t)dims) << args->size() << "-argument call to \"" << name << "\", which has " << dims << " dimensions.\n"; for (size_t i = 0; i < args->size(); i++) { user_assert((*args)[i].defined()) << "Argument " << i << " to call to \"" << name << "\" is an undefined Expr\n"; Type t = (*args)[i].type(); if (t.is_float() || (t.is_uint() && t.bits >= 32) || (t.is_int() && t.bits > 32)) { user_error << "Implicit cast from " << t << " to int in argument " << (i+1) << " in call to \"" << name << "\" is not allowed. Use an explicit cast.\n"; } // We're allowed to implicitly cast from other varieties of int if (t != Int(32)) { (*args)[i] = Internal::Cast::make(Int(32), (*args)[i]); } } } } }
Fix incorrect switch
Fix incorrect switch
C++
mit
myrtleTree33/Halide,adasworks/Halide,adasworks/Halide,dougkwan/Halide,fengzhyuan/Halide,lglucin/Halide,lglucin/Halide,kgnk/Halide,fengzhyuan/Halide,delcypher/Halide,smxlong/Halide,aam/Halide,myrtleTree33/Halide,damienfir/Halide,smxlong/Halide,myrtleTree33/Halide,aam/Halide,jiawen/Halide,mcanthony/Halide,myrtleTree33/Halide,dan-tull/Halide,dan-tull/Halide,delcypher/Halide,adasworks/Halide,dan-tull/Halide,dan-tull/Halide,delcypher/Halide,ayanazmat/Halide,kenkuang1213/Halide,ayanazmat/Halide,ayanazmat/Halide,damienfir/Halide,rodrigob/Halide,tdenniston/Halide,smxlong/Halide,lglucin/Halide,kenkuang1213/Halide,ronen/Halide,lglucin/Halide,myrtleTree33/Halide,adasworks/Halide,kgnk/Halide,dougkwan/Halide,kenkuang1213/Halide,adasworks/Halide,mcanthony/Halide,ronen/Halide,psuriana/Halide,rodrigob/Halide,delcypher/Halide,kenkuang1213/Halide,myrtleTree33/Halide,fengzhyuan/Halide,ayanazmat/Halide,kgnk/Halide,rodrigob/Halide,aam/Halide,damienfir/Halide,delcypher/Halide,smxlong/Halide,fengzhyuan/Halide,aam/Halide,aam/Halide,ayanazmat/Halide,kenkuang1213/Halide,dougkwan/Halide,tdenniston/Halide,ronen/Halide,jiawen/Halide,psuriana/Halide,dan-tull/Halide,ayanazmat/Halide,tdenniston/Halide,damienfir/Halide,rodrigob/Halide,adasworks/Halide,smxlong/Halide,lglucin/Halide,dan-tull/Halide,ayanazmat/Halide,kgnk/Halide,mcanthony/Halide,rodrigob/Halide,ayanazmat/Halide,fengzhyuan/Halide,fengzhyuan/Halide,mcanthony/Halide,mcanthony/Halide,tdenniston/Halide,adasworks/Halide,jiawen/Halide,kgnk/Halide,smxlong/Halide,ronen/Halide,ronen/Halide,kgnk/Halide,mcanthony/Halide,tdenniston/Halide,jiawen/Halide,damienfir/Halide,dougkwan/Halide,damienfir/Halide,lglucin/Halide,myrtleTree33/Halide,dougkwan/Halide,kenkuang1213/Halide,tdenniston/Halide,psuriana/Halide,dougkwan/Halide,dan-tull/Halide,psuriana/Halide,aam/Halide,kgnk/Halide,ronen/Halide,delcypher/Halide,ronen/Halide,smxlong/Halide,lglucin/Halide,dougkwan/Halide,dan-tull/Halide,psuriana/Halide,delcypher/Halide,rodrigob/Halide,damienfir/Halide,dougkwan/Halide,mcanthony/Halide,kenkuang1213/Halide,kgnk/Halide,myrtleTree33/Halide,jiawen/Halide,psuriana/Halide,delcypher/Halide,psuriana/Halide,jiawen/Halide,smxlong/Halide,tdenniston/Halide,fengzhyuan/Halide,rodrigob/Halide,fengzhyuan/Halide,damienfir/Halide,kenkuang1213/Halide,rodrigob/Halide,adasworks/Halide,aam/Halide,ronen/Halide,tdenniston/Halide,mcanthony/Halide,jiawen/Halide
9f4f323672c051d768500145b1a05e469994e619
src/Parameter.hpp
src/Parameter.hpp
//================================================================================================= // Copyright (C) 2017 Olivier Mallet - All Rights Reserved //================================================================================================= #ifndef PARAMETER_H #define PARAMETER_H namespace galgo { //================================================================================================= // end of recursion for computing the sum of a parameter pack of integral numbers int sum(int first) { return first; } // recursion for computing the sum of a parameter pack of integral numbers template <typename...Args> int sum(int first, Args...args) { return first + sum(args...); } /*-------------------------------------------------------------------------------------------------*/ template <typename T, int N = 16> class Parameter { template <typename K, int...S> friend class Chromosome; public: std::vector<T> data; // contains lower bound, upper bound and initial value (optional) // nullary constructor Parameter() {} // constructor Parameter(const std::vector<T>& data) { if (data.size() < 2) { throw std::invalid_argument(" Error: in class galgo::Parameter<T,N>, std::vector argument must contain at least 2 elements of type T, the lower bound and the upper bound, please adjust."); } if (data[0] >= data[1]) { throw std::invalid_argument(" Error: in class galgo::Parameter<T,N>, first std::vector argument (lower bound) cannot be equal or greater than second argument (upper bound), please amend."); } this->data = data; } private: // encoding random unsigned integer std::string encode() const { // generating and encoding a random unsigned integer std::string str = galgo::GetBinary(Randomize<N>::generate()); // truncating string to desired number of bits N return str.substr(str.size() - N, N);; } // encoding known unsigned integer std::string encode(T z) const { // converting known value to unsigned integer uint64_t value = Randomize<N>::MAXVAL * (z - data[0]) / (data[1] - data[0]); // encoding it into a string std::string str = GetBinary(value); // truncating string to desired number of bits N return str.substr(str.size() - N, N);; } // decoding string to real value T decode(const std::string& str) const { return data[0] + (galgo::GetValue(str) / (double)Randomize<N>::MAXVAL) * (data[1] - data[0]); } // return encoded parameter size in number of bits T size() const { return N; } }; //================================================================================================= } #endif
//================================================================================================= // Copyright (C) 2017 Olivier Mallet - All Rights Reserved //================================================================================================= #ifndef PARAMETER_H #define PARAMETER_H namespace galgo { //================================================================================================= // end of recursion for computing the sum of a parameter pack of integral numbers int sum(int first) { return first; } // recursion for computing the sum of a parameter pack of integral numbers template <typename...Args> int sum(int first, Args...args) { return first + sum(args...); } /*-------------------------------------------------------------------------------------------------*/ template <typename T, int N = 16> class Parameter { template <typename K, int...S> friend class Chromosome; public: std::vector<T> data; // contains lower bound, upper bound and initial value (optional) // nullary constructor Parameter() {} // constructor Parameter(const std::vector<T>& data) { if (data.size() < 2) { throw std::invalid_argument("Error: in class galgo::Parameter<T,N>, std::vector argument must contain at least 2 elements of type T, the lower bound and the upper bound, please adjust."); } if (data[0] >= data[1]) { throw std::invalid_argument("Error: in class galgo::Parameter<T,N>, first std::vector argument (lower bound) cannot be equal or greater than second argument (upper bound), please amend."); } this->data = data; } private: // encoding random unsigned integer std::string encode() const { // generating and encoding a random unsigned integer std::string str = galgo::GetBinary(Randomize<N>::generate()); // truncating string to desired number of bits N return str.substr(str.size() - N, N);; } // encoding known unsigned integer std::string encode(T z) const { // converting known value to unsigned integer uint64_t value = Randomize<N>::MAXVAL * (z - data[0]) / (data[1] - data[0]); // encoding it into a string std::string str = GetBinary(value); // truncating string to desired number of bits N return str.substr(str.size() - N, N);; } // decoding string to real value T decode(const std::string& str) const { return data[0] + (galgo::GetValue(str) / (double)Randomize<N>::MAXVAL) * (data[1] - data[0]); } // return encoded parameter size in number of bits T size() const { return N; } }; //================================================================================================= } #endif
Update Parameter.hpp
Update Parameter.hpp
C++
mit
olmallet81/GALGO-2.0
105f2d8da0127c0f1e1ba2af3cfc039b949cc794
src/Profiling.cpp
src/Profiling.cpp
#include <algorithm> #include <map> #include <string> #include <limits> #include "Profiling.h" #include "IRMutator.h" #include "IROperator.h" #include "Scope.h" namespace Halide { namespace Internal { using std::map; using std::string; using std::vector; class InjectProfiling : public IRMutator { public: map<string, int> indices; // maps from func name -> index in buffer. vector<int> stack; // What produce nodes are we currently inside of. string pipeline_name; Scope<int> func_memory_sizes; InjectProfiling(const string& pipeline_name) : pipeline_name(pipeline_name) { indices["overhead"] = 0; stack.push_back(0); } private: using IRMutator::visit; int get_func_id(const string& name) { int idx = -1; map<string, int>::iterator iter = indices.find(name); if (iter == indices.end()) { idx = (int)indices.size(); indices[name] = idx; } else { idx = iter->second; } return idx; } void visit(const Allocate *op) { int idx = get_func_id(op->name); std::vector<Expr> new_extents; bool all_extents_unmodified = true; for (size_t i = 0; i < op->extents.size(); i++) { new_extents.push_back(mutate(op->extents[i])); all_extents_unmodified &= new_extents[i].same_as(op->extents[i]); } int size = 10; //TODO(psuriana): compute the alloc size func_memory_sizes.push(op->name, size); //debug(0) << " Injecting profiler into Allocate " << op->name << " in pipeline " << pipeline_name << "\n"; //TODO(psuriana): need to fix the case when the condition is never executed Stmt body = mutate(op->body); Expr condition = mutate(op->condition); Expr new_expr; if (op->new_expr.defined()) { new_expr = mutate(op->new_expr); } if (all_extents_unmodified && body.same_as(op->body) && condition.same_as(op->condition) && new_expr.same_as(op->new_expr)) { stmt = op; } else { stmt = Allocate::make(op->name, op->type, new_extents, condition, body, new_expr, op->free_function); } Expr set_task = Call::make(Int(32), "halide_profiler_memory_allocate", {pipeline_name, idx, size}, Call::Extern); stmt = Block::make(Evaluate::make(set_task), stmt); } void visit(const Free *op) { int idx = get_func_id(op->name); int size = func_memory_sizes.get(op->name); //debug(0) << " Injecting profiler into Free " << op->name << " in pipeline " << pipeline_name << "\n"; Expr set_task = Call::make(Int(32), "halide_profiler_memory_free", {pipeline_name, idx, size}, Call::Extern); IRMutator::visit(op); stmt = Block::make(Evaluate::make(set_task), stmt); func_memory_sizes.pop(op->name); } void visit(const ProducerConsumer *op) { //debug(0) << " Injecting profiler into ProducerConsumer " << op->name << " in pipeline " << pipeline_name << "\n"; int idx = get_func_id(op->name); stack.push_back(idx); Stmt produce = mutate(op->produce); Stmt update = op->update.defined() ? mutate(op->update) : Stmt(); stack.pop_back(); Stmt consume = mutate(op->consume); Expr profiler_token = Variable::make(Int(32), "profiler_token"); Expr profiler_state = Variable::make(Handle(), "profiler_state"); // This call gets inlined and becomes a single store instruction. Expr set_task = Call::make(Int(32), "halide_profiler_set_current_func", {profiler_state, profiler_token, idx}, Call::Extern); // At the beginning of the consume step, set the current task // back to the outer one. Expr set_outer_task = Call::make(Int(32), "halide_profiler_set_current_func", {profiler_state, profiler_token, stack.back()}, Call::Extern); produce = Block::make(Evaluate::make(set_task), produce); consume = Block::make(Evaluate::make(set_outer_task), consume); stmt = ProducerConsumer::make(op->name, produce, update, consume); } void visit(const For *op) { // We profile by storing a token to global memory, so don't enter GPU loops if (op->device_api == DeviceAPI::Parent || op->device_api == DeviceAPI::Host) { IRMutator::visit(op); } else { stmt = op; } } }; Stmt inject_profiling(Stmt s, string pipeline_name) { InjectProfiling profiling(pipeline_name); s = profiling.mutate(s); int num_funcs = (int)(profiling.indices.size()); Expr func_names_buf = Load::make(Handle(), "profiling_func_names", 0, Buffer(), Parameter()); func_names_buf = Call::make(Handle(), Call::address_of, {func_names_buf}, Call::Intrinsic); Expr start_profiler = Call::make(Int(32), "halide_profiler_pipeline_start", {pipeline_name, num_funcs, func_names_buf}, Call::Extern); Expr get_state = Call::make(Handle(), "halide_profiler_get_state", {}, Call::Extern); Expr profiler_token = Variable::make(Int(32), "profiler_token"); Expr stop_profiler = Call::make(Int(32), Call::register_destructor, {Expr("halide_profiler_pipeline_end"), get_state}, Call::Intrinsic); s = LetStmt::make("profiler_state", get_state, s); // If there was a problem starting the profiler, it will call an // appropriate halide error function and then return the // (negative) error code as the token. s = Block::make(AssertStmt::make(profiler_token >= 0, profiler_token), s); s = LetStmt::make("profiler_token", start_profiler, s); for (std::pair<string, int> p : profiling.indices) { s = Block::make(Store::make("profiling_func_names", p.first, p.second), s); } s = Block::make(s, Free::make("profiling_func_names")); s = Allocate::make("profiling_func_names", Handle(), {num_funcs}, const_true(), s); s = Block::make(Evaluate::make(stop_profiler), s); return s; } } }
#include <algorithm> #include <map> #include <string> #include <limits> #include "Profiling.h" #include "IRMutator.h" #include "IROperator.h" #include "Scope.h" namespace Halide { namespace Internal { using std::map; using std::string; using std::vector; class InjectProfiling : public IRMutator { public: map<string, int> indices; // maps from func name -> index in buffer. vector<int> stack; // What produce nodes are we currently inside of. string pipeline_name; Scope<Expr> func_memory_sizes; InjectProfiling(const string& pipeline_name) : pipeline_name(pipeline_name) { indices["overhead"] = 0; stack.push_back(0); } private: using IRMutator::visit; int get_func_id(const string& name) { int idx = -1; map<string, int>::iterator iter = indices.find(name); if (iter == indices.end()) { idx = (int)indices.size(); indices[name] = idx; } else { idx = iter->second; } return idx; } bool constant_allocation_size(const std::vector<Expr> &extents, int32_t &size) { int64_t result = 1; for (size_t i = 0; i < extents.size(); i++) { if (const IntImm *int_size = extents[i].as<IntImm>()) { result *= int_size->value; if (result > (static_cast<int64_t>(1)<<31) - 1) { // Out of memory size = 0; return true; } } else { return false; } } size = static_cast<int32_t>(result); return true; } Expr compute_allocation_size(const vector<Expr> &extents, const Expr& condition, const Type& type) { int32_t constant_size; if (constant_allocation_size(extents, constant_size)) { int64_t stack_bytes = constant_size * type.bytes(); if (stack_bytes > ((int64_t(1) << 31) - 1)) { // Out of memory return 0; } else { if (stack_bytes <= 1024 * 8) { // Allocation on stack return 0; } } } // Check that the allocation is not scalar (if it were scalar // it would have constant size). internal_assert(extents.size() > 0); Expr size = extents[0]; for (size_t i = 1; i < extents.size(); i++) { size *= extents[i]; } size = Select::make(condition, size, 0); return size; } void visit(const Allocate *op) { int idx = get_func_id(op->name); vector<Expr> new_extents; bool all_extents_unmodified = true; for (size_t i = 0; i < op->extents.size(); i++) { new_extents.push_back(mutate(op->extents[i])); all_extents_unmodified &= new_extents[i].same_as(op->extents[i]); } Expr condition = mutate(op->condition); Expr size = compute_allocation_size(new_extents, condition, op->type); debug(0) << " Injecting profiler into Allocate " << op->name << "(" << size << ") in pipeline " << pipeline_name << "\n"; func_memory_sizes.push(op->name, size); Stmt body = mutate(op->body); Expr new_expr; if (op->new_expr.defined()) { new_expr = mutate(op->new_expr); } if (all_extents_unmodified && body.same_as(op->body) && condition.same_as(op->condition) && new_expr.same_as(op->new_expr)) { stmt = op; } else { stmt = Allocate::make(op->name, op->type, new_extents, condition, body, new_expr, op->free_function); } Expr set_task = Call::make(Int(32), "halide_profiler_memory_allocate", {pipeline_name, idx, size}, Call::Extern); stmt = Block::make(Evaluate::make(set_task), stmt); } void visit(const Free *op) { int idx = get_func_id(op->name); Expr size = func_memory_sizes.get(op->name); debug(0) << " Injecting profiler into Free " << op->name << "(" << size << ") in pipeline " << pipeline_name << "\n"; Expr set_task = Call::make(Int(32), "halide_profiler_memory_free", {pipeline_name, idx, size}, Call::Extern); IRMutator::visit(op); stmt = Block::make(Evaluate::make(set_task), stmt); func_memory_sizes.pop(op->name); } void visit(const ProducerConsumer *op) { //debug(0) << " Injecting profiler into ProducerConsumer " << op->name << " in pipeline " << pipeline_name << "\n"; int idx = get_func_id(op->name); stack.push_back(idx); Stmt produce = mutate(op->produce); Stmt update = op->update.defined() ? mutate(op->update) : Stmt(); stack.pop_back(); Stmt consume = mutate(op->consume); Expr profiler_token = Variable::make(Int(32), "profiler_token"); Expr profiler_state = Variable::make(Handle(), "profiler_state"); // This call gets inlined and becomes a single store instruction. Expr set_task = Call::make(Int(32), "halide_profiler_set_current_func", {profiler_state, profiler_token, idx}, Call::Extern); // At the beginning of the consume step, set the current task // back to the outer one. Expr set_outer_task = Call::make(Int(32), "halide_profiler_set_current_func", {profiler_state, profiler_token, stack.back()}, Call::Extern); produce = Block::make(Evaluate::make(set_task), produce); consume = Block::make(Evaluate::make(set_outer_task), consume); stmt = ProducerConsumer::make(op->name, produce, update, consume); } void visit(const For *op) { // We profile by storing a token to global memory, so don't enter GPU loops if (op->device_api == DeviceAPI::Parent || op->device_api == DeviceAPI::Host) { IRMutator::visit(op); } else { stmt = op; } } }; Stmt inject_profiling(Stmt s, string pipeline_name) { InjectProfiling profiling(pipeline_name); s = profiling.mutate(s); int num_funcs = (int)(profiling.indices.size()); Expr func_names_buf = Load::make(Handle(), "profiling_func_names", 0, Buffer(), Parameter()); func_names_buf = Call::make(Handle(), Call::address_of, {func_names_buf}, Call::Intrinsic); Expr start_profiler = Call::make(Int(32), "halide_profiler_pipeline_start", {pipeline_name, num_funcs, func_names_buf}, Call::Extern); Expr get_state = Call::make(Handle(), "halide_profiler_get_state", {}, Call::Extern); Expr profiler_token = Variable::make(Int(32), "profiler_token"); Expr stop_profiler = Call::make(Int(32), Call::register_destructor, {Expr("halide_profiler_pipeline_end"), get_state}, Call::Intrinsic); s = LetStmt::make("profiler_state", get_state, s); // If there was a problem starting the profiler, it will call an // appropriate halide error function and then return the // (negative) error code as the token. s = Block::make(AssertStmt::make(profiler_token >= 0, profiler_token), s); s = LetStmt::make("profiler_token", start_profiler, s); for (std::pair<string, int> p : profiling.indices) { s = Block::make(Store::make("profiling_func_names", p.first, p.second), s); } s = Block::make(s, Free::make("profiling_func_names")); s = Allocate::make("profiling_func_names", Handle(), {num_funcs}, const_true(), s); s = Block::make(Evaluate::make(stop_profiler), s); return s; } } }
Implement handler for Allocate condition and alloc size computation
Implement handler for Allocate condition and alloc size computation Need to add unit test for the memory profiler Former-commit-id: e8a181a68e98720cf75f5443c5cf816ff57cbb59
C++
mit
Trass3r/Halide,Trass3r/Halide,Trass3r/Halide,darkbuck/Halide,Trass3r/Halide,darkbuck/Halide,Trass3r/Halide,darkbuck/Halide,Trass3r/Halide,darkbuck/Halide,darkbuck/Halide,darkbuck/Halide,darkbuck/Halide,Trass3r/Halide
504c033f0507cfe82c3a18fe6fbc2681b3067334
Modules/Core/src/Rendering/mitkOverlay.cpp
Modules/Core/src/Rendering/mitkOverlay.cpp
/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkOverlay.h" mitk::Overlay::Overlay() : m_LayoutedBy(nullptr) { m_PropertyList = mitk::PropertyList::New(); this->SetName(this->GetNameOfClass()); this->SetVisibility(true); this->SetOpacity(1.0); } mitk::Overlay::~Overlay() { } void mitk::Overlay::SetProperty(const std::string &propertyKey, const BaseProperty::Pointer &propertyValue) { this->m_PropertyList->SetProperty(propertyKey, propertyValue); this->m_PropertyList->Modified(); } void mitk::Overlay::ReplaceProperty(const std::string &propertyKey, const BaseProperty::Pointer &propertyValue) { this->m_PropertyList->ReplaceProperty(propertyKey, propertyValue); this->m_PropertyList->Modified(); } void mitk::Overlay::AddProperty(const std::string &propertyKey, const BaseProperty::Pointer &propertyValue, bool overwrite) { if ((overwrite) || (GetProperty(propertyKey) == NULL)) { SetProperty(propertyKey, propertyValue); } } void mitk::Overlay::ConcatenatePropertyList(PropertyList *pList, bool replace) { m_PropertyList->ConcatenatePropertyList(pList, replace); } mitk::BaseProperty *mitk::Overlay::GetProperty(const std::string &propertyKey) const { mitk::BaseProperty::Pointer property = m_PropertyList->GetProperty(propertyKey); if (property.IsNotNull()) return property; // only to satisfy compiler! return NULL; } bool mitk::Overlay::GetBoolProperty(const std::string &propertyKey, bool &boolValue) const { mitk::BoolProperty::Pointer boolprop = dynamic_cast<mitk::BoolProperty *>(GetProperty(propertyKey)); if (boolprop.IsNull()) return false; boolValue = boolprop->GetValue(); return true; } bool mitk::Overlay::GetIntProperty(const std::string &propertyKey, int &intValue) const { mitk::IntProperty::Pointer intprop = dynamic_cast<mitk::IntProperty *>(GetProperty(propertyKey)); if (intprop.IsNull()) return false; intValue = intprop->GetValue(); return true; } bool mitk::Overlay::GetFloatProperty(const std::string &propertyKey, float &floatValue) const { mitk::FloatProperty::Pointer floatprop = dynamic_cast<mitk::FloatProperty *>(GetProperty(propertyKey)); if (floatprop.IsNull()) return false; floatValue = floatprop->GetValue(); return true; } bool mitk::Overlay::GetStringProperty(const std::string &propertyKey, std::string &string) const { mitk::StringProperty::Pointer stringProp = dynamic_cast<mitk::StringProperty *>(GetProperty(propertyKey)); if (stringProp.IsNull()) { return false; } else { // memcpy((void*)string, stringProp->GetValue(), strlen(stringProp->GetValue()) + 1 ); // looks dangerous string = stringProp->GetValue(); return true; } } void mitk::Overlay::SetIntProperty(const std::string &propertyKey, int intValue) { this->m_PropertyList->SetProperty(propertyKey, mitk::IntProperty::New(intValue)); Modified(); } void mitk::Overlay::SetBoolProperty(const std::string &propertyKey, bool boolValue) { this->m_PropertyList->SetProperty(propertyKey, mitk::BoolProperty::New(boolValue)); Modified(); } void mitk::Overlay::SetFloatProperty(const std::string &propertyKey, float floatValue) { this->m_PropertyList->SetProperty(propertyKey, mitk::FloatProperty::New(floatValue)); Modified(); } void mitk::Overlay::SetStringProperty(const std::string &propertyKey, const std::string &stringValue) { this->m_PropertyList->SetProperty(propertyKey, mitk::StringProperty::New(stringValue)); Modified(); } std::string mitk::Overlay::GetName() const { mitk::StringProperty *sp = dynamic_cast<mitk::StringProperty *>(this->GetProperty("name")); if (sp == NULL) return ""; return sp->GetValue(); } void mitk::Overlay::SetName(const std::string &name) { this->SetStringProperty("name", name); } bool mitk::Overlay::GetName(std::string &nodeName, const std::string &propertyKey) const { return GetStringProperty(propertyKey, nodeName); } void mitk::Overlay::SetText(std::string text) { SetStringProperty("Text", text.c_str()); } std::string mitk::Overlay::GetText() const { std::string text; GetStringProperty("Text", text); return text; } void mitk::Overlay::SetFontSize(int fontSize) { SetIntProperty("FontSize", fontSize); } int mitk::Overlay::GetFontSize() const { int fontSize = 1; GetIntProperty("FontSize", fontSize); return fontSize; } bool mitk::Overlay::GetVisibility(bool &visible, const std::string &propertyKey) const { return GetBoolProperty(propertyKey, visible); } bool mitk::Overlay::IsVisible(const std::string &propertyKey, bool defaultIsOn) const { return IsOn(propertyKey, defaultIsOn); } bool mitk::Overlay::GetColor(float rgb[], const std::string &propertyKey) const { mitk::ColorProperty::Pointer colorprop = dynamic_cast<mitk::ColorProperty *>(GetProperty(propertyKey)); if (colorprop.IsNull()) return false; memcpy(rgb, colorprop->GetColor().GetDataPointer(), 3 * sizeof(float)); return true; } void mitk::Overlay::SetColor(const mitk::Color &color, const std::string &propertyKey) { mitk::ColorProperty::Pointer prop; prop = mitk::ColorProperty::New(color); this->m_PropertyList->SetProperty(propertyKey, prop); } void mitk::Overlay::SetColor(float red, float green, float blue, const std::string &propertyKey) { float color[3]; color[0] = red; color[1] = green; color[2] = blue; SetColor(color, propertyKey); } void mitk::Overlay::SetColor(const float rgb[], const std::string &propertyKey) { mitk::ColorProperty::Pointer prop; prop = mitk::ColorProperty::New(rgb); this->m_PropertyList->SetProperty(propertyKey, prop); } bool mitk::Overlay::GetOpacity(float &opacity, const std::string &propertyKey) const { mitk::FloatProperty::Pointer opacityprop = dynamic_cast<mitk::FloatProperty *>(GetProperty(propertyKey)); if (opacityprop.IsNull()) return false; opacity = opacityprop->GetValue(); return true; } void mitk::Overlay::SetOpacity(float opacity, const std::string &propertyKey) { mitk::FloatProperty::Pointer prop; prop = mitk::FloatProperty::New(opacity); this->m_PropertyList->SetProperty(propertyKey, prop); } void mitk::Overlay::SetVisibility(bool visible, const std::string &propertyKey) { mitk::BoolProperty::Pointer prop; prop = mitk::BoolProperty::New(visible); bool mitk::Overlay::BaseLocalStorage::IsGenerateDataRequired(mitk::BaseRenderer * renderer, mitk::Overlay * overlay) { if (m_LastGenerateDataTime < overlay->GetMTime()) return true; if (m_LastGenerateDataTime < overlay->GetPropertyList()->GetMTime()) return true; if (m_LastGenerateDataTime < overlay->GetPropertyList(renderer)->GetMTime()) return true; if (renderer && m_LastGenerateDataTime < renderer->GetTimeStepUpdateTime()) return true; return false; } mitk::Overlay::Bounds mitk::Overlay::GetBoundsOnDisplay(mitk::BaseRenderer *) const { mitk::Overlay::Bounds bounds; bounds.Position[0] = bounds.Position[1] = bounds.Size[0] = bounds.Size[1] = 0; return bounds; } void mitk::Overlay::SetBoundsOnDisplay(mitk::BaseRenderer *, const mitk::Overlay::Bounds &) {} void mitk::Overlay::SetForceInForeground(bool forceForeground) { m_ForceInForeground = forceForeground; } bool mitk::Overlay::IsForceInForeground() const { return m_ForceInForeground; }
/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkOverlay.h" mitk::Overlay::Overlay() : m_LayoutedBy(nullptr) { m_PropertyList = mitk::PropertyList::New(); this->SetName(this->GetNameOfClass()); this->SetVisibility(true); this->SetOpacity(1.0); } mitk::Overlay::~Overlay() { } void mitk::Overlay::SetProperty(const std::string &propertyKey, const BaseProperty::Pointer &propertyValue) { this->m_PropertyList->SetProperty(propertyKey, propertyValue); this->m_PropertyList->Modified(); } void mitk::Overlay::ReplaceProperty(const std::string &propertyKey, const BaseProperty::Pointer &propertyValue) { this->m_PropertyList->ReplaceProperty(propertyKey, propertyValue); this->m_PropertyList->Modified(); } void mitk::Overlay::AddProperty(const std::string &propertyKey, const BaseProperty::Pointer &propertyValue, bool overwrite) { if ((overwrite) || (GetProperty(propertyKey) == NULL)) { SetProperty(propertyKey, propertyValue); } } void mitk::Overlay::ConcatenatePropertyList(PropertyList *pList, bool replace) { m_PropertyList->ConcatenatePropertyList(pList, replace); } mitk::BaseProperty *mitk::Overlay::GetProperty(const std::string &propertyKey) const { mitk::BaseProperty::Pointer property = m_PropertyList->GetProperty(propertyKey); if (property.IsNotNull()) return property; // only to satisfy compiler! return NULL; } bool mitk::Overlay::GetBoolProperty(const std::string &propertyKey, bool &boolValue) const { mitk::BoolProperty::Pointer boolprop = dynamic_cast<mitk::BoolProperty *>(GetProperty(propertyKey)); if (boolprop.IsNull()) return false; boolValue = boolprop->GetValue(); return true; } bool mitk::Overlay::GetIntProperty(const std::string &propertyKey, int &intValue) const { mitk::IntProperty::Pointer intprop = dynamic_cast<mitk::IntProperty *>(GetProperty(propertyKey)); if (intprop.IsNull()) return false; intValue = intprop->GetValue(); return true; } bool mitk::Overlay::GetFloatProperty(const std::string &propertyKey, float &floatValue) const { mitk::FloatProperty::Pointer floatprop = dynamic_cast<mitk::FloatProperty *>(GetProperty(propertyKey)); if (floatprop.IsNull()) return false; floatValue = floatprop->GetValue(); return true; } bool mitk::Overlay::GetStringProperty(const std::string &propertyKey, std::string &string) const { mitk::StringProperty::Pointer stringProp = dynamic_cast<mitk::StringProperty *>(GetProperty(propertyKey)); if (stringProp.IsNull()) { return false; } else { // memcpy((void*)string, stringProp->GetValue(), strlen(stringProp->GetValue()) + 1 ); // looks dangerous string = stringProp->GetValue(); return true; } } void mitk::Overlay::SetIntProperty(const std::string &propertyKey, int intValue) { this->m_PropertyList->SetProperty(propertyKey, mitk::IntProperty::New(intValue)); Modified(); } void mitk::Overlay::SetBoolProperty(const std::string &propertyKey, bool boolValue) { this->m_PropertyList->SetProperty(propertyKey, mitk::BoolProperty::New(boolValue)); Modified(); } void mitk::Overlay::SetFloatProperty(const std::string &propertyKey, float floatValue) { this->m_PropertyList->SetProperty(propertyKey, mitk::FloatProperty::New(floatValue)); Modified(); } void mitk::Overlay::SetStringProperty(const std::string &propertyKey, const std::string &stringValue) { this->m_PropertyList->SetProperty(propertyKey, mitk::StringProperty::New(stringValue)); Modified(); } std::string mitk::Overlay::GetName() const { mitk::StringProperty *sp = dynamic_cast<mitk::StringProperty *>(this->GetProperty("name")); if (sp == NULL) return ""; return sp->GetValue(); } void mitk::Overlay::SetName(const std::string &name) { this->SetStringProperty("name", name); } bool mitk::Overlay::GetName(std::string &nodeName, const std::string &propertyKey) const { return GetStringProperty(propertyKey, nodeName); } void mitk::Overlay::SetText(std::string text) { SetStringProperty("Text", text.c_str()); } std::string mitk::Overlay::GetText() const { std::string text; GetStringProperty("Text", text); return text; } void mitk::Overlay::SetFontSize(int fontSize) { SetIntProperty("FontSize", fontSize); } int mitk::Overlay::GetFontSize() const { int fontSize = 1; GetIntProperty("FontSize", fontSize); return fontSize; } bool mitk::Overlay::GetVisibility(bool &visible, const std::string &propertyKey) const { return GetBoolProperty(propertyKey, visible); } bool mitk::Overlay::IsVisible(const std::string &propertyKey, bool defaultIsOn) const { return IsOn(propertyKey, defaultIsOn); } bool mitk::Overlay::GetColor(float rgb[], const std::string &propertyKey) const { mitk::ColorProperty::Pointer colorprop = dynamic_cast<mitk::ColorProperty *>(GetProperty(propertyKey)); if (colorprop.IsNull()) return false; memcpy(rgb, colorprop->GetColor().GetDataPointer(), 3 * sizeof(float)); return true; } void mitk::Overlay::SetColor(const mitk::Color &color, const std::string &propertyKey) { mitk::ColorProperty::Pointer prop; prop = mitk::ColorProperty::New(color); this->m_PropertyList->SetProperty(propertyKey, prop); } void mitk::Overlay::SetColor(float red, float green, float blue, const std::string &propertyKey) { float color[3]; color[0] = red; color[1] = green; color[2] = blue; SetColor(color, propertyKey); } void mitk::Overlay::SetColor(const float rgb[], const std::string &propertyKey) { mitk::ColorProperty::Pointer prop; prop = mitk::ColorProperty::New(rgb); this->m_PropertyList->SetProperty(propertyKey, prop); } bool mitk::Overlay::GetOpacity(float &opacity, const std::string &propertyKey) const { mitk::FloatProperty::Pointer opacityprop = dynamic_cast<mitk::FloatProperty *>(GetProperty(propertyKey)); if (opacityprop.IsNull()) return false; opacity = opacityprop->GetValue(); return true; } void mitk::Overlay::SetOpacity(float opacity, const std::string &propertyKey) { mitk::FloatProperty::Pointer prop; prop = mitk::FloatProperty::New(opacity); this->m_PropertyList->SetProperty(propertyKey, prop); } void mitk::Overlay::SetVisibility(bool visible, const std::string &propertyKey) { mitk::BoolProperty::Pointer prop; prop = mitk::BoolProperty::New(visible); this->m_PropertyList->SetProperty(propertyKey, prop); } bool mitk::Overlay::BaseLocalStorage::IsGenerateDataRequired(mitk::BaseRenderer * renderer, mitk::Overlay * overlay) { if (m_LastGenerateDataTime < overlay->GetMTime()) return true; if (m_LastGenerateDataTime < overlay->GetPropertyList()->GetMTime()) return true; if (m_LastGenerateDataTime < overlay->GetPropertyList(renderer)->GetMTime()) return true; if (renderer && m_LastGenerateDataTime < renderer->GetTimeStepUpdateTime()) return true; return false; } mitk::Overlay::Bounds mitk::Overlay::GetBoundsOnDisplay(mitk::BaseRenderer *) const { mitk::Overlay::Bounds bounds; bounds.Position[0] = bounds.Position[1] = bounds.Size[0] = bounds.Size[1] = 0; return bounds; } void mitk::Overlay::SetBoundsOnDisplay(mitk::BaseRenderer *, const mitk::Overlay::Bounds &) {} void mitk::Overlay::SetForceInForeground(bool forceForeground) { m_ForceInForeground = forceForeground; } bool mitk::Overlay::IsForceInForeground() const { return m_ForceInForeground; }
fix merge error
fix merge error
C++
bsd-3-clause
fmilano/mitk,MITK/MITK,fmilano/mitk,fmilano/mitk,MITK/MITK,MITK/MITK,fmilano/mitk,fmilano/mitk,MITK/MITK,MITK/MITK,fmilano/mitk,fmilano/mitk,MITK/MITK
45e272ac5d825d8cca49ed9eedc426e8355431d3
DK/DKFoundation/DKThread.cpp
DK/DKFoundation/DKThread.cpp
// // File: DKThread.cpp // Author: Hongtae Kim ([email protected]) // // Copyright (c) 2004-2016 Hongtae Kim. All rights reserved. // #ifdef _WIN32 #include <process.h> #include <windows.h> #else #include <pthread.h> #include <sys/select.h> #include <sched.h> // to using sched_yield() in DKThread::Yield() #include <errno.h> #include <limits.h> #endif #include "DKThread.h" #include "DKObject.h" #include "DKError.h" #include "DKMap.h" #include "DKMutex.h" #include "DKCondition.h" #include "DKSpinLock.h" #include "DKFunction.h" #include "DKLog.h" #ifndef POSIX_USE_SELECT_SLEEP /// Set POSIX_USE_SELECT_SLEEP to 1 if you want use 'select' instead of 'nanosleep'. /// ignored on Win32. #define POSIX_USE_SELECT_SLEEP 1 #endif namespace DKFoundation { namespace Private { #if defined(__APPLE__) && defined(__MACH__) bool InitializeMultiThreadedEnvironment(); void PerformOperationInsidePool(DKOperation* op); #else FORCEINLINE bool InitializeMultiThreadedEnvironment() { return true; } FORCEINLINE void PerformOperationInsidePool(DKOperation* op) {op->Perform();} #endif void PerformOperationWithErrorHandler(const DKOperation*, size_t); struct ThreadCreationInfo { DKThread::ThreadId id; DKObject<DKOperation> op; }; struct ThreadContext { DKThread::ThreadId id; DKObject<DKOperation> op; bool running; }; typedef DKMap<DKThread::ThreadId, ThreadContext> RunningThreadsMap; static RunningThreadsMap runningThreads; static DKCondition threadCond; #ifdef _WIN32 unsigned int __stdcall ThreadProc(void* p) { #else void* ThreadProc(void* p) { //pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL); //pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL); #endif ThreadCreationInfo* param = reinterpret_cast<ThreadCreationInfo*>(p); // register running threads; threadCond.Lock(); DKThread::ThreadId tid = DKThread::CurrentThreadId(); ThreadContext& ctxt = runningThreads.Value(tid); ctxt.id = tid; ctxt.op = param->op; ctxt.running = false; param->id = tid; threadCond.Broadcast(); // waiting for ctxt.running is being flagged. while (!ctxt.running) threadCond.Wait(); threadCond.Unlock(); if (ctxt.op) { // Calling thread procedure. // To use NSAutoreleasePool in Cocoa, // Wrap operation with PerformOperatonInsidePool. struct OpWrapper : public DKOperation { OpWrapper(DKOperation* o) : op(o) {} DKOperation* op; void Perform() const override { PerformOperationWithErrorHandler(op, DKERROR_DEFAULT_CALLSTACK_TRACE_DEPTH); } }; OpWrapper wrapper(ctxt.op); PerformOperationInsidePool(&wrapper); } threadCond.Lock(); runningThreads.Remove(tid); threadCond.Broadcast(); threadCond.Unlock(); // terminate thread. #ifdef _WIN32 //ExitThread(0); _endthreadex(0); #else pthread_exit(0); #endif return 0; } static ThreadContext* CreateThread(DKOperation* op, size_t stackSize) { if (op == NULL) return NULL; InitializeMultiThreadedEnvironment(); ThreadCreationInfo param; param.id = DKThread::invalidId; param.op = op; bool failed = true; #ifdef _WIN32 if (stackSize > 0) { size_t pageSize = DKMemoryPageSize(); if (stackSize % pageSize) stackSize += pageSize - (stackSize % pageSize); } unsigned int id; HANDLE h = (HANDLE)_beginthreadex(0, stackSize, ThreadProc, reinterpret_cast<void*>(&param), 0, &id); if (h) { // a closed handle could be recycled by system. CloseHandle(h); failed = false; } #else // set pthread to detached, unable to be joined. pthread_t id; pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); if (stackSize > 0) { stackSize = Max(stackSize, (size_t)PTHREAD_STACK_MIN); size_t pageSize = DKMemoryPageSize(); if (stackSize % pageSize) stackSize += pageSize - (stackSize % pageSize); pthread_attr_setstacksize(&attr, stackSize); } failed = (bool)pthread_create((pthread_t*)&id, &attr, ThreadProc, reinterpret_cast<void*>(&param)); pthread_attr_destroy(&attr); #endif if (!failed) { DKCriticalSection<DKCondition> guard(threadCond); while (param.id == DKThread::invalidId) threadCond.Wait(); while (true) { RunningThreadsMap::Pair* p = runningThreads.Find(param.id); if (p) return &p->value; threadCond.Wait(); } } return NULL; } } } using namespace DKFoundation; using namespace DKFoundation::Private; const DKThread::ThreadId DKThread::invalidId = (DKThread::ThreadId)0; DKThread::DKThread() : threadId(invalidId) { } DKThread::~DKThread() { } DKObject<DKThread> DKThread::FindThread(ThreadId id) { DKCriticalSection<DKCondition> guard(threadCond); if (runningThreads.Find(id) != NULL) { DKObject<DKThread> ret = DKObject<DKThread>::New(); ret->threadId = id; return ret; } return NULL; } DKObject<DKThread> DKThread::CurrentThread() { return FindThread(CurrentThreadId()); } DKThread::ThreadId DKThread::CurrentThreadId() { #ifdef _WIN32 return (ThreadId)::GetCurrentThreadId(); #else return (ThreadId)pthread_self(); #endif } void DKThread::Yield() { #ifdef _WIN32 if (SwitchToThread() == 0) Sleep(0); #else if (sched_yield() != 0) Sleep(0); #endif } void DKThread::Sleep(double d) { d = Max(d, 0.0); #ifdef _WIN32 DWORD dwTime = static_cast<DWORD>(d * 1000.0f); ::Sleep(dwTime); #elif POSIX_USE_SELECT_SLEEP timeval tm; uint64_t ms = (uint64_t)(d * 1000000.0); tm.tv_sec = ms / 1000000; tm.tv_usec = ms % 1000000; select(0, 0, 0, 0, &tm); #else long sec = static_cast<long>(d); long usec = (d - sec) * 1000000; struct timespec req = {sec, usec * 1000}; while ( nanosleep(&req, &req) != 0 ) { // internal error! (except for signal, intrrupt) if (errno != EINTR) break; } #endif } DKObject<DKThread> DKThread::Create(const DKOperation* operation, size_t stackSize) { if (operation == NULL) return NULL; ThreadContext* ctxt = CreateThread(const_cast<DKOperation*>(operation), stackSize); if (ctxt) { DKObject<DKThread> ret = DKObject<DKThread>::New(); DKCriticalSection<DKCondition> guard(threadCond); if (true) { ctxt->running = true; threadCond.Broadcast(); } ret->threadId = ctxt->id; // param will be deleted by thread. return ret; } return NULL; } void DKThread::WaitTerminate() const { if (threadId != invalidId) { DKASSERT_DESC(threadId != CurrentThreadId(), "Cannot wait current thread"); DKCriticalSection<DKCondition> guard(threadCond); while (runningThreads.Find(threadId)) threadCond.Wait(); threadId = invalidId; Yield(); } } DKThread::ThreadId DKThread::Id() const { if (threadId != invalidId) { DKCriticalSection<DKCondition> guard(threadCond); if (runningThreads.Find(threadId)) return threadId; threadId = invalidId; } return invalidId; } bool DKThread::IsAlive() const { if (threadId != invalidId) { if (CurrentThreadId() == threadId) return true; DKCriticalSection<DKCondition> guard(threadCond); if (runningThreads.Find(threadId)) return true; threadId = invalidId; } return false; } bool DKThread::SetPriority(double p) { ThreadId tid = Id(); #if _WIN32 HANDLE hThread = OpenThread(THREAD_SET_INFORMATION, FALSE, (DWORD)tid); if (hThread) { const int priorities[5] = { THREAD_PRIORITY_LOWEST, THREAD_PRIORITY_BELOW_NORMAL, THREAD_PRIORITY_NORMAL, THREAD_PRIORITY_ABOVE_NORMAL, THREAD_PRIORITY_HIGHEST }; int prio = Clamp<int>(floor(p * 4.0 + 0.5), 0, 4); bool ret = ::SetThreadPriority(hThread, priorities[prio]) != 0; CloseHandle(hThread); return ret; } else { DKLogE("DKThread::SetPriority Error: OpenThread Error"); } return false; #else int policy = SCHED_FIFO; struct sched_param schedule; if (pthread_getschedparam((pthread_t)tid, &policy, &schedule) != 0) { return false; } p = Clamp(p, 0.0, 1.0); int min_priority = sched_get_priority_min(policy); int max_priority = sched_get_priority_max(policy); schedule.sched_priority = (int)p * (max_priority - min_priority) + min_priority; return pthread_setschedparam((pthread_t)tid, policy, &schedule) == 0; #endif } double DKThread::Priority() const { ThreadId tid = Id(); #if _WIN32 HANDLE hThread = OpenThread(THREAD_QUERY_INFORMATION, FALSE, (DWORD)tid); if (hThread) { int prio = ::GetThreadPriority(hThread); CloseHandle(hThread); if (prio == THREAD_PRIORITY_ERROR_RETURN) { DKLogE("DKThread::Priority Error: GetThreadPriority failed"); } else { const int priorities[5] = { THREAD_PRIORITY_LOWEST, THREAD_PRIORITY_BELOW_NORMAL, THREAD_PRIORITY_NORMAL, THREAD_PRIORITY_ABOVE_NORMAL, THREAD_PRIORITY_HIGHEST }; for (int i = 0; i < 4; ++i) { if (prio < priorities[i+1]) { return Clamp(double(i) / 4.0, 0.0, 1.0); } } } } else { DKLogE("DKThread::SetPriority Error: OpenThread Error"); } return 1.0; #else int policy = SCHED_FIFO; struct sched_param schedule; if (pthread_getschedparam((pthread_t)tid, &policy, &schedule) != 0) { return 1.0; } int min_priority = sched_get_priority_min(policy); int max_priority = sched_get_priority_max(policy); return (double)(schedule.sched_priority - min_priority) / (double)(max_priority - min_priority); #endif }
// // File: DKThread.cpp // Author: Hongtae Kim ([email protected]) // // Copyright (c) 2004-2016 Hongtae Kim. All rights reserved. // #ifdef _WIN32 #include <process.h> #include <windows.h> #else #include <pthread.h> #include <sys/select.h> #include <sched.h> // to using sched_yield() in DKThread::Yield() #include <errno.h> #include <limits.h> #endif #include "DKThread.h" #include "DKObject.h" #include "DKError.h" #include "DKMap.h" #include "DKMutex.h" #include "DKCondition.h" #include "DKSpinLock.h" #include "DKFunction.h" #include "DKLog.h" #ifndef POSIX_USE_SELECT_SLEEP /// Set POSIX_USE_SELECT_SLEEP to 1 if you want use 'select' instead of 'nanosleep'. /// ignored on Win32. #define POSIX_USE_SELECT_SLEEP 1 #endif namespace DKFoundation::Private { #if defined(__APPLE__) && defined(__MACH__) bool InitializeMultiThreadedEnvironment(); void PerformOperationInsidePool(DKOperation* op); #else FORCEINLINE bool InitializeMultiThreadedEnvironment() { return true; } FORCEINLINE void PerformOperationInsidePool(DKOperation* op) { op->Perform(); } #endif void PerformOperationWithErrorHandler(const DKOperation*, size_t); struct ThreadCreationInfo { DKThread::ThreadId id; DKObject<DKOperation> op; }; struct ThreadContext { DKThread::ThreadId id; DKObject<DKOperation> op; bool running; }; typedef DKMap<DKThread::ThreadId, ThreadContext> RunningThreadsMap; static RunningThreadsMap runningThreads; static DKCondition threadCond; #ifdef _WIN32 DKString GetWin32ErrorString(DWORD dwError); // defined DKError.cpp unsigned int __stdcall ThreadProc(void* p) { #else void* ThreadProc(void* p) { //pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL); //pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL); #endif ThreadCreationInfo* param = reinterpret_cast<ThreadCreationInfo*>(p); // register running threads; threadCond.Lock(); DKThread::ThreadId tid = DKThread::CurrentThreadId(); ThreadContext& ctxt = runningThreads.Value(tid); ctxt.id = tid; ctxt.op = param->op; ctxt.running = false; param->id = tid; threadCond.Broadcast(); // waiting for ctxt.running is being flagged. while (!ctxt.running) threadCond.Wait(); threadCond.Unlock(); if (ctxt.op) { // Calling thread procedure. // To use NSAutoreleasePool in Cocoa, // Wrap operation with PerformOperatonInsidePool. struct OpWrapper : public DKOperation { OpWrapper(DKOperation* o) : op(o) {} DKOperation* op; void Perform() const override { PerformOperationWithErrorHandler(op, DKERROR_DEFAULT_CALLSTACK_TRACE_DEPTH); } }; OpWrapper wrapper(ctxt.op); PerformOperationInsidePool(&wrapper); } threadCond.Lock(); runningThreads.Remove(tid); threadCond.Broadcast(); threadCond.Unlock(); // terminate thread. #ifdef _WIN32 //ExitThread(0); _endthreadex(0); #else pthread_exit(0); #endif return 0; } static ThreadContext* CreateThread(DKOperation* op, size_t stackSize) { if (op == NULL) return NULL; InitializeMultiThreadedEnvironment(); ThreadCreationInfo param; param.id = DKThread::invalidId; param.op = op; bool failed = true; #ifdef _WIN32 if (stackSize > 0) { size_t pageSize = DKMemoryPageSize(); if (stackSize % pageSize) stackSize += pageSize - (stackSize % pageSize); } unsigned int id; HANDLE h = (HANDLE)_beginthreadex(0, stackSize, ThreadProc, reinterpret_cast<void*>(&param), 0, &id); if (h) { static const int numProcessorGroups = GetMaximumProcessorGroupCount(); if (numProcessorGroups > 1) { static WORD groupId = 0; WORD affinityGroup = groupId++; affinityGroup = affinityGroup % numProcessorGroups; DKLogI("Setting thread group affinity: %d / %d", affinityGroup, numProcessorGroups); GROUP_AFFINITY groupAffinity = {}; groupAffinity.Mask = ~KAFFINITY(0); groupAffinity.Group = affinityGroup; if (!SetThreadGroupAffinity(h, &groupAffinity, NULL)) { DKLogE("SetThreadGroupAffinity Error: %ls", (const wchar_t*)GetWin32ErrorString(GetLastError())); } } // a closed handle could be recycled by system. CloseHandle(h); failed = false; } #else // set pthread to detached, unable to be joined. pthread_t id; pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); if (stackSize > 0) { stackSize = Max(stackSize, (size_t)PTHREAD_STACK_MIN); size_t pageSize = DKMemoryPageSize(); if (stackSize % pageSize) stackSize += pageSize - (stackSize % pageSize); pthread_attr_setstacksize(&attr, stackSize); } failed = (bool)pthread_create((pthread_t*)&id, &attr, ThreadProc, reinterpret_cast<void*>(&param)); pthread_attr_destroy(&attr); #endif if (!failed) { DKCriticalSection<DKCondition> guard(threadCond); while (param.id == DKThread::invalidId) threadCond.Wait(); DKASSERT_DEBUG(param.id == (DKThread::ThreadId)id); while (true) { RunningThreadsMap::Pair* p = runningThreads.Find(param.id); if (p) return &p->value; threadCond.Wait(); } } return NULL; } } using namespace DKFoundation; using namespace DKFoundation::Private; const DKThread::ThreadId DKThread::invalidId = (DKThread::ThreadId)0; DKThread::DKThread() : threadId(invalidId) { } DKThread::~DKThread() { } DKObject<DKThread> DKThread::FindThread(ThreadId id) { DKCriticalSection<DKCondition> guard(threadCond); if (runningThreads.Find(id) != NULL) { DKObject<DKThread> ret = DKObject<DKThread>::New(); ret->threadId = id; return ret; } return NULL; } DKObject<DKThread> DKThread::CurrentThread() { return FindThread(CurrentThreadId()); } DKThread::ThreadId DKThread::CurrentThreadId() { #ifdef _WIN32 return (ThreadId)::GetCurrentThreadId(); #else return (ThreadId)pthread_self(); #endif } void DKThread::Yield() { #ifdef _WIN32 if (SwitchToThread() == 0) Sleep(0); #else if (sched_yield() != 0) Sleep(0); #endif } void DKThread::Sleep(double d) { d = Max(d, 0.0); #ifdef _WIN32 DWORD dwTime = static_cast<DWORD>(d * 1000.0f); ::Sleep(dwTime); #elif POSIX_USE_SELECT_SLEEP timeval tm; uint64_t ms = (uint64_t)(d * 1000000.0); tm.tv_sec = ms / 1000000; tm.tv_usec = ms % 1000000; select(0, 0, 0, 0, &tm); #else long sec = static_cast<long>(d); long usec = (d - sec) * 1000000; struct timespec req = {sec, usec * 1000}; while ( nanosleep(&req, &req) != 0 ) { // internal error! (except for signal, intrrupt) if (errno != EINTR) break; } #endif } DKObject<DKThread> DKThread::Create(const DKOperation* operation, size_t stackSize) { if (operation == NULL) return NULL; ThreadContext* ctxt = CreateThread(const_cast<DKOperation*>(operation), stackSize); if (ctxt) { DKObject<DKThread> ret = DKObject<DKThread>::New(); DKCriticalSection<DKCondition> guard(threadCond); if (true) { ctxt->running = true; threadCond.Broadcast(); } ret->threadId = ctxt->id; // param will be deleted by thread. return ret; } return NULL; } void DKThread::WaitTerminate() const { if (threadId != invalidId) { DKASSERT_DESC(threadId != CurrentThreadId(), "Cannot wait current thread"); DKCriticalSection<DKCondition> guard(threadCond); while (runningThreads.Find(threadId)) threadCond.Wait(); threadId = invalidId; Yield(); } } DKThread::ThreadId DKThread::Id() const { if (threadId != invalidId) { DKCriticalSection<DKCondition> guard(threadCond); if (runningThreads.Find(threadId)) return threadId; threadId = invalidId; } return invalidId; } bool DKThread::IsAlive() const { if (threadId != invalidId) { if (CurrentThreadId() == threadId) return true; DKCriticalSection<DKCondition> guard(threadCond); if (runningThreads.Find(threadId)) return true; threadId = invalidId; } return false; } bool DKThread::SetPriority(double p) { ThreadId tid = Id(); #if _WIN32 HANDLE hThread = OpenThread(THREAD_SET_INFORMATION, FALSE, (DWORD)tid); if (hThread) { const int priorities[5] = { THREAD_PRIORITY_LOWEST, THREAD_PRIORITY_BELOW_NORMAL, THREAD_PRIORITY_NORMAL, THREAD_PRIORITY_ABOVE_NORMAL, THREAD_PRIORITY_HIGHEST }; int prio = Clamp<int>(floor(p * 4.0 + 0.5), 0, 4); bool ret = ::SetThreadPriority(hThread, priorities[prio]) != 0; CloseHandle(hThread); return ret; } else { DKLogE("DKThread::SetPriority Error: OpenThread Error"); } return false; #else int policy = SCHED_FIFO; struct sched_param schedule; if (pthread_getschedparam((pthread_t)tid, &policy, &schedule) != 0) { return false; } p = Clamp(p, 0.0, 1.0); int min_priority = sched_get_priority_min(policy); int max_priority = sched_get_priority_max(policy); schedule.sched_priority = (int)p * (max_priority - min_priority) + min_priority; return pthread_setschedparam((pthread_t)tid, policy, &schedule) == 0; #endif } double DKThread::Priority() const { ThreadId tid = Id(); #if _WIN32 HANDLE hThread = OpenThread(THREAD_QUERY_INFORMATION, FALSE, (DWORD)tid); if (hThread) { int prio = ::GetThreadPriority(hThread); CloseHandle(hThread); if (prio == THREAD_PRIORITY_ERROR_RETURN) { DKLogE("DKThread::Priority Error: GetThreadPriority failed"); } else { const int priorities[5] = { THREAD_PRIORITY_LOWEST, THREAD_PRIORITY_BELOW_NORMAL, THREAD_PRIORITY_NORMAL, THREAD_PRIORITY_ABOVE_NORMAL, THREAD_PRIORITY_HIGHEST }; for (int i = 0; i < 4; ++i) { if (prio < priorities[i+1]) { return Clamp(double(i) / 4.0, 0.0, 1.0); } } } } else { DKLogE("DKThread::SetPriority Error: OpenThread Error"); } return 1.0; #else int policy = SCHED_FIFO; struct sched_param schedule; if (pthread_getschedparam((pthread_t)tid, &policy, &schedule) != 0) { return 1.0; } int min_priority = sched_get_priority_min(policy); int max_priority = sched_get_priority_max(policy); return (double)(schedule.sched_priority - min_priority) / (double)(max_priority - min_priority); #endif }
Set the thread process affinity group for multiple processor groups when creating a thread (when using more than 64 cores on Win32)
Set the thread process affinity group for multiple processor groups when creating a thread (when using more than 64 cores on Win32)
C++
bsd-3-clause
DKGL/DKGL,tiff2766/DKLib,DKGL/DKGL,Hongtae/DKGL,Hongtae/DKGL,Hongtae/DKGL,DKGL/DKGL,DKGL/DKGL,DKGL/DKGL,tiff2766/DKLib,DKGL/DKGL,Hongtae/DKGL,tiff2766/DKLib,DKGL/DKGL,Hongtae/DKGL,Hongtae/DKGL,tiff2766/DKLib,Hongtae/DKGL,DKGL/DKGL,Hongtae/DKGL,tiff2766/DKLib,tiff2766/DKLib
00634c0620f9a6718661173cbd3ab5e2a5a7eafe
OpenSim/Common/Test/testC3DFileAdapter.cpp
OpenSim/Common/Test/testC3DFileAdapter.cpp
/* -------------------------------------------------------------------------- * * OpenSim: testC3DFileAdapter.cpp * * -------------------------------------------------------------------------- * * The OpenSim API is a toolkit for musculoskeletal modeling and simulation. * * See http://opensim.stanford.edu and the NOTICE file for more information. * * OpenSim is developed at Stanford University and supported by the US * * National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA * * through the Warrior Web program. * * * * Copyright (c) 2005-2017 Stanford University and the 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 "OpenSim/Common/C3DFileAdapter.h" #include "OpenSim/Common/TRCFileAdapter.h" #include <OpenSim/Auxiliary/auxiliaryTestFunctions.h> #include <vector> #include <unordered_map> #include <cstdlib> #include <chrono> #include <thread> #include <cmath> template<typename> class shrik; void compare_tables(const OpenSim::TimeSeriesTableVec3& table1, const OpenSim::TimeSeriesTableVec3& table2, const double tolerance = SimTK::SignificantReal) { using namespace OpenSim; try { OPENSIM_THROW_IF(table1.getColumnLabels() != table2.getColumnLabels(), Exception, "Column labels are not the same for tables."); ASSERT_EQUAL( table1.getIndependentColumn(), table2.getIndependentColumn(), tolerance, __FILE__, __LINE__, "Independent columns are not equivalent."); } catch (const OpenSim::KeyNotFound&) {} const auto& matrix1 = table1.getMatrix(); const auto& matrix2 = table2.getMatrix(); for(int r = 0; r < matrix1.nrow(); ++r) for(int c = 0; c < matrix1.ncol(); ++c) { auto elt1 = matrix1.getElt(r, c); auto elt2 = matrix2.getElt(r, c); if (elt1.isNaN() && elt2.isNaN()) continue; ASSERT_EQUAL(elt1, elt2, tolerance, __FILE__, __LINE__, "Elements at row, " + std::to_string(r) + " col, " + std::to_string(c) + " failed to match value of " + elt1.toString()); } } void test(const std::string filename) { using namespace OpenSim; std::clock_t startTime = std::clock(); auto tables = C3DFileAdapter::read(filename, C3DFileAdapter::ForceLocation::Origin); std::cout << "\nC3DFileAdapter '" << filename << "' read time = " << 1.e3*(std::clock() - startTime) / CLOCKS_PER_SEC << "ms\n" << std::endl; auto& marker_table = tables.at("markers"); auto& force_table = tables.at("forces"); size_t ext = filename.rfind("."); std::string base = filename.substr(0, ext); const std::string marker_file = base + "_markers.trc"; const std::string forces_file = base + "_grfs.sto"; ASSERT(marker_table->getNumRows() > 0, __FILE__, __LINE__, "Failed to read marker data from " + filename); marker_table->updTableMetaData().setValueForKey("Units", std::string{"mm"}); TRCFileAdapter trc_adapter{}; trc_adapter.write(*marker_table, marker_file); ASSERT(force_table->getNumRows() > 0, __FILE__, __LINE__, "Failed to read forces data from " + filename); force_table->updTableMetaData().setValueForKey("Units", std::string{"mm"}); STOFileAdapter sto_adapter{}; sto_adapter.write((force_table->flatten()), forces_file); // Verify that marker data was written out and can be read in auto markers = trc_adapter.read(marker_file); auto std_markers = trc_adapter.read("std_" + marker_file); // Compare C3DFileAdapter read-in and written marker data compare_tables(markers, *marker_table); // Compare C3DFileAdapter written marker data to standard // Note std exported from Mokka with only 5 decimal places compare_tables(markers, std_markers, 1e-4); } int main() { std::vector<std::string> filenames{}; filenames.push_back("walking2.c3d"); filenames.push_back("walking5.c3d"); for(const auto& filename : filenames) { std::cout << "Test reading '" + filename + "'." << std::endl; try { test(filename); } catch (const std::exception& ex) { std::cout << "testC3DFileAdapter FAILED: " << ex.what() << std::endl; return 1; } } std::cout << "\nAll testC3DFileAdapter cases passed." << std::endl; return 0; }
/* -------------------------------------------------------------------------- * * OpenSim: testC3DFileAdapter.cpp * * -------------------------------------------------------------------------- * * The OpenSim API is a toolkit for musculoskeletal modeling and simulation. * * See http://opensim.stanford.edu and the NOTICE file for more information. * * OpenSim is developed at Stanford University and supported by the US * * National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA * * through the Warrior Web program. * * * * Copyright (c) 2005-2017 Stanford University and the 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 "OpenSim/Common/C3DFileAdapter.h" #include "OpenSim/Common/TRCFileAdapter.h" #include <OpenSim/Auxiliary/auxiliaryTestFunctions.h> #include <vector> #include <unordered_map> #include <cstdlib> #include <chrono> #include <thread> #include <cmath> template<typename ETY = SimTK::Real> void compare_tables(const OpenSim::TimeSeriesTable_<ETY>& table1, const OpenSim::TimeSeriesTable_<ETY>& table2, const double tolerance = SimTK::SignificantReal) { using namespace OpenSim; try { OPENSIM_THROW_IF(table1.getColumnLabels() != table2.getColumnLabels(), Exception, "Column labels are not the same for tables."); ASSERT_EQUAL( table1.getIndependentColumn(), table2.getIndependentColumn(), tolerance, __FILE__, __LINE__, "Independent columns are not equivalent."); } catch (const OpenSim::KeyNotFound&) {} const auto& matrix1 = table1.getMatrix(); const auto& matrix2 = table2.getMatrix(); for(int r = 0; r < matrix1.nrow(); ++r) for(int c = 0; c < matrix1.ncol(); ++c) { auto elt1 = matrix1.getElt(r, c); auto elt2 = matrix2.getElt(r, c); ASSERT_EQUAL(elt1, elt2, tolerance, __FILE__, __LINE__, "Elements at row, " + std::to_string(r) + " col, " + std::to_string(c) + " failed to have matching value."); } } void test(const std::string filename) { using namespace OpenSim; std::clock_t startTime = std::clock(); auto tables = C3DFileAdapter::read(filename, C3DFileAdapter::ForceLocation::Origin); std::cout << "\nC3DFileAdapter '" << filename << "' read time = " << 1.e3*(std::clock() - startTime) / CLOCKS_PER_SEC << "ms\n" << std::endl; auto& marker_table = tables.at("markers"); auto& force_table = tables.at("forces"); size_t ext = filename.rfind("."); std::string base = filename.substr(0, ext); const std::string marker_file = base + "_markers.trc"; const std::string forces_file = base + "_grfs.sto"; ASSERT(marker_table->getNumRows() > 0, __FILE__, __LINE__, "Failed to read marker data from " + filename); marker_table->updTableMetaData().setValueForKey("Units", std::string{"mm"}); TRCFileAdapter trc_adapter{}; trc_adapter.write(*marker_table, marker_file); ASSERT(force_table->getNumRows() > 0, __FILE__, __LINE__, "Failed to read forces data from " + filename); force_table->updTableMetaData().setValueForKey("Units", std::string{"mm"}); STOFileAdapter sto_adapter{}; sto_adapter.write((force_table->flatten()), forces_file); // Verify that marker data was written out and can be read in auto markers = trc_adapter.read(marker_file); auto std_markers = trc_adapter.read("std_" + marker_file); // Compare C3DFileAdapter read-in and written marker data compare_tables<SimTK::Vec3>(markers, *marker_table); // Compare C3DFileAdapter written marker data to standard // Note std exported from Mokka with only 5 decimal places compare_tables<SimTK::Vec3>(markers, std_markers, 1e-4); std::cout << marker_file << " equivalent to std_" << marker_file << std::endl; // Verify that grfs data was written out and can be read in auto forces = sto_adapter.read(forces_file); auto std_forces = sto_adapter.read("std_" + forces_file); // Compare C3DFileAdapter read-in and written forces data compare_tables<SimTK::Vec3>(forces.pack<SimTK::Vec3>(), *force_table); // Compare C3DFileAdapter written forces data to standard // Note std generated using MATLAB C3D processing scripts compare_tables(forces, std_forces, SimTK::SqrtEps); std::cout << forces_file << " equivalent to std_" << forces_file << std::endl; } int main() { std::vector<std::string> filenames{}; filenames.push_back("walking2.c3d"); filenames.push_back("walking5.c3d"); for(const auto& filename : filenames) { std::cout << "Test reading '" + filename + "'." << std::endl; try { test(filename); } catch (const std::exception& ex) { std::cout << "testC3DFileAdapter FAILED: " << ex.what() << std::endl; return 1; } } std::cout << "\nAll testC3DFileAdapter cases passed." << std::endl; return 0; }
Add comparison of read-in forces and moments resolved at the Origin of the force-plate.
Add comparison of read-in forces and moments resolved at the Origin of the force-plate.
C++
apache-2.0
opensim-org/opensim-core,opensim-org/opensim-core,opensim-org/opensim-core,opensim-org/opensim-core,opensim-org/opensim-core,opensim-org/opensim-core,opensim-org/opensim-core
f6e3c1674376f53e3b0432560b2f55e5993d821c
src/SunSet.cpp
src/SunSet.cpp
/* The MIT License (MIT) Copyright (c) 2015 Peter Buelow (goballstate at gmail) 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 "SunSet.h" SunSet::SunSet() { latitude = 0.0; longitude = 0.0; julianDate = 0.0; tzOffset = 0; } SunSet::SunSet(double lat, double lon, int tz) { latitude = lat; longitude = lon; julianDate = 0.0; tzOffset = tz; } SunSet::~SunSet() { } void SunSet::setPosition(double lat, double lon, int tz) { latitude = lat; longitude = lon; tzOffset = tz; } double SunSet::degToRad(double angleDeg) { return (M_PI * angleDeg / 180.0); } double SunSet::radToDeg(double angleRad) { return (180.0 * angleRad / M_PI); } double SunSet::calcMeanObliquityOfEcliptic(double t) { double seconds = 21.448 - t*(46.8150 + t*(0.00059 - t*(0.001813))); double e0 = 23.0 + (26.0 + (seconds/60.0))/60.0; return e0; // in degrees } double SunSet::calcGeomMeanLongSun(double t) { double L = 280.46646 + t * (36000.76983 + 0.0003032 * t); while ((int) L > 360) { L -= 360.0; } while (L < 0) { L += 360.0; } return L; // in degrees } double SunSet::calcObliquityCorrection(double t) { double e0 = calcMeanObliquityOfEcliptic(t); double omega = 125.04 - 1934.136 * t; double e = e0 + 0.00256 * cos(degToRad(omega)); return e; // in degrees } double SunSet::calcEccentricityEarthOrbit(double t) { double e = 0.016708634 - t * (0.000042037 + 0.0000001267 * t); return e; // unitless } double SunSet::calcGeomMeanAnomalySun(double t) { double M = 357.52911 + t * (35999.05029 - 0.0001537 * t); return M; // in degrees } double SunSet::calcEquationOfTime(double t) { double epsilon = calcObliquityCorrection(t); double l0 = calcGeomMeanLongSun(t); double e = calcEccentricityEarthOrbit(t); double m = calcGeomMeanAnomalySun(t); double y = tan(degToRad(epsilon)/2.0); y *= y; double sin2l0 = sin(2.0 * degToRad(l0)); double sinm = sin(degToRad(m)); double cos2l0 = cos(2.0 * degToRad(l0)); double sin4l0 = sin(4.0 * degToRad(l0)); double sin2m = sin(2.0 * degToRad(m)); double Etime = y * sin2l0 - 2.0 * e * sinm + 4.0 * e * y * sinm * cos2l0 - 0.5 * y * y * sin4l0 - 1.25 * e * e * sin2m; return radToDeg(Etime)*4.0; // in minutes of time } double SunSet::calcTimeJulianCent(double jd) { double T = ( jd - 2451545.0)/36525.0; return T; } double SunSet::calcSunTrueLong(double t) { double l0 = calcGeomMeanLongSun(t); double c = calcSunEqOfCenter(t); double O = l0 + c; return O; // in degrees } double SunSet::calcSunApparentLong(double t) { double o = calcSunTrueLong(t); double omega = 125.04 - 1934.136 * t; double lambda = o - 0.00569 - 0.00478 * sin(degToRad(omega)); return lambda; // in degrees } double SunSet::calcSunDeclination(double t) { double e = calcObliquityCorrection(t); double lambda = calcSunApparentLong(t); double sint = sin(degToRad(e)) * sin(degToRad(lambda)); double theta = radToDeg(asin(sint)); return theta; // in degrees } double SunSet::calcHourAngleSunrise(double lat, double solarDec) { double latRad = degToRad(lat); double sdRad = degToRad(solarDec); double HA = (acos(cos(degToRad(90.833))/(cos(latRad)*cos(sdRad))-tan(latRad) * tan(sdRad))); return HA; // in radians } double SunSet::calcHourAngleSunset(double lat, double solarDec) { double latRad = degToRad(lat); double sdRad = degToRad(solarDec); double HA = (acos(cos(degToRad(90.833))/(cos(latRad)*cos(sdRad))-tan(latRad) * tan(sdRad))); return -HA; // in radians } double SunSet::calcJD(int y, int m, int d) { if (m <= 2) { y -= 1; m += 12; } int A = floor(y/100); int B = 2 - A + floor(A/4); double JD = floor(365.25*(y + 4716)) + floor(30.6001*(m+1)) + d + B - 1524.5; return JD; } double SunSet::calcJDFromJulianCent(double t) { double JD = t * 36525.0 + 2451545.0; return JD; } double SunSet::calcSunEqOfCenter(double t) { double m = calcGeomMeanAnomalySun(t); double mrad = degToRad(m); double sinm = sin(mrad); double sin2m = sin(mrad+mrad); double sin3m = sin(mrad+mrad+mrad); double C = sinm * (1.914602 - t * (0.004817 + 0.000014 * t)) + sin2m * (0.019993 - 0.000101 * t) + sin3m * 0.000289; return C; // in degrees } double SunSet::calcSunriseUTC() { double t = calcTimeJulianCent(julianDate); // *** First pass to approximate sunrise double eqTime = calcEquationOfTime(t); double solarDec = calcSunDeclination(t); double hourAngle = calcHourAngleSunrise(latitude, solarDec); double delta = longitude - radToDeg(hourAngle); double timeDiff = 4 * delta; // in minutes of time double timeUTC = 720 + timeDiff - eqTime; // in minutes double newt = calcTimeJulianCent(calcJDFromJulianCent(t) + timeUTC/1440.0); eqTime = calcEquationOfTime(newt); solarDec = calcSunDeclination(newt); hourAngle = calcHourAngleSunrise(latitude, solarDec); delta = longitude - radToDeg(hourAngle); timeDiff = 4 * delta; timeUTC = 720 + timeDiff - eqTime; // in minutes return timeUTC; } double SunSet::calcSunrise() { double t = calcTimeJulianCent(julianDate); // *** First pass to approximate sunrise double eqTime = calcEquationOfTime(t); double solarDec = calcSunDeclination(t); double hourAngle = calcHourAngleSunrise(latitude, solarDec); double delta = longitude - radToDeg(hourAngle); double timeDiff = 4 * delta; // in minutes of time double timeUTC = 720 + timeDiff - eqTime; // in minutes double newt = calcTimeJulianCent(calcJDFromJulianCent(t) + timeUTC/1440.0); eqTime = calcEquationOfTime(newt); solarDec = calcSunDeclination(newt); hourAngle = calcHourAngleSunrise(latitude, solarDec); delta = longitude - radToDeg(hourAngle); timeDiff = 4 * delta; timeUTC = 720 + timeDiff - eqTime; // in minutes double localTime = timeUTC + (60 * tzOffset); return localTime; // return time in minutes from midnight } double SunSet::calcSunsetUTC() { double t = calcTimeJulianCent(julianDate); // *** First pass to approximate sunset double eqTime = calcEquationOfTime(t); double solarDec = calcSunDeclination(t); double hourAngle = calcHourAngleSunset(latitude, solarDec); double delta = longitude - radToDeg(hourAngle); double timeDiff = 4 * delta; // in minutes of time double timeUTC = 720 + timeDiff - eqTime; // in minutes double newt = calcTimeJulianCent(calcJDFromJulianCent(t) + timeUTC/1440.0); eqTime = calcEquationOfTime(newt); solarDec = calcSunDeclination(newt); hourAngle = calcHourAngleSunset(latitude, solarDec); delta = longitude - radToDeg(hourAngle); timeDiff = 4 * delta; timeUTC = 720 + timeDiff - eqTime; // in minutes return timeUTC; // return time in minutes from midnight } double SunSet::calcSunset() { double t = calcTimeJulianCent(julianDate); // *** First pass to approximate sunset double eqTime = calcEquationOfTime(t); double solarDec = calcSunDeclination(t); double hourAngle = calcHourAngleSunset(latitude, solarDec); double delta = longitude - radToDeg(hourAngle); double timeDiff = 4 * delta; // in minutes of time double timeUTC = 720 + timeDiff - eqTime; // in minutes double newt = calcTimeJulianCent(calcJDFromJulianCent(t) + timeUTC/1440.0); eqTime = calcEquationOfTime(newt); solarDec = calcSunDeclination(newt); hourAngle = calcHourAngleSunset(latitude, solarDec); delta = longitude - radToDeg(hourAngle); timeDiff = 4 * delta; timeUTC = 720 + timeDiff - eqTime; // in minutes double localTime = timeUTC + (60 * tzOffset); return localTime; // return time in minutes from midnight } double SunSet::setCurrentDate(int y, int m, int d) { m_year = y; m_month = m; m_day = d; julianDate = calcJD(y, m, d); return julianDate; } void SunSet::setTZOffset(int tz) { tzOffset = tz; } int SunSet::moonPhase(int fromepoch) { int moonepoch = 614100; int phase = (fromepoch - moonepoch) % 2551443; int res = floor(phase / (24 * 3600)) + 1; if (res == 30) res = 0; return res; }
/* The MIT License (MIT) Copyright (c) 2015 Peter Buelow (goballstate at gmail) 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 "SunSet.h" SunSet::SunSet() { latitude = 0.0; longitude = 0.0; julianDate = 0.0; tzOffset = 0; } SunSet::SunSet(double lat, double lon, int tz) { latitude = lat; longitude = lon; julianDate = 0.0; tzOffset = tz; } SunSet::~SunSet() { } void SunSet::setPosition(double lat, double lon, int tz) { latitude = lat; longitude = lon; tzOffset = tz; } double SunSet::degToRad(double angleDeg) { return (M_PI * angleDeg / 180.0); } double SunSet::radToDeg(double angleRad) { return (180.0 * angleRad / M_PI); } double SunSet::calcMeanObliquityOfEcliptic(double t) { double seconds = 21.448 - t*(46.8150 + t*(0.00059 - t*(0.001813))); double e0 = 23.0 + (26.0 + (seconds/60.0))/60.0; return e0; // in degrees } double SunSet::calcGeomMeanLongSun(double t) { double L = 280.46646 + t * (36000.76983 + 0.0003032 * t); while ((int) L > 360) { L -= 360.0; } while (L < 0) { L += 360.0; } return L; // in degrees } double SunSet::calcObliquityCorrection(double t) { double e0 = calcMeanObliquityOfEcliptic(t); double omega = 125.04 - 1934.136 * t; double e = e0 + 0.00256 * cos(degToRad(omega)); return e; // in degrees } double SunSet::calcEccentricityEarthOrbit(double t) { double e = 0.016708634 - t * (0.000042037 + 0.0000001267 * t); return e; // unitless } double SunSet::calcGeomMeanAnomalySun(double t) { double M = 357.52911 + t * (35999.05029 - 0.0001537 * t); return M; // in degrees } double SunSet::calcEquationOfTime(double t) { double epsilon = calcObliquityCorrection(t); double l0 = calcGeomMeanLongSun(t); double e = calcEccentricityEarthOrbit(t); double m = calcGeomMeanAnomalySun(t); double y = tan(degToRad(epsilon)/2.0); y *= y; double sin2l0 = sin(2.0 * degToRad(l0)); double sinm = sin(degToRad(m)); double cos2l0 = cos(2.0 * degToRad(l0)); double sin4l0 = sin(4.0 * degToRad(l0)); double sin2m = sin(2.0 * degToRad(m)); double Etime = y * sin2l0 - 2.0 * e * sinm + 4.0 * e * y * sinm * cos2l0 - 0.5 * y * y * sin4l0 - 1.25 * e * e * sin2m; return radToDeg(Etime)*4.0; // in minutes of time } double SunSet::calcTimeJulianCent(double jd) { double T = ( jd - 2451545.0)/36525.0; return T; } double SunSet::calcSunTrueLong(double t) { double l0 = calcGeomMeanLongSun(t); double c = calcSunEqOfCenter(t); double O = l0 + c; return O; // in degrees } double SunSet::calcSunApparentLong(double t) { double o = calcSunTrueLong(t); double omega = 125.04 - 1934.136 * t; double lambda = o - 0.00569 - 0.00478 * sin(degToRad(omega)); return lambda; // in degrees } double SunSet::calcSunDeclination(double t) { double e = calcObliquityCorrection(t); double lambda = calcSunApparentLong(t); double sint = sin(degToRad(e)) * sin(degToRad(lambda)); double theta = radToDeg(asin(sint)); return theta; // in degrees } double SunSet::calcHourAngleSunrise(double lat, double solarDec) { double latRad = degToRad(lat); double sdRad = degToRad(solarDec); double HA = (acos(cos(degToRad(90.833))/(cos(latRad)*cos(sdRad))-tan(latRad) * tan(sdRad))); return HA; // in radians } double SunSet::calcHourAngleSunset(double lat, double solarDec) { double latRad = degToRad(lat); double sdRad = degToRad(solarDec); double HA = (acos(cos(degToRad(90.833))/(cos(latRad)*cos(sdRad))-tan(latRad) * tan(sdRad))); return -HA; // in radians } double SunSet::calcJD(int y, int m, int d) { if (m <= 2) { y -= 1; m += 12; } int A = floor(y/100); int B = 2 - A + floor(A/4); double JD = floor(365.25*(y + 4716)) + floor(30.6001*(m+1)) + d + B - 1524.5; return JD; } double SunSet::calcJDFromJulianCent(double t) { double JD = t * 36525.0 + 2451545.0; return JD; } double SunSet::calcSunEqOfCenter(double t) { double m = calcGeomMeanAnomalySun(t); double mrad = degToRad(m); double sinm = sin(mrad); double sin2m = sin(mrad+mrad); double sin3m = sin(mrad+mrad+mrad); double C = sinm * (1.914602 - t * (0.004817 + 0.000014 * t)) + sin2m * (0.019993 - 0.000101 * t) + sin3m * 0.000289; return C; // in degrees } double SunSet::calcSunriseUTC() { double t = calcTimeJulianCent(julianDate); // *** First pass to approximate sunrise double eqTime = calcEquationOfTime(t); double solarDec = calcSunDeclination(t); double hourAngle = calcHourAngleSunrise(latitude, solarDec); double delta = longitude + radToDeg(hourAngle); double timeDiff = 4 * delta; // in minutes of time double timeUTC = 720 - timeDiff - eqTime; // in minutes double newt = calcTimeJulianCent(calcJDFromJulianCent(t) + timeUTC/1440.0); eqTime = calcEquationOfTime(newt); solarDec = calcSunDeclination(newt); hourAngle = calcHourAngleSunrise(latitude, solarDec); delta = longitude + radToDeg(hourAngle); timeDiff = 4 * delta; timeUTC = 720 - timeDiff - eqTime; // in minutes return timeUTC; } double SunSet::calcSunrise() { double t = calcTimeJulianCent(julianDate); // *** First pass to approximate sunrise double eqTime = calcEquationOfTime(t); double solarDec = calcSunDeclination(t); double hourAngle = calcHourAngleSunrise(latitude, solarDec); double delta = longitude + radToDeg(hourAngle); double timeDiff = 4 * delta; // in minutes of time double timeUTC = 720 - timeDiff - eqTime; // in minutes double newt = calcTimeJulianCent(calcJDFromJulianCent(t) + timeUTC/1440.0); eqTime = calcEquationOfTime(newt); solarDec = calcSunDeclination(newt); hourAngle = calcHourAngleSunrise(latitude, solarDec); delta = longitude + radToDeg(hourAngle); timeDiff = 4 * delta; timeUTC = 720 - timeDiff - eqTime; // in minutes double localTime = timeUTC + (60 * tzOffset); return localTime; // return time in minutes from midnight } double SunSet::calcSunsetUTC() { double t = calcTimeJulianCent(julianDate); // *** First pass to approximate sunset double eqTime = calcEquationOfTime(t); double solarDec = calcSunDeclination(t); double hourAngle = calcHourAngleSunset(latitude, solarDec); double delta = longitude + radToDeg(hourAngle); double timeDiff = 4 * delta; // in minutes of time double timeUTC = 720 - timeDiff - eqTime; // in minutes double newt = calcTimeJulianCent(calcJDFromJulianCent(t) + timeUTC/1440.0); eqTime = calcEquationOfTime(newt); solarDec = calcSunDeclination(newt); hourAngle = calcHourAngleSunset(latitude, solarDec); delta = longitude + radToDeg(hourAngle); timeDiff = 4 * delta; timeUTC = 720 - timeDiff - eqTime; // in minutes return timeUTC; // return time in minutes from midnight } double SunSet::calcSunset() { double t = calcTimeJulianCent(julianDate); // *** First pass to approximate sunset double eqTime = calcEquationOfTime(t); double solarDec = calcSunDeclination(t); double hourAngle = calcHourAngleSunset(latitude, solarDec); double delta = longitude + radToDeg(hourAngle); double timeDiff = 4 * delta; // in minutes of time double timeUTC = 720 - timeDiff - eqTime; // in minutes double newt = calcTimeJulianCent(calcJDFromJulianCent(t) + timeUTC/1440.0); eqTime = calcEquationOfTime(newt); solarDec = calcSunDeclination(newt); hourAngle = calcHourAngleSunset(latitude, solarDec); delta = longitude + radToDeg(hourAngle); timeDiff = 4 * delta; timeUTC = 720 - timeDiff - eqTime; // in minutes double localTime = timeUTC + (60 * tzOffset); return localTime; // return time in minutes from midnight } double SunSet::setCurrentDate(int y, int m, int d) { m_year = y; m_month = m; m_day = d; julianDate = calcJD(y, m, d); return julianDate; } void SunSet::setTZOffset(int tz) { tzOffset = tz; } int SunSet::moonPhase(int fromepoch) { int moonepoch = 614100; int phase = (fromepoch - moonepoch) % 2551443; int res = floor(phase / (24 * 3600)) + 1; if (res == 30) res = 0; return res; }
Fix sunrise/sunset calculation
Fix sunrise/sunset calculation
C++
mit
buelowp/sunrise
d16e592d8da7627c10811277a7e4f180a9eae726
apps/src/ConvertDir.cpp
apps/src/ConvertDir.cpp
#include <iostream> #include <boost/filesystem.hpp> #include <boost/program_options.hpp> #include <opencv2/core.hpp> #include <opencv2/imgcodecs.hpp> #include <opencv2/photo.hpp> #include "envitools/EnviUtils.hpp" namespace fs = boost::filesystem; namespace po = boost::program_options; namespace et = envitools; constexpr static uint8_t MAX_INTENSITY_8BPC = std::numeric_limits<uint8_t>::max(); constexpr static uint16_t MAX_INTENSITY_16BPC = std::numeric_limits<uint16_t>::max(); enum class BitDepth { Unsigned8 = 8, Unsigned16 = 16 }; int main(int argc, char* argv[]) { ///// Parse the cmd line ///// fs::path imgDir, outputPath; std::cout.width(10); // clang-format off po::options_description options("Options"); options.add_options() ("help,h","Show this message") ("input-dir,i",po::value<std::string>()->required(), "Input directory") ("output-dir,o", po::value<std::string>()->required(), "Output directory") ("bpc,b",po::value<int>()->default_value(16), "Output bit depth:\n" " 8 = 8bpc (unsigned)\n" " 16 = 16bpc (unsigned)") ("gamma", po::value<float>()->default_value(2.2f), "Gamma for floating point image tone mapping"); // clang-format on // parsedOptions will hold the values of all parsed options as a Map po::variables_map parsedOptions; po::store( po::command_line_parser(argc, argv).options(options).run(), parsedOptions); // show the help message if (parsedOptions.count("help") || argc < 3) { std::cout << argv[0] << std::endl; std::cout.fill('-'); std::cout.width(20); std::cout << "\n"; std::cout << "A utility for converting a directory of 32bpc, " "floating-point TIFFs into" << std::endl; std::cout << "8 or 16bpc TIFFs." << std::endl; std::cout << "\n"; std::cout << options << std::endl; return EXIT_SUCCESS; } // warn of missing options try { po::notify(parsedOptions); } catch (po::error& e) { std::cerr << "ERROR: " << e.what() << std::endl; return EXIT_FAILURE; } // Get the output options outputPath = parsedOptions["output-dir"].as<std::string>(); auto depth = static_cast<BitDepth>(parsedOptions["bpc"].as<int>()); ///// Collect the tif files ///// imgDir = parsedOptions["input-dir"].as<std::string>(); auto imgPaths = et::FindByExtension(imgDir, ".tif"); if (imgPaths.empty()) { std::cerr << "Error opening/parsing image directory. No files found." << std::endl; return EXIT_FAILURE; } ///// Convert ///// cv::Mat image; std::cout << "Converting to " << static_cast<int>(depth) << " bpc..." << std::endl; for (auto path : imgPaths) { // Get wavelength for key std::string id = path.stem().string(); std::cout << "Image: " << id << "\r" << std::flush; // Load the image image = cv::imread(path.string(), -1); if (!image.data) { std::cout << "Could not open or find the image: "; std::cout << path.string() << std::endl; continue; } if (image.depth() != CV_32F) { std::cout << "Input image is not floating point: "; std::cout << path.string() << std::endl; continue; } // Tone map for contrast auto gamma = parsedOptions["gamma"].as<float>(); image = et::ToneMap(image, gamma); // Scale to output bit depth switch (depth) { case BitDepth::Unsigned8: image *= MAX_INTENSITY_8BPC; image.convertTo(image, CV_8UC1); break; case BitDepth::Unsigned16: image *= MAX_INTENSITY_16BPC; image.convertTo(image, CV_16UC1); break; } // Save the output image fs::path outpath = outputPath / (id + ".tif"); cv::imwrite(outpath.string(), image); } std::cout << std::endl; }
#include <iostream> #include <boost/filesystem.hpp> #include <boost/program_options.hpp> #include <opencv2/core.hpp> #include <opencv2/imgcodecs.hpp> #include <opencv2/photo.hpp> #include "envitools/EnviUtils.hpp" namespace fs = boost::filesystem; namespace po = boost::program_options; namespace et = envitools; constexpr static float DEFAULT_GAMMA = 2.2f; constexpr static uint8_t MAX_INTENSITY_8BPC = std::numeric_limits<uint8_t>::max(); constexpr static uint16_t MAX_INTENSITY_16BPC = std::numeric_limits<uint16_t>::max(); enum class BitDepth { Unsigned8 = 8, Unsigned16 = 16 }; int main(int argc, char* argv[]) { ///// Parse the cmd line ///// fs::path imgDir, outputPath; std::cout.width(10); // clang-format off po::options_description options("Options"); options.add_options() ("help,h","Show this message") ("input-dir,i",po::value<std::string>()->required(), "Input directory") ("output-dir,o", po::value<std::string>()->required(), "Output directory") ("bpc,b",po::value<int>()->default_value(16), "Output bit depth:\n" " 8 = 8bpc (unsigned)\n" " 16 = 16bpc (unsigned)") ("gamma", po::value<float>()->default_value(DEFAULT_GAMMA), "Gamma for floating point image tone mapping"); // clang-format on // parsedOptions will hold the values of all parsed options as a Map po::variables_map parsedOptions; po::store( po::command_line_parser(argc, argv).options(options).run(), parsedOptions); // show the help message if (parsedOptions.count("help") || argc < 3) { std::cout << argv[0] << std::endl; std::cout.fill('-'); std::cout.width(20); std::cout << "\n"; std::cout << "A utility for converting a directory of 32bpc, " "floating-point TIFFs into" << std::endl; std::cout << "8 or 16bpc TIFFs." << std::endl; std::cout << "\n"; std::cout << options << std::endl; return EXIT_SUCCESS; } // warn of missing options try { po::notify(parsedOptions); } catch (po::error& e) { std::cerr << "ERROR: " << e.what() << std::endl; return EXIT_FAILURE; } // Get the output options outputPath = parsedOptions["output-dir"].as<std::string>(); auto depth = static_cast<BitDepth>(parsedOptions["bpc"].as<int>()); ///// Collect the tif files ///// imgDir = parsedOptions["input-dir"].as<std::string>(); auto imgPaths = et::FindByExtension(imgDir, ".tif"); if (imgPaths.empty()) { std::cerr << "Error opening/parsing image directory. No files found." << std::endl; return EXIT_FAILURE; } ///// Convert ///// cv::Mat image; std::cout << "Converting to " << static_cast<int>(depth) << " bpc..." << std::endl; for (auto path : imgPaths) { // Get wavelength for key std::string id = path.stem().string(); std::cout << "Image: " << id << "\r" << std::flush; // Load the image image = cv::imread(path.string(), -1); if (!image.data) { std::cout << "Could not open or find the image: "; std::cout << path.string() << std::endl; continue; } if (image.depth() != CV_32F) { std::cout << "Input image is not floating point: "; std::cout << path.string() << std::endl; continue; } // Tone map for contrast auto gamma = parsedOptions["gamma"].as<float>(); image = et::ToneMap(image, gamma); // Scale to output bit depth switch (depth) { case BitDepth::Unsigned8: image *= MAX_INTENSITY_8BPC; image.convertTo(image, CV_8UC(image.channels())); break; case BitDepth::Unsigned16: image *= MAX_INTENSITY_16BPC; image.convertTo(image, CV_16UC(image.channels())); break; } // Save the output image fs::path outpath = outputPath / (id + ".tif"); cv::imwrite(outpath.string(), image); } std::cout << std::endl; }
Update convert_dir with channel count independent scaling
Update convert_dir with channel count independent scaling
C++
bsd-3-clause
viscenter/envi-tools,viscenter/envi-tools,viscenter/envi-tools
6f536a5e9e9ae359941730fef93f8a5dfe9c33fc
src/http/src/http.cpp
src/http/src/http.cpp
// Copyright (C) 2018 Egor Pugin <[email protected]> // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include <primitives/http.h> #include <curl/curl.h> #ifdef _WIN32 #include <windows.h> #include <Winhttp.h> #endif HttpSettings httpSettings; String getAutoProxy() { String proxy_addr; std::wstring wproxy_addr; #ifdef _WIN32 WINHTTP_PROXY_INFO proxy = { 0 }; WINHTTP_CURRENT_USER_IE_PROXY_CONFIG proxy2 = { 0 }; if (WinHttpGetDefaultProxyConfiguration(&proxy) && proxy.lpszProxy) wproxy_addr = proxy.lpszProxy; else if (WinHttpGetIEProxyConfigForCurrentUser(&proxy2) && proxy2.lpszProxy) wproxy_addr = proxy2.lpszProxy; proxy_addr = to_string(wproxy_addr); #endif return proxy_addr; } size_t curl_write_file(char *ptr, size_t size, size_t nmemb, void *userdata) { auto read = size * nmemb; fwrite(ptr, read, 1, (FILE *)userdata); return read; } int curl_transfer_info(void *clientp, curl_off_t dltotal, curl_off_t dlnow, curl_off_t ultotal, curl_off_t ulnow) { int64_t file_size_limit = *(int64_t*)clientp; if (dlnow > file_size_limit) return 1; return 0; } size_t curl_write_string(char *ptr, size_t size, size_t nmemb, String *s) { auto read = size * nmemb; try { s->append(ptr, ptr + read); } catch (...) { return 0; } return read; } void download_file(const String &url, const path &fn, int64_t file_size_limit) { auto parent = fn.parent_path(); if (!parent.empty() && !fs::exists(parent)) fs::create_directories(parent); ScopedFile ofile(fn, "wb"); // set up curl request auto curl = curl_easy_init(); if (httpSettings.verbose) curl_easy_setopt(curl, CURLOPT_VERBOSE, 1); curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1); // proxy settings auto proxy_addr = getAutoProxy(); if (!proxy_addr.empty()) { curl_easy_setopt(curl, CURLOPT_PROXY, proxy_addr.c_str()); curl_easy_setopt(curl, CURLOPT_PROXYAUTH, CURLAUTH_ANY); } if (!httpSettings.proxy.host.empty()) { curl_easy_setopt(curl, CURLOPT_PROXY, httpSettings.proxy.host.c_str()); curl_easy_setopt(curl, CURLOPT_PROXYAUTH, CURLAUTH_ANY); if (httpSettings.proxy.host.find("socks5") == 0) { curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5); curl_easy_setopt(curl, CURLOPT_SOCKS5_AUTH, CURLAUTH_BASIC); } if (!httpSettings.proxy.user.empty()) curl_easy_setopt(curl, CURLOPT_PROXYUSERPWD, httpSettings.proxy.user.c_str()); } curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curl_write_file); curl_easy_setopt(curl, CURLOPT_WRITEDATA, ofile.getHandle()); curl_easy_setopt(curl, CURLOPT_XFERINFOFUNCTION, curl_transfer_info); curl_easy_setopt(curl, CURLOPT_XFERINFODATA, &file_size_limit); if (url.find("https") == 0) { curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0); curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 2); if (httpSettings.ignore_ssl_checks) { curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0); //curl_easy_setopt(curl, CURLOPT_SSL_VERIFYSTATUS, 0); } } auto res = curl_easy_perform(curl); long http_code = 0; curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_code); curl_easy_cleanup(curl); if (res == CURLE_ABORTED_BY_CALLBACK) { fs::remove(fn); throw std::runtime_error("File '" + url + "' is too big. Limit is " + std::to_string(file_size_limit) + " bytes."); } if (res != CURLE_OK) throw std::runtime_error("curl error: "s + curl_easy_strerror(res)); if (http_code / 100 != 2) throw std::runtime_error("Http returned " + std::to_string(http_code)); } HttpResponse url_request(const HttpRequest &request) { auto curl = curl_easy_init(); if (request.verbose) curl_easy_setopt(curl, CURLOPT_VERBOSE, 1); if (!request.agent.empty()) curl_easy_setopt(curl, CURLOPT_USERAGENT, request.agent.c_str()); if (!request.username.empty()) curl_easy_setopt(curl, CURLOPT_USERNAME, request.username.c_str()); if (!request.password.empty()) curl_easy_setopt(curl, CURLOPT_USERPWD, request.password.c_str()); curl_easy_setopt(curl, CURLOPT_URL, request.url.c_str()); curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1); if (request.connect_timeout != -1) curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, request.connect_timeout); if (request.timeout != -1) curl_easy_setopt(curl, CURLOPT_TIMEOUT, request.timeout); // proxy settings auto proxy_addr = getAutoProxy(); if (!proxy_addr.empty()) { curl_easy_setopt(curl, CURLOPT_PROXY, proxy_addr.c_str()); curl_easy_setopt(curl, CURLOPT_PROXYAUTH, CURLAUTH_ANY); } if (!request.proxy.host.empty()) { curl_easy_setopt(curl, CURLOPT_PROXY, request.proxy.host.c_str()); curl_easy_setopt(curl, CURLOPT_PROXYAUTH, CURLAUTH_ANY); if (request.proxy.host.find("socks5") == 0) { curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5); curl_easy_setopt(curl, CURLOPT_SOCKS5_AUTH, CURLAUTH_BASIC); } if (!request.proxy.user.empty()) curl_easy_setopt(curl, CURLOPT_PROXYUSERPWD, request.proxy.user.c_str()); } std::string data; std::vector<char *> escaped; switch (request.type) { case HttpRequest::Post: if (!request.data_kv.empty()) { for (auto &a : request.data_kv) { escaped.push_back(curl_easy_escape(curl, a.first.c_str(), (int)a.first.size())); data += escaped.back() + std::string("="); escaped.push_back(curl_easy_escape(curl, a.second.c_str(), (int)a.second.size())); data += escaped.back() + std::string("&"); } data.resize(data.size() - 1); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data.c_str()); curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, (long)data.size()); } else { curl_easy_setopt(curl, CURLOPT_POSTFIELDS, request.data.c_str()); } break; case HttpRequest::Delete: curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "DELETE"); break; } if (request.url.find("https") == 0) { curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0); curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 2); if (request.ignore_ssl_checks) { curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0); //curl_easy_setopt(curl, CURLOPT_SSL_VERIFYSTATUS, 0); } } HttpResponse response; curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response.response); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curl_write_string); struct curl_slist *list = NULL; auto ct = "Content-Type: " + request.content_type; if (!request.content_type.empty()) { list = curl_slist_append(list, ct.c_str()); } curl_easy_setopt(curl, CURLOPT_HTTPHEADER, list); auto res = curl_easy_perform(curl); curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response.http_code); curl_slist_free_all(list); curl_easy_cleanup(curl); for (auto &e : escaped) curl_free(e); if (res != CURLE_OK) throw std::runtime_error("curl error: "s + curl_easy_strerror(res)); return response; } String download_file(const String &url) { auto fn = fs::temp_directory_path() / unique_path(); download_file(url, fn, 1_GB); auto s = read_file(fn); fs::remove(fn); return s; } bool isUrl(const String &s) { if (s.find("http://") == 0 || s.find("https://") == 0 || s.find("ftp://") == 0 || s.find("git://") == 0 || // could be dangerous in case of vulnerabilities on client side? //s.find("ssh://") == 0 || 0 ) { return true; } return false; }
// Copyright (C) 2018 Egor Pugin <[email protected]> // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include <primitives/http.h> #include <curl/curl.h> #ifdef _WIN32 #include <windows.h> #include <Winhttp.h> #endif HttpSettings httpSettings; String getAutoProxy() { String proxy_addr; std::wstring wproxy_addr; #ifdef _WIN32 WINHTTP_PROXY_INFO proxy = { 0 }; WINHTTP_CURRENT_USER_IE_PROXY_CONFIG proxy2 = { 0 }; if (WinHttpGetDefaultProxyConfiguration(&proxy) && proxy.lpszProxy) wproxy_addr = proxy.lpszProxy; else if (WinHttpGetIEProxyConfigForCurrentUser(&proxy2) && proxy2.lpszProxy) wproxy_addr = proxy2.lpszProxy; proxy_addr = to_string(wproxy_addr); #endif return proxy_addr; } size_t curl_write_file(char *ptr, size_t size, size_t nmemb, void *userdata) { auto read = size * nmemb; fwrite(ptr, read, 1, (FILE *)userdata); return read; } int curl_transfer_info(void *clientp, curl_off_t dltotal, curl_off_t dlnow, curl_off_t ultotal, curl_off_t ulnow) { int64_t file_size_limit = *(int64_t*)clientp; if (dlnow > file_size_limit) return 1; return 0; } size_t curl_write_string(char *ptr, size_t size, size_t nmemb, String *s) { auto read = size * nmemb; try { s->append(ptr, ptr + read); } catch (...) { return 0; } return read; } void download_file(const String &url, const path &fn, int64_t file_size_limit) { auto parent = fn.parent_path(); if (!parent.empty() && !fs::exists(parent)) fs::create_directories(parent); ScopedFile ofile(fn, "wb"); // set up curl request auto curl = curl_easy_init(); if (httpSettings.verbose) curl_easy_setopt(curl, CURLOPT_VERBOSE, 1); curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1); // proxy settings auto proxy_addr = getAutoProxy(); if (!proxy_addr.empty()) { curl_easy_setopt(curl, CURLOPT_PROXY, proxy_addr.c_str()); curl_easy_setopt(curl, CURLOPT_PROXYAUTH, CURLAUTH_ANY); } if (!httpSettings.proxy.host.empty()) { curl_easy_setopt(curl, CURLOPT_PROXY, httpSettings.proxy.host.c_str()); curl_easy_setopt(curl, CURLOPT_PROXYAUTH, CURLAUTH_ANY); if (httpSettings.proxy.host.find("socks5") == 0) { curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5); curl_easy_setopt(curl, CURLOPT_SOCKS5_AUTH, CURLAUTH_BASIC); } if (!httpSettings.proxy.user.empty()) curl_easy_setopt(curl, CURLOPT_PROXYUSERPWD, httpSettings.proxy.user.c_str()); } curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curl_write_file); curl_easy_setopt(curl, CURLOPT_WRITEDATA, ofile.getHandle()); curl_easy_setopt(curl, CURLOPT_XFERINFOFUNCTION, curl_transfer_info); curl_easy_setopt(curl, CURLOPT_XFERINFODATA, &file_size_limit); if (url.find("https") == 0) { curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0); curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 2); if (httpSettings.ignore_ssl_checks) { curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0); //curl_easy_setopt(curl, CURLOPT_SSL_VERIFYSTATUS, 0); } } auto res = curl_easy_perform(curl); long http_code = 0; curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_code); curl_easy_cleanup(curl); if (res == CURLE_ABORTED_BY_CALLBACK) { fs::remove(fn); throw std::runtime_error("File '" + url + "' is too big. Limit is " + std::to_string(file_size_limit) + " bytes."); } if (res != CURLE_OK) throw std::runtime_error("url = " + url + ", curl error: "s + curl_easy_strerror(res)); if (http_code / 100 != 2) throw std::runtime_error("url = " + url + ", http returned " + std::to_string(http_code)); } HttpResponse url_request(const HttpRequest &request) { auto curl = curl_easy_init(); if (request.verbose) curl_easy_setopt(curl, CURLOPT_VERBOSE, 1); if (!request.agent.empty()) curl_easy_setopt(curl, CURLOPT_USERAGENT, request.agent.c_str()); if (!request.username.empty()) curl_easy_setopt(curl, CURLOPT_USERNAME, request.username.c_str()); if (!request.password.empty()) curl_easy_setopt(curl, CURLOPT_USERPWD, request.password.c_str()); curl_easy_setopt(curl, CURLOPT_URL, request.url.c_str()); curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1); if (request.connect_timeout != -1) curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, request.connect_timeout); if (request.timeout != -1) curl_easy_setopt(curl, CURLOPT_TIMEOUT, request.timeout); // proxy settings auto proxy_addr = getAutoProxy(); if (!proxy_addr.empty()) { curl_easy_setopt(curl, CURLOPT_PROXY, proxy_addr.c_str()); curl_easy_setopt(curl, CURLOPT_PROXYAUTH, CURLAUTH_ANY); } if (!request.proxy.host.empty()) { curl_easy_setopt(curl, CURLOPT_PROXY, request.proxy.host.c_str()); curl_easy_setopt(curl, CURLOPT_PROXYAUTH, CURLAUTH_ANY); if (request.proxy.host.find("socks5") == 0) { curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5); curl_easy_setopt(curl, CURLOPT_SOCKS5_AUTH, CURLAUTH_BASIC); } if (!request.proxy.user.empty()) curl_easy_setopt(curl, CURLOPT_PROXYUSERPWD, request.proxy.user.c_str()); } std::string data; std::vector<char *> escaped; switch (request.type) { case HttpRequest::Post: if (!request.data_kv.empty()) { for (auto &a : request.data_kv) { escaped.push_back(curl_easy_escape(curl, a.first.c_str(), (int)a.first.size())); data += escaped.back() + std::string("="); escaped.push_back(curl_easy_escape(curl, a.second.c_str(), (int)a.second.size())); data += escaped.back() + std::string("&"); } data.resize(data.size() - 1); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data.c_str()); curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, (long)data.size()); } else { curl_easy_setopt(curl, CURLOPT_POSTFIELDS, request.data.c_str()); } break; case HttpRequest::Delete: curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "DELETE"); break; } if (request.url.find("https") == 0) { curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0); curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 2); if (request.ignore_ssl_checks) { curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0); //curl_easy_setopt(curl, CURLOPT_SSL_VERIFYSTATUS, 0); } } HttpResponse response; curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response.response); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curl_write_string); struct curl_slist *list = NULL; auto ct = "Content-Type: " + request.content_type; if (!request.content_type.empty()) { list = curl_slist_append(list, ct.c_str()); } curl_easy_setopt(curl, CURLOPT_HTTPHEADER, list); auto res = curl_easy_perform(curl); curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response.http_code); curl_slist_free_all(list); curl_easy_cleanup(curl); for (auto &e : escaped) curl_free(e); if (res != CURLE_OK) throw std::runtime_error("url = " + request.url + ", curl error: "s + curl_easy_strerror(res)); return response; } String download_file(const String &url) { auto fn = fs::temp_directory_path() / unique_path(); download_file(url, fn, 1_GB); auto s = read_file(fn); fs::remove(fn); return s; } bool isUrl(const String &s) { if (s.find("http://") == 0 || s.find("https://") == 0 || s.find("ftp://") == 0 || s.find("git://") == 0 || // could be dangerous in case of vulnerabilities on client side? //s.find("ssh://") == 0 || 0 ) { return true; } return false; }
Add url to error message.
Add url to error message.
C++
mpl-2.0
egorpugin/primitives,egorpugin/primitives
471d40cf13c9f130e05509e067f3699016b59146
Gpu_Rvd/src/mesh/mesh_io.cpp
Gpu_Rvd/src/mesh/mesh_io.cpp
#include <mesh\mesh_io.h> namespace Gpu_Rvd{ bool mesh_load(const std::string filename, Mesh& M, FileType filetype){ coords_index_t dim = M.dimension(); std::vector<double> P(dim); LineInput in(filename); if (!in.OK()){ return false; } std::vector<index_t> facet_vertices; bool first_facet_attribute = true; bool read_facet_regions = false; while (!in.eof() && in.get_line()){ in.get_fields(); //must be called after get_line() if (in.nb_fields() >= 1){ if (in.field_matches(0, "v")){ for (coords_index_t c = 0; c < dim; ++c){ if (index_t(c + 1) < in.nb_fields()){ P[c] = in.field_as_double(index_t(c + 1)); } else{ P[c] = 0.0; } } M.add_vertexd(P); } else if (in.field_matches(0, "f")){ if (in.nb_fields() < 3){ fprintf(stderr, "facet only has %d corners(at least 3 required)", in.nb_fields()); return false; } facet_vertices.resize(0); for (index_t i = 1; i < in.nb_fields(); ++i){ for (char* ptr = in.field(i); *ptr != '\0'; ++ptr){ if (*ptr == '/'){ *ptr = '\0'; break; } } index_t vertex_index = in.field_as_uint(i); if ( (vertex_index < 1) || (vertex_index > M.get_vertex_nb()) ){ fprintf(stderr, "facet corner %d references an invalid vertex index", in.nb_fields()); return false; } facet_vertices.push_back(vertex_index - 1); } M.add_facet(facet_vertices); } } } return true; } }
#include <mesh\mesh_io.h> namespace Gpu_Rvd{ bool mesh_load_obj(const std::string filename, Mesh& M){ coords_index_t dim = M.dimension(); std::vector<double> P(dim); LineInput in(filename); if (!in.OK()){ return false; } std::vector<index_t> facet_vertices; bool first_facet_attribute = true; bool read_facet_regions = false; while (!in.eof() && in.get_line()){ in.get_fields(); //must be called after get_line() if (in.nb_fields() >= 1){ if (in.field_matches(0, "v")){ for (coords_index_t c = 0; c < dim; ++c){ if (index_t(c + 1) < in.nb_fields()){ P[c] = in.field_as_double(index_t(c + 1)); } else{ P[c] = 0.0; } } M.add_vertexd(P); } else if (in.field_matches(0, "f")){ if (in.nb_fields() < 3){ fprintf(stderr, "facet only has %d corners(at least 3 required)", in.nb_fields()); return false; } facet_vertices.resize(0); for (index_t i = 1; i < in.nb_fields(); ++i){ for (char* ptr = in.field(i); *ptr != '\0'; ++ptr){ if (*ptr == '/'){ *ptr = '\0'; break; } } index_t vertex_index = in.field_as_uint(i); if ( (vertex_index < 1) || (vertex_index > M.get_vertex_nb()) ){ fprintf(stderr, "facet corner %d references an invalid vertex index", in.nb_fields()); return false; } facet_vertices.push_back(vertex_index - 1); } M.add_facet(facet_vertices); } } } return true; } bool points_load_obj(const std::string filename, Points& points){ coords_index_t dim = points.dimension(); std::vector<double> P(dim); LineInput in(filename); if (!in.OK()){ return false; } bool first_facet_attribute = true; bool read_facet_regions = false; while (!in.eof() && in.get_line()){ in.get_fields(); //must be called after get_line() if (in.nb_fields() >= 1){ if (in.field_matches(0, "v")){ for (coords_index_t c = 0; c < dim; ++c){ if (index_t(c + 1) < in.nb_fields()){ P[c] = in.field_as_double(index_t(c + 1)); } else{ P[c] = 0.0; } } points.add_vertexd(P); } } } return true; } }
add mesh_io
add mesh_io
C++
mit
stormHan/gpu_rvd,stormHan/gpu_rvd
aad5257dbf671a6545272d15effeb1864c5033d5
src/assert.cpp
src/assert.cpp
/* Copyright (c) 2007-2012, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/config.hpp" #if (defined TORRENT_DEBUG && !TORRENT_NO_ASSERTS) || defined TORRENT_ASIO_DEBUGGING || TORRENT_RELEASE_ASSERTS #ifdef __APPLE__ #include <AvailabilityMacros.h> #endif #include <string> #include <cstring> #include <stdlib.h> // uClibc++ doesn't have cxxabi.h #if defined __GNUC__ && __GNUC__ >= 3 \ && !defined __UCLIBCXX_MAJOR__ #include <cxxabi.h> std::string demangle(char const* name) { // in case this string comes // this is needed on linux char const* start = strchr(name, '('); if (start != 0) { ++start; } else { // this is needed on macos x start = strstr(name, "0x"); if (start != 0) { start = strchr(start, ' '); if (start != 0) ++start; else start = name; } else start = name; } char const* end = strchr(start, '+'); if (end) while (*(end-1) == ' ') --end; std::string in; if (end == 0) in.assign(start); else in.assign(start, end); size_t len; int status; char* unmangled = ::abi::__cxa_demangle(in.c_str(), 0, &len, &status); if (unmangled == 0) return in; std::string ret(unmangled); free(unmangled); return ret; } #elif defined WIN32 #undef _WIN32_WINNT #define _WIN32_WINNT 0x0501 // XP #include "windows.h" #include "dbghelp.h" std::string demangle(char const* name) { char demangled_name[256]; if (UnDecorateSymbolName(name, demangled_name, sizeof(demangled_name), UNDNAME_NO_THROW_SIGNATURES) == 0) demangled_name[0] = 0; return demangled_name; } #else std::string demangle(char const* name) { return name; } #endif #include <stdlib.h> #include <stdio.h> #include <signal.h> #include "libtorrent/version.hpp" // execinfo.h is available in the MacOS X 10.5 SDK. #if (defined __linux__ || (defined __APPLE__ && MAC_OS_X_VERSION_MIN_REQUIRED >= 1050)) #include <execinfo.h> TORRENT_EXPORT void print_backtrace(char* out, int len, int max_depth) { void* stack[50]; int size = backtrace(stack, 50); char** symbols = backtrace_symbols(stack, size); for (int i = 1; i < size && len > 0; ++i) { int ret = snprintf(out, len, "%d: %s\n", i, demangle(symbols[i]).c_str()); out += ret; len -= ret; if (i - 1 == max_depth && max_depth > 0) break; } free(symbols); } // visual studio 9 and up appears to support this #elif defined WIN32 && _MSC_VER >= 1500 #undef _WIN32_WINNT #define _WIN32_WINNT 0x0501 // XP #include "windows.h" #include "libtorrent/utf8.hpp" #include "winbase.h" #include "dbghelp.h" TORRENT_EXPORT void print_backtrace(char* out, int len, int max_depth) { typedef USHORT (WINAPI *RtlCaptureStackBackTrace_t)( __in ULONG FramesToSkip, __in ULONG FramesToCapture, __out PVOID *BackTrace, __out_opt PULONG BackTraceHash); static RtlCaptureStackBackTrace_t RtlCaptureStackBackTrace = 0; if (RtlCaptureStackBackTrace == 0) { // we don't actually have to free this library, everyone has it loaded HMODULE lib = LoadLibrary(TEXT("kernel32.dll")); RtlCaptureStackBackTrace = (RtlCaptureStackBackTrace_t)GetProcAddress(lib, "RtlCaptureStackBackTrace"); if (RtlCaptureStackBackTrace == 0) { out[0] = 0; return; } } int i; void* stack[50]; int size = CaptureStackBackTrace(0, 50, stack, 0); SYMBOL_INFO* symbol = (SYMBOL_INFO*)calloc(sizeof(SYMBOL_INFO) + MAX_SYM_NAME * sizeof(TCHAR), 1); symbol->MaxNameLen = MAX_SYM_NAME; symbol->SizeOfStruct = sizeof(SYMBOL_INFO); HANDLE p = GetCurrentProcess(); static bool sym_initialized = false; if (!sym_initialized) { sym_initialized = true; SymInitialize(p, NULL, true); } for (i = 0; i < size && len > 0; ++i) { int ret; if (SymFromAddr(p, uintptr_t(stack[i]), 0, symbol)) ret = snprintf(out, len, "%d: %s\n", i, symbol->Name); else ret = snprintf(out, len, "%d: <unknown>\n", i); out += ret; len -= ret; if (i == max_depth && max_depth > 0) break; } free(symbol); } #else TORRENT_EXPORT void print_backtrace(char* out, int len, int max_depth) {} #endif #if TORRENT_PRODUCTION_ASSERTS char const* libtorrent_assert_log = "asserts.log"; #endif TORRENT_EXPORT void assert_fail(char const* expr, int line, char const* file , char const* function, char const* value) { #if TORRENT_PRODUCTION_ASSERTS FILE* out = fopen(libtorrent_assert_log, "a+"); if (out == 0) out = stderr; #else FILE* out = stderr; #endif char stack[8192]; print_backtrace(stack, sizeof(stack), 0); fprintf(out, "assertion failed. Please file a bugreport at " "http://code.google.com/p/libtorrent/issues\n" "Please include the following information:\n\n" "version: " LIBTORRENT_VERSION "\n" "%s\n" "file: '%s'\n" "line: %d\n" "function: %s\n" "expression: %s\n" "%s%s\n" "stack:\n" "%s\n" , LIBTORRENT_REVISION, file, line, function, expr , value ? value : "", value ? "\n" : "" , stack); // if production asserts are defined, don't abort, just print the error #if TORRENT_PRODUCTION_ASSERTS if (out != stderr) fclose(out); #else // send SIGINT to the current process // to break into the debugger raise(SIGINT); abort(); #endif } #else TORRENT_EXPORT void assert_fail(char const* expr, int line, char const* file, char const* function) {} #endif
/* Copyright (c) 2007-2012, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/config.hpp" #if TORRENT_PRODUCTION_ASSERTS #include <boost/detail/atomic_count.hpp> #endif #if (defined TORRENT_DEBUG && !TORRENT_NO_ASSERTS) || defined TORRENT_ASIO_DEBUGGING || TORRENT_RELEASE_ASSERTS #ifdef __APPLE__ #include <AvailabilityMacros.h> #endif #include <string> #include <cstring> #include <stdlib.h> // uClibc++ doesn't have cxxabi.h #if defined __GNUC__ && __GNUC__ >= 3 \ && !defined __UCLIBCXX_MAJOR__ #include <cxxabi.h> std::string demangle(char const* name) { // in case this string comes // this is needed on linux char const* start = strchr(name, '('); if (start != 0) { ++start; } else { // this is needed on macos x start = strstr(name, "0x"); if (start != 0) { start = strchr(start, ' '); if (start != 0) ++start; else start = name; } else start = name; } char const* end = strchr(start, '+'); if (end) while (*(end-1) == ' ') --end; std::string in; if (end == 0) in.assign(start); else in.assign(start, end); size_t len; int status; char* unmangled = ::abi::__cxa_demangle(in.c_str(), 0, &len, &status); if (unmangled == 0) return in; std::string ret(unmangled); free(unmangled); return ret; } #elif defined WIN32 #undef _WIN32_WINNT #define _WIN32_WINNT 0x0501 // XP #include "windows.h" #include "dbghelp.h" std::string demangle(char const* name) { char demangled_name[256]; if (UnDecorateSymbolName(name, demangled_name, sizeof(demangled_name), UNDNAME_NO_THROW_SIGNATURES) == 0) demangled_name[0] = 0; return demangled_name; } #else std::string demangle(char const* name) { return name; } #endif #include <stdlib.h> #include <stdio.h> #include <signal.h> #include "libtorrent/version.hpp" // execinfo.h is available in the MacOS X 10.5 SDK. #if (defined __linux__ || (defined __APPLE__ && MAC_OS_X_VERSION_MIN_REQUIRED >= 1050)) #include <execinfo.h> TORRENT_EXPORT void print_backtrace(char* out, int len, int max_depth) { void* stack[50]; int size = backtrace(stack, 50); char** symbols = backtrace_symbols(stack, size); for (int i = 1; i < size && len > 0; ++i) { int ret = snprintf(out, len, "%d: %s\n", i, demangle(symbols[i]).c_str()); out += ret; len -= ret; if (i - 1 == max_depth && max_depth > 0) break; } free(symbols); } // visual studio 9 and up appears to support this #elif defined WIN32 && _MSC_VER >= 1500 #undef _WIN32_WINNT #define _WIN32_WINNT 0x0501 // XP #include "windows.h" #include "libtorrent/utf8.hpp" #include "winbase.h" #include "dbghelp.h" TORRENT_EXPORT void print_backtrace(char* out, int len, int max_depth) { typedef USHORT (WINAPI *RtlCaptureStackBackTrace_t)( __in ULONG FramesToSkip, __in ULONG FramesToCapture, __out PVOID *BackTrace, __out_opt PULONG BackTraceHash); static RtlCaptureStackBackTrace_t RtlCaptureStackBackTrace = 0; if (RtlCaptureStackBackTrace == 0) { // we don't actually have to free this library, everyone has it loaded HMODULE lib = LoadLibrary(TEXT("kernel32.dll")); RtlCaptureStackBackTrace = (RtlCaptureStackBackTrace_t)GetProcAddress(lib, "RtlCaptureStackBackTrace"); if (RtlCaptureStackBackTrace == 0) { out[0] = 0; return; } } int i; void* stack[50]; int size = CaptureStackBackTrace(0, 50, stack, 0); SYMBOL_INFO* symbol = (SYMBOL_INFO*)calloc(sizeof(SYMBOL_INFO) + MAX_SYM_NAME * sizeof(TCHAR), 1); symbol->MaxNameLen = MAX_SYM_NAME; symbol->SizeOfStruct = sizeof(SYMBOL_INFO); HANDLE p = GetCurrentProcess(); static bool sym_initialized = false; if (!sym_initialized) { sym_initialized = true; SymInitialize(p, NULL, true); } for (i = 0; i < size && len > 0; ++i) { int ret; if (SymFromAddr(p, uintptr_t(stack[i]), 0, symbol)) ret = snprintf(out, len, "%d: %s\n", i, symbol->Name); else ret = snprintf(out, len, "%d: <unknown>\n", i); out += ret; len -= ret; if (i == max_depth && max_depth > 0) break; } free(symbol); } #else TORRENT_EXPORT void print_backtrace(char* out, int len, int max_depth) {} #endif #if TORRENT_PRODUCTION_ASSERTS char const* libtorrent_assert_log = "asserts.log"; // the number of asserts we've printed to the log boost::detail::atomic_count assert_counter(0); #endif TORRENT_EXPORT void assert_fail(char const* expr, int line, char const* file , char const* function, char const* value) { #if TORRENT_PRODUCTION_ASSERTS // no need to flood the assert log with infinite number of asserts if (++assert_counter > 500) return; FILE* out = fopen(libtorrent_assert_log, "a+"); if (out == 0) out = stderr; #else FILE* out = stderr; #endif char stack[8192]; print_backtrace(stack, sizeof(stack), 0); fprintf(out, "assertion failed. Please file a bugreport at " "http://code.google.com/p/libtorrent/issues\n" "Please include the following information:\n\n" "version: " LIBTORRENT_VERSION "\n" "%s\n" "file: '%s'\n" "line: %d\n" "function: %s\n" "expression: %s\n" "%s%s\n" "stack:\n" "%s\n" , LIBTORRENT_REVISION, file, line, function, expr , value ? value : "", value ? "\n" : "" , stack); // if production asserts are defined, don't abort, just print the error #if TORRENT_PRODUCTION_ASSERTS if (out != stderr) fclose(out); #else // send SIGINT to the current process // to break into the debugger raise(SIGINT); abort(); #endif } #else TORRENT_EXPORT void assert_fail(char const* expr, int line, char const* file, char const* function) {} #endif
stop logging production asserts after 500 hits
stop logging production asserts after 500 hits
C++
bsd-3-clause
jpetso/libtorrent,jpetso/libtorrent,jpetso/libtorrent,jpetso/libtorrent
b27aedb76823ddd23529bc98a1136f3002cc33dd
src/attacks.cc
src/attacks.cc
#include "attacks.h" #include "bitutils.h" #include <cstring> #include <stdexcept> U64 Attacks::detail::NON_SLIDING_ATTACKS[2][6][64] = {{{0}}}; U64 Attacks::detail::RAYS[8][64] = {{0}}; void Attacks::init() { detail::_initPawnAttacks(); detail::_initKnightAttacks(); detail::_initKingAttacks(); detail::_initNorthRays(); detail::_initNorthEastRays(); detail::_initEastRays(); detail::_initNorthWestRays(); detail::_initSouthRays(); detail::_initSouthWestRays(); detail::_initWestRays(); detail::_initSouthEastRays(); } U64 Attacks::getNonSlidingAttacks(PieceType pieceType, int square, Color color) { return detail::NON_SLIDING_ATTACKS[color][pieceType][square]; } U64 Attacks::getSlidingAttacks(PieceType pieceType, int square, U64 blockers) { switch (pieceType) { case BISHOP: return detail::_getBishopAttacks(square, blockers); case ROOK: return detail::_getRookAttacks(square, blockers); case QUEEN: return detail::_getBishopAttacks(square, blockers) | detail::_getRookAttacks(square, blockers); default: fatal("Not a sliding piece"); } } U64 Attacks::detail::_getBishopAttacks(int square, U64 blockers) { return _getPositiveRayAttack(detail::NORTH_WEST, square, blockers) | _getPositiveRayAttack(detail::NORTH_EAST, square, blockers) | _getNegativeRayAttack(detail::SOUTH_WEST, square, blockers) | _getNegativeRayAttack(detail::SOUTH_EAST, square, blockers); } U64 Attacks::detail::_getRookAttacks(int square, U64 blockers) { return _getPositiveRayAttack(detail::NORTH, square, blockers) | _getPositiveRayAttack(detail::EAST, square, blockers) | _getNegativeRayAttack(detail::SOUTH, square, blockers) | _getNegativeRayAttack(detail::WEST, square, blockers); } U64 Attacks::detail::_getPositiveRayAttack(Attacks::detail::Dir dir, int square, U64 blockers) { U64 attacks = RAYS[dir][square]; U64 blocked = attacks & blockers; if (blocked) { int blockSquare = _bitscanForward(blocked); attacks ^= RAYS[dir][blockSquare]; } return attacks; } U64 Attacks::detail::_getNegativeRayAttack(Attacks::detail::Dir dir, int square, U64 blockers) { U64 attacks = RAYS[dir][square]; U64 blocked = attacks & blockers; if (blocked) { int blockSquare = 64 - _bitscanReverse(blocked); attacks ^= RAYS[dir][blockSquare]; } return attacks; } void Attacks::detail::_initPawnAttacks() { for (int i = 0; i < 64; i++) { U64 start = ONE << i; U64 whiteAttackBb = ((start << 9) & ~FILE_A) | ((start << 7) & ~FILE_H); U64 blackAttackBb = ((start >> 9) & ~FILE_H) | ((start >> 7) & ~FILE_A); NON_SLIDING_ATTACKS[WHITE][PAWN][i] = whiteAttackBb; NON_SLIDING_ATTACKS[BLACK][PAWN][i] = blackAttackBb; } } void Attacks::detail::_initKnightAttacks() { for (int i = 0; i < 64; i++) { U64 start = ONE << i; U64 attackBb = (((start << 15) | (start >> 17)) & ~FILE_H) | // Left 1 (((start >> 15) | (start << 17)) & ~FILE_A) | // Right 1 (((start << 6) | (start >> 10)) & ~(FILE_G | FILE_H)) | // Left 2 (((start >> 6) | (start << 10)) & ~(FILE_A | FILE_B)); // Right 2 NON_SLIDING_ATTACKS[WHITE][KNIGHT][i] = attackBb; NON_SLIDING_ATTACKS[BLACK][KNIGHT][i] = attackBb; } } void Attacks::detail::_initKingAttacks() { for (int i = 0; i < 64; i++) { U64 start = ONE << i; U64 attackBb = (((start << 7) | (start >> 9) | (start >> 1)) & (~FILE_H)) | (((start << 9) | (start >> 7) | (start << 1)) & (~FILE_A)) | ((start >> 8) | (start << 8)); NON_SLIDING_ATTACKS[WHITE][KING][i] = attackBb; NON_SLIDING_ATTACKS[BLACK][KING][i] = attackBb; } } void Attacks::detail::_initNorthRays() { U64 north = U64(0x0101010101010100); for (int square = 0; square < 64; square++, north <<= 1) { RAYS[NORTH][square] = north; } } void Attacks::detail::_initEastRays() { for (int square = 0; square < 64; square++) { RAYS[EAST][square] = 2 * ((ONE << (square | 7)) - (ONE << square)); } } void Attacks::detail::_initNorthEastRays() { U64 startRay = U64(0x8040201008040200); for (int file = 0; file < 8; file++, startRay = _eastOne(startRay)) { U64 currRay = startRay; for (int rank8 = 0; rank8 < 64; rank8 += 8, currRay <<= 8ull) { RAYS[NORTH_EAST][rank8 + file] = currRay; } } } void Attacks::detail::_initNorthWestRays() { U64 startRay = U64(0x102040810204000); for (int file = 7; file >= 0; file--, startRay = _westOne(startRay)) { U64 currRay = startRay; for (int rank8 = 0; rank8 < 64; rank8 += 8, currRay <<= 8ull) { RAYS[NORTH_WEST][rank8 + file] = currRay; } } } void Attacks::detail::_initSouthEastRays() { U64 startRay = U64(0x2040810204080); for (int file = 0; file < 8; file++, startRay = _eastOne(startRay)) { U64 currRay = startRay; for (int rank8 = 56; rank8 >= 0; rank8 -= 8, currRay >>= 8ull) { RAYS[SOUTH_EAST][rank8 + file] = currRay; } } } void Attacks::detail::_initSouthRays() { U64 south = U64(0x0080808080808080); for (int square = 63; square >= 0; square--, south >>= 1) { RAYS[SOUTH][square] = south; } } void Attacks::detail::_initSouthWestRays() { U64 startRay = U64(0x40201008040201); for (int file = 7; file >= 0; file--, startRay = _westOne(startRay)) { U64 currRay = startRay; for (int rank8 = 56; rank8 >= 0; rank8 -= 8, currRay >>= 8ull) { RAYS[SOUTH_WEST][rank8 + file] = currRay; } } } void Attacks::detail::_initWestRays() { for (int square = 0; square < 64; square++) { RAYS[WEST][square] = (ONE << square) - (ONE << (square & 56)); } }
#include "attacks.h" #include "bitutils.h" #include <cstring> U64 Attacks::detail::NON_SLIDING_ATTACKS[2][6][64] = {{{0}}}; U64 Attacks::detail::RAYS[8][64] = {{0}}; void Attacks::init() { detail::_initPawnAttacks(); detail::_initKnightAttacks(); detail::_initKingAttacks(); detail::_initNorthRays(); detail::_initNorthEastRays(); detail::_initEastRays(); detail::_initNorthWestRays(); detail::_initSouthRays(); detail::_initSouthWestRays(); detail::_initWestRays(); detail::_initSouthEastRays(); } U64 Attacks::getNonSlidingAttacks(PieceType pieceType, int square, Color color) { return detail::NON_SLIDING_ATTACKS[color][pieceType][square]; } U64 Attacks::getSlidingAttacks(PieceType pieceType, int square, U64 blockers) { switch (pieceType) { case BISHOP: return detail::_getBishopAttacks(square, blockers); case ROOK: return detail::_getRookAttacks(square, blockers); case QUEEN: return detail::_getBishopAttacks(square, blockers) | detail::_getRookAttacks(square, blockers); default: fatal("Not a sliding piece"); } } U64 Attacks::detail::_getBishopAttacks(int square, U64 blockers) { return _getPositiveRayAttack(detail::NORTH_WEST, square, blockers) | _getPositiveRayAttack(detail::NORTH_EAST, square, blockers) | _getNegativeRayAttack(detail::SOUTH_WEST, square, blockers) | _getNegativeRayAttack(detail::SOUTH_EAST, square, blockers); } U64 Attacks::detail::_getRookAttacks(int square, U64 blockers) { return _getPositiveRayAttack(detail::NORTH, square, blockers) | _getPositiveRayAttack(detail::EAST, square, blockers) | _getNegativeRayAttack(detail::SOUTH, square, blockers) | _getNegativeRayAttack(detail::WEST, square, blockers); } U64 Attacks::detail::_getPositiveRayAttack(Attacks::detail::Dir dir, int square, U64 blockers) { U64 attacks = RAYS[dir][square]; U64 blocked = attacks & blockers; if (blocked) { int blockSquare = _bitscanForward(blocked); attacks ^= RAYS[dir][blockSquare]; } return attacks; } U64 Attacks::detail::_getNegativeRayAttack(Attacks::detail::Dir dir, int square, U64 blockers) { U64 attacks = RAYS[dir][square]; U64 blocked = attacks & blockers; if (blocked) { int blockSquare = 64 - _bitscanReverse(blocked); attacks ^= RAYS[dir][blockSquare]; } return attacks; } void Attacks::detail::_initPawnAttacks() { for (int i = 0; i < 64; i++) { U64 start = ONE << i; U64 whiteAttackBb = ((start << 9) & ~FILE_A) | ((start << 7) & ~FILE_H); U64 blackAttackBb = ((start >> 9) & ~FILE_H) | ((start >> 7) & ~FILE_A); NON_SLIDING_ATTACKS[WHITE][PAWN][i] = whiteAttackBb; NON_SLIDING_ATTACKS[BLACK][PAWN][i] = blackAttackBb; } } void Attacks::detail::_initKnightAttacks() { for (int i = 0; i < 64; i++) { U64 start = ONE << i; U64 attackBb = (((start << 15) | (start >> 17)) & ~FILE_H) | // Left 1 (((start >> 15) | (start << 17)) & ~FILE_A) | // Right 1 (((start << 6) | (start >> 10)) & ~(FILE_G | FILE_H)) | // Left 2 (((start >> 6) | (start << 10)) & ~(FILE_A | FILE_B)); // Right 2 NON_SLIDING_ATTACKS[WHITE][KNIGHT][i] = attackBb; NON_SLIDING_ATTACKS[BLACK][KNIGHT][i] = attackBb; } } void Attacks::detail::_initKingAttacks() { for (int i = 0; i < 64; i++) { U64 start = ONE << i; U64 attackBb = (((start << 7) | (start >> 9) | (start >> 1)) & (~FILE_H)) | (((start << 9) | (start >> 7) | (start << 1)) & (~FILE_A)) | ((start >> 8) | (start << 8)); NON_SLIDING_ATTACKS[WHITE][KING][i] = attackBb; NON_SLIDING_ATTACKS[BLACK][KING][i] = attackBb; } } void Attacks::detail::_initNorthRays() { U64 north = U64(0x0101010101010100); for (int square = 0; square < 64; square++, north <<= 1) { RAYS[NORTH][square] = north; } } void Attacks::detail::_initEastRays() { for (int square = 0; square < 64; square++) { RAYS[EAST][square] = 2 * ((ONE << (square | 7)) - (ONE << square)); } } void Attacks::detail::_initNorthEastRays() { U64 startRay = U64(0x8040201008040200); for (int file = 0; file < 8; file++, startRay = _eastOne(startRay)) { U64 currRay = startRay; for (int rank8 = 0; rank8 < 64; rank8 += 8, currRay <<= 8ull) { RAYS[NORTH_EAST][rank8 + file] = currRay; } } } void Attacks::detail::_initNorthWestRays() { U64 startRay = U64(0x102040810204000); for (int file = 7; file >= 0; file--, startRay = _westOne(startRay)) { U64 currRay = startRay; for (int rank8 = 0; rank8 < 64; rank8 += 8, currRay <<= 8ull) { RAYS[NORTH_WEST][rank8 + file] = currRay; } } } void Attacks::detail::_initSouthEastRays() { U64 startRay = U64(0x2040810204080); for (int file = 0; file < 8; file++, startRay = _eastOne(startRay)) { U64 currRay = startRay; for (int rank8 = 56; rank8 >= 0; rank8 -= 8, currRay >>= 8ull) { RAYS[SOUTH_EAST][rank8 + file] = currRay; } } } void Attacks::detail::_initSouthRays() { U64 south = U64(0x0080808080808080); for (int square = 63; square >= 0; square--, south >>= 1) { RAYS[SOUTH][square] = south; } } void Attacks::detail::_initSouthWestRays() { U64 startRay = U64(0x40201008040201); for (int file = 7; file >= 0; file--, startRay = _westOne(startRay)) { U64 currRay = startRay; for (int rank8 = 56; rank8 >= 0; rank8 -= 8, currRay >>= 8ull) { RAYS[SOUTH_WEST][rank8 + file] = currRay; } } } void Attacks::detail::_initWestRays() { for (int square = 0; square < 64; square++) { RAYS[WEST][square] = (ONE << square) - (ONE << (square & 56)); } }
Remove stdexcept include
Remove stdexcept include
C++
mit
GunshipPenguin/shallow-blue,GunshipPenguin/shallow-blue,GunshipPenguin/shallow-blue,GunshipPenguin/shallow-blue
629acfb35e79679cd4be967bbe7c6a77223a69cf
ModelBuilder/ModelRunner.cpp
ModelBuilder/ModelRunner.cpp
//===----------------------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "ModelBuilder/ModelRunner.h" #include "llvm/Support/TargetSelect.h" #include "mlir/Conversion/AffineToStandard/AffineToStandard.h" #include "mlir/Conversion/GPUToSPIRV/GPUToSPIRVPass.h" #include "mlir/Conversion/GPUToVulkan/ConvertGPUToVulkanPass.h" #include "mlir/Conversion/LinalgToLLVM/LinalgToLLVM.h" #include "mlir/Conversion/SCFToStandard/SCFToStandard.h" #include "mlir/Conversion/StandardToLLVM/ConvertStandardToLLVMPass.h" #include "mlir/Conversion/StandardToSPIRV/StandardToSPIRVPass.h" #include "mlir/Conversion/VectorToLLVM/ConvertVectorToLLVM.h" #include "mlir/Conversion/VectorToSCF/VectorToSCF.h" #include "mlir/Dialect/GPU/Passes.h" #include "mlir/Dialect/Linalg/Passes.h" #include "mlir/Dialect/MemRef/Transforms/Passes.h" #include "mlir/Dialect/SPIRV/IR/SPIRVOps.h" #include "mlir/Dialect/SPIRV/Transforms/Passes.h" #include "mlir/ExecutionEngine/ExecutionEngine.h" #include "mlir/ExecutionEngine/OptUtils.h" #include "mlir/IR/PatternMatch.h" #include "mlir/Pass/Pass.h" #include "mlir/Pass/PassManager.h" #include "mlir/Transforms/GreedyPatternRewriteDriver.h" #include "mlir/Transforms/Passes.h" static llvm::cl::opt<bool> mlirDebug( "mlir-debug", llvm::cl::desc("Single thread and print-ir-after-all"), llvm::cl::init(false)); struct LLVMInitializer { LLVMInitializer() { llvm::InitializeNativeTarget(); llvm::InitializeNativeTargetAsmPrinter(); } }; static LLVMInitializer initializer; namespace llvm { extern Pass* createLowerMatrixIntrinsicsPass(); } // end namespace llvm void mlir::ModelRunner::compile( CompilationOptions compilationOptions, llvm::ArrayRef<const std::string> runtime, llvm::ArrayRef<std::pair<std::string, void*>> extra_symbols) { if (target == Target::CPUTarget) { // Lower vector operations progressively into more elementary // vector operations before running the regular compiler passes. mlir::OwningRewritePatternList patterns(module->getContext()); mlir::vector::populateVectorSlicesLoweringPatterns(patterns); mlir::vector::populateVectorContractLoweringPatterns( patterns, compilationOptions.vectorTransformsOptions); mlir::vector::populateVectorTransposeLoweringPatterns( patterns, compilationOptions.vectorTransformsOptions); (void)mlir::applyPatternsAndFoldGreedily(*module, std::move(patterns)); } runLoweringPass(compilationOptions.loweringPasses ? compilationOptions.loweringPasses : getDefaultMLIRPassBuilder()); // Make sure the execution engine runs LLVM passes for the specified // optimization level. auto tmBuilderOrError = llvm::orc::JITTargetMachineBuilder::detectHost(); if (!tmBuilderOrError) { llvm::errs() << tmBuilderOrError.takeError() << "\n"; return; } auto t = tmBuilderOrError->getTargetTriple().getTriple(); auto tmOrError = tmBuilderOrError->createTargetMachine(); if (!tmOrError) { llvm::errs() << tmOrError.takeError() << "\n"; return; } targetMachine = std::move(tmOrError.get()); SmallVector<const llvm::PassInfo*, 4> llvmPasses; if (target == Target::CPUTarget) { // TODO(ntv): Looking up the pass by name fails quite surprisingly. Just // build the pass to get its ID to look up the PassInfo. std::unique_ptr<llvm::Pass> owningLowerMatrixIntrinsicsPass( llvm::createLowerMatrixIntrinsicsPass()); const llvm::PassInfo* lowerMatrixIntrinsics = llvm::Pass::lookupPassInfo( owningLowerMatrixIntrinsicsPass->getPassID()); assert(lowerMatrixIntrinsics); llvmPasses.push_back(lowerMatrixIntrinsics); } auto transformer = mlir::makeLLVMPassesTransformer( llvmPasses, compilationOptions.llvmOptLevel, targetMachine.get(), /*optPassesInsertPos=*/0); // Pass in runtime support library when specified. SmallVector<StringRef, 4> libs(runtime.begin(), runtime.end()); // Obtain the execution engine. auto created = mlir::ExecutionEngine::create( *module, /*llvmModuleBuilder=*/nullptr, transformer, static_cast<llvm::CodeGenOpt::Level>(compilationOptions.llcOptLevel), libs, /*enableObjectCache=*/true, /*enableGDBNotificationListener=*/false); llvm::handleAllErrors(created.takeError(), [](const llvm::ErrorInfoBase& b) { b.log(llvm::errs()); assert(false); }); engine = std::move(*created); // Define any extra symbols so they're available at runtime. auto symbolRegisterer = [&extra_symbols](llvm::orc::MangleAndInterner interner) { llvm::orc::SymbolMap symbolMap; for (auto& symbol : extra_symbols) { const std::string& name = symbol.first; void* function_pointer = symbol.second; symbolMap[interner(name)] = llvm::JITEvaluatedSymbol::fromPointer(function_pointer); } return symbolMap; }; engine->registerSymbols(symbolRegisterer); } static void addVulkanLoweringPass(mlir::PassManager& manager) { manager.addPass(mlir::createGpuKernelOutliningPass()); manager.addPass(mlir::memref::createFoldSubViewOpsPass()); manager.addPass(mlir::createConvertGPUToSPIRVPass()); mlir::OpPassManager& modulePM = manager.nest<mlir::spirv::ModuleOp>(); modulePM.addPass(mlir::spirv::createLowerABIAttributesPass()); modulePM.addPass(mlir::spirv::createUpdateVersionCapabilityExtensionPass()); manager.addPass(mlir::createConvertGpuLaunchFuncToVulkanLaunchFuncPass()); mlir::LowerToLLVMOptions llvmOptions(manager.getContext()); llvmOptions.emitCWrappers = true; manager.addPass(createLowerToLLVMPass(llvmOptions)); manager.addPass(mlir::createConvertVulkanLaunchFuncToVulkanCallsPass()); } static void addCPULoweringPass(mlir::PassManager& manager) { // Set up compiler passes. manager.addNestedPass<mlir::FuncOp>(mlir::createConvertVectorToSCFPass()); manager.addNestedPass<mlir::FuncOp>(mlir::createConvertLinalgToLoopsPass()); manager.addPass(mlir::createConvertLinalgToLLVMPass()); manager.addPass(mlir::createConvertLinalgToLoopsPass()); manager.addPass(mlir::createLowerAffinePass()); manager.addPass(mlir::createLowerToCFGPass()); manager.addPass(mlir::createConvertVectorToLLVMPass()); manager.addPass(mlir::createLowerToLLVMPass()); } std::function<void(mlir::PassManager&)> mlir::ModelRunner::getDefaultMLIRPassBuilder() { if (target == Target::CPUTarget) { return addCPULoweringPass; } else { assert(target == Target::GPUTarget); return addVulkanLoweringPass; } } void mlir::ModelRunner::runLoweringPass( std::function<void(mlir::PassManager&)> passBuilder) { PassManager manager(module->getContext(), mlir::OpPassManager::Nesting::Implicit); if (mlirDebug) { manager.getContext()->disableMultithreading(); manager.enableIRPrinting([](Pass*, Operation*) { return true; }, [](Pass*, Operation*) { return true; }, true, true, llvm::errs()); } passBuilder(manager); if (failed(manager.run(*module))) { llvm::errs() << "conversion to the LLVM IR dialect failed\n"; return; } }
//===----------------------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "ModelBuilder/ModelRunner.h" #include "llvm/Support/TargetSelect.h" #include "mlir/Conversion/AffineToStandard/AffineToStandard.h" #include "mlir/Conversion/GPUToSPIRV/GPUToSPIRVPass.h" #include "mlir/Conversion/GPUToVulkan/ConvertGPUToVulkanPass.h" #include "mlir/Conversion/LinalgToLLVM/LinalgToLLVM.h" #include "mlir/Conversion/SCFToStandard/SCFToStandard.h" #include "mlir/Conversion/StandardToLLVM/ConvertStandardToLLVMPass.h" #include "mlir/Conversion/StandardToSPIRV/StandardToSPIRVPass.h" #include "mlir/Conversion/VectorToLLVM/ConvertVectorToLLVM.h" #include "mlir/Conversion/VectorToSCF/VectorToSCF.h" #include "mlir/Dialect/GPU/Passes.h" #include "mlir/Dialect/Linalg/Passes.h" #include "mlir/Dialect/MemRef/Transforms/Passes.h" #include "mlir/Dialect/SPIRV/IR/SPIRVOps.h" #include "mlir/Dialect/SPIRV/Transforms/Passes.h" #include "mlir/ExecutionEngine/ExecutionEngine.h" #include "mlir/ExecutionEngine/OptUtils.h" #include "mlir/IR/PatternMatch.h" #include "mlir/Pass/Pass.h" #include "mlir/Pass/PassManager.h" #include "mlir/Transforms/GreedyPatternRewriteDriver.h" #include "mlir/Transforms/Passes.h" static llvm::cl::opt<bool> mlirDebug( "mlir-debug", llvm::cl::desc("Single thread and print-ir-after-all"), llvm::cl::init(false)); struct LLVMInitializer { LLVMInitializer() { llvm::InitializeNativeTarget(); llvm::InitializeNativeTargetAsmPrinter(); } }; static LLVMInitializer initializer; namespace llvm { extern Pass* createLowerMatrixIntrinsicsPass(); } // end namespace llvm void mlir::ModelRunner::compile( CompilationOptions compilationOptions, llvm::ArrayRef<const std::string> runtime, llvm::ArrayRef<std::pair<std::string, void*>> extra_symbols) { if (target == Target::CPUTarget) { // Lower vector operations progressively into more elementary // vector operations before running the regular compiler passes. mlir::OwningRewritePatternList patterns(module->getContext()); mlir::vector::populateVectorSlicesLoweringPatterns(patterns); mlir::vector::populateVectorContractLoweringPatterns( patterns, compilationOptions.vectorTransformsOptions); mlir::vector::populateVectorTransposeLoweringPatterns( patterns, compilationOptions.vectorTransformsOptions); (void)mlir::applyPatternsAndFoldGreedily(*module, std::move(patterns)); } runLoweringPass(compilationOptions.loweringPasses ? compilationOptions.loweringPasses : getDefaultMLIRPassBuilder()); // Make sure the execution engine runs LLVM passes for the specified // optimization level. auto tmBuilderOrError = llvm::orc::JITTargetMachineBuilder::detectHost(); if (!tmBuilderOrError) { llvm::errs() << tmBuilderOrError.takeError() << "\n"; return; } auto t = tmBuilderOrError->getTargetTriple().getTriple(); auto tmOrError = tmBuilderOrError->createTargetMachine(); if (!tmOrError) { llvm::errs() << tmOrError.takeError() << "\n"; return; } targetMachine = std::move(tmOrError.get()); SmallVector<const llvm::PassInfo*, 4> llvmPasses; if (target == Target::CPUTarget) { // TODO(ntv): Looking up the pass by name fails quite surprisingly. Just // build the pass to get its ID to look up the PassInfo. std::unique_ptr<llvm::Pass> owningLowerMatrixIntrinsicsPass( llvm::createLowerMatrixIntrinsicsPass()); const llvm::PassInfo* lowerMatrixIntrinsics = llvm::Pass::lookupPassInfo( owningLowerMatrixIntrinsicsPass->getPassID()); assert(lowerMatrixIntrinsics); llvmPasses.push_back(lowerMatrixIntrinsics); } auto transformer = mlir::makeLLVMPassesTransformer( llvmPasses, compilationOptions.llvmOptLevel, targetMachine.get(), /*optPassesInsertPos=*/0); // Pass in runtime support library when specified. SmallVector<StringRef, 4> libs(runtime.begin(), runtime.end()); // Obtain the execution engine. auto created = mlir::ExecutionEngine::create( *module, /*llvmModuleBuilder=*/nullptr, transformer, static_cast<llvm::CodeGenOpt::Level>(compilationOptions.llcOptLevel), libs, /*enableObjectCache=*/true, /*enableGDBNotificationListener=*/false); llvm::handleAllErrors(created.takeError(), [](const llvm::ErrorInfoBase& b) { b.log(llvm::errs()); assert(false); }); engine = std::move(*created); // Define any extra symbols so they're available at runtime. auto symbolRegisterer = [&extra_symbols](llvm::orc::MangleAndInterner interner) { llvm::orc::SymbolMap symbolMap; for (auto& symbol : extra_symbols) { const std::string& name = symbol.first; void* function_pointer = symbol.second; symbolMap[interner(name)] = llvm::JITEvaluatedSymbol::fromPointer(function_pointer); } return symbolMap; }; engine->registerSymbols(symbolRegisterer); } static void addVulkanLoweringPass(mlir::PassManager& manager) { manager.addPass(mlir::createGpuKernelOutliningPass()); manager.addPass(mlir::memref::createFoldSubViewOpsPass()); manager.addPass(mlir::createConvertGPUToSPIRVPass()); mlir::OpPassManager& modulePM = manager.nest<mlir::spirv::ModuleOp>(); modulePM.addPass(mlir::spirv::createLowerABIAttributesPass()); modulePM.addPass(mlir::spirv::createUpdateVersionCapabilityExtensionPass()); manager.addPass(mlir::createConvertGpuLaunchFuncToVulkanLaunchFuncPass()); mlir::LowerToLLVMOptions llvmOptions(manager.getContext()); llvmOptions.emitCWrappers = true; manager.addPass(createLowerToLLVMPass(llvmOptions)); manager.addPass(mlir::createConvertVulkanLaunchFuncToVulkanCallsPass()); } static void addCPULoweringPass(mlir::PassManager& manager) { // Set up compiler passes. manager.addNestedPass<mlir::FuncOp>(mlir::createConvertVectorToSCFPass()); manager.addNestedPass<mlir::FuncOp>(mlir::createConvertLinalgToLoopsPass()); manager.addPass(mlir::createConvertLinalgToLLVMPass()); manager.addPass(mlir::createConvertLinalgToLoopsPass()); manager.addPass(mlir::createLowerAffinePass()); manager.addPass(mlir::createLowerToCFGPass()); manager.addPass(mlir::createConvertVectorToLLVMPass()); manager.addPass(mlir::createLowerToLLVMPass()); } std::function<void(mlir::PassManager&)> mlir::ModelRunner::getDefaultMLIRPassBuilder() { if (target == Target::CPUTarget) { return addCPULoweringPass; } else { assert(target == Target::GPUTarget); return addVulkanLoweringPass; } } void mlir::ModelRunner::runLoweringPass( std::function<void(mlir::PassManager&)> passBuilder) { PassManager manager(module->getContext(), mlir::OpPassManager::Nesting::Implicit); if (mlirDebug) { manager.getContext()->disableMultithreading(); manager.enableIRPrinting([](Pass*, Operation*) { return true; }, [](Pass*, Operation*) { return true; }, true, true, /*printAfterOnlyOnFailure=*/false, llvm::errs()); } passBuilder(manager); if (failed(manager.run(*module))) { llvm::errs() << "conversion to the LLVM IR dialect failed\n"; return; } }
Integrate LLVM at llvm/llvm-project@cb82e8ea33e3
Integrate LLVM at llvm/llvm-project@cb82e8ea33e3 Updates LLVM usage to match [cb82e8ea33e3](https://github.com/llvm/llvm-project/commit/cb82e8ea33e3) PiperOrigin-RevId: 374977251
C++
apache-2.0
iree-org/iree-llvm-sandbox,iree-org/iree-llvm-sandbox,iree-org/iree-llvm-sandbox,iree-org/iree-llvm-sandbox
b8746fee29306a89ec5426dd67acc463f810a886
src/faunus.cpp
src/faunus.cpp
#include "core.h" #include "mpicontroller.h" #include "move.h" #include "montecarlo.h" #include "analysis.h" #include "multipole.h" #include "docopt.h" #include "progress_tracker.h" #include <cstdlib> #include "spdlog/spdlog.h" #include <spdlog/sinks/null_sink.h> #include <spdlog/sinks/stdout_color_sinks.h> #include <iomanip> #include <unistd.h> #ifdef ENABLE_SID #include "cppsid.h" #include <thread> using namespace std::this_thread; // sleep_for, sleep_until using namespace std::chrono_literals; // ns, us, ms, s, h, etc. using std::chrono::system_clock; // some forward declarations std::pair<std::string, int> findSIDsong(); std::shared_ptr<CPPSID::Player> createLoadedSIDplayer(); #endif using namespace Faunus; using namespace std; #define Q(x) #x #define QUOTE(x) Q(x) #ifndef FAUNUS_TIPSFILE #define FAUNUS_TIPSFILE "" #endif static const char USAGE[] = R"(Faunus - the Monte Carlo code you're looking for! http://github.com/mlund/faunus Usage: faunus [-q] [--verbosity <N>] [--nobar] [--nopfx] [--notips] [--nofun] [--state=<file>] [--input=<file>] [--output=<file>] faunus (-h | --help) faunus --version Options: -i <file> --input <file> Input file [default: /dev/stdin]. -o <file> --output <file> Output file [default: out.json]. -s <file> --state <file> State file to start from (.json/.ubj). -v <N> --verbosity <N> Log verbosity level (0 = off, 1 = critical, ..., 6 = trace) [default: 4] -q --quiet Less verbose output. It implicates -v0 --nobar --notips --nofun. -h --help Show this screen. --nobar No progress bar. --nopfx Do not prefix input file with MPI rank. --notips Do not give input assistance --nofun No fun --version Show version. Multiple processes using MPI: 1. input and output files are prefixed with "mpi{rank}." 2. standard output is redirected to "mpi{rank}.stdout" 3. Input prefixing can be suppressed with --nopfx )"; using ProgressIndicator::ProgressTracker; // forward declarations std::shared_ptr<ProgressTracker> createProgressTracker(bool, unsigned int); int main(int argc, char **argv) { using namespace Faunus::MPI; bool quiet = false, nofun = true; // conservative defaults try { std::string version = "Faunus"; #ifdef GIT_LATEST_TAG version += " "s + QUOTE(GIT_LATEST_TAG); #endif #ifdef GIT_COMMIT_HASH version += " git " + std::string(GIT_COMMIT_HASH); #endif #ifdef ENABLE_SID version += " [sid]"; #endif #ifdef ENABLE_MPI version += " [mpi]"; #endif #ifdef _OPENMP version += " [openmp]"; #endif auto args = docopt::docopt(USAGE, {argv + 1, argv + argc}, true, version); // --quiet; set quiet first as it also affects exception handling quiet = args["--quiet"].asBool(); if (quiet) { cout.setstate(std::ios_base::failbit); // hold kæft } mpi.init(); // initialize MPI, if available // prepare loggers // TODO refactor to a standalone function and use cmd line options for different sinks, etc. faunus_logger = spdlog::stderr_color_mt("faunus"); faunus_logger->set_pattern("[%n %P] %^%L: %v%$"); mcloop_logger = spdlog::stderr_color_mt("mcloop"); mcloop_logger->set_pattern("[%n %P] [%E.%f] %L: %v"); // --verbosity (log level) long log_level = spdlog::level::off - (quiet ? 0 : args["--verbosity"].asLong()); // reverse sequence 0 → 6 to 6 → 0 spdlog::set_level(static_cast<spdlog::level::level_enum>(log_level)); // --notips if (!quiet && !args["--notips"].asBool()) { usageTip.load({FAUNUS_TIPSFILE}); } // --nobar bool show_progress = !quiet && !args["--nobar"].asBool(); // --nofun nofun = args["--nofun"].asBool(); usageTip.asciiart = !quiet && !nofun; #ifdef ENABLE_SID usageTip.asciiart = false; // if SID is enabled, disable ascii #endif // --nopfx bool prefix = !args["--nopfx"].asBool(); // --input json json_in; auto input = args["--input"].asString(); if (input == "/dev/stdin") { std::cin >> json_in; } else { if (prefix) { input = Faunus::MPI::prefix + input; } json_in = openjson(input); } { pc::temperature = json_in.at("temperature").get<double>() * 1.0_K; MCSimulation sim(json_in, mpi); // --state if (args["--state"]) { std::ifstream f; std::string state = Faunus::MPI::prefix + args["--state"].asString(); std::string suffix = state.substr(state.find_last_of(".") + 1); bool binary = (suffix == "ubj"); auto mode = std::ios::in; if (binary) mode = std::ifstream::ate | std::ios::binary; // ate = open at end f.open(state, mode); if (f) { json json_state; faunus_logger->info("loading state file {}", state); if (binary) { size_t size = f.tellg(); // get file size std::vector<std::uint8_t> v(size / sizeof(std::uint8_t)); f.seekg(0, f.beg); // go back to start f.read((char *)v.data(), size); json_state = json::from_ubjson(v); } else { f >> json_state; } sim.restore(json_state); } else { throw std::runtime_error("state file error: " + state); } } // warn if initial system has a net charge { auto p = sim.space().activeParticles(); double system_charge = Faunus::monopoleMoment(p.begin(), p.end()); if (std::fabs(system_charge) > 0) faunus_logger->warn("non-zero system charge of {}e", system_charge); } Analysis::CombinedAnalysis analysis(json_in.at("analysis"), sim.space(), sim.pot()); auto &loop = json_in.at("mcloop"); int macro = loop.at("macro"); int micro = loop.at("micro"); auto progress_tracker = createProgressTracker(show_progress, macro * micro); for (int i = 0; i < macro; i++) { for (int j = 0; j < micro; j++) { if (progress_tracker && mpi.isMaster()) { if(++(*progress_tracker) % 10 == 0) { progress_tracker->display(); } } sim.move(); analysis.sample(); } // end of micro steps analysis.to_disk(); // save analysis to disk } // end of macro steps if (progress_tracker && mpi.isMaster()) { progress_tracker->done(); } faunus_logger->log((sim.drift() < 1E-9) ? spdlog::level::info : spdlog::level::warn, "relative drift = {}", sim.drift()); // --output std::ofstream f(Faunus::MPI::prefix + args["--output"].asString()); if (f) { json json_out; Faunus::to_json(json_out, sim); json_out["relative drift"] = sim.drift(); json_out["analysis"] = analysis; if (mpi.nproc() > 1) { json_out["mpi"] = mpi; } #ifdef GIT_COMMIT_HASH json_out["git revision"] = GIT_COMMIT_HASH; #endif #ifdef __VERSION__ json_out["compiler"] = __VERSION__; #endif f << std::setw(4) << json_out << endl; } } mpi.finalize(); } catch (std::exception &e) { faunus_logger->error(e.what()); if (!usageTip.buffer.empty()) { faunus_logger->error(usageTip.buffer); } #ifdef ENABLE_SID // easter egg... if (!quiet && !nofun && mpi.isMaster()) { // -> fun auto player = createLoadedSIDplayer(); // create C64 SID emulation and load a random tune if (player) { faunus_logger->info("error message music '{}' by {}, {} (6502/SID emulation)", player->title(), player->author(), player->info()); faunus_logger->info("\033[1mpress ctrl-c to quit\033[0m"); player->start(); // start music sleep_for(10ns); // short delay sleep_until(system_clock::now() + 240s); // play for 4 minutes, then exit player->stop(); std::cout << std::endl; } } // end of easter egg #endif return EXIT_FAILURE; } return EXIT_SUCCESS; } #ifdef ENABLE_SID /* * finds a random SID music file and picks a random sub-song if available * * will look for `music.json` as well as sid files in the following * directories and order: * * - BINARY_DIR/sids/ * - INSTALL_PREFIX/share/faunus/sids */ std::pair<std::string, int> findSIDsong() { std::string filename; int subsong = -1; try { // look for json file with hvsc sid tune names std::string pfx; json json_music; for (std::string dir : {FAUNUS_BINARY_DIR, FAUNUS_INSTALL_PREFIX "/share/faunus/"}) { // installed and uninstalled cmake builds json_music = Faunus::openjson(dir + "/sids/music.json", false); if (!json_music.empty()) { pfx = dir + "/"; break; } } if (not json_music.empty()) { json_music = json_music.at("songs"); // load playlist std::vector<size_t> weight; // weight for each tune (= number of subsongs) for (auto &i : json_music) weight.push_back(i.at("subsongs").size()); std::discrete_distribution<size_t> dist(weight.begin(), weight.end()); Faunus::random.seed(); // give global random a hardware seed auto it = json_music.begin() + dist(Faunus::random.engine); // pick random tune weighted by subsongs auto subsongs = (*it).at("subsongs").get<std::vector<int>>(); // all subsongs subsong = *(Faunus::random.sample(subsongs.begin(), subsongs.end())) - 1; // random subsong filename = pfx + it->at("file").get<std::string>(); } } catch (const std::exception &) { // silently ignore if something fails; it's just for fun! } return {filename, subsong}; } std::shared_ptr<CPPSID::Player> createLoadedSIDplayer() { std::shared_ptr<CPPSID::Player> player; if (isatty(fileno(stdout))) { // only play music if on console if (not std::getenv("SSH_CLIENT")) { // and not through a ssh connection player = std::make_shared<CPPSID::Player>(); // let's emulate a Commodore 64... auto tune = findSIDsong(); // pick a song from our pre-defined library player->load(tune.first, tune.second); } } return player; } #endif std::shared_ptr<ProgressTracker> createProgressTracker(bool show_progress, unsigned int steps) { using namespace ProgressIndicator; using namespace std::chrono; std::shared_ptr<ProgressTracker> tracker = nullptr; if(show_progress) { if (isatty(fileno(stdout))) { // show a progress bar on the console tracker = std::make_shared<ProgressBar>(steps); } else { // not in a console tracker = std::make_shared<TaciturnDecorator>( // hence print a new line std::make_shared<ProgressLog>(steps), // at most every 10 minutes or after 0.5% of progress, whatever comes first duration_cast<milliseconds>(minutes(10)), 0.005); } } return tracker; }
#include "core.h" #include "mpicontroller.h" #include "move.h" #include "montecarlo.h" #include "analysis.h" #include "multipole.h" #include "docopt.h" #include "progress_tracker.h" #include <cstdlib> #include "spdlog/spdlog.h" #include <spdlog/sinks/null_sink.h> #include <spdlog/sinks/stdout_color_sinks.h> #include <iomanip> #include <unistd.h> #include <chrono> #ifdef ENABLE_SID #include "cppsid.h" #include <thread> using namespace std::this_thread; // sleep_for, sleep_until using namespace std::chrono_literals; // ns, us, ms, s, h, etc. using std::chrono::system_clock; // some forward declarations std::pair<std::string, int> findSIDsong(); std::shared_ptr<CPPSID::Player> createLoadedSIDplayer(); #endif using namespace Faunus; using namespace std; #define Q(x) #x #define QUOTE(x) Q(x) #ifndef FAUNUS_TIPSFILE #define FAUNUS_TIPSFILE "" #endif static const char USAGE[] = R"(Faunus - the Monte Carlo code you're looking for! https://faunus.readthedocs.io Usage: faunus [-q] [--verbosity <N>] [--nobar] [--nopfx] [--notips] [--nofun] [--state=<file>] [--input=<file>] [--output=<file>] faunus (-h | --help) faunus --version Options: -i <file> --input <file> Input file [default: /dev/stdin]. -o <file> --output <file> Output file [default: out.json]. -s <file> --state <file> State file to start from (.json/.ubj). -v <N> --verbosity <N> Log verbosity level (0 = off, 1 = critical, ..., 6 = trace) [default: 4] -q --quiet Less verbose output. It implicates -v0 --nobar --notips --nofun. -h --help Show this screen. --nobar No progress bar. --nopfx Do not prefix input file with MPI rank. --notips Do not give input assistance --nofun No fun --version Show version. Multiple processes using MPI: 1. input and output files are prefixed with "mpi{rank}." 2. standard output is redirected to "mpi{rank}.stdout" 3. Input prefixing can be suppressed with --nopfx )"; using ProgressIndicator::ProgressTracker; // forward declarations std::shared_ptr<ProgressTracker> createProgressTracker(bool, unsigned int); int main(int argc, char **argv) { using namespace Faunus::MPI; bool quiet = false, nofun = true; // conservative defaults try { auto starting_time = std::chrono::steady_clock::now(); // used to time the simulation std::string version = "Faunus"; #ifdef GIT_LATEST_TAG version += " "s + QUOTE(GIT_LATEST_TAG); #endif #ifdef GIT_COMMIT_HASH version += " git " + std::string(GIT_COMMIT_HASH); #endif #ifdef ENABLE_SID version += " [sid]"; #endif #ifdef ENABLE_MPI version += " [mpi]"; #endif #ifdef _OPENMP version += " [openmp]"; #endif auto args = docopt::docopt(USAGE, {argv + 1, argv + argc}, true, version); // --quiet; set quiet first as it also affects exception handling quiet = args["--quiet"].asBool(); if (quiet) { cout.setstate(std::ios_base::failbit); // hold kæft } mpi.init(); // initialize MPI, if available // prepare loggers // TODO refactor to a standalone function and use cmd line options for different sinks, etc. faunus_logger = spdlog::stderr_color_mt("faunus"); faunus_logger->set_pattern("[%n %P] %^%L: %v%$"); mcloop_logger = spdlog::stderr_color_mt("mcloop"); mcloop_logger->set_pattern("[%n %P] [%E.%f] %L: %v"); // --verbosity (log level) long log_level = spdlog::level::off - (quiet ? 0 : args["--verbosity"].asLong()); // reverse sequence 0 → 6 to 6 → 0 spdlog::set_level(static_cast<spdlog::level::level_enum>(log_level)); // --notips if (!quiet && !args["--notips"].asBool()) { usageTip.load({FAUNUS_TIPSFILE}); } // --nobar bool show_progress = !quiet && !args["--nobar"].asBool(); // --nofun nofun = args["--nofun"].asBool(); usageTip.asciiart = !quiet && !nofun; #ifdef ENABLE_SID usageTip.asciiart = false; // if SID is enabled, disable ascii #endif // --nopfx bool prefix = !args["--nopfx"].asBool(); // --input json json_in; if (auto input = args["--input"].asString(); input == "/dev/stdin") { std::cin >> json_in; } else { if (prefix) { input = Faunus::MPI::prefix + input; } json_in = openjson(input); } { pc::temperature = json_in.at("temperature").get<double>() * 1.0_K; MCSimulation sim(json_in, mpi); // --state if (args["--state"]) { std::ifstream f; std::string state = Faunus::MPI::prefix + args["--state"].asString(); std::string suffix = state.substr(state.find_last_of(".") + 1); bool binary = (suffix == "ubj"); auto mode = std::ios::in; if (binary) { mode = std::ifstream::ate | std::ios::binary; // ate = open at end } f.open(state, mode); if (f) { json j; faunus_logger->info("loading state file {}", state); if (binary) { size_t size = f.tellg(); // get file size std::vector<std::uint8_t> v(size / sizeof(std::uint8_t)); f.seekg(0, f.beg); // go back to start f.read((char *)v.data(), size); j = json::from_ubjson(v); } else { f >> j; } sim.restore(j); } else { throw std::runtime_error("state file error: " + state); } } // warn if initial system has a net charge { auto p = sim.space().activeParticles(); if (double system_charge = Faunus::monopoleMoment(p.begin(), p.end()); std::fabs(system_charge) > 0) { faunus_logger->warn("non-zero system charge of {}e", system_charge); } } Analysis::CombinedAnalysis analysis(json_in.at("analysis"), sim.space(), sim.pot()); auto &loop = json_in.at("mcloop"); int macro = loop.at("macro"); int micro = loop.at("micro"); auto progress_tracker = createProgressTracker(show_progress, macro * micro); for (int i = 0; i < macro; i++) { for (int j = 0; j < micro; j++) { if (progress_tracker && mpi.isMaster()) { if(++(*progress_tracker) % 10 == 0) { progress_tracker->display(); } } sim.move(); analysis.sample(); } // end of micro steps analysis.to_disk(); // save analysis to disk } // end of macro steps if (progress_tracker && mpi.isMaster()) { progress_tracker->done(); } faunus_logger->log((sim.drift() < 1E-9) ? spdlog::level::info : spdlog::level::warn, "relative energy drift = {}", sim.drift()); // --output if (std::ofstream file(Faunus::MPI::prefix + args["--output"].asString()); file) { json j; Faunus::to_json(j, sim); j["relative drift"] = sim.drift(); j["analysis"] = analysis; if (mpi.nproc() > 1) { j["mpi"] = mpi; } #ifdef GIT_COMMIT_HASH j["git revision"] = GIT_COMMIT_HASH; #endif #ifdef __VERSION__ j["compiler"] = __VERSION__; #endif { // report on total simulation time using namespace std::chrono; auto ending_time = steady_clock::now(); auto secs = duration_cast<seconds>(ending_time - starting_time).count(); j["simulation time"] = {{"in minutes", secs / 60.0}, {"in seconds", secs}}; } file << std::setw(4) << j << std::endl; } } mpi.finalize(); } catch (std::exception &e) { faunus_logger->error(e.what()); if (!usageTip.buffer.empty()) { faunus_logger->error(usageTip.buffer); } #ifdef ENABLE_SID // easter egg... if (!quiet && !nofun && mpi.isMaster()) { // -> fun auto player = createLoadedSIDplayer(); // create C64 SID emulation and load a random tune if (player) { faunus_logger->info("error message music '{}' by {}, {} (6502/SID emulation)", player->title(), player->author(), player->info()); faunus_logger->info("\033[1mpress ctrl-c to quit\033[0m"); player->start(); // start music sleep_for(10ns); // short delay sleep_until(system_clock::now() + 240s); // play for 4 minutes, then exit player->stop(); std::cout << std::endl; } } // end of easter egg #endif return EXIT_FAILURE; } return EXIT_SUCCESS; } #ifdef ENABLE_SID /* * finds a random SID music file and picks a random sub-song if available * * will look for `music.json` as well as sid files in the following * directories and order: * * - BINARY_DIR/sids/ * - INSTALL_PREFIX/share/faunus/sids */ std::pair<std::string, int> findSIDsong() { std::string filename; int subsong = -1; try { // look for json file with hvsc sid tune names std::string pfx; json json_music; for (std::string dir : {FAUNUS_BINARY_DIR, FAUNUS_INSTALL_PREFIX "/share/faunus/"}) { // installed and uninstalled cmake builds json_music = Faunus::openjson(dir + "/sids/music.json", false); if (!json_music.empty()) { pfx = dir + "/"; break; } } if (not json_music.empty()) { json_music = json_music.at("songs"); // load playlist std::vector<size_t> weight; // weight for each tune (= number of subsongs) for (auto &i : json_music) weight.push_back(i.at("subsongs").size()); std::discrete_distribution<size_t> dist(weight.begin(), weight.end()); Faunus::random.seed(); // give global random a hardware seed auto it = json_music.begin() + dist(Faunus::random.engine); // pick random tune weighted by subsongs auto subsongs = (*it).at("subsongs").get<std::vector<int>>(); // all subsongs subsong = *(Faunus::random.sample(subsongs.begin(), subsongs.end())) - 1; // random subsong filename = pfx + it->at("file").get<std::string>(); } } catch (const std::exception &) { // silently ignore if something fails; it's just for fun! } return {filename, subsong}; } std::shared_ptr<CPPSID::Player> createLoadedSIDplayer() { std::shared_ptr<CPPSID::Player> player; if (isatty(fileno(stdout))) { // only play music if on console if (not std::getenv("SSH_CLIENT")) { // and not through a ssh connection player = std::make_shared<CPPSID::Player>(); // let's emulate a Commodore 64... auto tune = findSIDsong(); // pick a song from our pre-defined library player->load(tune.first, tune.second); } } return player; } #endif std::shared_ptr<ProgressTracker> createProgressTracker(bool show_progress, unsigned int steps) { using namespace ProgressIndicator; using namespace std::chrono; std::shared_ptr<ProgressTracker> tracker = nullptr; if(show_progress) { if (isatty(fileno(stdout))) { // show a progress bar on the console tracker = std::make_shared<ProgressBar>(steps); } else { // not in a console tracker = std::make_shared<TaciturnDecorator>( // hence print a new line std::make_shared<ProgressLog>(steps), // at most every 10 minutes or after 0.5% of progress, whatever comes first duration_cast<milliseconds>(minutes(10)), 0.005); } } return tracker; }
Store simulation duration in json output (#290)
Store simulation duration in json output (#290) * Time simulation and save to json output * Reduced scope on a few variables in faunus.cpp * Point information link to https://faunus.readthedocs.oi
C++
mit
mlund/faunus,mlund/faunus,bjornstenqvist/faunus,bjornstenqvist/faunus,bjornstenqvist/faunus,mlund/faunus
0f7e3641995cac15df4e96cdf05eb3fb83927070
src/fstream.cc
src/fstream.cc
/* Copyright (c) 2014 Noel R. Cower 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 USEOR OTHER DEALINGS IN THE SOFTWARE. */ #include <snowball.h> #include <cstdio> struct SZ_HIDDEN sz_fstream_t { sz_stream_t base; sz_allocator_t *allocator; FILE *file; }; static size_t sz_fstream_read(void *out, size_t length, sz_stream_t *stream); static size_t sz_fstream_write(const void *in, size_t length, sz_stream_t *stream); static off_t sz_fstream_seek(off_t off, int whence, sz_stream_t *stream); static int sz_fstream_eof(sz_stream_t *stream); static void sz_fstream_close(sz_stream_t *stream); static sz_stream_t sz_fstream_base = { sz_fstream_read, sz_fstream_write, sz_fstream_seek, sz_fstream_eof, sz_fstream_close }; SZ_DEF_BEGIN sz_stream_t * sz_stream_fopen(const char *filename, sz_mode_t mode, sz_allocator_t *alloc) { sz_fstream_t *stream = NULL; FILE *file = NULL; switch (mode) { case SZ_READER: file = fopen(filename, "rb+"); break; case SZ_WRITER: file = fopen(filename, "wb+"); break; default: break; } if (file) { stream = (sz_fstream_t *)sz_malloc(sizeof(sz_fstream_t), alloc); stream->base = sz_fstream_base; stream->allocator = alloc; stream->file = file; } return (sz_stream_t *)stream; } SZ_DEF_END static size_t sz_fstream_read(void *out, size_t length, sz_stream_t *stream) { sz_fstream_t *fstream = (sz_fstream_t *)stream; return fread(out, length, 1, fstream->file); } static size_t sz_fstream_write(const void *in, size_t length, sz_stream_t *stream) { sz_fstream_t *fstream = (sz_fstream_t *)stream; return fwrite(in, length, 1, fstream->file); } static off_t sz_fstream_seek(off_t off, int whence, sz_stream_t *stream) { sz_fstream_t *fstream = (sz_fstream_t *)stream; if (off != 0 && whence != SEEK_CUR) { int result = fseek(fstream->file, long(off), whence); if (result) { return off_t(result); } } return ftell(fstream->file); } static int sz_fstream_eof(sz_stream_t *stream) { sz_fstream_t *fstream = (sz_fstream_t *)stream; return feof(fstream->file); } static void sz_fstream_close(sz_stream_t *stream) { sz_fstream_t *fstream = (sz_fstream_t *)stream; fclose(fstream->file); sz_free(fstream, fstream->allocator); }
/* Copyright (c) 2014 Noel R. Cower 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 USEOR OTHER DEALINGS IN THE SOFTWARE. */ #include <snowball.h> #include <cstdio> struct SZ_HIDDEN sz_fstream_t { sz_stream_t base; sz_allocator_t *allocator; FILE *file; }; static size_t sz_fstream_read(void *out, size_t length, sz_stream_t *stream); static size_t sz_fstream_write(const void *in, size_t length, sz_stream_t *stream); static off_t sz_fstream_seek(off_t off, int whence, sz_stream_t *stream); static int sz_fstream_eof(sz_stream_t *stream); static void sz_fstream_close(sz_stream_t *stream); static sz_stream_t sz_fstream_base = { sz_fstream_read, sz_fstream_write, sz_fstream_seek, sz_fstream_eof, sz_fstream_close }; SZ_DEF_BEGIN sz_stream_t * sz_stream_fopen(const char *filename, sz_mode_t mode, sz_allocator_t *alloc) { sz_fstream_t *stream = NULL; FILE *file = NULL; switch (mode) { case SZ_READER: file = fopen(filename, "rb+"); break; case SZ_WRITER: file = fopen(filename, "wb+"); break; default: break; } if (file) { stream = (sz_fstream_t *)sz_malloc(sizeof(sz_fstream_t), alloc); stream->base = sz_fstream_base; stream->allocator = alloc; stream->file = file; } return (sz_stream_t *)stream; } SZ_DEF_END static size_t sz_fstream_read(void *out, size_t length, sz_stream_t *stream) { sz_fstream_t *fstream = (sz_fstream_t *)stream; return fread(out, length, 1, fstream->file) * length; } static size_t sz_fstream_write(const void *in, size_t length, sz_stream_t *stream) { sz_fstream_t *fstream = (sz_fstream_t *)stream; return fwrite(in, length, 1, fstream->file) * length; } static off_t sz_fstream_seek(off_t off, int whence, sz_stream_t *stream) { sz_fstream_t *fstream = (sz_fstream_t *)stream; if (off != 0 && whence != SEEK_CUR) { int result = fseek(fstream->file, long(off), whence); if (result) { return off_t(result); } } return ftell(fstream->file); } static int sz_fstream_eof(sz_stream_t *stream) { sz_fstream_t *fstream = (sz_fstream_t *)stream; return feof(fstream->file); } static void sz_fstream_close(sz_stream_t *stream) { sz_fstream_t *fstream = (sz_fstream_t *)stream; fclose(fstream->file); sz_free(fstream, fstream->allocator); }
Fix return value of sz_fstream_read and _write.
Fix return value of sz_fstream_read and _write. Because fread/write returns the number of objects read, and fstreams try to write the entire thing at once, only one or zero is returned. As such, it's necessary to multiply the result by the number of bytes written.
C++
mit
nilium/libsnowball
87cabf0fc5ce3da8ff382a948daf8c8e769a184d
src/ed25519.cc
src/ed25519.cc
#include <node.h> #include <node_buffer.h> #include <nan.h> #include <stdlib.h> #include "ed25519/ed25519.h" using namespace v8; using namespace node; /** * MakeKeypair(Buffer seed) * seed: A 32 byte buffer * returns: an Object with PublicKey and PrivateKey **/ NAN_METHOD(MakeKeypair) { Nan::HandleScope scope; if ((info.Length() < 1) || (!Buffer::HasInstance(info[0])) || (Buffer::Length(info[0]->ToObject()) != 32)) { return Nan::ThrowError("MakeKeypair requires a 32 byte buffer"); } const unsigned char* seed = (unsigned char*)Buffer::Data(info[0]->ToObject()); v8::Local<v8::Object> privateKey = Nan::NewBuffer(64).ToLocalChecked(); unsigned char* privateKeyData = (unsigned char*)Buffer::Data(privateKey); v8::Local<v8::Object> publicKey = Nan::NewBuffer(32).ToLocalChecked(); unsigned char* publicKeyData = (unsigned char*)Buffer::Data(publicKey); for (int i = 0; i < 32; i++) privateKeyData[i] = seed[i]; crypto_sign_keypair(publicKeyData, privateKeyData); Local<Object> result = Nan::New<Object>(); result->Set(Nan::New("publicKey").ToLocalChecked(), publicKey); result->Set(Nan::New("privateKey").ToLocalChecked(), privateKey); info.GetReturnValue().Set(result); } /** * Sign(Buffer message, Buffer seed) * Sign(Buffer message, Buffer privateKey) * Sign(Buffer message, Object keyPair) * message: the message to be signed * seed: 32 byte buffer to make a keypair * keyPair: the object from the MakeKeypair function * returns: the signature as a Buffer **/ NAN_METHOD(Sign) { Nan::HandleScope scope; unsigned char* privateKey; if ((info.Length() < 2) || (!Buffer::HasInstance(info[0]->ToObject()))) { return Nan::ThrowError("Sign requires (Buffer, {Buffer(32 or 64) | keyPair object})"); } if ((Buffer::HasInstance(info[1])) && (Buffer::Length(info[1]->ToObject()) == 32)) { unsigned char* seed = (unsigned char*)Buffer::Data(info[1]->ToObject()); unsigned char publicKeyData[32]; unsigned char privateKeyData[64]; for (int i = 0; i < 32; i++) { privateKeyData[i] = seed[i]; } crypto_sign_keypair(publicKeyData, privateKeyData); privateKey = privateKeyData; } else if ((Buffer::HasInstance(info[1])) && (Buffer::Length(info[1]->ToObject()) == 64)) { privateKey = (unsigned char*)Buffer::Data(info[1]->ToObject()); } else if ((info[1]->IsObject()) && (!Buffer::HasInstance(info[1]))) { Local<Value> privateKeyBuffer = info[1]->ToObject()->Get(Nan::New<String>("privateKey").ToLocalChecked())->ToObject(); if (!Buffer::HasInstance(privateKeyBuffer)) { return Nan::ThrowError("Sign requires (Buffer, {Buffer(32 or 64) | keyPair object})"); } privateKey = (unsigned char*)Buffer::Data(privateKeyBuffer); } else { return Nan::ThrowError("Sign requires (Buffer, {Buffer(32 or 64) | keyPair object})"); } Handle<Object> message = info[0]->ToObject(); const unsigned char* messageData = (unsigned char*)Buffer::Data(message); size_t messageLen = Buffer::Length(message); unsigned long long sigLen = 64 + messageLen; unsigned char *signatureMessageData = (unsigned char*) malloc(sigLen); crypto_sign(signatureMessageData, &sigLen, messageData, messageLen, privateKey); v8::Local<v8::Object> signature = Nan::NewBuffer(64).ToLocalChecked(); unsigned char* signatureData = (unsigned char*)Buffer::Data(signature); for (int i = 0; i < 64; i++) { signatureData[i] = signatureMessageData[i]; } free(signatureMessageData); info.GetReturnValue().Set(signature); } /** * Verify(Buffer message, Buffer signature, Buffer publicKey) * message: message the signature is for * signature: signature to be verified * publicKey: publicKey to the private key that created the signature * returns: boolean **/ NAN_METHOD(Verify) { if ((info.Length() < 3) || (!Buffer::HasInstance(info[0]->ToObject())) || (!Buffer::HasInstance(info[1]->ToObject())) || (!Buffer::HasInstance(info[2]->ToObject()))) { return Nan::ThrowError("Verify requires (Buffer, Buffer(64), Buffer(32)"); } Handle<Object> message = info[0]->ToObject(); Handle<Object> signature = info[1]->ToObject(); Handle<Object> publicKey = info[2]->ToObject(); if ((Buffer::Length(signature) != 64) || (Buffer::Length(publicKey) != 32)) { return Nan::ThrowError("Verify requires (Buffer, Buffer(64), Buffer(32)"); } unsigned char* messageData = (unsigned char*)Buffer::Data(message); size_t messageLen = Buffer::Length(message); unsigned char* signatureData = (unsigned char*)Buffer::Data(signature); unsigned char* publicKeyData = (unsigned char*)Buffer::Data(publicKey); info.GetReturnValue().Set(crypto_sign_verify(signatureData, messageData, messageLen, publicKeyData) == 0); } void InitModule(Handle<Object> exports) { Nan::SetMethod(exports, "MakeKeypair", MakeKeypair); Nan::SetMethod(exports, "Sign", Sign); Nan::SetMethod(exports, "Verify", Verify); } NODE_MODULE(ed25519, InitModule)
#include <node.h> #include <node_buffer.h> #include <nan.h> #include <stdlib.h> #include "ed25519/ed25519.h" using namespace v8; using namespace node; /** * MakeKeypair(Buffer seed) * seed: A 32 byte buffer * returns: an Object with PublicKey and PrivateKey **/ NAN_METHOD(MakeKeypair) { Nan::HandleScope scope; if ((info.Length() < 1) || (!Buffer::HasInstance(info[0])) || (Buffer::Length(info[0]->ToObject()) != 32)) { return Nan::ThrowError("MakeKeypair requires a 32 byte buffer"); } const unsigned char* seed = (unsigned char*)Buffer::Data(info[0]->ToObject()); v8::Local<v8::Object> privateKey = Nan::NewBuffer(64).ToLocalChecked(); unsigned char* privateKeyData = (unsigned char*)Buffer::Data(privateKey); v8::Local<v8::Object> publicKey = Nan::NewBuffer(32).ToLocalChecked(); unsigned char* publicKeyData = (unsigned char*)Buffer::Data(publicKey); for (int i = 0; i < 32; i++) privateKeyData[i] = seed[i]; crypto_sign_keypair(publicKeyData, privateKeyData); Local<Object> result = Nan::New<Object>(); result->Set(Nan::New("publicKey").ToLocalChecked(), publicKey); result->Set(Nan::New("privateKey").ToLocalChecked(), privateKey); info.GetReturnValue().Set(result); } /** * Sign(Buffer message, Buffer seed) * Sign(Buffer message, Buffer privateKey) * Sign(Buffer message, Object keyPair) * message: the message to be signed * seed: 32 byte buffer to make a keypair * keyPair: the object from the MakeKeypair function * returns: the signature as a Buffer **/ NAN_METHOD(Sign) { Nan::HandleScope scope; unsigned char* privateKey; if ((info.Length() < 2) || (!Buffer::HasInstance(info[0]->ToObject()))) { return Nan::ThrowError("Sign requires (Buffer, {Buffer(32 or 64) | keyPair object})"); } // Place outside of the block it's used in - possible macOS compiler bug. unsigned char privateKeyData[64]; if ((Buffer::HasInstance(info[1])) && (Buffer::Length(info[1]->ToObject()) == 32)) { unsigned char* seed = (unsigned char*)Buffer::Data(info[1]->ToObject()); unsigned char publicKeyData[32]; for (int i = 0; i < 32; i++) { privateKeyData[i] = seed[i]; } crypto_sign_keypair(publicKeyData, privateKeyData); privateKey = privateKeyData; } else if ((Buffer::HasInstance(info[1])) && (Buffer::Length(info[1]->ToObject()) == 64)) { privateKey = (unsigned char*)Buffer::Data(info[1]->ToObject()); } else if ((info[1]->IsObject()) && (!Buffer::HasInstance(info[1]))) { Local<Value> privateKeyBuffer = info[1]->ToObject()->Get(Nan::New<String>("privateKey").ToLocalChecked())->ToObject(); if (!Buffer::HasInstance(privateKeyBuffer)) { return Nan::ThrowError("Sign requires (Buffer, {Buffer(32 or 64) | keyPair object})"); } privateKey = (unsigned char*)Buffer::Data(privateKeyBuffer); } else { return Nan::ThrowError("Sign requires (Buffer, {Buffer(32 or 64) | keyPair object})"); } Handle<Object> message = info[0]->ToObject(); const unsigned char* messageData = (unsigned char*)Buffer::Data(message); size_t messageLen = Buffer::Length(message); unsigned long long sigLen = 64 + messageLen; unsigned char *signatureMessageData = (unsigned char*) malloc(sigLen); crypto_sign(signatureMessageData, &sigLen, messageData, messageLen, privateKey); v8::Local<v8::Object> signature = Nan::NewBuffer(64).ToLocalChecked(); unsigned char* signatureData = (unsigned char*)Buffer::Data(signature); for (int i = 0; i < 64; i++) { signatureData[i] = signatureMessageData[i]; } free(signatureMessageData); info.GetReturnValue().Set(signature); } /** * Verify(Buffer message, Buffer signature, Buffer publicKey) * message: message the signature is for * signature: signature to be verified * publicKey: publicKey to the private key that created the signature * returns: boolean **/ NAN_METHOD(Verify) { if ((info.Length() < 3) || (!Buffer::HasInstance(info[0]->ToObject())) || (!Buffer::HasInstance(info[1]->ToObject())) || (!Buffer::HasInstance(info[2]->ToObject()))) { return Nan::ThrowError("Verify requires (Buffer, Buffer(64), Buffer(32)"); } Handle<Object> message = info[0]->ToObject(); Handle<Object> signature = info[1]->ToObject(); Handle<Object> publicKey = info[2]->ToObject(); if ((Buffer::Length(signature) != 64) || (Buffer::Length(publicKey) != 32)) { return Nan::ThrowError("Verify requires (Buffer, Buffer(64), Buffer(32)"); } unsigned char* messageData = (unsigned char*)Buffer::Data(message); size_t messageLen = Buffer::Length(message); unsigned char* signatureData = (unsigned char*)Buffer::Data(signature); unsigned char* publicKeyData = (unsigned char*)Buffer::Data(publicKey); info.GetReturnValue().Set(crypto_sign_verify(signatureData, messageData, messageLen, publicKeyData) == 0); } void InitModule(Handle<Object> exports) { Nan::SetMethod(exports, "MakeKeypair", MakeKeypair); Nan::SetMethod(exports, "Sign", Sign); Nan::SetMethod(exports, "Verify", Verify); } NODE_MODULE(ed25519, InitModule)
Fix for bad signature on macOS
Fix for bad signature on macOS Reimplement commit 42d04f9 from https://github.com/gaoxiangxyz/ed25519 to fix apparent compiler bug on macOS
C++
bsd-2-clause
dazoe/ed25519,dazoe/ed25519,dazoe/ed25519,dazoe/ed25519
945640361833bc47d6ac6c538e762d3bfac8968c
src/gui/app.cc
src/gui/app.cc
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- vim:set ts=4 sw=4 sts=4 noet: */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "gui/app.h" #include <boost/process/search_path.hpp> #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wcast-qual" #include <wx/config.h> #include <wx/filename.h> #include <wx/persist.h> #pragma GCC diagnostic pop #include "cli.pb.h" #include "gui/filename.h" #include "gui/httpd.h" #include "gui/main-frame.h" #include "gui/pref-page-general.h" #include "run.h" #include <cstdlib> #include <cstdio> #include <iostream> #include <limits> namespace flint { namespace gui { namespace { class PersistentApp : public wxPersistentObject { public: PersistentApp(App *, wxString &gnuplot_executable); virtual void Save() const override; virtual bool Restore() override; virtual wxString GetKind() const override; virtual wxString GetName() const override; private: wxString &gnuplot_executable_; }; PersistentApp::PersistentApp(App *obj, wxString &gnuplot_executable) : wxPersistentObject(obj) , gnuplot_executable_(gnuplot_executable) { } void PersistentApp::Save() const { SaveValue("gnuplot_executable", gnuplot_executable_); } bool PersistentApp::Restore() { return RestoreValue("gnuplot_executable", &gnuplot_executable_); } wxString PersistentApp::GetKind() const { return "Preference"; } wxString PersistentApp::GetName() const { return "File"; } const wxCmdLineEntryDesc kCommandLineDesc[] = { { wxCMD_LINE_SWITCH, "h", "help", "show this help message", wxCMD_LINE_VAL_NONE, wxCMD_LINE_OPTION_HELP }, { wxCMD_LINE_SWITCH, "headless", "headless", "enable the headless mode", wxCMD_LINE_VAL_NONE, 0 }, { wxCMD_LINE_OPTION, "e", nullptr, "save error messages as specified file (only with the headless mode)", wxCMD_LINE_VAL_STRING, 0 }, { wxCMD_LINE_OPTION, "g", nullptr, "specify output sampling rate i.e. 1 output per given step (only with the headless mode)", wxCMD_LINE_VAL_NUMBER, 0 }, { wxCMD_LINE_OPTION, "s", nullptr, "choose output variables with specified file (only with the headless mode)", wxCMD_LINE_VAL_STRING, 0 }, { wxCMD_LINE_PARAM, nullptr, nullptr, "file", wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL|wxCMD_LINE_PARAM_MULTIPLE }, { wxCMD_LINE_NONE, nullptr, nullptr, nullptr, wxCMD_LINE_VAL_NONE, 0 } // the same as { wxCMD_LINE_NONE }, and suppress compiler warnig }; /* * We need this as we have to change directory before simulation. */ wxFileName GetAbsoluteFilename(const wxString &file) { wxFileName fileName(file); if (!fileName.IsAbsolute()) fileName.MakeAbsolute(); return fileName; } std::string GetAbsoluteFilenameInUtf8(const wxString &file) { auto fileName = GetAbsoluteFilename(file); return fileName.GetFullPath().utf8_str().data(); } wxFileName GetFlintDirectory() { wxFileName fileName; fileName.AssignHomeDir(); fileName.AppendDir(".flint"); fileName.AppendDir("2"); return fileName; } } bool App::OnInit() { if (!wxApp::OnInit()) return false; checker_ = new wxSingleInstanceChecker; if (checker_->IsAnotherRunning()) { wxLogError("Another instance of this program is already running, aborting."); delete checker_; return false; } SetAppDisplayName("Flint"); SetVendorDisplayName("Flint project"); wxPersistenceManager::Get().RegisterAndRestore(this, new PersistentApp(this, gnuplot_executable_)); auto fileName = GetFlintDirectory(); fileName.Rmdir(wxPATH_RMDIR_RECURSIVE); // clean up working directory at first fileName.Mkdir(wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL); // make sure that it exists fileName.SetCwd(); auto frame = new MainFrame(input_files_); SetTopWindow(frame); frame->CentreOnScreen(); frame->Show(); pref_editor_ = nullptr; httpd_.reset(new Httpd); httpd_->Start(frame); return true; } void App::OnInitCmdLine(wxCmdLineParser &parser) { parser.SetDesc(kCommandLineDesc); parser.SetSwitchChars("-"); } bool App::OnCmdLineParsed(wxCmdLineParser &parser) { if (parser.Found("headless")) { // the headless mode if (parser.GetParamCount() != 2) { std::cerr << "just 2 arguments (i.e. <input> and <output>) needed for the headless mode" << std::endl; std::exit(EXIT_FAILURE); } wxString param0 = parser.GetParam(0); wxString param1 = parser.GetParam(1); cli::RunOption option; option.set_model_filename(GetAbsoluteFilenameInUtf8(param0)); option.set_output_filename(GetAbsoluteFilenameInUtf8(param1)); wxString e; if (parser.Found("e", &e)) option.set_error_filename(GetAbsoluteFilenameInUtf8(e)); long g; if (parser.Found("g", &g)) { if (g <= 0) { std::cerr << "non-positive value is invalid for -g option: " << g << std::endl; std::exit(EXIT_FAILURE); } if (std::numeric_limits<int>::max() < g) { std::cerr << "too huge value for -g option: " << g << std::endl; std::exit(EXIT_FAILURE); } option.set_granularity(static_cast<int>(g)); } wxString s; if (parser.Found("s", &s)) option.set_spec_filename(GetAbsoluteFilenameInUtf8(s)); auto fileName = GetFlintDirectory(); AppendCurrentTimestampDir(fileName); fileName.Mkdir(wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL); // make sure that it exists std::exit(run::Run(option, GetPathFromWxFileName(fileName)) ? EXIT_SUCCESS : EXIT_FAILURE); } for (const auto &arg : parser.GetArguments()) { if (arg.GetKind() == wxCMD_LINE_PARAM) { auto fileName = GetAbsoluteFilename(arg.GetStrVal()); input_files_.Add(fileName.GetFullPath()); } } return true; } int App::OnExit() { httpd_.reset(); wxPersistenceManager::Get().SaveAndUnregister(this); delete checker_; return wxApp::OnExit(); } boost::filesystem::path App::GetGnuplotExecutable() const { boost::filesystem::path p(gnuplot_executable_.ToStdString()); if (p.empty()) { // search executable from PATH p = boost::process::search_path("gnuplot"); } return p; } void App::OnGnuplotExecutable(wxFileDirPickerEvent &event) { gnuplot_executable_ = event.GetPath(); } void App::ShowPreferencesEditor(wxWindow *parent) { if (!pref_editor_) { pref_editor_ = new wxPreferencesEditor; pref_editor_->AddPage(new PrefPageGeneral(gnuplot_executable_)); } pref_editor_->Show(parent); } } } wxIMPLEMENT_APP(flint::gui::App);
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- vim:set ts=4 sw=4 sts=4 noet: */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "gui/app.h" #include <boost/process/search_path.hpp> #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wcast-qual" #include <wx/config.h> #include <wx/filename.h> #include <wx/persist.h> #pragma GCC diagnostic pop #include "cli.pb.h" #include "gui/filename.h" #include "gui/httpd.h" #include "gui/main-frame.h" #include "gui/pref-page-general.h" #include "run.h" #include <cstdlib> #include <cstdio> #include <iostream> #include <limits> namespace flint { namespace gui { namespace { class PersistentApp : public wxPersistentObject { public: PersistentApp(App *, wxString &gnuplot_executable); virtual void Save() const override; virtual bool Restore() override; virtual wxString GetKind() const override; virtual wxString GetName() const override; private: wxString &gnuplot_executable_; }; PersistentApp::PersistentApp(App *obj, wxString &gnuplot_executable) : wxPersistentObject(obj) , gnuplot_executable_(gnuplot_executable) { } void PersistentApp::Save() const { SaveValue("gnuplot_executable", gnuplot_executable_); } bool PersistentApp::Restore() { return RestoreValue("gnuplot_executable", &gnuplot_executable_); } wxString PersistentApp::GetKind() const { return "Preference"; } wxString PersistentApp::GetName() const { return "File"; } const wxCmdLineEntryDesc kCommandLineDesc[] = { { wxCMD_LINE_SWITCH, "h", "help", "show this help message", wxCMD_LINE_VAL_NONE, wxCMD_LINE_OPTION_HELP }, { wxCMD_LINE_SWITCH, "headless", "headless", "enable the headless mode", wxCMD_LINE_VAL_NONE, 0 }, { wxCMD_LINE_OPTION, "e", nullptr, "save error messages as specified file (only with the headless mode)", wxCMD_LINE_VAL_STRING, 0 }, { wxCMD_LINE_OPTION, "g", nullptr, "specify output sampling rate i.e. 1 output per given step (only with the headless mode)", wxCMD_LINE_VAL_NUMBER, 0 }, { wxCMD_LINE_OPTION, "s", nullptr, "choose output variables with specified file (only with the headless mode)", wxCMD_LINE_VAL_STRING, 0 }, { wxCMD_LINE_PARAM, nullptr, nullptr, "file", wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL|wxCMD_LINE_PARAM_MULTIPLE }, { wxCMD_LINE_NONE, nullptr, nullptr, nullptr, wxCMD_LINE_VAL_NONE, 0 } // the same as { wxCMD_LINE_NONE }, and suppress compiler warnig }; /* * We need this as we have to change directory before simulation. */ wxFileName GetAbsoluteFilename(const wxString &file) { wxFileName fileName(file); if (!fileName.IsAbsolute()) fileName.MakeAbsolute(); return fileName; } std::string GetAbsoluteFilenameInUtf8(const wxString &file) { auto fileName = GetAbsoluteFilename(file); return fileName.GetFullPath().utf8_str().data(); } wxFileName GetFlintDirectory() { wxFileName fileName; fileName.AssignHomeDir(); fileName.AppendDir(".flint"); fileName.AppendDir("2"); return fileName; } } bool App::OnInit() { if (!wxApp::OnInit()) return false; checker_ = new wxSingleInstanceChecker; if (checker_->IsAnotherRunning()) { wxLogError("Another instance of this program is already running, aborting."); delete checker_; return false; } SetAppName("flint2"); SetAppDisplayName("Flint"); SetVendorDisplayName("Flint project"); wxPersistenceManager::Get().RegisterAndRestore(this, new PersistentApp(this, gnuplot_executable_)); auto fileName = GetFlintDirectory(); fileName.Rmdir(wxPATH_RMDIR_RECURSIVE); // clean up working directory at first fileName.Mkdir(wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL); // make sure that it exists fileName.SetCwd(); auto frame = new MainFrame(input_files_); SetTopWindow(frame); frame->CentreOnScreen(); frame->Show(); pref_editor_ = nullptr; httpd_.reset(new Httpd); httpd_->Start(frame); return true; } void App::OnInitCmdLine(wxCmdLineParser &parser) { parser.SetDesc(kCommandLineDesc); parser.SetSwitchChars("-"); } bool App::OnCmdLineParsed(wxCmdLineParser &parser) { if (parser.Found("headless")) { // the headless mode if (parser.GetParamCount() != 2) { std::cerr << "just 2 arguments (i.e. <input> and <output>) needed for the headless mode" << std::endl; std::exit(EXIT_FAILURE); } wxString param0 = parser.GetParam(0); wxString param1 = parser.GetParam(1); cli::RunOption option; option.set_model_filename(GetAbsoluteFilenameInUtf8(param0)); option.set_output_filename(GetAbsoluteFilenameInUtf8(param1)); wxString e; if (parser.Found("e", &e)) option.set_error_filename(GetAbsoluteFilenameInUtf8(e)); long g; if (parser.Found("g", &g)) { if (g <= 0) { std::cerr << "non-positive value is invalid for -g option: " << g << std::endl; std::exit(EXIT_FAILURE); } if (std::numeric_limits<int>::max() < g) { std::cerr << "too huge value for -g option: " << g << std::endl; std::exit(EXIT_FAILURE); } option.set_granularity(static_cast<int>(g)); } wxString s; if (parser.Found("s", &s)) option.set_spec_filename(GetAbsoluteFilenameInUtf8(s)); auto fileName = GetFlintDirectory(); AppendCurrentTimestampDir(fileName); fileName.Mkdir(wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL); // make sure that it exists std::exit(run::Run(option, GetPathFromWxFileName(fileName)) ? EXIT_SUCCESS : EXIT_FAILURE); } for (const auto &arg : parser.GetArguments()) { if (arg.GetKind() == wxCMD_LINE_PARAM) { auto fileName = GetAbsoluteFilename(arg.GetStrVal()); input_files_.Add(fileName.GetFullPath()); } } return true; } int App::OnExit() { httpd_.reset(); wxPersistenceManager::Get().SaveAndUnregister(this); delete checker_; return wxApp::OnExit(); } boost::filesystem::path App::GetGnuplotExecutable() const { boost::filesystem::path p(gnuplot_executable_.ToStdString()); if (p.empty()) { // search executable from PATH p = boost::process::search_path("gnuplot"); } return p; } void App::OnGnuplotExecutable(wxFileDirPickerEvent &event) { gnuplot_executable_ = event.GetPath(); } void App::ShowPreferencesEditor(wxWindow *parent) { if (!pref_editor_) { pref_editor_ = new wxPreferencesEditor; pref_editor_->AddPage(new PrefPageGeneral(gnuplot_executable_)); } pref_editor_->Show(parent); } } } wxIMPLEMENT_APP(flint::gui::App);
Use .flint2 as the configuration file
Use .flint2 as the configuration file
C++
mit
flintproject/Flint,flintproject/Flint
04ea72c7873a5d9db1549d30ff3367ab38d36948
src/matrix.cpp
src/matrix.cpp
#include "../include/matrix.h" #include <string> template <class T> matrix<T>::matrix() {} template <class T> matrix<T>::matrix(unsigned int x, unsigned int y){ resize(x,y); } template <class T> matrix<T>::matrix(const matrix& matrix){ *this = matrix; } template <class T> void matrix<T>::resize(unsigned int x, unsigned int y){ m.resize(x, vector<T>(y)); } template <class T> vector<T> & matrix<T>::operator[](unsigned int i) const { return m[i]; } template <class T> matrix<T>& matrix<T>::operator=(const matrix& matrix){ m = matrix.m; return (*this); } // template class matrix <int>; template class matrix <double>; template class matrix <float>; template class matrix <char>; template class matrix <string>; template class matrix <bool>;
#include "../include/matrix.h" #include <string> template <class T> matrix<T>::matrix() {} template <class T> matrix<T>::matrix(unsigned int x, unsigned int y){ resize(x,y); } template <class T> matrix<T>::matrix(const matrix& matrix){ *this = matrix; } template <class T> void matrix<T>::resize(unsigned int x, unsigned int y){ m.resize(x, vector<T>(y)); } template <class T> vector<T> & matrix<T>::operator[](unsigned int i){ return m[i]; } template <class T> matrix<T>& matrix<T>::operator=(const matrix& matrix){ m = matrix.m; return (*this); } // template class matrix <int>; template class matrix <double>; template class matrix <float>; template class matrix <char>; template class matrix <string>; template class matrix <bool>;
Update matrix.cpp
Update matrix.cpp
C++
mit
HDxDaniel/Matrix-Cplusplus,illescasDaniel/Matrix-Cplusplus
838b62de3e9317933d047a85f851a3c9f7b3453b
src/mvf_mvb.cc
src/mvf_mvb.cc
#include "../../../src/show_message.hh" #include "move.hh" template<class T> inline static T fixLen(T len) { return len ? len : 1; } boost::optional< std::shared_ptr<change> > mvf(contents& contents, boost::optional<int> op) { if (contents.y == contents.cont.size() - 1 && contents.x == contents.cont[contents.y].size() - 1) { show_message("Can't move to that location (start/end of buffer)"); return boost::none; } int times = op ? op.get() : 1; long newx = contents.x + times; try { while(fixLen(contents.cont.at(contents.y).length()) <= newx) { newx -= fixLen(contents.cont[contents.y].length()); contents.y++; } } catch(...) { } if(contents.y >= contents.cont.size()) contents.y = contents.cont.size() - 1; if((long) contents.x < 0) contents.x = 0; else contents.x = newx; contents.waiting_for_desired = false; return boost::none; } boost::optional< std::shared_ptr<change> > mvb(contents& contents, boost::optional<int> op) { if (contents.y == 0 && contents.x == 0) { show_message("Can't move to that location (start/end of buffer)"); return boost::none; } int times = op ? op.get() : 1; long newx = contents.x - times; try { while(newx < 0) { contents.y--; newx += fixLen(contents.cont.at(contents.y).length()); } } catch(...) { } if(newx < 0) contents.x = 0; else contents.x = newx; contents.waiting_for_desired = false; return boost::none; }
#include "../../../src/show_message.hh" #include "move.hh" template<class T> inline static T fixLen(T len) { return len ? len : 1; } boost::optional< std::shared_ptr<change> > mvf(contents& contents, boost::optional<int> op) { if (contents.y == contents.cont.size() - 1 && contents.x == contents.cont[contents.y].size() - 1) { show_message("Can't move to that location (start/end of buffer)"); return boost::none; } int times = op ? op.get() : 1; move_ts newx = contents.x + times; try { while(fixLen(contents.cont.at(contents.y).length()) <= newx) { newx -= fixLen(contents.cont[contents.y].length()); contents.y++; } } catch(...) { } if(contents.y >= contents.cont.size()) contents.y = contents.cont.size() - 1; if((long) contents.x < 0) contents.x = 0; else contents.x = newx; contents.waiting_for_desired = false; return boost::none; } boost::optional< std::shared_ptr<change> > mvb(contents& contents, boost::optional<int> op) { if (contents.y == 0 && contents.x == 0) { show_message("Can't move to that location (start/end of buffer)"); return boost::none; } int times = op ? op.get() : 1; long newx = contents.x - times; try { while(newx < 0) { contents.y--; newx += fixLen(contents.cont.at(contents.y).length()); } } catch(...) { } if(newx < 0) contents.x = 0; else contents.x = newx; contents.waiting_for_desired = false; return boost::none; }
Use ``move_ts`` to get a signed ``move_t``
Use ``move_ts`` to get a signed ``move_t``
C++
mpl-2.0
czipperz/vick-move
603e02f4fa9a1d467b002a3ca40f7f3e3205494c
src/packet.cpp
src/packet.cpp
/* packet.c - an elf and spin binary loader for the Parallax Propeller microcontroller Copyright (c) 2011 David Michael Betz 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 <stdio.h> #include <string.h> #include "packet.h" #ifndef TRUE #define TRUE 1 #define FALSE 0 #endif /* timeouts for waiting for ACK/NAK */ #define INITIAL_TIMEOUT 10000 // 10 seconds #define PACKET_TIMEOUT 10000 // 10 seconds - this is long because SD cards may take a file to scan the FAT /* packet format: SOH pkt# type length-lo length-hi hdrchk length*data crc1 crc2 */ #define HDR_SOH 0 #define HDR_TYPE 1 #define HDR_LEN_HI 2 #define HDR_LEN_LO 3 #define HDR_CHK 4 /* packet header and crc lengths */ #define PKTHDRLEN 5 #define PKTCRCLEN 2 /* maximum length of a frame */ #define FRAMELEN (PKTHDRLEN + PKTMAXLEN + PKTCRCLEN) /* protocol characters */ #define SOH 0x01 /* start of a packet */ #define ACK 0x06 /* positive acknowledgement */ #define NAK 0x15 /* negative acknowledgement */ #define ESC 0x1b /* escape from terminal mode */ #define updcrc(crc, ch) (crctab[((crc) >> 8) & 0xff] ^ ((crc) << 8) ^ (ch)) static const uint16_t crctab[256] = { 0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7, 0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef, 0x1231, 0x0210, 0x3273, 0x2252, 0x52b5, 0x4294, 0x72f7, 0x62d6, 0x9339, 0x8318, 0xb37b, 0xa35a, 0xd3bd, 0xc39c, 0xf3ff, 0xe3de, 0x2462, 0x3443, 0x0420, 0x1401, 0x64e6, 0x74c7, 0x44a4, 0x5485, 0xa56a, 0xb54b, 0x8528, 0x9509, 0xe5ee, 0xf5cf, 0xc5ac, 0xd58d, 0x3653, 0x2672, 0x1611, 0x0630, 0x76d7, 0x66f6, 0x5695, 0x46b4, 0xb75b, 0xa77a, 0x9719, 0x8738, 0xf7df, 0xe7fe, 0xd79d, 0xc7bc, 0x48c4, 0x58e5, 0x6886, 0x78a7, 0x0840, 0x1861, 0x2802, 0x3823, 0xc9cc, 0xd9ed, 0xe98e, 0xf9af, 0x8948, 0x9969, 0xa90a, 0xb92b, 0x5af5, 0x4ad4, 0x7ab7, 0x6a96, 0x1a71, 0x0a50, 0x3a33, 0x2a12, 0xdbfd, 0xcbdc, 0xfbbf, 0xeb9e, 0x9b79, 0x8b58, 0xbb3b, 0xab1a, 0x6ca6, 0x7c87, 0x4ce4, 0x5cc5, 0x2c22, 0x3c03, 0x0c60, 0x1c41, 0xedae, 0xfd8f, 0xcdec, 0xddcd, 0xad2a, 0xbd0b, 0x8d68, 0x9d49, 0x7e97, 0x6eb6, 0x5ed5, 0x4ef4, 0x3e13, 0x2e32, 0x1e51, 0x0e70, 0xff9f, 0xefbe, 0xdfdd, 0xcffc, 0xbf1b, 0xaf3a, 0x9f59, 0x8f78, 0x9188, 0x81a9, 0xb1ca, 0xa1eb, 0xd10c, 0xc12d, 0xf14e, 0xe16f, 0x1080, 0x00a1, 0x30c2, 0x20e3, 0x5004, 0x4025, 0x7046, 0x6067, 0x83b9, 0x9398, 0xa3fb, 0xb3da, 0xc33d, 0xd31c, 0xe37f, 0xf35e, 0x02b1, 0x1290, 0x22f3, 0x32d2, 0x4235, 0x5214, 0x6277, 0x7256, 0xb5ea, 0xa5cb, 0x95a8, 0x8589, 0xf56e, 0xe54f, 0xd52c, 0xc50d, 0x34e2, 0x24c3, 0x14a0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405, 0xa7db, 0xb7fa, 0x8799, 0x97b8, 0xe75f, 0xf77e, 0xc71d, 0xd73c, 0x26d3, 0x36f2, 0x0691, 0x16b0, 0x6657, 0x7676, 0x4615, 0x5634, 0xd94c, 0xc96d, 0xf90e, 0xe92f, 0x99c8, 0x89e9, 0xb98a, 0xa9ab, 0x5844, 0x4865, 0x7806, 0x6827, 0x18c0, 0x08e1, 0x3882, 0x28a3, 0xcb7d, 0xdb5c, 0xeb3f, 0xfb1e, 0x8bf9, 0x9bd8, 0xabbb, 0xbb9a, 0x4a75, 0x5a54, 0x6a37, 0x7a16, 0x0af1, 0x1ad0, 0x2ab3, 0x3a92, 0xfd2e, 0xed0f, 0xdd6c, 0xcd4d, 0xbdaa, 0xad8b, 0x9de8, 0x8dc9, 0x7c26, 0x6c07, 0x5c64, 0x4c45, 0x3ca2, 0x2c83, 0x1ce0, 0x0cc1, 0xef1f, 0xff3e, 0xcf5d, 0xdf7c, 0xaf9b, 0xbfba, 0x8fd9, 0x9ff8, 0x6e17, 0x7e36, 0x4e55, 0x5e74, 0x2e93, 0x3eb2, 0x0ed1, 0x1ef0 }; int PacketDriver::waitForInitialAck(void) { return waitForAckNak(INITIAL_TIMEOUT) == ACK; } int PacketDriver::sendPacket(int type, uint8_t *buf, int len) { uint8_t hdr[PKTHDRLEN], crc[PKTCRCLEN], *p; uint16_t crc16 = 0; int cnt, ch; /* setup the frame header */ hdr[HDR_SOH] = SOH; /* SOH */ hdr[HDR_TYPE] = type; /* type type */ hdr[HDR_LEN_HI] = (uint8_t)(len >> 8); /* data length - high byte */ hdr[HDR_LEN_LO] = (uint8_t)len; /* data length - low byte */ hdr[HDR_CHK] = hdr[1] + hdr[2] + hdr[3]; /* header checksum */ /* compute the crc */ for (p = buf, cnt = len; --cnt >= 0; ++p) crc16 = updcrc(crc16, *p); crc16 = updcrc(crc16, '\0'); crc16 = updcrc(crc16, '\0'); /* add the crc to the frame */ crc[0] = (uint8_t)(crc16 >> 8); crc[1] = (uint8_t)crc16; /* send the packet */ m_connection.sendData(hdr, PKTHDRLEN); if (len > 0) m_connection.sendData(buf, len); m_connection.sendData(crc, PKTCRCLEN); /* wait for an ACK/NAK */ if ((ch = waitForAckNak(PACKET_TIMEOUT)) < 0) { printf("Timeout waiting for ACK/NAK\n"); ch = NAK; } /* return status */ return ch == ACK; } int PacketDriver::receivePacket(int *pType, uint8_t *buf, int len, int timeout) { uint8_t hdr[PKTHDRLEN], crc[PKTCRCLEN]; int actual_len, chk; uint16_t crc16 = 0; /* look for start of packet */ do { if (m_connection.receiveDataExactTimeout(&hdr[HDR_SOH], 1, timeout) == -1) return -1; } while (hdr[HDR_SOH] != SOH); /* receive the rest of the header */ if (m_connection.receiveDataExactTimeout(&hdr[HDR_TYPE], PKTHDRLEN - 1, timeout) == -1) return -1; /* check the header checksum */ chk = (hdr[1] + hdr[2] + hdr[3]) & 0xff; if (hdr[HDR_CHK] != chk) return -1; /* make sure the buffer is big enough for the payload */ actual_len = hdr[HDR_LEN_HI] << 8 | hdr[HDR_LEN_LO]; if (actual_len > len) return -1; /* receive the packet payload */ if (m_connection.receiveDataExactTimeout(buf, actual_len, timeout) == -1) return -1; /* compute the crc */ for (len = actual_len; --len >= 0; ) crc16 = updcrc(crc16, *buf++); /* receive the crc */ if (m_connection.receiveDataExactTimeout(crc, PKTCRCLEN, timeout) == -1) return-1; /* check the crc */ crc16 = updcrc(crc16, crc[0]); crc16 = updcrc(crc16, crc[1]); if (crc16 != 0) return -1; /* return packet type and the length of the payload */ *pType = hdr[HDR_TYPE]; return actual_len; } int PacketDriver::waitForAckNak(int timeout) { uint8_t buf[1]; return m_connection.receiveDataExactTimeout(buf, 1, timeout) == 1 ? buf[0] : -1; }
/* packet.c - an elf and spin binary loader for the Parallax Propeller microcontroller Copyright (c) 2011 David Michael Betz 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 <stdio.h> #include <string.h> #include "packet.h" #include "proploader.h" #ifndef TRUE #define TRUE 1 #define FALSE 0 #endif /* timeouts for waiting for ACK/NAK */ #define INITIAL_TIMEOUT 10000 // 10 seconds #define PACKET_TIMEOUT 10000 // 10 seconds - this is long because SD cards may take a file to scan the FAT /* packet format: SOH pkt# type length-lo length-hi hdrchk length*data crc1 crc2 */ #define HDR_SOH 0 #define HDR_TYPE 1 #define HDR_LEN_HI 2 #define HDR_LEN_LO 3 #define HDR_CHK 4 /* packet header and crc lengths */ #define PKTHDRLEN 5 #define PKTCRCLEN 2 /* maximum length of a frame */ #define FRAMELEN (PKTHDRLEN + PKTMAXLEN + PKTCRCLEN) /* protocol characters */ #define SOH 0x01 /* start of a packet */ #define ACK 0x06 /* positive acknowledgement */ #define NAK 0x15 /* negative acknowledgement */ #define ESC 0x1b /* escape from terminal mode */ #define updcrc(crc, ch) (crctab[((crc) >> 8) & 0xff] ^ ((crc) << 8) ^ (ch)) static const uint16_t crctab[256] = { 0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7, 0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef, 0x1231, 0x0210, 0x3273, 0x2252, 0x52b5, 0x4294, 0x72f7, 0x62d6, 0x9339, 0x8318, 0xb37b, 0xa35a, 0xd3bd, 0xc39c, 0xf3ff, 0xe3de, 0x2462, 0x3443, 0x0420, 0x1401, 0x64e6, 0x74c7, 0x44a4, 0x5485, 0xa56a, 0xb54b, 0x8528, 0x9509, 0xe5ee, 0xf5cf, 0xc5ac, 0xd58d, 0x3653, 0x2672, 0x1611, 0x0630, 0x76d7, 0x66f6, 0x5695, 0x46b4, 0xb75b, 0xa77a, 0x9719, 0x8738, 0xf7df, 0xe7fe, 0xd79d, 0xc7bc, 0x48c4, 0x58e5, 0x6886, 0x78a7, 0x0840, 0x1861, 0x2802, 0x3823, 0xc9cc, 0xd9ed, 0xe98e, 0xf9af, 0x8948, 0x9969, 0xa90a, 0xb92b, 0x5af5, 0x4ad4, 0x7ab7, 0x6a96, 0x1a71, 0x0a50, 0x3a33, 0x2a12, 0xdbfd, 0xcbdc, 0xfbbf, 0xeb9e, 0x9b79, 0x8b58, 0xbb3b, 0xab1a, 0x6ca6, 0x7c87, 0x4ce4, 0x5cc5, 0x2c22, 0x3c03, 0x0c60, 0x1c41, 0xedae, 0xfd8f, 0xcdec, 0xddcd, 0xad2a, 0xbd0b, 0x8d68, 0x9d49, 0x7e97, 0x6eb6, 0x5ed5, 0x4ef4, 0x3e13, 0x2e32, 0x1e51, 0x0e70, 0xff9f, 0xefbe, 0xdfdd, 0xcffc, 0xbf1b, 0xaf3a, 0x9f59, 0x8f78, 0x9188, 0x81a9, 0xb1ca, 0xa1eb, 0xd10c, 0xc12d, 0xf14e, 0xe16f, 0x1080, 0x00a1, 0x30c2, 0x20e3, 0x5004, 0x4025, 0x7046, 0x6067, 0x83b9, 0x9398, 0xa3fb, 0xb3da, 0xc33d, 0xd31c, 0xe37f, 0xf35e, 0x02b1, 0x1290, 0x22f3, 0x32d2, 0x4235, 0x5214, 0x6277, 0x7256, 0xb5ea, 0xa5cb, 0x95a8, 0x8589, 0xf56e, 0xe54f, 0xd52c, 0xc50d, 0x34e2, 0x24c3, 0x14a0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405, 0xa7db, 0xb7fa, 0x8799, 0x97b8, 0xe75f, 0xf77e, 0xc71d, 0xd73c, 0x26d3, 0x36f2, 0x0691, 0x16b0, 0x6657, 0x7676, 0x4615, 0x5634, 0xd94c, 0xc96d, 0xf90e, 0xe92f, 0x99c8, 0x89e9, 0xb98a, 0xa9ab, 0x5844, 0x4865, 0x7806, 0x6827, 0x18c0, 0x08e1, 0x3882, 0x28a3, 0xcb7d, 0xdb5c, 0xeb3f, 0xfb1e, 0x8bf9, 0x9bd8, 0xabbb, 0xbb9a, 0x4a75, 0x5a54, 0x6a37, 0x7a16, 0x0af1, 0x1ad0, 0x2ab3, 0x3a92, 0xfd2e, 0xed0f, 0xdd6c, 0xcd4d, 0xbdaa, 0xad8b, 0x9de8, 0x8dc9, 0x7c26, 0x6c07, 0x5c64, 0x4c45, 0x3ca2, 0x2c83, 0x1ce0, 0x0cc1, 0xef1f, 0xff3e, 0xcf5d, 0xdf7c, 0xaf9b, 0xbfba, 0x8fd9, 0x9ff8, 0x6e17, 0x7e36, 0x4e55, 0x5e74, 0x2e93, 0x3eb2, 0x0ed1, 0x1ef0 }; int PacketDriver::waitForInitialAck(void) { return waitForAckNak(INITIAL_TIMEOUT) == ACK; } int PacketDriver::sendPacket(int type, uint8_t *buf, int len) { uint8_t hdr[PKTHDRLEN], crc[PKTCRCLEN], *p; uint16_t crc16 = 0; int cnt, ch; /* setup the frame header */ hdr[HDR_SOH] = SOH; /* SOH */ hdr[HDR_TYPE] = type; /* type type */ hdr[HDR_LEN_HI] = (uint8_t)(len >> 8); /* data length - high byte */ hdr[HDR_LEN_LO] = (uint8_t)len; /* data length - low byte */ hdr[HDR_CHK] = hdr[1] + hdr[2] + hdr[3]; /* header checksum */ /* compute the crc */ for (p = buf, cnt = len; --cnt >= 0; ++p) crc16 = updcrc(crc16, *p); crc16 = updcrc(crc16, '\0'); crc16 = updcrc(crc16, '\0'); /* add the crc to the frame */ crc[0] = (uint8_t)(crc16 >> 8); crc[1] = (uint8_t)crc16; /* send the packet */ m_connection.sendData(hdr, PKTHDRLEN); if (len > 0) m_connection.sendData(buf, len); m_connection.sendData(crc, PKTCRCLEN); /* wait for an ACK/NAK */ if ((ch = waitForAckNak(PACKET_TIMEOUT)) < 0) { message("Timeout waiting for ACK/NAK"); ch = NAK; } /* return status */ return ch == ACK; } int PacketDriver::receivePacket(int *pType, uint8_t *buf, int len, int timeout) { uint8_t hdr[PKTHDRLEN], crc[PKTCRCLEN]; int actual_len, chk; uint16_t crc16 = 0; /* look for start of packet */ do { if (m_connection.receiveDataExactTimeout(&hdr[HDR_SOH], 1, timeout) == -1) return -1; } while (hdr[HDR_SOH] != SOH); /* receive the rest of the header */ if (m_connection.receiveDataExactTimeout(&hdr[HDR_TYPE], PKTHDRLEN - 1, timeout) == -1) return -1; /* check the header checksum */ chk = (hdr[1] + hdr[2] + hdr[3]) & 0xff; if (hdr[HDR_CHK] != chk) return -1; /* make sure the buffer is big enough for the payload */ actual_len = hdr[HDR_LEN_HI] << 8 | hdr[HDR_LEN_LO]; if (actual_len > len) return -1; /* receive the packet payload */ if (m_connection.receiveDataExactTimeout(buf, actual_len, timeout) == -1) return -1; /* compute the crc */ for (len = actual_len; --len >= 0; ) crc16 = updcrc(crc16, *buf++); /* receive the crc */ if (m_connection.receiveDataExactTimeout(crc, PKTCRCLEN, timeout) == -1) return-1; /* check the crc */ crc16 = updcrc(crc16, crc[0]); crc16 = updcrc(crc16, crc[1]); if (crc16 != 0) return -1; /* return packet type and the length of the payload */ *pType = hdr[HDR_TYPE]; return actual_len; } int PacketDriver::waitForAckNak(int timeout) { uint8_t buf[1]; return m_connection.receiveDataExactTimeout(buf, 1, timeout) == 1 ? buf[0] : -1; }
Switch a ACK/NAK error to a -v informational message.
Switch a ACK/NAK error to a -v informational message.
C++
mit
parallaxinc/PropLoader,dbetz/proploader,parallaxinc/PropLoader,dbetz/proploader
9d3f81fc751044cc93e8ee03ba0f7ffc8cc7c86a
src/memory.cxx
src/memory.cxx
/* -*- coding: utf-8; mode: c++; tab-width: 3 -*- Copyright 2010, 2011, 2012, 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/>. --------------------------------------------------------------------------------------------------*/ #include <abc/core.hxx> #include <abc/memory.hxx> //////////////////////////////////////////////////////////////////////////////////////////////////// // :: globals - standard new/delete operators // Forward declarations. namespace abc { namespace memory { void * _raw_alloc(size_t cb); template <typename T> void free(T * pt); } //namespace memory } //namespace abc #ifdef _MSC_VER #pragma warning(push) // “'operator': exception specification does not match previous declaration” #pragma warning(disable: 4986) #endif void * ABC_STL_CALLCONV operator new(size_t cb) ABC_STL_NOEXCEPT_FALSE((std::bad_alloc)) { return abc::memory::_raw_alloc(cb); } void * ABC_STL_CALLCONV operator new[](size_t cb) ABC_STL_NOEXCEPT_FALSE((std::bad_alloc)) { return abc::memory::_raw_alloc(cb); } void * ABC_STL_CALLCONV operator new(size_t cb, std::nothrow_t const &) ABC_STL_NOEXCEPT_TRUE() { return ::malloc(cb); } void * ABC_STL_CALLCONV operator new[](size_t cb, std::nothrow_t const &) ABC_STL_NOEXCEPT_TRUE() { return ::malloc(cb); } void ABC_STL_CALLCONV operator delete(void * p) ABC_STL_NOEXCEPT_TRUE() { abc::memory::free(p); } void ABC_STL_CALLCONV operator delete[](void * p) ABC_STL_NOEXCEPT_TRUE() { abc::memory::free(p); } void ABC_STL_CALLCONV operator delete(void * p, std::nothrow_t const &) ABC_STL_NOEXCEPT_TRUE() { abc::memory::free(p); } void ABC_STL_CALLCONV operator delete[](void * p, std::nothrow_t const &) ABC_STL_NOEXCEPT_TRUE() { abc::memory::free(p); } #ifdef _MSC_VER #pragma warning(pop) #endif
/* -*- coding: utf-8; mode: c++; tab-width: 3 -*- Copyright 2010, 2011, 2012, 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/>. --------------------------------------------------------------------------------------------------*/ #include <abc/core.hxx> #include <abc/memory.hxx> //////////////////////////////////////////////////////////////////////////////////////////////////// // :: globals - standard new/delete operators #ifdef _MSC_VER #pragma warning(push) // “'operator': exception specification does not match previous declaration” #pragma warning(disable: 4986) #endif void * ABC_STL_CALLCONV operator new(size_t cb) ABC_STL_NOEXCEPT_FALSE((std::bad_alloc)) { return abc::memory::_raw_alloc(cb); } void * ABC_STL_CALLCONV operator new[](size_t cb) ABC_STL_NOEXCEPT_FALSE((std::bad_alloc)) { return abc::memory::_raw_alloc(cb); } void * ABC_STL_CALLCONV operator new(size_t cb, std::nothrow_t const &) ABC_STL_NOEXCEPT_TRUE() { return ::malloc(cb); } void * ABC_STL_CALLCONV operator new[](size_t cb, std::nothrow_t const &) ABC_STL_NOEXCEPT_TRUE() { return ::malloc(cb); } void ABC_STL_CALLCONV operator delete(void * p) ABC_STL_NOEXCEPT_TRUE() { abc::memory::free(p); } void ABC_STL_CALLCONV operator delete[](void * p) ABC_STL_NOEXCEPT_TRUE() { abc::memory::free(p); } void ABC_STL_CALLCONV operator delete(void * p, std::nothrow_t const &) ABC_STL_NOEXCEPT_TRUE() { abc::memory::free(p); } void ABC_STL_CALLCONV operator delete[](void * p, std::nothrow_t const &) ABC_STL_NOEXCEPT_TRUE() { abc::memory::free(p); } #ifdef _MSC_VER #pragma warning(pop) #endif
Remove unnecessary forward declarations
Remove unnecessary forward declarations
C++
lgpl-2.1
raffaellod/lofty,raffaellod/lofty
4412c5a759affdcdb8c9c81b64465979aaba147a
src/rpcnet.cpp
src/rpcnet.cpp
// Copyright (c) 2009-2013 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "rpcserver.h" #include "main.h" #include "net.h" #include "netbase.h" #include "protocol.h" #include "sync.h" #include "util.h" #ifdef ENABLE_WALLET #include "init.h" // for getinfo #include "wallet.h" // for getinfo #endif #include <inttypes.h> #include <boost/foreach.hpp> #include "json/json_spirit_value.h" using namespace json_spirit; using namespace std; Value getconnectioncount(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getconnectioncount\n" "\nReturns the number of connections to other nodes.\n" "\nbResult:\n" "n (numeric) The connection count\n" "\nExamples:\n" + HelpExampleCli("getconnectioncount", "") + HelpExampleRpc("getconnectioncount", "") ); LOCK(cs_vNodes); return (int)vNodes.size(); } Value ping(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "ping\n" "\nRequests that a ping be sent to all other nodes, to measure ping time.\n" "Results provided in getpeerinfo, pingtime and pingwait fields are decimal seconds.\n" "Ping command is handled in queue with all other commands, so it measures processing backlog, not just network ping." "\nExamples:\n" + HelpExampleCli("ping", "") + HelpExampleRpc("ping", "") ); // Request that each node send a ping during next message processing pass LOCK(cs_vNodes); BOOST_FOREACH(CNode* pNode, vNodes) { pNode->fPingQueued = true; } return Value::null; } static void CopyNodeStats(std::vector<CNodeStats>& vstats) { vstats.clear(); LOCK(cs_vNodes); vstats.reserve(vNodes.size()); BOOST_FOREACH(CNode* pnode, vNodes) { CNodeStats stats; pnode->copyStats(stats); vstats.push_back(stats); } } Value getpeerinfo(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getpeerinfo\n" "\nReturns data about each connected network node as a json array of objects.\n" "\nbResult:\n" "[\n" " {\n" " \"addr\":\"host:port\", (string) The ip address and port of the peer\n" " \"addrlocal\":\"ip:port\", (string) local address\n" " \"services\":\"00000001\", (string) The services\n" " \"lastsend\": ttt, (numeric) The time in seconds since epoch (Jan 1 1970 GMT) of the last send\n" " \"lastrecv\": ttt, (numeric) The time in seconds since epoch (Jan 1 1970 GMT) of the last receive\n" " \"bytessent\": n, (numeric) The total bytes sent\n" " \"bytesrecv\": n, (numeric) The total bytes received\n" " \"conntime\": ttt, (numeric) The connection time in seconds since epoch (Jan 1 1970 GMT)\n" " \"pingtime\": n, (numeric) ping time\n" " \"pingwait\": n, (numeric) ping wait\n" " \"version\": v, (numeric) The peer version, such as 7001\n" " \"subver\": \"/Satoshi:0.8.5/\", (string) The string version\n" " \"inbound\": true|false, (boolean) Inbound (true) or Outbound (false)\n" " \"startingheight\": n, (numeric) The starting height (block) of the peer\n" " \"banscore\": n, (numeric) The ban score (stats.nMisbehavior)\n" " \"syncnode\" : true|false (booleamn) if sync node\n" " }\n" " ,...\n" "}\n" "\nExamples:\n" + HelpExampleCli("getpeerinfo", "") + HelpExampleRpc("getpeerinfo", "") ); vector<CNodeStats> vstats; CopyNodeStats(vstats); Array ret; BOOST_FOREACH(const CNodeStats& stats, vstats) { Object obj; CNodeStateStats statestats; bool fStateStats = GetNodeStateStats(stats.nodeid, statestats); obj.push_back(Pair("addr", stats.addrName)); if (!(stats.addrLocal.empty())) obj.push_back(Pair("addrlocal", stats.addrLocal)); obj.push_back(Pair("services", strprintf("%08"PRIx64, stats.nServices))); obj.push_back(Pair("lastsend", (boost::int64_t)stats.nLastSend)); obj.push_back(Pair("lastrecv", (boost::int64_t)stats.nLastRecv)); obj.push_back(Pair("bytessent", (boost::int64_t)stats.nSendBytes)); obj.push_back(Pair("bytesrecv", (boost::int64_t)stats.nRecvBytes)); obj.push_back(Pair("conntime", (boost::int64_t)stats.nTimeConnected)); obj.push_back(Pair("pingtime", stats.dPingTime)); if (stats.dPingWait > 0.0) obj.push_back(Pair("pingwait", stats.dPingWait)); obj.push_back(Pair("version", stats.nVersion)); // Use the sanitized form of subver here, to avoid tricksy remote peers from // corrupting or modifiying the JSON output by putting special characters in // their ver message. obj.push_back(Pair("subver", stats.cleanSubVer)); obj.push_back(Pair("inbound", stats.fInbound)); obj.push_back(Pair("startingheight", stats.nStartingHeight)); if (fStateStats) { obj.push_back(Pair("banscore", statestats.nMisbehavior)); } if (stats.fSyncNode) obj.push_back(Pair("syncnode", true)); ret.push_back(obj); } return ret; } Value addnode(const Array& params, bool fHelp) { string strCommand; if (params.size() == 2) strCommand = params[1].get_str(); if (fHelp || params.size() != 2 || (strCommand != "onetry" && strCommand != "add" && strCommand != "remove")) throw runtime_error( "addnode \"node\" \"add|remove|onetry\"\n" "\nAttempts add or remove a node from the addnode list.\n" "Or try a connection to a node once.\n" "\nArguments:\n" "1. \"node\" (string, required) The node (see getpeerinfo for nodes)\n" "2. \"command\" (string, required) 'add' to add a node to the list, 'remove' to remove a node from the list, 'onetry' to try a connection to the node once\n" "\nExamples:\n" + HelpExampleCli("addnode", "\"192.168.0.6:8333\" \"onetry\"") + HelpExampleRpc("addnode", "\"192.168.0.6:8333\", \"onetry\"") ); string strNode = params[0].get_str(); if (strCommand == "onetry") { CAddress addr; ConnectNode(addr, strNode.c_str()); return Value::null; } LOCK(cs_vAddedNodes); vector<string>::iterator it = vAddedNodes.begin(); for(; it != vAddedNodes.end(); it++) if (strNode == *it) break; if (strCommand == "add") { if (it != vAddedNodes.end()) throw JSONRPCError(RPC_CLIENT_NODE_ALREADY_ADDED, "Error: Node already added"); vAddedNodes.push_back(strNode); } else if(strCommand == "remove") { if (it == vAddedNodes.end()) throw JSONRPCError(RPC_CLIENT_NODE_NOT_ADDED, "Error: Node has not been added."); vAddedNodes.erase(it); } return Value::null; } Value getaddednodeinfo(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "getaddednodeinfo dns ( \"node\" )\n" "\nReturns information about the given added node, or all added nodes\n" "(note that onetry addnodes are not listed here)\n" "If dns is false, only a list of added nodes will be provided,\n" "otherwise connected information will also be available.\n" "\nArguments:\n" "1. dns (boolean, required) If false, only a list of added nodes will be provided, otherwise connected information will also be available.\n" "2. \"node\" (string, optional) If provided, return information about this specific node, otherwise all nodes are returned.\n" "\nResult:\n" "[\n" " {\n" " \"addednode\" : \"192.168.0.201\", (string) The node ip address\n" " \"connected\" : true|false, (boolean) If connected\n" " \"addresses\" : [\n" " {\n" " \"address\" : \"192.168.0.201:8333\", (string) The bitcoin server host and port\n" " \"connected\" : \"outbound\" (string) connection, inbound or outbound\n" " }\n" " ,...\n" " ]\n" " }\n" " ,...\n" "]\n" "\nExamples:\n" + HelpExampleCli("getaddednodeinfo", "true") + HelpExampleCli("getaddednodeinfo", "true \"192.168.0.201\"") + HelpExampleRpc("getaddednodeinfo", "true, \"192.168.0.201\"") ); bool fDns = params[0].get_bool(); list<string> laddedNodes(0); if (params.size() == 1) { LOCK(cs_vAddedNodes); BOOST_FOREACH(string& strAddNode, vAddedNodes) laddedNodes.push_back(strAddNode); } else { string strNode = params[1].get_str(); LOCK(cs_vAddedNodes); BOOST_FOREACH(string& strAddNode, vAddedNodes) if (strAddNode == strNode) { laddedNodes.push_back(strAddNode); break; } if (laddedNodes.size() == 0) throw JSONRPCError(RPC_CLIENT_NODE_NOT_ADDED, "Error: Node has not been added."); } if (!fDns) { Object ret; BOOST_FOREACH(string& strAddNode, laddedNodes) ret.push_back(Pair("addednode", strAddNode)); return ret; } Array ret; list<pair<string, vector<CService> > > laddedAddreses(0); BOOST_FOREACH(string& strAddNode, laddedNodes) { vector<CService> vservNode(0); if(Lookup(strAddNode.c_str(), vservNode, Params().GetDefaultPort(), fNameLookup, 0)) laddedAddreses.push_back(make_pair(strAddNode, vservNode)); else { Object obj; obj.push_back(Pair("addednode", strAddNode)); obj.push_back(Pair("connected", false)); Array addresses; obj.push_back(Pair("addresses", addresses)); } } LOCK(cs_vNodes); for (list<pair<string, vector<CService> > >::iterator it = laddedAddreses.begin(); it != laddedAddreses.end(); it++) { Object obj; obj.push_back(Pair("addednode", it->first)); Array addresses; bool fConnected = false; BOOST_FOREACH(CService& addrNode, it->second) { bool fFound = false; Object node; node.push_back(Pair("address", addrNode.ToString())); BOOST_FOREACH(CNode* pnode, vNodes) if (pnode->addr == addrNode) { fFound = true; fConnected = true; node.push_back(Pair("connected", pnode->fInbound ? "inbound" : "outbound")); break; } if (!fFound) node.push_back(Pair("connected", "false")); addresses.push_back(node); } obj.push_back(Pair("connected", fConnected)); obj.push_back(Pair("addresses", addresses)); ret.push_back(obj); } return ret; } Value getnettotals(const Array& params, bool fHelp) { if (fHelp || params.size() > 0) throw runtime_error( "getnettotals\n" "\nReturns information about network traffic, including bytes in, bytes out,\n" "and current time.\n" "\nResult:\n" "{\n" " \"totalbytesrecv\": n, (numeric) Total bytes received\n" " \"totalbytessent\": n, (numeric) Total bytes sent\n" " \"timemillis\": t (numeric) Total cpu time\n" "}\n" "\nExamples:\n" + HelpExampleCli("getnettotals", "") + HelpExampleRpc("getnettotals", "") ); Object obj; obj.push_back(Pair("totalbytesrecv", static_cast< boost::uint64_t>(CNode::GetTotalBytesRecv()))); obj.push_back(Pair("totalbytessent", static_cast<boost::uint64_t>(CNode::GetTotalBytesSent()))); obj.push_back(Pair("timemillis", static_cast<boost::int64_t>(GetTimeMillis()))); return obj; }
// Copyright (c) 2009-2013 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "rpcserver.h" #include "main.h" #include "net.h" #include "netbase.h" #include "protocol.h" #include "sync.h" #include "util.h" #ifdef ENABLE_WALLET #include "init.h" // for getinfo #include "wallet.h" // for getinfo #endif #include <inttypes.h> #include <boost/foreach.hpp> #include "json/json_spirit_value.h" using namespace json_spirit; using namespace std; Value getconnectioncount(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getconnectioncount\n" "\nReturns the number of connections to other nodes.\n" "\nbResult:\n" "n (numeric) The connection count\n" "\nExamples:\n" + HelpExampleCli("getconnectioncount", "") + HelpExampleRpc("getconnectioncount", "") ); LOCK(cs_vNodes); return (int)vNodes.size(); } Value ping(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "ping\n" "\nRequests that a ping be sent to all other nodes, to measure ping time.\n" "Results provided in getpeerinfo, pingtime and pingwait fields are decimal seconds.\n" "Ping command is handled in queue with all other commands, so it measures processing backlog, not just network ping." "\nExamples:\n" + HelpExampleCli("ping", "") + HelpExampleRpc("ping", "") ); // Request that each node send a ping during next message processing pass LOCK(cs_vNodes); BOOST_FOREACH(CNode* pNode, vNodes) { pNode->fPingQueued = true; } return Value::null; } static void CopyNodeStats(std::vector<CNodeStats>& vstats) { vstats.clear(); LOCK(cs_vNodes); vstats.reserve(vNodes.size()); BOOST_FOREACH(CNode* pnode, vNodes) { CNodeStats stats; pnode->copyStats(stats); vstats.push_back(stats); } } Value getpeerinfo(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getpeerinfo\n" "\nReturns data about each connected network node as a json array of objects.\n" "\nbResult:\n" "[\n" " {\n" " \"addr\":\"host:port\", (string) The ip address and port of the peer\n" " \"addrlocal\":\"ip:port\", (string) local address\n" " \"services\":\"00000001\", (string) The services\n" " \"lastsend\": ttt, (numeric) The time in seconds since epoch (Jan 1 1970 GMT) of the last send\n" " \"lastrecv\": ttt, (numeric) The time in seconds since epoch (Jan 1 1970 GMT) of the last receive\n" " \"bytessent\": n, (numeric) The total bytes sent\n" " \"bytesrecv\": n, (numeric) The total bytes received\n" " \"conntime\": ttt, (numeric) The connection time in seconds since epoch (Jan 1 1970 GMT)\n" " \"pingtime\": n, (numeric) ping time\n" " \"pingwait\": n, (numeric) ping wait\n" " \"version\": v, (numeric) The peer version, such as 7001\n" " \"subver\": \"/Satoshi:0.8.5/\", (string) The string version\n" " \"inbound\": true|false, (boolean) Inbound (true) or Outbound (false)\n" " \"startingheight\": n, (numeric) The starting height (block) of the peer\n" " \"banscore\": n, (numeric) The ban score (stats.nMisbehavior)\n" " \"syncnode\" : true|false (booleamn) if sync node\n" " }\n" " ,...\n" "}\n" "\nExamples:\n" + HelpExampleCli("getpeerinfo", "") + HelpExampleRpc("getpeerinfo", "") ); vector<CNodeStats> vstats; CopyNodeStats(vstats); Array ret; BOOST_FOREACH(const CNodeStats& stats, vstats) { Object obj; CNodeStateStats statestats; bool fStateStats = GetNodeStateStats(stats.nodeid, statestats); obj.push_back(Pair("addr", stats.addrName)); if (!(stats.addrLocal.empty())) obj.push_back(Pair("addrlocal", stats.addrLocal)); obj.push_back(Pair("services", strprintf("%08"PRIx64, stats.nServices))); obj.push_back(Pair("lastsend", (boost::int64_t)stats.nLastSend)); obj.push_back(Pair("lastrecv", (boost::int64_t)stats.nLastRecv)); obj.push_back(Pair("bytessent", (boost::int64_t)stats.nSendBytes)); obj.push_back(Pair("bytesrecv", (boost::int64_t)stats.nRecvBytes)); obj.push_back(Pair("conntime", (boost::int64_t)stats.nTimeConnected)); obj.push_back(Pair("pingtime", stats.dPingTime)); if (stats.dPingWait > 0.0) obj.push_back(Pair("pingwait", stats.dPingWait)); obj.push_back(Pair("version", stats.nVersion)); // Use the sanitized form of subver here, to avoid tricksy remote peers from // corrupting or modifiying the JSON output by putting special characters in // their ver message. obj.push_back(Pair("subver", stats.cleanSubVer)); obj.push_back(Pair("inbound", stats.fInbound)); obj.push_back(Pair("startingheight", stats.nStartingHeight)); if (fStateStats) { obj.push_back(Pair("banscore", statestats.nMisbehavior)); } if (stats.fSyncNode) obj.push_back(Pair("syncnode", true)); ret.push_back(obj); } return ret; } Value addnode(const Array& params, bool fHelp) { string strCommand; if (params.size() == 2) strCommand = params[1].get_str(); if (fHelp || params.size() != 2 || (strCommand != "onetry" && strCommand != "add" && strCommand != "remove")) throw runtime_error( "addnode \"node\" \"add|remove|onetry\"\n" "\nAttempts add or remove a node from the addnode list.\n" "Or try a connection to a node once.\n" "\nArguments:\n" "1. \"node\" (string, required) The node (see getpeerinfo for nodes)\n" "2. \"command\" (string, required) 'add' to add a node to the list, 'remove' to remove a node from the list, 'onetry' to try a connection to the node once\n" "\nExamples:\n" + HelpExampleCli("addnode", "\"192.168.0.6:8333\" \"onetry\"") + HelpExampleRpc("addnode", "\"192.168.0.6:8333\", \"onetry\"") ); string strNode = params[0].get_str(); if (strCommand == "onetry") { CAddress addr; ConnectNode(addr, strNode.c_str()); return Value::null; } LOCK(cs_vAddedNodes); vector<string>::iterator it = vAddedNodes.begin(); for(; it != vAddedNodes.end(); it++) if (strNode == *it) break; if (strCommand == "add") { if (it != vAddedNodes.end()) throw JSONRPCError(RPC_CLIENT_NODE_ALREADY_ADDED, "Error: Node already added"); vAddedNodes.push_back(strNode); } else if(strCommand == "remove") { if (it == vAddedNodes.end()) throw JSONRPCError(RPC_CLIENT_NODE_NOT_ADDED, "Error: Node has not been added."); vAddedNodes.erase(it); } return Value::null; } Value getaddednodeinfo(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "getaddednodeinfo dns ( \"node\" )\n" "\nReturns information about the given added node, or all added nodes\n" "(note that onetry addnodes are not listed here)\n" "If dns is false, only a list of added nodes will be provided,\n" "otherwise connected information will also be available.\n" "\nArguments:\n" "1. dns (boolean, required) If false, only a list of added nodes will be provided, otherwise connected information will also be available.\n" "2. \"node\" (string, optional) If provided, return information about this specific node, otherwise all nodes are returned.\n" "\nResult:\n" "[\n" " {\n" " \"addednode\" : \"192.168.0.201\", (string) The node ip address\n" " \"connected\" : true|false, (boolean) If connected\n" " \"addresses\" : [\n" " {\n" " \"address\" : \"192.168.0.201:8333\", (string) The bitcoin server host and port\n" " \"connected\" : \"outbound\" (string) connection, inbound or outbound\n" " }\n" " ,...\n" " ]\n" " }\n" " ,...\n" "]\n" "\nExamples:\n" + HelpExampleCli("getaddednodeinfo", "true") + HelpExampleCli("getaddednodeinfo", "true \"192.168.0.201\"") + HelpExampleRpc("getaddednodeinfo", "true, \"192.168.0.201\"") ); bool fDns = params[0].get_bool(); list<string> laddedNodes(0); if (params.size() == 1) { LOCK(cs_vAddedNodes); BOOST_FOREACH(string& strAddNode, vAddedNodes) laddedNodes.push_back(strAddNode); } else { string strNode = params[1].get_str(); LOCK(cs_vAddedNodes); BOOST_FOREACH(string& strAddNode, vAddedNodes) if (strAddNode == strNode) { laddedNodes.push_back(strAddNode); break; } if (laddedNodes.size() == 0) throw JSONRPCError(RPC_CLIENT_NODE_NOT_ADDED, "Error: Node has not been added."); } Array ret; if (!fDns) { BOOST_FOREACH(string& strAddNode, laddedNodes) { Object obj; obj.push_back(Pair("addednode", strAddNode)); ret.push_back(obj); } return ret; } list<pair<string, vector<CService> > > laddedAddreses(0); BOOST_FOREACH(string& strAddNode, laddedNodes) { vector<CService> vservNode(0); if(Lookup(strAddNode.c_str(), vservNode, Params().GetDefaultPort(), fNameLookup, 0)) laddedAddreses.push_back(make_pair(strAddNode, vservNode)); else { Object obj; obj.push_back(Pair("addednode", strAddNode)); obj.push_back(Pair("connected", false)); Array addresses; obj.push_back(Pair("addresses", addresses)); } } LOCK(cs_vNodes); for (list<pair<string, vector<CService> > >::iterator it = laddedAddreses.begin(); it != laddedAddreses.end(); it++) { Object obj; obj.push_back(Pair("addednode", it->first)); Array addresses; bool fConnected = false; BOOST_FOREACH(CService& addrNode, it->second) { bool fFound = false; Object node; node.push_back(Pair("address", addrNode.ToString())); BOOST_FOREACH(CNode* pnode, vNodes) if (pnode->addr == addrNode) { fFound = true; fConnected = true; node.push_back(Pair("connected", pnode->fInbound ? "inbound" : "outbound")); break; } if (!fFound) node.push_back(Pair("connected", "false")); addresses.push_back(node); } obj.push_back(Pair("connected", fConnected)); obj.push_back(Pair("addresses", addresses)); ret.push_back(obj); } return ret; } Value getnettotals(const Array& params, bool fHelp) { if (fHelp || params.size() > 0) throw runtime_error( "getnettotals\n" "\nReturns information about network traffic, including bytes in, bytes out,\n" "and current time.\n" "\nResult:\n" "{\n" " \"totalbytesrecv\": n, (numeric) Total bytes received\n" " \"totalbytessent\": n, (numeric) Total bytes sent\n" " \"timemillis\": t (numeric) Total cpu time\n" "}\n" "\nExamples:\n" + HelpExampleCli("getnettotals", "") + HelpExampleRpc("getnettotals", "") ); Object obj; obj.push_back(Pair("totalbytesrecv", static_cast< boost::uint64_t>(CNode::GetTotalBytesRecv()))); obj.push_back(Pair("totalbytessent", static_cast<boost::uint64_t>(CNode::GetTotalBytesSent()))); obj.push_back(Pair("timemillis", static_cast<boost::int64_t>(GetTimeMillis()))); return obj; }
Fix `getaddednodeinfo` RPC call with dns=false
Fix `getaddednodeinfo` RPC call with dns=false The getaddednodeinfo RPC call, when invoked with the dns flag set to false, returns a malformed JSON object with duplicate keys. Change this to return an array of objects with one key as shown in the help message. Fixes #3581.
C++
mit
genavarov/brcoin,XertroV/bitcoin-nulldata,faircoin/faircoin,Christewart/bitcoin,torresalyssa/bitcoin,PRabahy/bitcoin,fussl/elements,CodeShark/bitcoin,jonghyeopkim/bitcoinxt,ingresscoin/ingresscoin,sarielsaz/sarielsaz,sirk390/bitcoin,sugruedes/bitcoinxt,MazaCoin/maza,pelorusjack/BlockDX,dgarage/bc2,FeatherCoin/Feathercoin,coinkeeper/2015-06-22_19-00_ziftrcoin,deuscoin/deuscoin,Flurbos/Flurbo,syscoin/syscoin,nigeriacoin/nigeriacoin,aspanta/bitcoin,koharjidan/bitcoin,cryptodev35/icash,dogecoin/dogecoin,apoelstra/bitcoin,bankonmecoin/bitcoin,truthcoin/truthcoin-cpp,sdaftuar/bitcoin,KnCMiner/bitcoin,Sjors/bitcoin,romanornr/viacoin,donaloconnor/bitcoin,haraldh/bitcoin,awemany/BitcoinUnlimited,litecoin-project/litecoin,dannyperez/bolivarcoin,randy-waterhouse/bitcoin,dgenr8/bitcoinxt,Kixunil/keynescoin,hsavit1/bitcoin,brishtiteveja/truthcoin-cpp,Vector2000/bitcoin,bcpki/nonce2,rat4/bitcoin,joroob/reddcoin,Jeff88Ho/bitcoin,MazaCoin/maza,Kore-Core/kore,Kenwhite23/litecoin,coinwarp/dogecoin,greencoin-dev/digitalcoin,Thracky/monkeycoin,theuni/bitcoin,elliotolds/bitcoin,TBoehm/greedynode,dogecoin/dogecoin,vcoin-project/vcoincore,nathaniel-mahieu/bitcoin,shaolinfry/litecoin,capitalDIGI/DIGI-v-0-10-4,accraze/bitcoin,rjshaver/bitcoin,wederw/bitcoin,AllanDoensen/BitcoinUnlimited,odemolliens/bitcoinxt,jiangyonghang/bitcoin,tropa/axecoin,thrasher-/litecoin,DogTagRecon/Still-Leraning,cdecker/bitcoin,itmanagerro/tresting,AllanDoensen/BitcoinUnlimited,jaromil/faircoin2,misdess/bitcoin,TierNolan/bitcoin,axelxod/braincoin,cryptoprojects/ultimateonlinecash,fujicoin/fujicoin,bcpki/nonce2,hyperwang/bitcoin,thelazier/dash,Bitcoin-ABC/bitcoin-abc,cybermatatu/bitcoin,Rav3nPL/doubloons-0.10,unsystemizer/bitcoin,bitjson/hivemind,Kogser/bitcoin,habibmasuro/bitcoin,slingcoin/sling-market,shouhuas/bitcoin,Kangmo/bitcoin,Bitcoin-ABC/bitcoin-abc,romanornr/viacoin,CryptArc/bitcoin,2XL/bitcoin,DogTagRecon/Still-Leraning,genavarov/ladacoin,habibmasuro/bitcoinxt,namecoin/namecoin-core,BitcoinUnlimited/BitcoinUnlimited,gzuser01/zetacoin-bitcoin,prark/bitcoinxt,fussl/elements,CodeShark/bitcoin,dmrtsvetkov/flowercoin,Vector2000/bitcoin,simonmulser/bitcoin,ionomy/ion,Xekyo/bitcoin,npccoin/npccoin,Alonzo-Coeus/bitcoin,zcoinofficial/zcoin,hsavit1/bitcoin,arnuschky/bitcoin,EntropyFactory/creativechain-core,ajweiss/bitcoin,tjth/lotterycoin,jmgilbert2/energi,diggcoin/diggcoin,Alonzo-Coeus/bitcoin,BTCfork/hardfork_prototype_1_mvf-bu,pastday/bitcoinproject,neuroidss/bitcoin,puticcoin/putic,dmrtsvetkov/flowercoin,schildbach/bitcoin,Kangmo/bitcoin,ludbb/bitcoin,senadmd/coinmarketwatch,jeromewu/bitcoin-opennet,koharjidan/litecoin,habibmasuro/bitcoinxt,phelix/namecore,mobicoins/mobicoin-core,loxal/zcash,MasterX1582/bitcoin-becoin,jarymoth/dogecoin,shelvenzhou/BTCGPU,appop/bitcoin,zixan/bitcoin,ColossusCoinXT/ColossusCoinXT,se3000/bitcoin,cryptodev35/icash,fedoracoin-dev/fedoracoin,gapcoin/gapcoin,argentumproject/argentum,bespike/litecoin,kevcooper/bitcoin,dagurval/bitcoinxt,RHavar/bitcoin,PRabahy/bitcoin,puticcoin/putic,benosa/bitcoin,MonetaryUnit/MUE-Src,NunoEdgarGub1/elements,DGCDev/argentum,bespike/litecoin,ppcoin/ppcoin,KnCMiner/bitcoin,bitcoinclassic/bitcoinclassic,kazcw/bitcoin,CodeShark/bitcoin,constantine001/bitcoin,denverl/bitcoin,psionin/smartcoin,GroundRod/anoncoin,ixcoinofficialpage/master,stevemyers/bitcoinxt,dannyperez/bolivarcoin,DynamicCoinOrg/DMC,dgarage/bc2,fsb4000/bitcoin,senadmd/coinmarketwatch,fullcoins/fullcoin,DigiByte-Team/digibyte,joroob/reddcoin,nlgcoin/guldencoin-official,Theshadow4all/ShadowCoin,trippysalmon/bitcoin,anditto/bitcoin,dgarage/bc3,pelorusjack/BlockDX,Jeff88Ho/bitcoin,superjudge/bitcoin,GroundRod/anoncoin,braydonf/bitcoin,Krellan/bitcoin,BTCGPU/BTCGPU,bitcoinec/bitcoinec,psionin/smartcoin,lclc/bitcoin,NateBrune/bitcoin-fio,worldbit/worldbit,inkvisit/sarmacoins,appop/bitcoin,MonetaryUnit/MUE-Src,mapineda/litecoin,kaostao/bitcoin,wangliu/bitcoin,MazaCoin/mazacoin-new,BTCDDev/bitcoin,haobtc/bitcoin,fullcoins/fullcoin,nigeriacoin/nigeriacoin,metacoin/florincoin,cheehieu/bitcoin,myriadcoin/myriadcoin,mm-s/bitcoin,UdjinM6/dash,deadalnix/bitcoin,MasterX1582/bitcoin-becoin,segsignal/bitcoin,h4x3rotab/BTCGPU,thesoftwarejedi/bitcoin,lakepay/lake,krzysztofwos/BitcoinUnlimited,benosa/bitcoin,particl/particl-core,ivansib/sib16,RazorLove/cloaked-octo-spice,prusnak/bitcoin,braydonf/bitcoin,jmgilbert2/energi,cyrixhero/bitcoin,jeromewu/bitcoin-opennet,LIMXTEC/DMDv3,nmarley/dash,droark/bitcoin,DGCDev/argentum,dexX7/mastercore,my-first/octocoin,okinc/bitcoin,ivansib/sibcoin,nmarley/dash,SartoNess/BitcoinUnlimited,braydonf/bitcoin,dgarage/bc3,DigitalPandacoin/pandacoin,h4x3rotab/BTCGPU,anditto/bitcoin,axelxod/braincoin,jamesob/bitcoin,GroundRod/anoncoin,shaolinfry/litecoin,shaolinfry/litecoin,tecnovert/particl-core,butterflypay/bitcoin,goldcoin/Goldcoin-GLD,Vsync-project/Vsync,freelion93/mtucicoin,deeponion/deeponion,initaldk/bitcoin,myriadteam/myriadcoin,UASF/bitcoin,superjudge/bitcoin,pouta/bitcoin,andres-root/bitcoinxt,anditto/bitcoin,domob1812/bitcoin,KibiCoin/kibicoin,apoelstra/bitcoin,rdqw/sscoin,pascalguru/florincoin,TierNolan/bitcoin,faircoin/faircoin2,NateBrune/bitcoin-nate,nmarley/dash,FinalHashLLC/namecore,bitcoinxt/bitcoinxt,capitalDIGI/DIGI-v-0-10-4,NicolasDorier/bitcoin,capitalDIGI/DIGI-v-0-10-4,zotherstupidguy/bitcoin,nvmd/bitcoin,cerebrus29301/crowncoin,CTRoundTable/Encrypted.Cash,josephbisch/namecoin-core,StarbuckBG/BTCGPU,jiangyonghang/bitcoin,BitcoinUnlimited/BitcoinUnlimited,n1bor/bitcoin,my-first/octocoin,Bitcoinsulting/bitcoinxt,aniemerg/zcash,wellenreiter01/Feathercoin,Domer85/dogecoin,apoelstra/elements,segwit/atbcoin-insight,ashleyholman/bitcoin,rnicoll/bitcoin,NateBrune/bitcoin-nate,paveljanik/bitcoin,core-bitcoin/bitcoin,kleetus/bitcoin,2XL/bitcoin,Theshadow4all/ShadowCoin,MikeAmy/bitcoin,scmorse/bitcoin,mincoin-project/mincoin,wangliu/bitcoin,zander/bitcoinclassic,rjshaver/bitcoin,h4x3rotab/BTCGPU,presstab/PIVX,djpnewton/bitcoin,daveperkins-github/bitcoin-dev,TGDiamond/Diamond,Kangmo/bitcoin,Tetpay/bitcoin,nbenoit/bitcoin,keo/bitcoin,welshjf/bitcoin,BitzenyCoreDevelopers/bitzeny,hsavit1/bitcoin,lclc/bitcoin,DogTagRecon/Still-Leraning,ahmedbodi/temp_vert,GwangJin/gwangmoney-core,bmp02050/ReddcoinUpdates,nikkitan/bitcoin,KnCMiner/bitcoin,kirkalx/bitcoin,alejandromgk/Lunar,Bitcoin-ABC/bitcoin-abc,bitcoin/bitcoin,gandrewstone/BitcoinUnlimited,grumpydevelop/singularity,andreaskern/bitcoin,lbrtcoin/albertcoin,FinalHashLLC/namecore,jonghyeopkim/bitcoinxt,llluiop/bitcoin,s-matthew-english/bitcoin,phelix/bitcoin,RibbitFROG/ribbitcoin,nmarley/dash,ColossusCoinXT/ColossusCoinXT,ticclassic/ic,dexX7/bitcoin,KibiCoin/kibicoin,Petr-Economissa/gvidon,myriadcoin/myriadcoin,zottejos/merelcoin,1185/starwels,bitcoinclassic/bitcoinclassic,capitalDIGI/DIGI-v-0-10-4,crowning2/dash,ptschip/bitcoin,BlockchainTechLLC/3dcoin,puticcoin/putic,shouhuas/bitcoin,willwray/dash,stevemyers/bitcoinxt,NateBrune/bitcoin-fio,donaloconnor/bitcoin,accraze/bitcoin,genavarov/ladacoin,xurantju/bitcoin,ftrader-bitcoinunlimited/hardfork_prototype_1_mvf-bu,Jcing95/iop-hd,parvez3019/bitcoin,ivansib/sib16,kleetus/bitcoin,cmgustavo/bitcoin,basicincome/unpcoin-core,JeremyRubin/bitcoin,Kore-Core/kore,gjhiggins/vcoincore,CryptArc/bitcoin,mockcoin/mockcoin,bitpay/bitcoin,antcheck/antcoin,goldcoin/goldcoin,dan-mi-sun/bitcoin,krzysztofwos/BitcoinUnlimited,apoelstra/elements,thormuller/yescoin2,dexX7/mastercore,superjudge/bitcoin,droark/bitcoin,royosherove/bitcoinxt,Michagogo/bitcoin,rustyrussell/bitcoin,UFOCoins/ufo,phelix/namecore,shouhuas/bitcoin,antcheck/antcoin,paveljanik/bitcoin,omefire/bitcoin,DSPay/DSPay,bittylicious/bitcoin,Petr-Economissa/gvidon,brishtiteveja/truthcoin-cpp,DigiByte-Team/digibyte,MeshCollider/bitcoin,mastercoin-MSC/mastercore,XertroV/bitcoin-nulldata,Kore-Core/kore,Exgibichi/statusquo,bcpki/testblocks,funbucks/notbitcoinxt,crowning2/dash,czr5014iph/bitcoin4e,sbaks0820/bitcoin,koharjidan/bitcoin,namecoin/namecoin-core,btcdrak/bitcoin,aciddude/Feathercoin,jnewbery/bitcoin,Mrs-X/Darknet,domob1812/bitcoin,jonasschnelli/bitcoin,gravio-net/graviocoin,ElementsProject/elements,goku1997/bitcoin,czr5014iph/bitcoin4e,elecoin/elecoin,ShwoognationHQ/bitcoin,11755033isaprimenumber/Feathercoin,xawksow/GroestlCoin,GreenParhelia/bitcoin,GroundRod/anoncoin,Sjors/bitcoin,ahmedbodi/vertcoin,BTCTaras/bitcoin,BitcoinPOW/BitcoinPOW,AkioNak/bitcoin,svost/bitcoin,greenaddress/bitcoin,fanquake/bitcoin,Earlz/renamedcoin,andreaskern/bitcoin,jrick/bitcoin,czr5014iph/bitcoin4e,trippysalmon/bitcoin,DGCDev/argentum,particl/particl-core,digibyte/digibyte,patricklodder/dogecoin,NateBrune/bitcoin-fio,JeremyRand/namecoin-core,andres-root/bitcoinxt,Diapolo/bitcoin,schinzelh/dash,nigeriacoin/nigeriacoin,ardsu/bitcoin,droark/bitcoin,blocktrail/bitcoin,dan-mi-sun/bitcoin,bitreserve/bitcoin,haobtc/bitcoin,experiencecoin/experiencecoin,bitcoinxt/bitcoinxt,martindale/elements,instagibbs/bitcoin,shaulkf/bitcoin,goku1997/bitcoin,slingcoin/sling-market,GroundRod/anoncoin,romanornr/viacoin,putinclassic/putic,bitjson/hivemind,accraze/bitcoin,gandrewstone/BitcoinUnlimited,royosherove/bitcoinxt,CoinProjects/AmsterdamCoin-v4,ShwoognationHQ/bitcoin,cryptoprojects/ultimateonlinecash,hasanatkazmi/bitcoin,bitreserve/bitcoin,maaku/bitcoin,daveperkins-github/bitcoin-dev,FinalHashLLC/namecore,jtimon/elements,bdelzell/creditcoin-org-creditcoin,wederw/bitcoin,aspanta/bitcoin,dexX7/mastercore,174high/bitcoin,kallewoof/bitcoin,CTRoundTable/Encrypted.Cash,rnicoll/bitcoin,freelion93/mtucicoin,BitcoinUnlimited/BitcoinUnlimited,FeatherCoin/Feathercoin,inutoshi/inutoshi,DigiByte-Team/digibyte,nsacoin/nsacoin,sbaks0820/bitcoin,GIJensen/bitcoin,leofidus/glowing-octo-ironman,PandaPayProject/PandaPay,kallewoof/elements,rebroad/bitcoin,ryanofsky/bitcoin,sickpig/BitcoinUnlimited,segsignal/bitcoin,ericshawlinux/bitcoin,tjth/lotterycoin,wiggi/huntercore,misdess/bitcoin,OstlerDev/florincoin,dperel/bitcoin,ElementsProject/elements,Rav3nPL/PLNcoin,dev1972/Satellitecoin,koharjidan/bitcoin,denverl/bitcoin,cddjr/BitcoinUnlimited,coinkeeper/2015-06-22_18-37_dogecoin,grumpydevelop/singularity,m0gliE/fastcoin-cli,namecoin/namecore,BTCfork/hardfork_prototype_1_mvf-core,kleetus/bitcoinxt,cannabiscoindev/cannabiscoin420,nikkitan/bitcoin,ShadowMyst/creativechain-core,loxal/zcash,andres-root/bitcoinxt,pascalguru/florincoin,48thct2jtnf/P,tecnovert/particl-core,JeremyRand/namecore,ShwoognationHQ/bitcoin,DigitalPandacoin/pandacoin,bitcoinsSG/zcash,gmaxwell/bitcoin,BTCDDev/bitcoin,millennial83/bitcoin,roques/bitcoin,rnicoll/bitcoin,bankonmecoin/bitcoin,brishtiteveja/truthcoin-cpp,pinheadmz/bitcoin,wiggi/huntercore,pascalguru/florincoin,AllanDoensen/BitcoinUnlimited,Justaphf/BitcoinUnlimited,domob1812/i0coin,reddcoin-project/reddcoin,marklai9999/Taiwancoin,guncoin/guncoin,basicincome/unpcoin-core,dgarage/bc2,trippysalmon/bitcoin,Bushstar/UFO-Project,Mirobit/bitcoin,ediston/energi,jl2012/litecoin,zetacoin/zetacoin,FeatherCoin/Feathercoin,nomnombtc/bitcoin,qtumproject/qtum,bittylicious/bitcoin,andreaskern/bitcoin,aburan28/elements,Bitcoin-ABC/bitcoin-abc,Bloom-Project/Bloom,se3000/bitcoin,haraldh/bitcoin,peercoin/peercoin,goldcoin/goldcoin,cmgustavo/bitcoin,NunoEdgarGub1/elements,ahmedbodi/temp_vert,sbellem/bitcoin,AkioNak/bitcoin,ixcoinofficialpage/master,dgenr8/bitcoin,phelix/namecore,oleganza/bitcoin-duo,nsacoin/nsacoin,coinkeeper/2015-06-22_19-00_ziftrcoin,adpg211/bitcoin-master,gwillen/elements,cotner/bitcoin,Flowdalic/bitcoin,goldcoin/goldcoin,schinzelh/dash,destenson/bitcoin--bitcoin,wederw/bitcoin,goldcoin/goldcoin,thormuller/yescoin2,aspanta/bitcoin,pelorusjack/BlockDX,jmgilbert2/energi,brandonrobertz/namecoin-core,millennial83/bitcoin,Vector2000/bitcoin,BigBlueCeiling/augmentacoin,gzuser01/zetacoin-bitcoin,alejandromgk/Lunar,dgenr8/bitcoinxt,scippio/bitcoin,pstratem/bitcoin,jrick/bitcoin,drwasho/bitcoinxt,jakeva/bitcoin-pwcheck,itmanagerro/tresting,NicolasDorier/bitcoin,lbrtcoin/albertcoin,TGDiamond/Diamond,jameshilliard/bitcoin,jimmysong/bitcoin,braydonf/bitcoin,JeremyRand/bitcoin,kallewoof/bitcoin,adpg211/bitcoin-master,Bitcoinsulting/bitcoinxt,multicoins/marycoin,cyrixhero/bitcoin,m0gliE/fastcoin-cli,myriadteam/myriadcoin,ticclassic/ic,keesdewit82/LasVegasCoin,ahmedbodi/terracoin,HeliumGas/helium,andreaskern/bitcoin,janko33bd/bitcoin,aburan28/elements,guncoin/guncoin,biblepay/biblepay,tecnovert/particl-core,superjudge/bitcoin,vtafaucet/virtacoin,Petr-Economissa/gvidon,FarhanHaque/bitcoin,jlopp/statoshi,coinkeeper/2015-06-22_18-39_feathercoin,namecoin/namecore,argentumproject/argentum,Mrs-X/Darknet,isocolsky/bitcoinxt,botland/bitcoin,JeremyRubin/bitcoin,reorder/viacoin,crowning-/dash,Kogser/bitcoin,SartoNess/BitcoinUnlimited,namecoin/namecoin-core,credits-currency/credits,jrick/bitcoin,mincoin-project/mincoin,domob1812/huntercore,gandrewstone/bitcoinxt,nlgcoin/guldencoin-official,cddjr/BitcoinUnlimited,fullcoins/fullcoin,globaltoken/globaltoken,greencoin-dev/digitalcoin,gravio-net/graviocoin,ftrader-bitcoinabc/bitcoin-abc,btcdrak/bitcoin,xurantju/bitcoin,cheehieu/bitcoin,DigitalPandacoin/pandacoin,mastercoin-MSC/mastercore,romanornr/viacoin,kleetus/bitcoin,JeremyRand/namecoin-core,odemolliens/bitcoinxt,Bitcoinsulting/bitcoinxt,putinclassic/putic,bespike/litecoin,Vector2000/bitcoin,world-bank/unpay-core,cqtenq/feathercoin_core,haisee/dogecoin,JeremyRand/bitcoin,putinclassic/putic,GlobalBoost/GlobalBoost,Vsync-project/Vsync,genavarov/lamacoin,parvez3019/bitcoin,midnight-miner/LasVegasCoin,argentumproject/argentum,RyanLucchese/energi,koharjidan/dogecoin,slingcoin/sling-market,gandrewstone/BitcoinUnlimited,sipa/elements,aspirecoin/aspire,terracoin/terracoin,Kore-Core/kore,bitbrazilcoin-project/bitbrazilcoin,Har01d/bitcoin,jakeva/bitcoin-pwcheck,projectinterzone/ITZ,randy-waterhouse/bitcoin,adpg211/bitcoin-master,Bushstar/UFO-Project,cddjr/BitcoinUnlimited,terracoin/terracoin,lbryio/lbrycrd,supcoin/supcoin,welshjf/bitcoin,iosdevzone/bitcoin,nathaniel-mahieu/bitcoin,ashleyholman/bitcoin,donaloconnor/bitcoin,Xekyo/bitcoin,TrainMAnB/vcoincore,MikeAmy/bitcoin,shaulkf/bitcoin,sarielsaz/sarielsaz,senadmd/coinmarketwatch,simdeveloper/bitcoin,MarcoFalke/bitcoin,wtogami/bitcoin,denverl/bitcoin,Krellan/bitcoin,kbccoin/kbc,ftrader-bitcoinunlimited/hardfork_prototype_1_mvf-bu,zenywallet/bitzeny,gavinandresen/bitcoin-git,dexX7/bitcoin,constantine001/bitcoin,cculianu/bitcoin-abc,haisee/dogecoin,kbccoin/kbc,ArgonToken/ArgonToken,torresalyssa/bitcoin,coinkeeper/2015-06-22_18-36_darkcoin,koharjidan/bitcoin,droark/elements,janko33bd/bitcoin,Mrs-X/Darknet,BigBlueCeiling/augmentacoin,martindale/elements,afk11/bitcoin,joulecoin/joulecoin,knolza/gamblr,mitchellcash/bitcoin,TierNolan/bitcoin,digideskio/namecoin,mm-s/bitcoin,adpg211/bitcoin-master,gavinandresen/bitcoin-git,spiritlinxl/BTCGPU,Thracky/monkeycoin,mycointest/owncoin,bcpki/nonce2testblocks,cmgustavo/bitcoin,coinkeeper/2015-06-22_18-31_bitcoin,truthcoin/truthcoin-cpp,fussl/elements,BitcoinPOW/BitcoinPOW,Kcoin-project/kcoin,rdqw/sscoin,Diapolo/bitcoin,GlobalBoost/GlobalBoost,EntropyFactory/creativechain-core,shomeser/bitcoin,vlajos/bitcoin,omefire/bitcoin,x-kalux/bitcoin_WiG-B,n1bor/bitcoin,vtafaucet/virtacoin,ivansib/sibcoin,MikeAmy/bitcoin,constantine001/bitcoin,sdaftuar/bitcoin,ticclassic/ic,Kenwhite23/litecoin,zenywallet/bitzeny,kleetus/bitcoinxt,segwit/atbcoin-insight,zcoinofficial/zcoin,jmgilbert2/energi,marlengit/BitcoinUnlimited,dcousens/bitcoin,skaht/bitcoin,acid1789/bitcoin,marcusdiaz/BitcoinUnlimited,ravenbyron/phtevencoin,Petr-Economissa/gvidon,oklink-dev/bitcoin,millennial83/bitcoin,lakepay/lake,petertodd/bitcoin,dgarage/bc2,marlengit/BitcoinUnlimited,Flowdalic/bitcoin,GroestlCoin/bitcoin,keesdewit82/LasVegasCoin,FeatherCoin/Feathercoin,marlengit/hardfork_prototype_1_mvf-bu,uphold/bitcoin,Rav3nPL/polcoin,argentumproject/argentum,kbccoin/kbc,Kenwhite23/litecoin,cculianu/bitcoin-abc,DSPay/DSPay,experiencecoin/experiencecoin,RyanLucchese/energi,ahmedbodi/terracoin,174high/bitcoin,PandaPayProject/PandaPay,tecnovert/particl-core,guncoin/guncoin,coinkeeper/2015-06-22_18-31_bitcoin,cryptoprojects/ultimateonlinecash,GlobalBoost/GlobalBoost,Rav3nPL/PLNcoin,jmgilbert2/energi,EthanHeilman/bitcoin,coinkeeper/2015-06-22_18-39_feathercoin,r8921039/bitcoin,ripper234/bitcoin,fujicoin/fujicoin,ludbb/bitcoin,ftrader-bitcoinabc/bitcoin-abc,dmrtsvetkov/flowercoin,pastday/bitcoinproject,fussl/elements,bitcoinxt/bitcoinxt,jrmithdobbs/bitcoin,benzmuircroft/REWIRE.io,FeatherCoin/Feathercoin,vcoin-project/vcoincore,jonghyeopkim/bitcoinxt,rat4/bitcoin,vertcoin/vertcoin,amaivsimau/bitcoin,imharrywu/fastcoin,BitcoinHardfork/bitcoin,fujicoin/fujicoin,mikehearn/bitcoinxt,blood2/bloodcoin-0.9,bdelzell/creditcoin-org-creditcoin,KibiCoin/kibicoin,bitcoinknots/bitcoin,funkshelper/woodcoin-b,174high/bitcoin,simonmulser/bitcoin,bitcoin-hivemind/hivemind,JeremyRand/bitcoin,sipsorcery/bitcoin,rnicoll/bitcoin,ixcoinofficialpage/master,ftrader-bitcoinunlimited/hardfork_prototype_1_mvf-bu,meighti/bitcoin,imharrywu/fastcoin,sugruedes/bitcoin,tjth/lotterycoin,jrick/bitcoin,BTCDDev/bitcoin,prusnak/bitcoin,czr5014iph/bitcoin4e,apoelstra/elements,faircoin/faircoin2,Bushstar/UFO-Project,NateBrune/bitcoin-nate,magacoin/magacoin,Kogser/bitcoin,Christewart/bitcoin,ryanofsky/bitcoin,okinc/bitcoin,wellenreiter01/Feathercoin,wcwu/bitcoin,xurantju/bitcoin,theuni/bitcoin,mapineda/litecoin,zottejos/merelcoin,pouta/bitcoin,ionomy/ion,DigiByte-Team/digibyte,mikehearn/bitcoinxt,keesdewit82/LasVegasCoin,Mirobit/bitcoin,Kixunil/keynescoin,inutoshi/inutoshi,isocolsky/bitcoinxt,GreenParhelia/bitcoin,laudaa/bitcoin,ajtowns/bitcoin,dogecoin/dogecoin,alecalve/bitcoin,TrainMAnB/vcoincore,aciddude/Feathercoin,balajinandhu/bitcoin,dscotese/bitcoin,Kixunil/keynescoin,jn2840/bitcoin,zsulocal/bitcoin,monacoinproject/monacoin,EthanHeilman/bitcoin,jmcorgan/bitcoin,domob1812/namecore,mm-s/bitcoin,xuyangcn/opalcoin,Krellan/bitcoin,willwray/dash,Jeff88Ho/bitcoin,uphold/bitcoin,digibyte/digibyte,metacoin/florincoin,Exgibichi/statusquo,Darknet-Crypto/Darknet,nailtaras/nailcoin,gandrewstone/bitcoinxt,cannabiscoindev/cannabiscoin420,acid1789/bitcoin,ahmedbodi/test2,RazorLove/cloaked-octo-spice,gandrewstone/bitcoinxt,nathaniel-mahieu/bitcoin,bitcoinec/bitcoinec,pelorusjack/BlockDX,dgenr8/bitcoin,lbryio/lbrycrd,tjth/lotterycoin,multicoins/marycoin,okinc/bitcoin,ekankyesme/bitcoinxt,DMDcoin/Diamond,ripper234/bitcoin,vlajos/bitcoin,world-bank/unpay-core,schildbach/bitcoin,MikeAmy/bitcoin,coinkeeper/2015-06-22_18-37_dogecoin,sipsorcery/bitcoin,unsystemizer/bitcoin,Krellan/bitcoin,CoinProjects/AmsterdamCoin-v4,peercoin/peercoin,chaincoin/chaincoin,hophacker/bitcoin_malleability,jl2012/litecoin,svost/bitcoin,UFOCoins/ufo,RongxinZhang/bitcoinxt,BitzenyCoreDevelopers/bitzeny,destenson/bitcoin--bitcoin,vertcoin/vertcoin,instagibbs/bitcoin,wangliu/bitcoin,amaivsimau/bitcoin,koharjidan/litecoin,deeponion/deeponion,terracoin/terracoin,btcdrak/bitcoin,drwasho/bitcoinxt,KnCMiner/bitcoin,nathaniel-mahieu/bitcoin,elecoin/elecoin,CoinProjects/AmsterdamCoin-v4,litecoin-project/bitcoinomg,Kogser/bitcoin,zcoinofficial/zcoin,dogecoin/dogecoin,ppcoin/ppcoin,PRabahy/bitcoin,Diapolo/bitcoin,kevcooper/bitcoin,monacoinproject/monacoin,antcheck/antcoin,deeponion/deeponion,atgreen/bitcoin,imharrywu/fastcoin,rat4/bitcoin,practicalswift/bitcoin,gwillen/elements,haraldh/bitcoin,scmorse/bitcoin,namecoin/namecoin-core,dmrtsvetkov/flowercoin,lclc/bitcoin,jnewbery/bitcoin,karek314/bitcoin,joshrabinowitz/bitcoin,21E14/bitcoin,midnightmagic/bitcoin,jrmithdobbs/bitcoin,bitcoinec/bitcoinec,RongxinZhang/bitcoinxt,UASF/bitcoin,Bitcoin-com/BUcash,jonasschnelli/bitcoin,bitcoin-hivemind/hivemind,aburan28/elements,Justaphf/BitcoinUnlimited,deuscoin/deuscoin,phplaboratory/psiacoin,bitcoinsSG/bitcoin,coinkeeper/2015-06-22_18-52_viacoin,mockcoin/mockcoin,Lucky7Studio/bitcoin,gameunits/gameunits,nomnombtc/bitcoin,domob1812/i0coin,11755033isaprimenumber/Feathercoin,BTCTaras/bitcoin,keo/bitcoin,coinkeeper/2015-06-22_19-07_digitalcoin,welshjf/bitcoin,crowning-/dash,lclc/bitcoin,marklai9999/Taiwancoin,x-kalux/bitcoin_WiG-B,rsdevgun16e/energi,droark/elements,MonetaryUnit/MUE-Src,ShwoognationHQ/bitcoin,Alex-van-der-Peet/bitcoin,GroestlCoin/GroestlCoin,phelix/bitcoin,KaSt/ekwicoin,Har01d/bitcoin,itmanagerro/tresting,lbrtcoin/albertcoin,phelix/namecore,domob1812/huntercore,ZiftrCOIN/ziftrcoin,Justaphf/BitcoinUnlimited,upgradeadvice/MUE-Src,emc2foundation/einsteinium,jarymoth/dogecoin,deadalnix/bitcoin,balajinandhu/bitcoin,Mrs-X/Darknet,rjshaver/bitcoin,zcoinofficial/zcoin,mapineda/litecoin,funkshelper/woodcore,imharrywu/fastcoin,nbenoit/bitcoin,lateminer/bitcoin,goldcoin/Goldcoin-GLD,midnight-miner/LasVegasCoin,digideskio/namecoin,apoelstra/bitcoin,laudaa/bitcoin,bcpki/nonce2testblocks,matlongsi/micropay,coinkeeper/2015-06-22_19-07_digitalcoin,cheehieu/bitcoin,habibmasuro/bitcoinxt,bittylicious/bitcoin,KibiCoin/kibicoin,ahmedbodi/test2,Kogser/bitcoin,kirkalx/bitcoin,111t8e/bitcoin,Michagogo/bitcoin,monacoinproject/monacoin,greenaddress/bitcoin,aspirecoin/aspire,prark/bitcoinxt,Flowdalic/bitcoin,jlopp/statoshi,practicalswift/bitcoin,wcwu/bitcoin,vericoin/vericoin-core,ptschip/bitcoinxt,bitcoinplusorg/xbcwalletsource,TrainMAnB/vcoincore,kbccoin/kbc,omefire/bitcoin,elecoin/elecoin,goku1997/bitcoin,jmcorgan/bitcoin,RHavar/bitcoin,prusnak/bitcoin,dev1972/Satellitecoin,Christewart/bitcoin,shaulkf/bitcoin,jonasschnelli/bitcoin,Cloudsy/bitcoin,keo/bitcoin,digideskio/namecoin,llluiop/bitcoin,hasanatkazmi/bitcoin,npccoin/npccoin,PIVX-Project/PIVX,cmgustavo/bitcoin,balajinandhu/bitcoin,ryanofsky/bitcoin,n1bor/bitcoin,digibyte/digibyte,cerebrus29301/crowncoin,tmagik/catcoin,Rav3nPL/doubloons-0.10,genavarov/lamacoin,cddjr/BitcoinUnlimited,apoelstra/elements,Kogser/bitcoin,projectinterzone/ITZ,coinkeeper/2015-06-22_18-52_viacoin,Anfauglith/iop-hd,scippio/bitcoin,SartoNess/BitcoinUnlimited,truthcoin/blocksize-market,ashleyholman/bitcoin,janko33bd/bitcoin,hasanatkazmi/bitcoin,Kogser/bitcoin,midnightmagic/bitcoin,myriadteam/myriadcoin,greencoin-dev/digitalcoin,BlockchainTechLLC/3dcoin,Exgibichi/statusquo,gazbert/bitcoin,se3000/bitcoin,OstlerDev/florincoin,jambolo/bitcoin,1185/starwels,Bitcoin-ABC/bitcoin-abc,zottejos/merelcoin,KibiCoin/kibicoin,sirk390/bitcoin,kallewoof/elements,TierNolan/bitcoin,ixcoinofficialpage/master,pstratem/bitcoin,dgenr8/bitcoin,dgenr8/bitcoinxt,llluiop/bitcoin,AkioNak/bitcoin,itmanagerro/tresting,daliwangi/bitcoin,marcusdiaz/BitcoinUnlimited,lbrtcoin/albertcoin,mycointest/owncoin,dexX7/bitcoin,brishtiteveja/truthcoin-cpp,willwray/dash,blocktrail/bitcoin,maaku/bitcoin,jaromil/faircoin2,EntropyFactory/creativechain-core,ingresscoin/ingresscoin,randy-waterhouse/bitcoin,TeamBitBean/bitcoin-core,vertcoin/vertcoin,Friedbaumer/litecoin,mitchellcash/bitcoin,bitreserve/bitcoin,alejandromgk/Lunar,Thracky/monkeycoin,Kixunil/keynescoin,atgreen/bitcoin,parvez3019/bitcoin,octocoin-project/octocoin,Darknet-Crypto/Darknet,mastercoin-MSC/mastercore,mobicoins/mobicoin-core,funkshelper/woodcoin-b,JeremyRand/namecoin-core,bitcoinplusorg/xbcwalletsource,jaromil/faircoin2,oklink-dev/bitcoin_block,Mrs-X/PIVX,rromanchuk/bitcoinxt,irvingruan/bitcoin,shelvenzhou/BTCGPU,Alex-van-der-Peet/bitcoin,BitcoinUnlimited/BitcoinUnlimited,benosa/bitcoin,LIMXTEC/DMDv3,jtimon/bitcoin,ShwoognationHQ/bitcoin,leofidus/glowing-octo-ironman,koharjidan/dogecoin,DynamicCoinOrg/DMC,ingresscoin/ingresscoin,meighti/bitcoin,aspanta/bitcoin,svost/bitcoin,Jcing95/iop-hd,presstab/PIVX,hasanatkazmi/bitcoin,Flurbos/Flurbo,kleetus/bitcoinxt,BTCGPU/BTCGPU,GroestlCoin/GroestlCoin,bitcoin/bitcoin,donaloconnor/bitcoin,morcos/bitcoin,CryptArc/bitcoin,truthcoin/blocksize-market,alecalve/bitcoin,cqtenq/feathercoin_core,bankonmecoin/bitcoin,oklink-dev/bitcoin_block,cryptodev35/icash,simdeveloper/bitcoin,untrustbank/litecoin,nathaniel-mahieu/bitcoin,Lucky7Studio/bitcoin,brandonrobertz/namecoin-core,bitcoinec/bitcoinec,AllanDoensen/BitcoinUnlimited,botland/bitcoin,nmarley/dash,cqtenq/feathercoin_core,ctwiz/stardust,jambolo/bitcoin,shaulkf/bitcoin,amaivsimau/bitcoin,nvmd/bitcoin,rromanchuk/bitcoinxt,ravenbyron/phtevencoin,magacoin/magacoin,bdelzell/creditcoin-org-creditcoin,CryptArc/bitcoinxt,reorder/viacoin,Mrs-X/PIVX,willwray/dash,phplaboratory/psiacoin,royosherove/bitcoinxt,Kcoin-project/kcoin,Anoncoin/anoncoin,afk11/bitcoin,experiencecoin/experiencecoin,cybermatatu/bitcoin,aciddude/Feathercoin,vtafaucet/virtacoin,nikkitan/bitcoin,cheehieu/bitcoin,joshrabinowitz/bitcoin,ZiftrCOIN/ziftrcoin,shea256/bitcoin,botland/bitcoin,ravenbyron/phtevencoin,bitpay/bitcoin,PIVX-Project/PIVX,globaltoken/globaltoken,jonghyeopkim/bitcoinxt,lbryio/lbrycrd,Mrs-X/Darknet,Petr-Economissa/gvidon,s-matthew-english/bitcoin,arnuschky/bitcoin,dan-mi-sun/bitcoin,Theshadow4all/ShadowCoin,my-first/octocoin,BTCfork/hardfork_prototype_1_mvf-bu,ticclassic/ic,skaht/bitcoin,lbryio/lbrycrd,worldbit/worldbit,digideskio/namecoin,qtumproject/qtum,jimmykiselak/lbrycrd,sbaks0820/bitcoin,gameunits/gameunits,ajweiss/bitcoin,xuyangcn/opalcoin,janko33bd/bitcoin,JeremyRand/namecore,benma/bitcoin,rdqw/sscoin,MazaCoin/mazacoin-new,fullcoins/fullcoin,Bitcoin-ABC/bitcoin-abc,Kore-Core/kore,BigBlueCeiling/augmentacoin,AdrianaDinca/bitcoin,anditto/bitcoin,RyanLucchese/energi,sipsorcery/bitcoin,wellenreiter01/Feathercoin,domob1812/huntercore,jamesob/bitcoin,bcpki/nonce2,coinkeeper/2015-06-22_18-37_dogecoin,Rav3nPL/doubloons-0.10,BitcoinHardfork/bitcoin,likecoin-dev/bitcoin,welshjf/bitcoin,genavarov/ladacoin,keo/bitcoin,droark/elements,bitcoinsSG/bitcoin,antonio-fr/bitcoin,Alex-van-der-Peet/bitcoin,my-first/octocoin,accraze/bitcoin,ahmedbodi/vertcoin,isocolsky/bitcoinxt,kbccoin/kbc,bitcoin-hivemind/hivemind,gapcoin/gapcoin,21E14/bitcoin,digibyte/digibyte,gravio-net/graviocoin,REAP720801/bitcoin,UdjinM6/dash,Tetpay/bitcoin,Alonzo-Coeus/bitcoin,UASF/bitcoin,aspirecoin/aspire,ElementsProject/elements,maaku/bitcoin,mincoin-project/mincoin,arruah/ensocoin,mastercoin-MSC/mastercore,BitcoinHardfork/bitcoin,wiggi/huntercore,Darknet-Crypto/Darknet,EthanHeilman/bitcoin,bitcoinsSG/bitcoin,prusnak/bitcoin,ajweiss/bitcoin,unsystemizer/bitcoin,MasterX1582/bitcoin-becoin,randy-waterhouse/bitcoin,BitcoinPOW/BitcoinPOW,ppcoin/ppcoin,BlockchainTechLLC/3dcoin,emc2foundation/einsteinium,xieta/mincoin,h4x3rotab/BTCGPU,cdecker/bitcoin,segsignal/bitcoin,rromanchuk/bitcoinxt,xieta/mincoin,DynamicCoinOrg/DMC,jmcorgan/bitcoin,domob1812/bitcoin,deuscoin/deuscoin,blocktrail/bitcoin,Kenwhite23/litecoin,deuscoin/deuscoin,czr5014iph/bitcoin4e,florincoin/florincoin,ArgonToken/ArgonToken,gzuser01/zetacoin-bitcoin,crowning2/dash,krzysztofwos/BitcoinUnlimited,bittylicious/bitcoin,dagurval/bitcoinxt,jambolo/bitcoin,vericoin/vericoin-core,GroestlCoin/bitcoin,Flurbos/Flurbo,ripper234/bitcoin,lbryio/lbrycrd,laudaa/bitcoin,ftrader-bitcoinabc/bitcoin-abc,litecoin-project/litecore-litecoin,andres-root/bitcoinxt,zander/bitcoinclassic,Justaphf/BitcoinUnlimited,dev1972/Satellitecoin,antonio-fr/bitcoin,jl2012/litecoin,zottejos/merelcoin,basicincome/unpcoin-core,gavinandresen/bitcoin-git,genavarov/ladacoin,kallewoof/elements,yenliangl/bitcoin,EntropyFactory/creativechain-core,donaloconnor/bitcoin,Friedbaumer/litecoin,pouta/bitcoin,grumpydevelop/singularity,vtafaucet/virtacoin,Metronotes/bitcoin,EthanHeilman/bitcoin,lbrtcoin/albertcoin,PIVX-Project/PIVX,projectinterzone/ITZ,tdudz/elements,crowning-/dash,brishtiteveja/sherlockcoin,diggcoin/diggcoin,RazorLove/cloaked-octo-spice,gameunits/gameunits,oklink-dev/bitcoin,Rav3nPL/PLNcoin,projectinterzone/ITZ,globaltoken/globaltoken,Ziftr/bitcoin,pinkevich/dash,sebrandon1/bitcoin,jimmysong/bitcoin,bickojima/bitzeny,afk11/bitcoin,jl2012/litecoin,florincoin/florincoin,shaulkf/bitcoin,zetacoin/zetacoin,globaltoken/globaltoken,pstratem/elements,torresalyssa/bitcoin,constantine001/bitcoin,coinkeeper/2015-06-22_18-52_viacoin,1185/starwels,ryanxcharles/bitcoin,truthcoin/truthcoin-cpp,BitcoinHardfork/bitcoin,CodeShark/bitcoin,acid1789/bitcoin,octocoin-project/octocoin,shomeser/bitcoin,RyanLucchese/energi,josephbisch/namecoin-core,wiggi/huntercore,constantine001/bitcoin,Har01d/bitcoin,wangxinxi/litecoin,plncoin/PLNcoin_Core,domob1812/i0coin,Bitcoin-ABC/bitcoin-abc,emc2foundation/einsteinium,bcpki/testblocks,jn2840/bitcoin,karek314/bitcoin,uphold/bitcoin,isghe/bitcoinxt,zenywallet/bitzeny,hasanatkazmi/bitcoin,botland/bitcoin,x-kalux/bitcoin_WiG-B,oklink-dev/bitcoin,ShadowMyst/creativechain-core,Electronic-Gulden-Foundation/egulden,marklai9999/Taiwancoin,emc2foundation/einsteinium,Michagogo/bitcoin,kallewoof/bitcoin,BTCfork/hardfork_prototype_1_mvf-bu,DGCDev/digitalcoin,Cocosoft/bitcoin,domob1812/namecore,Bitcoin-com/BUcash,domob1812/huntercore,ahmedbodi/test2,cerebrus29301/crowncoin,CTRoundTable/Encrypted.Cash,sugruedes/bitcoinxt,loxal/zcash,prark/bitcoinxt,jtimon/elements,putinclassic/putic,kleetus/bitcoinxt,xurantju/bitcoin,cryptoprojects/ultimateonlinecash,credits-currency/credits,meighti/bitcoin,benzmuircroft/REWIRE.io,daveperkins-github/bitcoin-dev,thesoftwarejedi/bitcoin,ahmedbodi/test2,truthcoin/blocksize-market,dogecoin/dogecoin,fullcoins/fullcoin,alejandromgk/Lunar,biblepay/biblepay,domob1812/bitcoin,scippio/bitcoin,nvmd/bitcoin,x-kalux/bitcoin_WiG-B,octocoin-project/octocoin,coinwarp/dogecoin,ptschip/bitcoinxt,dexX7/bitcoin,domob1812/huntercore,cannabiscoindev/cannabiscoin420,sugruedes/bitcoin,cheehieu/bitcoin,putinclassic/putic,arruah/ensocoin,coinkeeper/2015-06-22_18-31_bitcoin,blood2/bloodcoin-0.9,robvanbentem/bitcoin,ivansib/sib16,masterbraz/dg,PIVX-Project/PIVX,ptschip/bitcoin,freelion93/mtucicoin,h4x3rotab/BTCGPU,putinclassic/putic,earonesty/bitcoin,MasterX1582/bitcoin-becoin,error10/bitcoin,domob1812/huntercore,nikkitan/bitcoin,fussl/elements,adpg211/bitcoin-master,kazcw/bitcoin,cyrixhero/bitcoin,rnicoll/dogecoin,BTCfork/hardfork_prototype_1_mvf-bu,trippysalmon/bitcoin,ahmedbodi/temp_vert,lclc/bitcoin,dagurval/bitcoinxt,MazaCoin/mazacoin-new,Rav3nPL/polcoin,pinkevich/dash,ivansib/sib16,pinkevich/dash,arnuschky/bitcoin,coinkeeper/2015-06-22_18-52_viacoin,droark/elements,projectinterzone/ITZ,roques/bitcoin,bcpki/testblocks,bitcoinplusorg/xbcwalletsource,masterbraz/dg,knolza/gamblr,JeremyRand/bitcoin,vertcoin/vertcoin,shaulkf/bitcoin,isle2983/bitcoin,monacoinproject/monacoin,axelxod/braincoin,litecoin-project/litecoin,zotherstupidguy/bitcoin,riecoin/riecoin,ajweiss/bitcoin,robvanbentem/bitcoin,jameshilliard/bitcoin,zander/bitcoinclassic,jonghyeopkim/bitcoinxt,UFOCoins/ufo,coinkeeper/2015-06-22_18-36_darkcoin,sarielsaz/sarielsaz,mincoin-project/mincoin,Darknet-Crypto/Darknet,oleganza/bitcoin-duo,simonmulser/bitcoin,REAP720801/bitcoin,yenliangl/bitcoin,practicalswift/bitcoin,jnewbery/bitcoin,cddjr/BitcoinUnlimited,masterbraz/dg,bitcoin/bitcoin,nathaniel-mahieu/bitcoin,TeamBitBean/bitcoin-core,Kixunil/keynescoin,Earlz/renamedcoin,HashUnlimited/Einsteinium-Unlimited,zcoinofficial/zcoin,Gazer022/bitcoin,Bitcoin-ABC/bitcoin-abc,jrmithdobbs/bitcoin,jtimon/bitcoin,mapineda/litecoin,world-bank/unpay-core,Flowdalic/bitcoin,koharjidan/bitcoin,ftrader-bitcoinunlimited/hardfork_prototype_1_mvf-bu,robvanbentem/bitcoin,Mrs-X/Darknet,Lucky7Studio/bitcoin,inkvisit/sarmacoins,terracoin/terracoin,benzmuircroft/REWIRE.io,phelix/bitcoin,bitcoinec/bitcoinec,SoreGums/bitcoinxt,funbucks/notbitcoinxt,riecoin/riecoin,pinkevich/dash,andreaskern/bitcoin,mobicoins/mobicoin-core,isocolsky/bitcoinxt,aburan28/elements,error10/bitcoin,marlengit/BitcoinUnlimited,ionomy/ion,skaht/bitcoin,globaltoken/globaltoken,ashleyholman/bitcoin,hyperwang/bitcoin,destenson/bitcoin--bitcoin,goldcoin/goldcoin,dan-mi-sun/bitcoin,amaivsimau/bitcoin,111t8e/bitcoin,sbellem/bitcoin,balajinandhu/bitcoin,Michagogo/bitcoin,aniemerg/zcash,benma/bitcoin,koharjidan/litecoin,deeponion/deeponion,roques/bitcoin,bitcoin/bitcoin,jn2840/bitcoin,npccoin/npccoin,langerhans/dogecoin,gravio-net/graviocoin,vericoin/vericoin-core,pastday/bitcoinproject,elliotolds/bitcoin,benzmuircroft/REWIRE.io,mycointest/owncoin,elliotolds/bitcoin,phplaboratory/psiacoin,gjhiggins/vcoincore,funkshelper/woodcore,cyrixhero/bitcoin,yenliangl/bitcoin,mikehearn/bitcoinxt,DGCDev/digitalcoin,domob1812/namecore,ekankyesme/bitcoinxt,ahmedbodi/temp_vert,Exceltior/dogecoin,langerhans/dogecoin,Jeff88Ho/bitcoin,bmp02050/ReddcoinUpdates,mrbandrews/bitcoin,truthcoin/blocksize-market,paveljanik/bitcoin,faircoin/faircoin2,marklai9999/Taiwancoin,se3000/bitcoin,lbrtcoin/albertcoin,thelazier/dash,fanquake/bitcoin,bittylicious/bitcoin,GwangJin/gwangmoney-core,vtafaucet/virtacoin,Kcoin-project/kcoin,bitcoin-hivemind/hivemind,dashpay/dash,RongxinZhang/bitcoinxt,kevcooper/bitcoin,antonio-fr/bitcoin,pascalguru/florincoin,GroestlCoin/GroestlCoin,UFOCoins/ufo,vlajos/bitcoin,benosa/bitcoin,biblepay/biblepay,UASF/bitcoin,gravio-net/graviocoin,neuroidss/bitcoin,sirk390/bitcoin,earonesty/bitcoin,CoinProjects/AmsterdamCoin-v4,stamhe/bitcoin,XertroV/bitcoin-nulldata,Metronotes/bitcoin,ahmedbodi/test2,gazbert/bitcoin,GroestlCoin/bitcoin,bitpay/bitcoin,shaolinfry/litecoin,xurantju/bitcoin,sbellem/bitcoin,mb300sd/bitcoin,achow101/bitcoin,gazbert/bitcoin,OmniLayer/omnicore,neuroidss/bitcoin,lbrtcoin/albertcoin,untrustbank/litecoin,fsb4000/bitcoin,FarhanHaque/bitcoin,hyperwang/bitcoin,prark/bitcoinxt,segwit/atbcoin-insight,marcusdiaz/BitcoinUnlimited,r8921039/bitcoin,mrbandrews/bitcoin,2XL/bitcoin,174high/bitcoin,brishtiteveja/truthcoin-cpp,bcpki/testblocks,appop/bitcoin,HashUnlimited/Einsteinium-Unlimited,nightlydash/darkcoin,sbellem/bitcoin,segsignal/bitcoin,XertroV/bitcoin-nulldata,dannyperez/bolivarcoin,crowning-/dash,terracoin/terracoin,zander/bitcoinclassic,wbchen99/bitcoin-hnote0,psionin/smartcoin,NunoEdgarGub1/elements,koharjidan/dogecoin,BTCfork/hardfork_prototype_1_mvf-bu,haobtc/bitcoin,blood2/bloodcoin-0.9,supcoin/supcoin,BTCGPU/BTCGPU,domob1812/namecore,royosherove/bitcoinxt,btc1/bitcoin,particl/particl-core,ivansib/sibcoin,BitcoinHardfork/bitcoin,djpnewton/bitcoin,RHavar/bitcoin,funbucks/notbitcoinxt,fedoracoin-dev/fedoracoin,Gazer022/bitcoin,oklink-dev/bitcoin_block,DMDcoin/Diamond,destenson/bitcoin--bitcoin,freelion93/mtucicoin,stamhe/bitcoin,Kogser/bitcoin,mitchellcash/bitcoin,florincoin/florincoin,JeremyRubin/bitcoin,ahmedbodi/vertcoin,gmaxwell/bitcoin,trippysalmon/bitcoin,joulecoin/joulecoin,bitbrazilcoin-project/bitbrazilcoin,nomnombtc/bitcoin,gandrewstone/BitcoinUnlimited,NateBrune/bitcoin-fio,oklink-dev/bitcoin_block,amaivsimau/bitcoin,Cocosoft/bitcoin,wederw/bitcoin,JeremyRand/namecore,coinwarp/dogecoin,jakeva/bitcoin-pwcheck,bitcoinclassic/bitcoinclassic,coinerd/krugercoin,ftrader-bitcoinabc/bitcoin-abc,irvingruan/bitcoin,wiggi/huntercore,dscotese/bitcoin,CryptArc/bitcoin,oleganza/bitcoin-duo,welshjf/bitcoin,capitalDIGI/litecoin,sipa/elements,morcos/bitcoin,Michagogo/bitcoin,hsavit1/bitcoin,ravenbyron/phtevencoin,Bloom-Project/Bloom,likecoin-dev/bitcoin,Vsync-project/Vsync,bitcoinxt/bitcoinxt,Ziftr/bitcoin,GlobalBoost/GlobalBoost,kaostao/bitcoin,afk11/bitcoin,m0gliE/fastcoin-cli,2XL/bitcoin,myriadcoin/myriadcoin,jmcorgan/bitcoin,ionomy/ion,habibmasuro/bitcoin,TGDiamond/Diamond,mruddy/bitcoin,nailtaras/nailcoin,blocktrail/bitcoin,Jcing95/iop-hd,haobtc/bitcoin,gavinandresen/bitcoin-git,guncoin/guncoin,dpayne9000/Rubixz-Coin,prark/bitcoinxt,KnCMiner/bitcoin,rnicoll/dogecoin,mycointest/owncoin,Rav3nPL/PLNcoin,mastercoin-MSC/mastercore,DMDcoin/Diamond,21E14/bitcoin,gwillen/elements,nightlydash/darkcoin,elecoin/elecoin,karek314/bitcoin,ludbb/bitcoin,tdudz/elements,tropa/axecoin,Bushstar/UFO-Project,reddcoin-project/reddcoin,kaostao/bitcoin,adpg211/bitcoin-master,nailtaras/nailcoin,fedoracoin-dev/fedoracoin,Kogser/bitcoin,arnuschky/bitcoin,GroestlCoin/bitcoin,domob1812/namecore,marcusdiaz/BitcoinUnlimited,OstlerDev/florincoin,omefire/bitcoin,wangxinxi/litecoin,knolza/gamblr,robvanbentem/bitcoin,48thct2jtnf/P,Rav3nPL/doubloons-0.10,syscoin/syscoin2,emc2foundation/einsteinium,RongxinZhang/bitcoinxt,funbucks/notbitcoinxt,gjhiggins/vcoincore,florincoin/florincoin,karek314/bitcoin,butterflypay/bitcoin,DGCDev/argentum,ftrader-bitcoinabc/bitcoin-abc,DSPay/DSPay,coinkeeper/2015-06-22_18-39_feathercoin,denverl/bitcoin,Kangmo/bitcoin,pstratem/bitcoin,mockcoin/mockcoin,ivansib/sibcoin,fujicoin/fujicoin,puticcoin/putic,spiritlinxl/BTCGPU,zsulocal/bitcoin,afk11/bitcoin,riecoin/riecoin,funkshelper/woodcore,bitcoinknots/bitcoin,simonmulser/bitcoin,dogecoin/dogecoin,jmgilbert2/energi,myriadteam/myriadcoin,irvingruan/bitcoin,daveperkins-github/bitcoin-dev,NateBrune/bitcoin-nate,supcoin/supcoin,Darknet-Crypto/Darknet,NunoEdgarGub1/elements,wederw/bitcoin,bitpay/bitcoin,ClusterCoin/ClusterCoin,coinkeeper/2015-06-22_18-31_bitcoin,antcheck/antcoin,GwangJin/gwangmoney-core,shaolinfry/litecoin,ryanofsky/bitcoin,irvingruan/bitcoin,btcdrak/bitcoin,pinheadmz/bitcoin,r8921039/bitcoin,dcousens/bitcoin,BitcoinUnlimited/BitcoinUnlimited,MonetaryUnit/MUE-Src,TBoehm/greedynode,petertodd/bitcoin,Thracky/monkeycoin,plncoin/PLNcoin_Core,sdaftuar/bitcoin,sstone/bitcoin,thelazier/dash,ardsu/bitcoin,ixcoinofficialpage/master,bcpki/nonce2,djpnewton/bitcoin,zottejos/merelcoin,oklink-dev/bitcoin_block,phelix/bitcoin,axelxod/braincoin,shomeser/bitcoin,bankonmecoin/bitcoin,PandaPayProject/PandaPay,Thracky/monkeycoin,loxal/zcash,thesoftwarejedi/bitcoin,bcpki/nonce2testblocks,psionin/smartcoin,aniemerg/zcash,wtogami/bitcoin,Lucky7Studio/bitcoin,nikkitan/bitcoin,CTRoundTable/Encrypted.Cash,dperel/bitcoin,atgreen/bitcoin,shouhuas/bitcoin,Bitcoin-ABC/bitcoin-abc,keesdewit82/LasVegasCoin,Vector2000/bitcoin,kallewoof/elements,1185/starwels,tjps/bitcoin,thesoftwarejedi/bitcoin,Har01d/bitcoin,coinkeeper/2015-06-22_18-52_viacoin,djpnewton/bitcoin,uphold/bitcoin,isle2983/bitcoin,BitcoinPOW/BitcoinPOW,crowning2/dash,m0gliE/fastcoin-cli,XertroV/bitcoin-nulldata,ShadowMyst/creativechain-core,irvingruan/bitcoin,instagibbs/bitcoin,ediston/energi,shelvenzhou/BTCGPU,inkvisit/sarmacoins,neuroidss/bitcoin,initaldk/bitcoin,robvanbentem/bitcoin,BitzenyCoreDevelopers/bitzeny,tropa/axecoin,brishtiteveja/truthcoin-cpp,BTCDDev/bitcoin,plncoin/PLNcoin_Core,jameshilliard/bitcoin,KaSt/ekwicoin,dexX7/mastercore,argentumproject/argentum,CTRoundTable/Encrypted.Cash,amaivsimau/bitcoin,genavarov/brcoin,capitalDIGI/DIGI-v-0-10-4,tjth/lotterycoin,coinkeeper/2015-06-22_19-00_ziftrcoin,nlgcoin/guldencoin-official,40thoughts/Coin-QualCoin,KibiCoin/kibicoin,mm-s/bitcoin,mockcoin/mockcoin,hophacker/bitcoin_malleability,spiritlinxl/BTCGPU,gameunits/gameunits,tecnovert/particl-core,dpayne9000/Rubixz-Coin,zixan/bitcoin,segsignal/bitcoin,gjhiggins/vcoincore,faircoin/faircoin,Bitcoin-ABC/bitcoin-abc,mruddy/bitcoin,thesoftwarejedi/bitcoin,MarcoFalke/bitcoin,Cloudsy/bitcoin,acid1789/bitcoin,rjshaver/bitcoin,rebroad/bitcoin,Har01d/bitcoin,2XL/bitcoin,faircoin/faircoin,pstratem/elements,fsb4000/bitcoin,nsacoin/nsacoin,Chancoin-core/CHANCOIN,loxal/zcash,unsystemizer/bitcoin,jlopp/statoshi,presstab/PIVX,jimmysong/bitcoin,CTRoundTable/Encrypted.Cash,martindale/elements,yenliangl/bitcoin,particl/particl-core,brandonrobertz/namecoin-core,slingcoin/sling-market,shomeser/bitcoin,florincoin/florincoin,kevcooper/bitcoin,Friedbaumer/litecoin,apoelstra/bitcoin,chaincoin/chaincoin,odemolliens/bitcoinxt,atgreen/bitcoin,TeamBitBean/bitcoin-core,martindale/elements,jmcorgan/bitcoin,SartoNess/BitcoinUnlimited,tropa/axecoin,dan-mi-sun/bitcoin,krzysztofwos/BitcoinUnlimited,nathan-at-least/zcash,2XL/bitcoin,isghe/bitcoinxt,Lucky7Studio/bitcoin,OstlerDev/florincoin,Anoncoin/anoncoin,gzuser01/zetacoin-bitcoin,aspanta/bitcoin,Rav3nPL/bitcoin,sirk390/bitcoin,benzmuircroft/REWIRE.io,zsulocal/bitcoin,zenywallet/bitzeny,ionomy/ion,antonio-fr/bitcoin,presstab/PIVX,segsignal/bitcoin,SartoNess/BitcoinUnlimited,deuscoin/deuscoin,BTCDDev/bitcoin,awemany/BitcoinUnlimited,litecoin-project/litecoin,Thracky/monkeycoin,btcdrak/bitcoin,Flowdalic/bitcoin,Krellan/bitcoin,vcoin-project/vcoincore,CryptArc/bitcoin,stevemyers/bitcoinxt,40thoughts/Coin-QualCoin,funkshelper/woodcore,multicoins/marycoin,Rav3nPL/polcoin,sugruedes/bitcoin,npccoin/npccoin,kaostao/bitcoin,cqtenq/feathercoin_core,xuyangcn/opalcoin,cmgustavo/bitcoin,marlengit/BitcoinUnlimited,arruah/ensocoin,jrmithdobbs/bitcoin,mycointest/owncoin,Rav3nPL/PLNcoin,phplaboratory/psiacoin,syscoin/syscoin,faircoin/faircoin,Alex-van-der-Peet/bitcoin,xawksow/GroestlCoin,hasanatkazmi/bitcoin,Exceltior/dogecoin,untrustbank/litecoin,peercoin/peercoin,CryptArc/bitcoinxt,josephbisch/namecoin-core,awemany/BitcoinUnlimited,KnCMiner/bitcoin,aspirecoin/aspire,cerebrus29301/crowncoin,pstratem/bitcoin,iosdevzone/bitcoin,jiangyonghang/bitcoin,bitcoinec/bitcoinec,thormuller/yescoin2,segwit/atbcoin-insight,kleetus/bitcoinxt,droark/elements,r8921039/bitcoin,blocktrail/bitcoin,spiritlinxl/BTCGPU,particl/particl-core,bitcoin/bitcoin,koharjidan/dogecoin,jn2840/bitcoin,reddcoin-project/reddcoin,reddink/reddcoin,thrasher-/litecoin,truthcoin/truthcoin-cpp,Xekyo/bitcoin,Bloom-Project/Bloom,UdjinM6/dash,nikkitan/bitcoin,aniemerg/zcash,PandaPayProject/PandaPay,jeromewu/bitcoin-opennet,scmorse/bitcoin,gwillen/elements,brishtiteveja/sherlockcoin,lbrtcoin/albertcoin,stamhe/bitcoin,crowning-/dash,pinkevich/dash,kirkalx/bitcoin,MasterX1582/bitcoin-becoin,schildbach/bitcoin,greenaddress/bitcoin,pinkevich/dash,arruah/ensocoin,dagurval/bitcoinxt,namecoin/namecore,bitcoin/bitcoin,bitreserve/bitcoin,MeshCollider/bitcoin,genavarov/brcoin,pelorusjack/BlockDX,matlongsi/micropay,torresalyssa/bitcoin,jameshilliard/bitcoin,petertodd/bitcoin,capitalDIGI/litecoin,xuyangcn/opalcoin,ixcoinofficialpage/master,bitcoinxt/bitcoinxt,dperel/bitcoin,jimmysong/bitcoin,royosherove/bitcoinxt,CryptArc/bitcoinxt,welshjf/bitcoin,xuyangcn/opalcoin,ahmedbodi/vertcoin,apoelstra/elements,cmgustavo/bitcoin,Cloudsy/bitcoin,Chancoin-core/CHANCOIN,wcwu/bitcoin,mm-s/bitcoin,martindale/elements,pascalguru/florincoin,NicolasDorier/bitcoin,coinkeeper/2015-06-22_19-07_digitalcoin,ryanxcharles/bitcoin,scippio/bitcoin,Electronic-Gulden-Foundation/egulden,Bitcoin-com/BUcash,jambolo/bitcoin,meighti/bitcoin,tuaris/bitcoin,odemolliens/bitcoinxt,chaincoin/chaincoin,JeremyRand/bitcoin,oleganza/bitcoin-duo,DogTagRecon/Still-Leraning,Jcing95/iop-hd,likecoin-dev/bitcoin,argentumproject/argentum,haobtc/bitcoin,s-matthew-english/bitcoin,brandonrobertz/namecoin-core,jamesob/bitcoin,pataquets/namecoin-core,ryanxcharles/bitcoin,cdecker/bitcoin,oklink-dev/bitcoin,rawodb/bitcoin,sickpig/BitcoinUnlimited,1185/starwels,SoreGums/bitcoinxt,ftrader-bitcoinabc/bitcoin-abc,DGCDev/digitalcoin,MazaCoin/mazacoin-new,qtumproject/qtum,rawodb/bitcoin,core-bitcoin/bitcoin,Xekyo/bitcoin,pastday/bitcoinproject,alecalve/bitcoin,CryptArc/bitcoinxt,shouhuas/bitcoin,error10/bitcoin,bitcoinclassic/bitcoinclassic,octocoin-project/octocoin,Kenwhite23/litecoin,omefire/bitcoin,btc1/bitcoin,mruddy/bitcoin,Cocosoft/bitcoin,dgenr8/bitcoin,se3000/bitcoin,myriadcoin/myriadcoin,NateBrune/bitcoin-nate,ericshawlinux/bitcoin,sugruedes/bitcoin,wangxinxi/litecoin,error10/bitcoin,Friedbaumer/litecoin,worldbit/worldbit,prusnak/bitcoin,imharrywu/fastcoin,aciddude/Feathercoin,PandaPayProject/PandaPay,bitcoinsSG/zcash,ryanxcharles/bitcoin,ravenbyron/phtevencoin,habibmasuro/bitcoinxt,misdess/bitcoin,ardsu/bitcoin,marlengit/BitcoinUnlimited,coinerd/krugercoin,MeshCollider/bitcoin,MikeAmy/bitcoin,bitcoinsSG/zcash,phelix/bitcoin,Domer85/dogecoin,pataquets/namecoin-core,Rav3nPL/bitcoin,21E14/bitcoin,zcoinofficial/zcoin,GreenParhelia/bitcoin,practicalswift/bitcoin,FinalHashLLC/namecore,deadalnix/bitcoin,atgreen/bitcoin,benma/bitcoin,genavarov/lamacoin,jlopp/statoshi,capitalDIGI/litecoin,NunoEdgarGub1/elements,shea256/bitcoin,KaSt/ekwicoin,syscoin/syscoin2,vmp32k/litecoin,truthcoin/truthcoin-cpp,ftrader-bitcoinunlimited/hardfork_prototype_1_mvf-bu,ptschip/bitcoinxt,riecoin/riecoin,zotherstupidguy/bitcoin,itmanagerro/tresting,sarielsaz/sarielsaz,ahmedbodi/terracoin,m0gliE/fastcoin-cli,cculianu/bitcoin-abc,accraze/bitcoin,rsdevgun16e/energi,arnuschky/bitcoin,habibmasuro/bitcoin,trippysalmon/bitcoin,Flurbos/Flurbo,wangxinxi/litecoin,gandrewstone/bitcoinxt,genavarov/brcoin,pataquets/namecoin-core,111t8e/bitcoin,sstone/bitcoin,cheehieu/bitcoin,dscotese/bitcoin,oleganza/bitcoin-duo,butterflypay/bitcoin,sstone/bitcoin,sbaks0820/bitcoin,domob1812/i0coin,puticcoin/putic,SoreGums/bitcoinxt,ajtowns/bitcoin,metacoin/florincoin,reorder/viacoin,haraldh/bitcoin,Anfauglith/iop-hd,Ziftr/bitcoin,kevcooper/bitcoin,meighti/bitcoin,ryanofsky/bitcoin,MazaCoin/mazacoin-new,Kangmo/bitcoin,skaht/bitcoin,superjudge/bitcoin,bitcoinknots/bitcoin,HashUnlimited/Einsteinium-Unlimited,TGDiamond/Diamond,kazcw/bitcoin,ClusterCoin/ClusterCoin,ediston/energi,svost/bitcoin,jonasschnelli/bitcoin,ZiftrCOIN/ziftrcoin,segwit/atbcoin-insight,BitzenyCoreDevelopers/bitzeny,syscoin/syscoin,freelion93/mtucicoin,rnicoll/dogecoin,mb300sd/bitcoin,cqtenq/feathercoin_core,starwels/starwels,fanquake/bitcoin,xurantju/bitcoin,EthanHeilman/bitcoin,wangxinxi/litecoin,UASF/bitcoin,Bitcoin-com/BUcash,irvingruan/bitcoin,basicincome/unpcoin-core,UASF/bitcoin,knolza/gamblr,GwangJin/gwangmoney-core,sickpig/BitcoinUnlimited,nathan-at-least/zcash,ahmedbodi/terracoin,jonghyeopkim/bitcoinxt,achow101/bitcoin,sipa/elements,fsb4000/bitcoin,DynamicCoinOrg/DMC,koharjidan/litecoin,namecoin/namecoin-core,starwels/starwels,hsavit1/bitcoin,bitcoinknots/bitcoin,martindale/elements,BitcoinPOW/BitcoinPOW,RongxinZhang/bitcoinxt,nomnombtc/bitcoin,benma/bitcoin,namecoin/namecore,GIJensen/bitcoin,SartoNess/BitcoinUnlimited,PandaPayProject/PandaPay,ftrader-bitcoinabc/bitcoin-abc,torresalyssa/bitcoin,worldbit/worldbit,PRabahy/bitcoin,vtafaucet/virtacoin,biblepay/biblepay,mrbandrews/bitcoin,marcusdiaz/BitcoinUnlimited,sipsorcery/bitcoin,NateBrune/bitcoin-fio,DSPay/DSPay,mm-s/bitcoin,initaldk/bitcoin,ericshawlinux/bitcoin,rnicoll/bitcoin,cannabiscoindev/cannabiscoin420,wbchen99/bitcoin-hnote0,jamesob/bitcoin,sipsorcery/bitcoin,ahmedbodi/temp_vert,zotherstupidguy/bitcoin,dannyperez/bolivarcoin,simonmulser/bitcoin,NunoEdgarGub1/elements,habibmasuro/bitcoin,domob1812/bitcoin,psionin/smartcoin,ivansib/sib16,RibbitFROG/ribbitcoin,Friedbaumer/litecoin,worldbit/worldbit,ColossusCoinXT/ColossusCoinXT,mitchellcash/bitcoin,josephbisch/namecoin-core,ctwiz/stardust,CodeShark/bitcoin,pinheadmz/bitcoin,vcoin-project/vcoincore,vertcoin/vertcoin,cdecker/bitcoin,credits-currency/credits,Lucky7Studio/bitcoin,balajinandhu/bitcoin,simonmulser/bitcoin,AkioNak/bitcoin,BitcoinUnlimited/BitcoinUnlimited,bitcoinplusorg/xbcwalletsource,koharjidan/bitcoin,DynamicCoinOrg/DMC,diggcoin/diggcoin,ludbb/bitcoin,Rav3nPL/PLNcoin,coinkeeper/2015-06-22_18-31_bitcoin,botland/bitcoin,reddcoin-project/reddcoin,TrainMAnB/vcoincore,LIMXTEC/DMDv3,bitcoinknots/bitcoin,fujicoin/fujicoin,RibbitFROG/ribbitcoin,dpayne9000/Rubixz-Coin,ludbb/bitcoin,Friedbaumer/litecoin,Electronic-Gulden-Foundation/egulden,rat4/bitcoin,paveljanik/bitcoin,jambolo/bitcoin,dperel/bitcoin,Bitcoin-ABC/bitcoin-abc,cculianu/bitcoin-abc,upgradeadvice/MUE-Src,174high/bitcoin,jimmykiselak/lbrycrd,coinerd/krugercoin,fedoracoin-dev/fedoracoin,shelvenzhou/BTCGPU,domob1812/i0coin,gandrewstone/bitcoinxt,coinerd/krugercoin,ericshawlinux/bitcoin,guncoin/guncoin,argentumproject/argentum,syscoin/syscoin2,terracoin/terracoin,dpayne9000/Rubixz-Coin,reorder/viacoin,dev1972/Satellitecoin,AdrianaDinca/bitcoin,grumpydevelop/singularity,Mirobit/bitcoin,stevemyers/bitcoinxt,patricklodder/dogecoin,wangliu/bitcoin,fussl/elements,core-bitcoin/bitcoin,skaht/bitcoin,kallewoof/elements,ArgonToken/ArgonToken,zixan/bitcoin,TeamBitBean/bitcoin-core,bitcoin-hivemind/hivemind,butterflypay/bitcoin,genavarov/brcoin,s-matthew-english/bitcoin,tjps/bitcoin,svost/bitcoin,Bitcoinsulting/bitcoinxt,qtumproject/qtum,sdaftuar/bitcoin,Earlz/renamedcoin,Electronic-Gulden-Foundation/egulden,inkvisit/sarmacoins,bespike/litecoin,tuaris/bitcoin,cybermatatu/bitcoin,josephbisch/namecoin-core,cybermatatu/bitcoin,thrasher-/litecoin,stamhe/bitcoin,OmniLayer/omnicore,cdecker/bitcoin,yenliangl/bitcoin,dan-mi-sun/bitcoin,goldcoin/Goldcoin-GLD,UdjinM6/dash,dcousens/bitcoin,jameshilliard/bitcoin,ctwiz/stardust,RibbitFROG/ribbitcoin,vlajos/bitcoin,xuyangcn/opalcoin,BTCGPU/BTCGPU,rsdevgun16e/energi,BigBlueCeiling/augmentacoin,deadalnix/bitcoin,gapcoin/gapcoin,Mirobit/bitcoin,balajinandhu/bitcoin,czr5014iph/bitcoin4e,jrick/bitcoin,misdess/bitcoin,error10/bitcoin,gazbert/bitcoin,gandrewstone/BitcoinUnlimited,supcoin/supcoin,bitcoinsSG/bitcoin,nmarley/dash,Ziftr/bitcoin,rnicoll/dogecoin,h4x3rotab/BTCGPU,ptschip/bitcoinxt,digibyte/digibyte,tjps/bitcoin,genavarov/ladacoin,MeshCollider/bitcoin,TheBlueMatt/bitcoin,bitcoinplusorg/xbcwalletsource,deadalnix/bitcoin,bitcoinxt/bitcoinxt,keo/bitcoin,isghe/bitcoinxt,nigeriacoin/nigeriacoin,HashUnlimited/Einsteinium-Unlimited,cannabiscoindev/cannabiscoin420,bitreserve/bitcoin,BlockchainTechLLC/3dcoin,metacoin/florincoin,Chancoin-core/CHANCOIN,marcusdiaz/BitcoinUnlimited,wiggi/huntercore,stamhe/bitcoin,okinc/bitcoin,Petr-Economissa/gvidon,fanquake/bitcoin,isghe/bitcoinxt,drwasho/bitcoinxt,Gazer022/bitcoin,BTCGPU/BTCGPU,DogTagRecon/Still-Leraning,Kogser/bitcoin,simdeveloper/bitcoin,blood2/bloodcoin-0.9,wellenreiter01/Feathercoin,Diapolo/bitcoin,dashpay/dash,dperel/bitcoin,sbaks0820/bitcoin,MarcoFalke/bitcoin,oklink-dev/bitcoin,donaloconnor/bitcoin,nvmd/bitcoin,genavarov/ladacoin,scippio/bitcoin,TheBlueMatt/bitcoin,zcoinofficial/zcoin,emc2foundation/einsteinium,Bitcoin-com/BUcash,Exceltior/dogecoin,RHavar/bitcoin,syscoin/syscoin,EntropyFactory/creativechain-core,bitjson/hivemind,xieta/mincoin,jakeva/bitcoin-pwcheck,nsacoin/nsacoin,likecoin-dev/bitcoin,Vsync-project/Vsync,DigitalPandacoin/pandacoin,zcoinofficial/zcoin,isghe/bitcoinxt,Cloudsy/bitcoin,cculianu/bitcoin-abc,djpnewton/bitcoin,MeshCollider/bitcoin,prusnak/bitcoin,hophacker/bitcoin_malleability,HeliumGas/helium,isle2983/bitcoin,romanornr/viacoin,axelxod/braincoin,dannyperez/bolivarcoin,PIVX-Project/PIVX,dgarage/bc3,ahmedbodi/vertcoin,dev1972/Satellitecoin,vcoin-project/vcoincore,Cocosoft/bitcoin,HeliumGas/helium,phelix/bitcoin,joulecoin/joulecoin,bitcoinsSG/bitcoin,earonesty/bitcoin,chaincoin/chaincoin,faircoin/faircoin,crowning2/dash,wtogami/bitcoin,butterflypay/bitcoin,alecalve/bitcoin,tmagik/catcoin,ediston/energi,blocktrail/bitcoin,Kangmo/bitcoin,cotner/bitcoin,cculianu/bitcoin-abc,mb300sd/bitcoin,LIMXTEC/DMDv3,40thoughts/Coin-QualCoin,ripper234/bitcoin,krzysztofwos/BitcoinUnlimited,Rav3nPL/doubloons-0.10,jeromewu/bitcoin-opennet,ClusterCoin/ClusterCoin,koharjidan/dogecoin,isocolsky/bitcoinxt,AdrianaDinca/bitcoin,111t8e/bitcoin,initaldk/bitcoin,deeponion/deeponion,jl2012/litecoin,Alex-van-der-Peet/bitcoin,jimmysong/bitcoin,GreenParhelia/bitcoin,fullcoins/fullcoin,butterflypay/bitcoin,48thct2jtnf/P,pataquets/namecoin-core,vcoin-project/vcoincore,FarhanHaque/bitcoin,bitbrazilcoin-project/bitbrazilcoin,crowning-/dash,upgradeadvice/MUE-Src,dannyperez/bolivarcoin,braydonf/bitcoin,mikehearn/bitcoinxt,inutoshi/inutoshi,instagibbs/bitcoin,ahmedbodi/terracoin,bitreserve/bitcoin,mikehearn/bitcoinxt,Anfauglith/iop-hd,coinkeeper/2015-06-22_18-36_darkcoin,vericoin/vericoin-core,llluiop/bitcoin,nvmd/bitcoin,theuni/bitcoin,morcos/bitcoin,rdqw/sscoin,wangliu/bitcoin,sstone/bitcoin,DynamicCoinOrg/DMC,GreenParhelia/bitcoin,janko33bd/bitcoin,awemany/BitcoinUnlimited,BlockchainTechLLC/3dcoin,bdelzell/creditcoin-org-creditcoin,GroestlCoin/bitcoin,wbchen99/bitcoin-hnote0,midnight-miner/LasVegasCoin,xawksow/GroestlCoin,bittylicious/bitcoin,dcousens/bitcoin,Electronic-Gulden-Foundation/egulden,48thct2jtnf/P,funkshelper/woodcore,presstab/PIVX,particl/particl-core,TeamBitBean/bitcoin-core,jiangyonghang/bitcoin,ftrader-bitcoinunlimited/hardfork_prototype_1_mvf-bu,jiangyonghang/bitcoin,wbchen99/bitcoin-hnote0,REAP720801/bitcoin,credits-currency/credits,globaltoken/globaltoken,s-matthew-english/bitcoin,NicolasDorier/bitcoin,karek314/bitcoin,dpayne9000/Rubixz-Coin,kallewoof/bitcoin,roques/bitcoin,lclc/bitcoin,tdudz/elements,aburan28/elements,RongxinZhang/bitcoinxt,elliotolds/bitcoin,KaSt/ekwicoin,kleetus/bitcoin,sebrandon1/bitcoin,Anfauglith/iop-hd,wangxinxi/litecoin,biblepay/biblepay,dscotese/bitcoin,spiritlinxl/BTCGPU,syscoin/syscoin,myriadteam/myriadcoin,midnight-miner/LasVegasCoin,jl2012/litecoin,Earlz/renamedcoin,core-bitcoin/bitcoin,ShadowMyst/creativechain-core,sdaftuar/bitcoin,chaincoin/chaincoin,leofidus/glowing-octo-ironman,basicincome/unpcoin-core,patricklodder/dogecoin,jtimon/elements,odemolliens/bitcoinxt,funkshelper/woodcoin-b,CodeShark/bitcoin,xawksow/GroestlCoin,SartoNess/BitcoinUnlimited,initaldk/bitcoin,nailtaras/nailcoin,credits-currency/credits,leofidus/glowing-octo-ironman,jimmykiselak/lbrycrd,qtumproject/qtum,coinkeeper/2015-06-22_19-00_ziftrcoin,Diapolo/bitcoin,OstlerDev/florincoin,janko33bd/bitcoin,goldcoin/Goldcoin-GLD,gzuser01/zetacoin-bitcoin,sugruedes/bitcoinxt,upgradeadvice/MUE-Src,ekankyesme/bitcoinxt,peercoin/peercoin,drwasho/bitcoinxt,rromanchuk/bitcoinxt,achow101/bitcoin,11755033isaprimenumber/Feathercoin,Michagogo/bitcoin,laudaa/bitcoin,nbenoit/bitcoin,pstratem/elements,romanornr/viacoin,joshrabinowitz/bitcoin,MarcoFalke/bitcoin,error10/bitcoin,mapineda/litecoin,XertroV/bitcoin-nulldata,Bloom-Project/Bloom,neuroidss/bitcoin,rnicoll/dogecoin,11755033isaprimenumber/Feathercoin,kleetus/bitcoin,shea256/bitcoin,ElementsProject/elements,40thoughts/Coin-QualCoin,BTCTaras/bitcoin,BlockchainTechLLC/3dcoin,Sjors/bitcoin,ajweiss/bitcoin,hyperwang/bitcoin,willwray/dash,bickojima/bitzeny,BTCDDev/bitcoin,bitcoinclassic/bitcoinclassic,ColossusCoinXT/ColossusCoinXT,keo/bitcoin,coinkeeper/2015-06-22_19-00_ziftrcoin,HeliumGas/helium,plncoin/PLNcoin_Core,iosdevzone/bitcoin,zander/bitcoinclassic,patricklodder/dogecoin,kleetus/bitcoin,sugruedes/bitcoin,kazcw/bitcoin,MazaCoin/mazacoin-new,sdaftuar/bitcoin,DigitalPandacoin/pandacoin,rat4/bitcoin,Vector2000/bitcoin,antonio-fr/bitcoin,gwillen/elements,jaromil/faircoin2,nightlydash/darkcoin,earonesty/bitcoin,karek314/bitcoin,stamhe/bitcoin,magacoin/magacoin,GlobalBoost/GlobalBoost,krzysztofwos/BitcoinUnlimited,Ziftr/bitcoin,daliwangi/bitcoin,gmaxwell/bitcoin,elliotolds/bitcoin,BTCTaras/bitcoin,pinheadmz/bitcoin,viacoin/viacoin,nomnombtc/bitcoin,starwels/starwels,yenliangl/bitcoin,GIJensen/bitcoin,tuaris/bitcoin,ekankyesme/bitcoinxt,coinkeeper/2015-06-22_18-52_viacoin,coinkeeper/2015-06-22_19-07_digitalcoin,gavinandresen/bitcoin-git,NicolasDorier/bitcoin,marlengit/hardfork_prototype_1_mvf-bu,kazcw/bitcoin,Earlz/renamedcoin,Christewart/bitcoin,ingresscoin/ingresscoin,GroestlCoin/bitcoin,truthcoin/blocksize-market,BTCfork/hardfork_prototype_1_mvf-core,MonetaryUnit/MUE-Src,ivansib/sibcoin,dscotese/bitcoin,TeamBitBean/bitcoin-core,Sjors/bitcoin,denverl/bitcoin,vmp32k/litecoin,aspirecoin/aspire,Flowdalic/bitcoin,theuni/bitcoin,hyperwang/bitcoin,keesdewit82/LasVegasCoin,ptschip/bitcoin,Christewart/bitcoin,Bushstar/UFO-Project,ZiftrCOIN/ziftrcoin,okinc/bitcoin,JeremyRand/namecore,mincoin-project/mincoin,sipsorcery/bitcoin,DSPay/DSPay,segwit/atbcoin-insight,ryanxcharles/bitcoin,ionomy/ion,ftrader-bitcoinabc/bitcoin-abc,plncoin/PLNcoin_Core,174high/bitcoin,bdelzell/creditcoin-org-creditcoin,mrbandrews/bitcoin,OmniLayer/omnicore,patricklodder/dogecoin,shelvenzhou/BTCGPU,RHavar/bitcoin,daveperkins-github/bitcoin-dev,pouta/bitcoin,domob1812/i0coin,zsulocal/bitcoin,dcousens/bitcoin,marlengit/hardfork_prototype_1_mvf-bu,zixan/bitcoin,omefire/bitcoin,kallewoof/bitcoin,OstlerDev/florincoin,nmarley/dash,Anoncoin/anoncoin,coinwarp/dogecoin,GIJensen/bitcoin,cryptoprojects/ultimateonlinecash,CryptArc/bitcoin,ticclassic/ic,scippio/bitcoin,florincoin/florincoin,Mirobit/bitcoin,maaku/bitcoin,coinkeeper/2015-06-22_18-37_dogecoin,Mrs-X/PIVX,langerhans/dogecoin,rustyrussell/bitcoin,jtimon/elements,iosdevzone/bitcoin,untrustbank/litecoin,wtogami/bitcoin,dashpay/dash,reddink/reddcoin,lakepay/lake,pastday/bitcoinproject,Xekyo/bitcoin,jtimon/bitcoin,BTCfork/hardfork_prototype_1_mvf-bu,xieta/mincoin,HeliumGas/helium,maaku/bitcoin,laudaa/bitcoin,lateminer/bitcoin,Cocosoft/bitcoin,scmorse/bitcoin,m0gliE/fastcoin-cli,BitzenyCoreDevelopers/bitzeny,anditto/bitcoin,coinkeeper/2015-06-22_19-07_digitalcoin,ahmedbodi/vertcoin,langerhans/dogecoin,dashpay/dash,Metronotes/bitcoin,TheBlueMatt/bitcoin,kevcooper/bitcoin,stevemyers/bitcoinxt,xieta/mincoin,droark/bitcoin,Tetpay/bitcoin,Jeff88Ho/bitcoin,Metronotes/bitcoin,sebrandon1/bitcoin,MarcoFalke/bitcoin,Bushstar/UFO-Project,coinkeeper/2015-06-22_18-36_darkcoin,morcos/bitcoin,cybermatatu/bitcoin,world-bank/unpay-core,masterbraz/dg,aspanta/bitcoin,DigitalPandacoin/pandacoin,reddink/reddcoin,ashleyholman/bitcoin,BigBlueCeiling/augmentacoin,untrustbank/litecoin,ArgonToken/ArgonToken,jlopp/statoshi,FeatherCoin/Feathercoin,jtimon/elements,viacoin/viacoin,ShwoognationHQ/bitcoin,nlgcoin/guldencoin-official,rustyrussell/bitcoin,knolza/gamblr,syscoin/syscoin,achow101/bitcoin,Mirobit/bitcoin,reddcoin-project/reddcoin,mycointest/owncoin,zetacoin/zetacoin,multicoins/marycoin,AllanDoensen/BitcoinUnlimited,wcwu/bitcoin,zetacoin/zetacoin,rebroad/bitcoin,BitcoinPOW/BitcoinPOW,domob1812/namecore,tecnovert/particl-core,syscoin/syscoin2,RyanLucchese/energi,llluiop/bitcoin,BTCfork/hardfork_prototype_1_mvf-core,gmaxwell/bitcoin,Kore-Core/kore,freelion93/mtucicoin,StarbuckBG/BTCGPU,Domer85/dogecoin,sipa/elements,gandrewstone/bitcoinxt,bitcoinclassic/bitcoinclassic,diggcoin/diggcoin,zottejos/merelcoin,faircoin/faircoin2,cddjr/BitcoinUnlimited,okinc/bitcoin,rjshaver/bitcoin,ptschip/bitcoinxt,dagurval/bitcoinxt,ajtowns/bitcoin,acid1789/bitcoin,Gazer022/bitcoin,TheBlueMatt/bitcoin,Anfauglith/iop-hd,Sjors/bitcoin,gjhiggins/vcoincore,JeremyRand/namecoin-core,sugruedes/bitcoinxt,JeremyRand/bitcoin,coinkeeper/2015-06-22_18-36_darkcoin,hophacker/bitcoin_malleability,fedoracoin-dev/fedoracoin,x-kalux/bitcoin_WiG-B,tjth/lotterycoin,vlajos/bitcoin,iosdevzone/bitcoin,denverl/bitcoin,pataquets/namecoin-core,koharjidan/dogecoin,gjhiggins/vcoincore,bdelzell/creditcoin-org-creditcoin,btc1/bitcoin,npccoin/npccoin,multicoins/marycoin,Rav3nPL/bitcoin,isghe/bitcoinxt,mb300sd/bitcoin,capitalDIGI/litecoin,tjps/bitcoin,benosa/bitcoin,Jcing95/iop-hd,phelix/namecore,Domer85/dogecoin,jn2840/bitcoin,Christewart/bitcoin,MazaCoin/maza,Rav3nPL/bitcoin,ashleyholman/bitcoin,ShadowMyst/creativechain-core,kirkalx/bitcoin,rsdevgun16e/energi,isle2983/bitcoin,achow101/bitcoin,xawksow/GroestlCoin,tmagik/catcoin,GlobalBoost/GlobalBoost,GroestlCoin/GroestlCoin,wcwu/bitcoin,PIVX-Project/PIVX,nathan-at-least/zcash,ptschip/bitcoin,kazcw/bitcoin,bitcoinsSG/zcash,CoinProjects/AmsterdamCoin-v4,vmp32k/litecoin,masterbraz/dg,Rav3nPL/doubloons-0.10,truthcoin/blocksize-market,mrbandrews/bitcoin,isle2983/bitcoin,cyrixhero/bitcoin,tmagik/catcoin,AkioNak/bitcoin,ekankyesme/bitcoinxt,practicalswift/bitcoin,jtimon/elements,bitcoinplusorg/xbcwalletsource,mapineda/litecoin,daliwangi/bitcoin,zsulocal/bitcoin,haobtc/bitcoin,Bloom-Project/Bloom,wellenreiter01/Feathercoin,daliwangi/bitcoin,experiencecoin/experiencecoin,rebroad/bitcoin,phplaboratory/psiacoin,biblepay/biblepay,genavarov/lamacoin,chaincoin/chaincoin,core-bitcoin/bitcoin,brandonrobertz/namecoin-core,Bitcoinsulting/bitcoinxt,biblepay/biblepay,langerhans/dogecoin,presstab/PIVX,Krellan/bitcoin,namecoin/namecoin-core,joshrabinowitz/bitcoin,DMDcoin/Diamond,guncoin/guncoin,NateBrune/bitcoin-fio,wcwu/bitcoin,tuaris/bitcoin,HeliumGas/helium,mruddy/bitcoin,syscoin/syscoin2,bcpki/nonce2testblocks,appop/bitcoin,ptschip/bitcoinxt,cerebrus29301/crowncoin,instagibbs/bitcoin,Bloom-Project/Bloom,isle2983/bitcoin,REAP720801/bitcoin,bcpki/nonce2,CoinProjects/AmsterdamCoin-v4,royosherove/bitcoinxt,jameshilliard/bitcoin,nlgcoin/guldencoin-official,Exceltior/dogecoin,syscoin/syscoin,fujicoin/fujicoin,pascalguru/florincoin,JeremyRubin/bitcoin,goldcoin/Goldcoin-GLD,vmp32k/litecoin,benzmuircroft/REWIRE.io,daliwangi/bitcoin,PIVX-Project/PIVX,supcoin/supcoin,oleganza/bitcoin-duo,worldbit/worldbit,11755033isaprimenumber/Feathercoin,schinzelh/dash,ericshawlinux/bitcoin,world-bank/unpay-core,qtumproject/qtum,langerhans/dogecoin,josephbisch/namecoin-core,bitpay/bitcoin,octocoin-project/octocoin,vericoin/vericoin-core,randy-waterhouse/bitcoin,appop/bitcoin,Alonzo-Coeus/bitcoin,inutoshi/inutoshi,millennial83/bitcoin,REAP720801/bitcoin,rromanchuk/bitcoinxt,shea256/bitcoin,x-kalux/bitcoin_WiG-B,destenson/bitcoin--bitcoin,funbucks/notbitcoinxt,parvez3019/bitcoin,bitcoin-hivemind/hivemind,ediston/energi,MasterX1582/bitcoin-becoin,odemolliens/bitcoinxt,hophacker/bitcoin_malleability,tjps/bitcoin,sickpig/BitcoinUnlimited,misdess/bitcoin,jtimon/bitcoin,millennial83/bitcoin,gravio-net/graviocoin,nlgcoin/guldencoin-official,arruah/ensocoin,kirkalx/bitcoin,pataquets/namecoin-core,Alex-van-der-Peet/bitcoin,CryptArc/bitcoinxt,ahmedbodi/test2,jaromil/faircoin2,afk11/bitcoin,LIMXTEC/DMDv3,inkvisit/sarmacoins,tjps/bitcoin,fanquake/bitcoin,bitcoinsSG/zcash,shelvenzhou/BTCGPU,jamesob/bitcoin,Chancoin-core/CHANCOIN,capitalDIGI/litecoin,TBoehm/greedynode,itmanagerro/tresting,myriadcoin/myriadcoin,atgreen/bitcoin,shaolinfry/litecoin,TierNolan/bitcoin,lbrtcoin/albertcoin,roques/bitcoin,jaromil/faircoin2,thormuller/yescoin2,NicolasDorier/bitcoin,nathan-at-least/zcash,tropa/axecoin,FarhanHaque/bitcoin,fanquake/bitcoin,scmorse/bitcoin,aspirecoin/aspire,lateminer/bitcoin,cryptoprojects/ultimateonlinecash,joulecoin/joulecoin,djpnewton/bitcoin,myriadcoin/myriadcoin,upgradeadvice/MUE-Src,phelix/namecore,marlengit/hardfork_prototype_1_mvf-bu,SoreGums/bitcoinxt,drwasho/bitcoinxt,Kcoin-project/kcoin,sickpig/BitcoinUnlimited,oklink-dev/bitcoin_block,btc1/bitcoin,habibmasuro/bitcoin,vlajos/bitcoin,coinkeeper/2015-06-22_18-37_dogecoin,Tetpay/bitcoin,ekankyesme/bitcoinxt,unsystemizer/bitcoin,TrainMAnB/vcoincore,litecoin-project/bitcoinomg,RibbitFROG/ribbitcoin,hsavit1/bitcoin,joroob/reddcoin,multicoins/marycoin,jtimon/bitcoin,RibbitFROG/ribbitcoin,midnightmagic/bitcoin,lbrtcoin/albertcoin,grumpydevelop/singularity,lakepay/lake,Kcoin-project/kcoin,vmp32k/litecoin,mb300sd/bitcoin,thormuller/yescoin2,digideskio/namecoin,marlengit/hardfork_prototype_1_mvf-bu,viacoin/viacoin,ajtowns/bitcoin,Mrs-X/PIVX,aniemerg/zcash,StarbuckBG/BTCGPU,OmniLayer/omnicore,rnicoll/bitcoin,dmrtsvetkov/flowercoin,meighti/bitcoin,andreaskern/bitcoin,Theshadow4all/ShadowCoin,rjshaver/bitcoin,jnewbery/bitcoin,TheBlueMatt/bitcoin,laudaa/bitcoin,nailtaras/nailcoin,StarbuckBG/BTCGPU,jimmysong/bitcoin,diggcoin/diggcoin,theuni/bitcoin,dpayne9000/Rubixz-Coin,cdecker/bitcoin,btc1/bitcoin,sipa/elements,alejandromgk/Lunar,gameunits/gameunits,TGDiamond/Diamond,joshrabinowitz/bitcoin,MazaCoin/maza,sebrandon1/bitcoin,sebrandon1/bitcoin,deeponion/deeponion,core-bitcoin/bitcoin,cotner/bitcoin,zander/bitcoinclassic,practicalswift/bitcoin,simdeveloper/bitcoin,funbucks/notbitcoinxt,syscoin/syscoin,jamesob/bitcoin,RazorLove/cloaked-octo-spice,gazbert/bitcoin,droark/elements,nathan-at-least/zcash,jakeva/bitcoin-pwcheck,bitcoin-hivemind/hivemind,fsb4000/bitcoin,petertodd/bitcoin,antcheck/antcoin,dexX7/bitcoin,bickojima/bitzeny,haraldh/bitcoin,alejandromgk/Lunar,cotner/bitcoin,thrasher-/litecoin,keesdewit82/LasVegasCoin,ColossusCoinXT/ColossusCoinXT,BTCfork/hardfork_prototype_1_mvf-core,gmaxwell/bitcoin,ColossusCoinXT/ColossusCoinXT,ppcoin/ppcoin,rromanchuk/bitcoinxt,Bitcoin-ABC/bitcoin-abc,sugruedes/bitcoinxt,diggcoin/diggcoin,millennial83/bitcoin,Theshadow4all/ShadowCoin,vertcoin/vertcoin,npccoin/npccoin,roques/bitcoin,phplaboratory/psiacoin,vmp32k/litecoin,my-first/octocoin,Cloudsy/bitcoin,mitchellcash/bitcoin,schildbach/bitcoin,earonesty/bitcoin,RyanLucchese/energi,capitalDIGI/litecoin,MikeAmy/bitcoin,lbryio/lbrycrd,Kogser/bitcoin,jmcorgan/bitcoin,Justaphf/BitcoinUnlimited,dgenr8/bitcoinxt,faircoin/faircoin2,MeshCollider/bitcoin,bickojima/bitzeny,Justaphf/BitcoinUnlimited,ElementsProject/elements,Rav3nPL/polcoin,faircoin/faircoin,schinzelh/dash,zcoinofficial/zcoin,BitzenyCoreDevelopers/bitzeny,faircoin/faircoin2,pstratem/bitcoin,ivansib/sib16,apoelstra/elements,gandrewstone/BitcoinUnlimited,rebroad/bitcoin,ajtowns/bitcoin,domob1812/bitcoin,ardsu/bitcoin,ajweiss/bitcoin,litecoin-project/litecore-litecoin,greenaddress/bitcoin,Mrs-X/PIVX,nvmd/bitcoin,litecoin-project/litecore-litecoin,Anoncoin/anoncoin,oklink-dev/bitcoin,droark/bitcoin,awemany/BitcoinUnlimited,aniemerg/zcash,reorder/viacoin,dgarage/bc3,drwasho/bitcoinxt,andres-root/bitcoinxt,bickojima/bitzeny,Rav3nPL/polcoin,TierNolan/bitcoin,lbrtcoin/albertcoin,appop/bitcoin,mitchellcash/bitcoin,mobicoins/mobicoin-core,monacoinproject/monacoin,ftrader-bitcoinabc/bitcoin-abc,pelorusjack/BlockDX,senadmd/coinmarketwatch,joulecoin/joulecoin,TBoehm/greedynode,TheBlueMatt/bitcoin,haisee/dogecoin,sirk390/bitcoin,gazbert/bitcoin,mikehearn/bitcoinxt,GroestlCoin/GroestlCoin,lbryio/lbrycrd,tmagik/catcoin,jiangyonghang/bitcoin,Alonzo-Coeus/bitcoin,Bitcoin-ABC/bitcoin-abc,isocolsky/bitcoinxt,wbchen99/bitcoin-hnote0,UdjinM6/dash,FinalHashLLC/namecore,jrmithdobbs/bitcoin,MonetaryUnit/MUE-Src,Exgibichi/statusquo,nbenoit/bitcoin,cotner/bitcoin,JeremyRubin/bitcoin,litecoin-project/litecoin,ftrader-bitcoinabc/bitcoin-abc,dcousens/bitcoin,RHavar/bitcoin,simdeveloper/bitcoin,rsdevgun16e/energi,mruddy/bitcoin,DigiByte-Team/digibyte,jimmykiselak/lbrycrd,nathan-at-least/zcash,ptschip/bitcoin,Bitcoin-com/BUcash,aburan28/elements,coinwarp/dogecoin,zotherstupidguy/bitcoin,experiencecoin/experiencecoin,mruddy/bitcoin,jtimon/bitcoin,zetacoin/zetacoin,tdudz/elements,AdrianaDinca/bitcoin,kleetus/bitcoinxt,rebroad/bitcoin,litecoin-project/bitcoinomg,uphold/bitcoin,sbellem/bitcoin,bitjson/hivemind,sipa/elements,zsulocal/bitcoin,accraze/bitcoin,gmaxwell/bitcoin,vericoin/vericoin-core,zixan/bitcoin,DGCDev/digitalcoin,gwillen/elements,elecoin/elecoin,sugruedes/bitcoinxt,kirkalx/bitcoin,imharrywu/fastcoin,biblepay/biblepay,antonio-fr/bitcoin,upgradeadvice/MUE-Src,digibyte/digibyte,starwels/starwels,AdrianaDinca/bitcoin,ptschip/bitcoin,sarielsaz/sarielsaz,capitalDIGI/DIGI-v-0-10-4,xieta/mincoin,willwray/dash,magacoin/magacoin,cculianu/bitcoin-abc,kaostao/bitcoin,kallewoof/elements,kallewoof/bitcoin,fedoracoin-dev/fedoracoin,magacoin/magacoin,acid1789/bitcoin,GreenParhelia/bitcoin,octocoin-project/octocoin,midnightmagic/bitcoin,Bitcoinsulting/bitcoinxt,earonesty/bitcoin,48thct2jtnf/P,coinkeeper/2015-06-22_18-31_bitcoin,CryptArc/bitcoinxt,litecoin-project/bitcoinomg,ajtowns/bitcoin,JeremyRand/namecoin-core,bespike/litecoin,40thoughts/Coin-QualCoin,knolza/gamblr,daliwangi/bitcoin,ingresscoin/ingresscoin,bankonmecoin/bitcoin,thrasher-/litecoin,experiencecoin/experiencecoin,PRabahy/bitcoin,KaSt/ekwicoin,Cocosoft/bitcoin,inkvisit/sarmacoins,wbchen99/bitcoin-hnote0,arruah/ensocoin,sugruedes/bitcoin,Vsync-project/Vsync,jrmithdobbs/bitcoin,shomeser/bitcoin,bitjson/hivemind,parvez3019/bitcoin,bcpki/testblocks,DMDcoin/Diamond,tdudz/elements,Rav3nPL/polcoin,joulecoin/joulecoin,JeremyRand/namecore,sstone/bitcoin,llluiop/bitcoin,BTCTaras/bitcoin,dgarage/bc2,bespike/litecoin,ripper234/bitcoin,HashUnlimited/Einsteinium-Unlimited,Xekyo/bitcoin,sickpig/BitcoinUnlimited,dmrtsvetkov/flowercoin,benma/bitcoin,matlongsi/micropay,111t8e/bitcoin,bitjson/hivemind,bitcoinsSG/zcash,rawodb/bitcoin,habibmasuro/bitcoin,nomnombtc/bitcoin,ryanofsky/bitcoin,ludbb/bitcoin,brishtiteveja/sherlockcoin,cyrixhero/bitcoin,braydonf/bitcoin,qtumproject/qtum,cannabiscoindev/cannabiscoin420,dgenr8/bitcoin,GlobalBoost/GlobalBoost,brishtiteveja/sherlockcoin,joroob/reddcoin,plncoin/PLNcoin_Core,BTCfork/hardfork_prototype_1_mvf-core,Metronotes/bitcoin,SoreGums/bitcoinxt,shouhuas/bitcoin,hyperwang/bitcoin,spiritlinxl/BTCGPU,litecoin-project/litecore-litecoin,randy-waterhouse/bitcoin,ahmedbodi/terracoin,PIVX-Project/PIVX,lbrtcoin/albertcoin,funkshelper/woodcoin-b,metacoin/florincoin,jrick/bitcoin,pouta/bitcoin,bitjson/hivemind,morcos/bitcoin,sstone/bitcoin,rustyrussell/bitcoin,morcos/bitcoin,bitbrazilcoin-project/bitbrazilcoin,REAP720801/bitcoin,theuni/bitcoin,syscoin/syscoin2,grumpydevelop/singularity,nigeriacoin/nigeriacoin,metacoin/florincoin,r8921039/bitcoin,Kenwhite23/litecoin,s-matthew-english/bitcoin,zixan/bitcoin,jn2840/bitcoin,namecoin/namecore,DMDcoin/Diamond,tdudz/elements,Electronic-Gulden-Foundation/egulden,NateBrune/bitcoin-nate,dexX7/bitcoin,jakeva/bitcoin-pwcheck,FarhanHaque/bitcoin,bmp02050/ReddcoinUpdates,Har01d/bitcoin,namecoin/namecore,Flurbos/Flurbo,daveperkins-github/bitcoin-dev,dgarage/bc3,ElementsProject/elements,DigiByte-Team/digibyte,misdess/bitcoin,40thoughts/Coin-QualCoin,dagurval/bitcoinxt,viacoin/viacoin,Jcing95/iop-hd,pinheadmz/bitcoin,LIMXTEC/DMDv3,Flurbos/Flurbo,reddink/reddcoin,simdeveloper/bitcoin,pstratem/bitcoin,matlongsi/micropay,habibmasuro/bitcoinxt,48thct2jtnf/P,elecoin/elecoin,litecoin-project/litecoin,nailtaras/nailcoin,Tetpay/bitcoin,uphold/bitcoin,UFOCoins/ufo,zetacoin/zetacoin,goku1997/bitcoin,EntropyFactory/creativechain-core,litecoin-project/litecore-litecoin,peercoin/peercoin,cculianu/bitcoin-abc,stevemyers/bitcoinxt,genavarov/lamacoin,monacoinproject/monacoin,Exceltior/dogecoin,MarcoFalke/bitcoin,midnight-miner/LasVegasCoin,constantine001/bitcoin,senadmd/coinmarketwatch,pinheadmz/bitcoin,TrainMAnB/vcoincore,sbaks0820/bitcoin,DGCDev/digitalcoin,Kogser/bitcoin,schinzelh/dash,ediston/energi,dscotese/bitcoin,svost/bitcoin,nightlydash/darkcoin,bcpki/nonce2testblocks,parvez3019/bitcoin,awemany/BitcoinUnlimited,r8921039/bitcoin,goku1997/bitcoin,bankonmecoin/bitcoin,FarhanHaque/bitcoin,matlongsi/micropay,ryanxcharles/bitcoin,rawodb/bitcoin,marlengit/hardfork_prototype_1_mvf-bu,deadalnix/bitcoin,shea256/bitcoin,myriadteam/myriadcoin,Vsync-project/Vsync,Theshadow4all/ShadowCoin,brishtiteveja/sherlockcoin,Kcoin-project/kcoin,sarielsaz/sarielsaz,antcheck/antcoin,mb300sd/bitcoin,xawksow/GroestlCoin,bitbrazilcoin-project/bitbrazilcoin,magacoin/magacoin,psionin/smartcoin,bmp02050/ReddcoinUpdates,schildbach/bitcoin,Gazer022/bitcoin,wtogami/bitcoin,instagibbs/bitcoin,RazorLove/cloaked-octo-spice,jonasschnelli/bitcoin,ardsu/bitcoin,MazaCoin/maza,thesoftwarejedi/bitcoin,initaldk/bitcoin,rdqw/sscoin,ahmedbodi/temp_vert,Gazer022/bitcoin,genavarov/lamacoin,marlengit/BitcoinUnlimited,brandonrobertz/namecoin-core,haisee/dogecoin,dexX7/bitcoin,rdqw/sscoin,unsystemizer/bitcoin,GroestlCoin/GroestlCoin,Diapolo/bitcoin,haraldh/bitcoin,starwels/starwels,sebrandon1/bitcoin,jarymoth/dogecoin,ArgonToken/ArgonToken,StarbuckBG/BTCGPU,Jeff88Ho/bitcoin,dev1972/Satellitecoin,alecalve/bitcoin,lateminer/bitcoin,joroob/reddcoin,wellenreiter01/Feathercoin,schinzelh/dash,mockcoin/mockcoin,BTCTaras/bitcoin,petertodd/bitcoin,puticcoin/putic,goldcoin/goldcoin,ravenbyron/phtevencoin,ShadowMyst/creativechain-core,pstratem/elements,peercoin/peercoin,elliotolds/bitcoin,paveljanik/bitcoin,loxal/zcash,gameunits/gameunits,GIJensen/bitcoin,BTCGPU/BTCGPU,ctwiz/stardust,ZiftrCOIN/ziftrcoin,21E14/bitcoin,Anfauglith/iop-hd,reorder/viacoin,ClusterCoin/ClusterCoin,dgarage/bc3,lateminer/bitcoin,pstratem/elements,zenywallet/bitzeny,torresalyssa/bitcoin,gzuser01/zetacoin-bitcoin,lakepay/lake,zcoinofficial/zcoin,dashpay/dash,habibmasuro/bitcoinxt,fsb4000/bitcoin,goku1997/bitcoin,nightlydash/darkcoin,pstratem/elements,litecoin-project/litecore-litecoin,Alonzo-Coeus/bitcoin,nbenoit/bitcoin,se3000/bitcoin,GIJensen/bitcoin,pouta/bitcoin,bitpay/bitcoin,rsdevgun16e/energi,SoreGums/bitcoinxt,sbellem/bitcoin,senadmd/coinmarketwatch,ctwiz/stardust,Exgibichi/statusquo,Cloudsy/bitcoin,haisee/dogecoin,cryptodev35/icash,nbenoit/bitcoin,andres-root/bitcoinxt,greencoin-dev/digitalcoin,matlongsi/micropay,Darknet-Crypto/Darknet,jeromewu/bitcoin-opennet,greencoin-dev/digitalcoin,ingresscoin/ingresscoin,funkshelper/woodcoin-b,maaku/bitcoin,superjudge/bitcoin,leofidus/glowing-octo-ironman,riecoin/riecoin,HashUnlimited/Einsteinium-Unlimited,droark/bitcoin,reddcoin-project/reddcoin,ericshawlinux/bitcoin,PIVX-Project/PIVX,Anoncoin/anoncoin,bitcoinsSG/bitcoin,cryptodev35/icash,joshrabinowitz/bitcoin,litecoin-project/litecoin,coinkeeper/2015-06-22_18-39_feathercoin,prark/bitcoinxt,ardsu/bitcoin,jlopp/statoshi,botland/bitcoin,arnuschky/bitcoin,tuaris/bitcoin,truthcoin/truthcoin-cpp,mrbandrews/bitcoin,midnightmagic/bitcoin,DGCDev/argentum,anditto/bitcoin,iosdevzone/bitcoin,Rav3nPL/bitcoin,wederw/bitcoin,viacoin/viacoin,slingcoin/sling-market,jimmykiselak/lbrycrd,JeremyRubin/bitcoin,StarbuckBG/BTCGPU,btcdrak/bitcoin,lakepay/lake,paveljanik/bitcoin,111t8e/bitcoin,n1bor/bitcoin,jnewbery/bitcoin,bitbrazilcoin-project/bitbrazilcoin,AllanDoensen/BitcoinUnlimited,starwels/starwels,koharjidan/litecoin,thelazier/dash,OmniLayer/omnicore,jarymoth/dogecoin,rustyrussell/bitcoin,n1bor/bitcoin,alecalve/bitcoin,AkioNak/bitcoin,coinkeeper/2015-06-22_18-39_feathercoin,slingcoin/sling-market,mincoin-project/mincoin,jimmykiselak/lbrycrd,mobicoins/mobicoin-core,bmp02050/ReddcoinUpdates,neuroidss/bitcoin,zotherstupidguy/bitcoin,UFOCoins/ufo,cerebrus29301/crowncoin,my-first/octocoin,rawodb/bitcoin,BitcoinHardfork/bitcoin,gapcoin/gapcoin,jambolo/bitcoin,greenaddress/bitcoin,Rav3nPL/bitcoin,btc1/bitcoin,Mrs-X/PIVX,ivansib/sibcoin,Exgibichi/statusquo,koharjidan/litecoin,untrustbank/litecoin,n1bor/bitcoin,cybermatatu/bitcoin,ArgonToken/ArgonToken,apoelstra/bitcoin,tropa/axecoin,likecoin-dev/bitcoin,aciddude/Feathercoin,PRabahy/bitcoin,EthanHeilman/bitcoin,Chancoin-core/CHANCOIN,gavinandresen/bitcoin-git,MazaCoin/maza,Chancoin-core/CHANCOIN,21E14/bitcoin,BigBlueCeiling/augmentacoin,ClusterCoin/ClusterCoin,midnight-miner/LasVegasCoin,jarymoth/dogecoin,AdrianaDinca/bitcoin,ticclassic/ic,lateminer/bitcoin,BTCfork/hardfork_prototype_1_mvf-core,mockcoin/mockcoin,apoelstra/bitcoin,genavarov/brcoin,dgarage/bc2,dperel/bitcoin,scmorse/bitcoin,thelazier/dash,rustyrussell/bitcoin,tuaris/bitcoin,achow101/bitcoin,blood2/bloodcoin-0.9,axelxod/braincoin,rat4/bitcoin,reddink/reddcoin,thrasher-/litecoin,viacoin/viacoin,1185/starwels,OmniLayer/omnicore,robvanbentem/bitcoin,destenson/bitcoin--bitcoin,pastday/bitcoinproject,goldcoin/Goldcoin-GLD,supcoin/supcoin,nsacoin/nsacoin,midnightmagic/bitcoin,ctwiz/stardust,rawodb/bitcoin
3900822a15d19f09d63b8fdcf075f71b023a2ac9
src/module.cpp
src/module.cpp
/* Copyright (c) 2016, Wemap SAS Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION #define _USE_MATH_DEFINES #include <Python.h> #include <numpy/arrayobject.h> #include <cmath> #include "supercluster.hpp" static double lngX(double lng) { return lng / 360.0 + 0.5; } static double latY(double lat) { if (lat <= -90) return 1.0; else if (lat >= 90) return 0.0; else { double sin = std::sin(lat * M_PI / 180); return 0.5 - 0.25 * std::log((1 + sin) / (1 - sin)) / M_PI; } } static double xLng(double x) { return (x - 0.5) * 360; } static double yLat(double y) { double y2 = (180 - y * 360) * M_PI / 180; return 360 * std::atan(std::exp(y2)) / M_PI - 90; } typedef struct { PyObject_HEAD SuperCluster *sc; } SuperClusterObject; static int SuperCluster_init(SuperClusterObject *self, PyObject *args, PyObject *kwargs) { const char *kwlist[] = {"points", "min_zoom", "max_zoom", "radius", "extent", NULL}; PyArrayObject *points; int min_zoom = 0; int max_zoom = 16; double radius = 40; double extent = 512; if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O!|iidd", const_cast<char **>(kwlist), &PyArray_Type, &points, &min_zoom, &max_zoom, &radius, &extent)) return -1; if (PyArray_DESCR(points)->type_num != NPY_DOUBLE || PyArray_NDIM(points) != 2 || PyArray_DIMS(points)[1] != 2 || PyArray_DIMS(points)[0] == 0){ PyErr_SetString(PyExc_ValueError, "Array must be of type double and 2 dimensional and must have a length >= 1."); return -1; } npy_intp count = PyArray_DIMS(points)[0]; std::vector<Point> items(count); for (npy_intp i = 0; i < count; ++i) { items[i] = std::make_pair( lngX(*(double*)PyArray_GETPTR2(points, i, 0)), latY(*(double*)PyArray_GETPTR2(points, i, 1))); } self->sc = new SuperCluster(items, min_zoom, max_zoom, radius, extent); return 0; } static void SuperCluster_dealloc(SuperClusterObject *self) { delete self->sc; } static PyObject * SuperCluster_getClusters(SuperClusterObject *self, PyObject *args, PyObject *kwargs) { const char *kwlist[] = {"top_left", "bottom_right", "zoom", NULL}; double minLng, minLat, maxLng, maxLat; int zoom; if (!PyArg_ParseTupleAndKeywords(args, kwargs, "(dd)(dd)i", const_cast<char **>(kwlist), &minLng, &minLat, &maxLng, &maxLat, &zoom)) return NULL; std::vector<Cluster*> clusters = self->sc->getClusters( std::make_pair(lngX(minLng), latY(minLat)), std::make_pair(lngX(maxLng), latY(maxLat)), zoom); PyObject *countKey = PyUnicode_FromString("count"); PyObject *expansionZoomKey = PyUnicode_FromString("expansion_zoom"); PyObject *idKey = PyUnicode_FromString("id"); PyObject *latitudeKey = PyUnicode_FromString("latitude"); PyObject *longitudeKey = PyUnicode_FromString("longitude"); PyObject *o = NULL; PyObject *list = PyList_New(clusters.size()); for (size_t i = 0; i < clusters.size(); ++i) { PyObject *dict = PyDict_New(); Cluster *cluster = clusters[i]; o = PyLong_FromSize_t(cluster->numPoints); PyDict_SetItem(dict, countKey, o); Py_DECREF(o); if (cluster->expansionZoom >= 0) { o = PyLong_FromSize_t(cluster->expansionZoom); PyDict_SetItem(dict, expansionZoomKey, o); Py_DECREF(o); } else { PyDict_SetItem(dict, expansionZoomKey, Py_None); } o = PyLong_FromSize_t(cluster->id); PyDict_SetItem(dict, idKey, o); Py_DECREF(o); o = PyFloat_FromDouble(yLat(cluster->point.second)); PyDict_SetItem(dict, latitudeKey, o); Py_DECREF(o); o = PyFloat_FromDouble(xLng(cluster->point.first)); PyDict_SetItem(dict, longitudeKey, o); Py_DECREF(o); PyList_SET_ITEM(list, i, dict); } Py_DECREF(countKey); Py_DECREF(expansionZoomKey); Py_DECREF(idKey); Py_DECREF(latitudeKey); Py_DECREF(longitudeKey); return list; } static PyMethodDef SuperCluster_methods[] = { {"getClusters", (PyCFunction)SuperCluster_getClusters, METH_VARARGS | METH_KEYWORDS, "Returns the clusters within the given bounding box at the given zoom level."}, {NULL} }; static PyTypeObject SuperClusterType = { PyVarObject_HEAD_INIT(NULL, 0) "pysupercluster.SuperCluster", /* tp_name */ sizeof(SuperClusterObject), /* tp_basicsize */ 0, /* tp_itemsize */ (destructor)SuperCluster_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ "SuperCluster objects", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ SuperCluster_methods, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc)SuperCluster_init, /* tp_init */ 0, /* tp_alloc */ }; static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "pysupercluster", /* m_name */ "A fast geospatial point clustering module.", /* m_doc */ -1, /* m_size */ NULL, /* m_methods */ NULL, /* m_reload */ NULL, /* m_traverse */ NULL, /* m_clear */ NULL, /* m_free */ }; PyMODINIT_FUNC PyInit_pysupercluster(void) { PyObject* m; import_array(); m = PyModule_Create(&moduledef); if (m == NULL) return NULL; SuperClusterType.tp_new = PyType_GenericNew; if (PyType_Ready(&SuperClusterType) < 0) return NULL; Py_INCREF(&SuperClusterType); PyModule_AddObject(m, "SuperCluster", (PyObject *)&SuperClusterType); return m; }
/* Copyright (c) 2016, Wemap SAS Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION #define _USE_MATH_DEFINES #include <Python.h> #include <numpy/arrayobject.h> #include <cmath> #include "supercluster.hpp" static double lngX(double lng) { return lng / 360.0 + 0.5; } static double latY(double lat) { if (lat <= -90) return 1.0; else if (lat >= 90) return 0.0; else { double sin = std::sin(lat * M_PI / 180); return 0.5 - 0.25 * std::log((1 + sin) / (1 - sin)) / M_PI; } } static double xLng(double x) { return (x - 0.5) * 360; } static double yLat(double y) { double y2 = (180 - y * 360) * M_PI / 180; return 360 * std::atan(std::exp(y2)) / M_PI - 90; } typedef struct { PyObject_HEAD SuperCluster *sc; } SuperClusterObject; static int SuperCluster_init(SuperClusterObject *self, PyObject *args, PyObject *kwargs) { const char *kwlist[] = {"points", "min_zoom", "max_zoom", "radius", "extent", NULL}; PyArrayObject *points; int min_zoom = 0; int max_zoom = 16; double radius = 40; double extent = 512; if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O!|iidd", const_cast<char **>(kwlist), &PyArray_Type, &points, &min_zoom, &max_zoom, &radius, &extent)) return -1; if (PyArray_DESCR(points)->type_num != NPY_DOUBLE || PyArray_NDIM(points) != 2 || PyArray_DIMS(points)[1] != 2 || PyArray_DIMS(points)[0] == 0){ PyErr_SetString(PyExc_ValueError, "Array must be of type double and 2 dimensional and must have a length >= 1."); return -1; } npy_intp count = PyArray_DIMS(points)[0]; std::vector<Point> items(count); for (npy_intp i = 0; i < count; ++i) { items[i] = std::make_pair( lngX(*(double*)PyArray_GETPTR2(points, i, 0)), latY(*(double*)PyArray_GETPTR2(points, i, 1))); } self->sc = new SuperCluster(items, min_zoom, max_zoom, radius, extent); return 0; } static void SuperCluster_dealloc(SuperClusterObject *self) { delete self->sc; Py_TYPE(self)->tp_free((PyObject *) self); } static PyObject * SuperCluster_getClusters(SuperClusterObject *self, PyObject *args, PyObject *kwargs) { const char *kwlist[] = {"top_left", "bottom_right", "zoom", NULL}; double minLng, minLat, maxLng, maxLat; int zoom; if (!PyArg_ParseTupleAndKeywords(args, kwargs, "(dd)(dd)i", const_cast<char **>(kwlist), &minLng, &minLat, &maxLng, &maxLat, &zoom)) return NULL; std::vector<Cluster*> clusters = self->sc->getClusters( std::make_pair(lngX(minLng), latY(minLat)), std::make_pair(lngX(maxLng), latY(maxLat)), zoom); PyObject *countKey = PyUnicode_FromString("count"); PyObject *expansionZoomKey = PyUnicode_FromString("expansion_zoom"); PyObject *idKey = PyUnicode_FromString("id"); PyObject *latitudeKey = PyUnicode_FromString("latitude"); PyObject *longitudeKey = PyUnicode_FromString("longitude"); PyObject *o = NULL; PyObject *list = PyList_New(clusters.size()); for (size_t i = 0; i < clusters.size(); ++i) { PyObject *dict = PyDict_New(); Cluster *cluster = clusters[i]; o = PyLong_FromSize_t(cluster->numPoints); PyDict_SetItem(dict, countKey, o); Py_DECREF(o); if (cluster->expansionZoom >= 0) { o = PyLong_FromSize_t(cluster->expansionZoom); PyDict_SetItem(dict, expansionZoomKey, o); Py_DECREF(o); } else { PyDict_SetItem(dict, expansionZoomKey, Py_None); } o = PyLong_FromSize_t(cluster->id); PyDict_SetItem(dict, idKey, o); Py_DECREF(o); o = PyFloat_FromDouble(yLat(cluster->point.second)); PyDict_SetItem(dict, latitudeKey, o); Py_DECREF(o); o = PyFloat_FromDouble(xLng(cluster->point.first)); PyDict_SetItem(dict, longitudeKey, o); Py_DECREF(o); PyList_SET_ITEM(list, i, dict); } Py_DECREF(countKey); Py_DECREF(expansionZoomKey); Py_DECREF(idKey); Py_DECREF(latitudeKey); Py_DECREF(longitudeKey); return list; } static PyMethodDef SuperCluster_methods[] = { {"getClusters", (PyCFunction)SuperCluster_getClusters, METH_VARARGS | METH_KEYWORDS, "Returns the clusters within the given bounding box at the given zoom level."}, {NULL} }; static PyTypeObject SuperClusterType = { PyVarObject_HEAD_INIT(NULL, 0) "pysupercluster.SuperCluster", /* tp_name */ sizeof(SuperClusterObject), /* tp_basicsize */ 0, /* tp_itemsize */ (destructor)SuperCluster_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ "SuperCluster objects", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ SuperCluster_methods, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc)SuperCluster_init, /* tp_init */ 0, /* tp_alloc */ }; static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "pysupercluster", /* m_name */ "A fast geospatial point clustering module.", /* m_doc */ -1, /* m_size */ NULL, /* m_methods */ NULL, /* m_reload */ NULL, /* m_traverse */ NULL, /* m_clear */ NULL, /* m_free */ }; PyMODINIT_FUNC PyInit_pysupercluster(void) { PyObject* m; import_array(); m = PyModule_Create(&moduledef); if (m == NULL) return NULL; SuperClusterType.tp_new = PyType_GenericNew; if (PyType_Ready(&SuperClusterType) < 0) return NULL; Py_INCREF(&SuperClusterType); PyModule_AddObject(m, "SuperCluster", (PyObject *)&SuperClusterType); return m; }
Fix SuperCluster destructor, fixes a memory leak
Fix SuperCluster destructor, fixes a memory leak
C++
isc
wemap/pysupercluster,wemap/pysupercluster
45eceb626f5ed3b6d4e6ebf1cd8712a76836a646
src/netconf.cc
src/netconf.cc
// Copyright 2015 Toggl Desktop developers. #include "../src/netconf.h" #include <string> #include <sstream> #include "./https_client.h" #include "Poco/Environment.h" #include "Poco/Logger.h" #include "Poco/Net/HTTPCredentials.h" #include "Poco/Net/HTTPSClientSession.h" #include "Poco/URI.h" #include "Poco/UnicodeConverter.h" #ifdef __MACH__ #include <CoreFoundation/CoreFoundation.h> // NOLINT #include <CoreServices/CoreServices.h> // NOLINT #endif #ifdef _WIN32 #include <winhttp.h> #pragma comment(lib, "winhttp") #endif namespace toggl { error Netconf::autodetectProxy( const std::string encoded_url, std::string *proxy_url) { *proxy_url = ""; if (encoded_url.empty()) { return noError; } #ifdef _WIN32 WINHTTP_CURRENT_USER_IE_PROXY_CONFIG ie_config = { 0 }; if (!WinHttpGetIEProxyConfigForCurrentUser(&ie_config)) { std::stringstream ss; ss << "WinHttpGetIEProxyConfigForCurrentUser error: " << GetLastError(); return ss.str(); } if (ie_config.lpszProxy) { std::wstring proxy_url_wide(ie_config.lpszProxy); std::string s(""); Poco::UnicodeConverter::toUTF8(proxy_url_wide, s); *proxy_url = s; } #endif // Inspired by VLC source code // https://github.com/videolan/vlc/blob/master/src/darwin/netconf.c #ifdef __MACH__ CFDictionaryRef dicRef = CFNetworkCopySystemProxySettings(); if (NULL != dicRef) { const CFStringRef proxyCFstr = (const CFStringRef)CFDictionaryGetValue( dicRef, (const void*)kCFNetworkProxiesHTTPProxy); const CFNumberRef portCFnum = (const CFNumberRef)CFDictionaryGetValue( dicRef, (const void*)kCFNetworkProxiesHTTPPort); if (NULL != proxyCFstr && NULL != portCFnum) { int port = 0; if (!CFNumberGetValue(portCFnum, kCFNumberIntType, &port)) { CFRelease(dicRef); return noError; } const std::size_t kBufsize(4096); char host_buffer[kBufsize]; memset(host_buffer, 0, sizeof(host_buffer)); if (CFStringGetCString(proxyCFstr, host_buffer, sizeof(host_buffer) - 1, kCFStringEncodingUTF8)) { char buffer[kBufsize]; snprintf(buffer, kBufsize, "%s:%d", host_buffer, port); *proxy_url = std::string(buffer); } } CFRelease(dicRef); } #endif return noError; } error Netconf::ConfigureProxy( const std::string encoded_url, Poco::Net::HTTPSClientSession *session) { Poco::Logger &logger = Poco::Logger::get("ConfigureProxy"); std::string proxy_url(""); if (HTTPSClient::Config.AutodetectProxy) { if (Poco::Environment::has("HTTP_PROXY")) { proxy_url = Poco::Environment::get("HTTP_PROXY"); } if (proxy_url.empty()) { error err = autodetectProxy(encoded_url, &proxy_url); if (err != noError) { return err; } } if (proxy_url.find("://") == std::string::npos) { proxy_url = "http://" + proxy_url; } Poco::URI proxy_uri(proxy_url); std::stringstream ss; ss << "Proxy detected URI=" + proxy_uri.toString() << " host=" << proxy_uri.getHost() << " port=" << proxy_uri.getPort(); logger.debug(ss.str()); session->setProxy( proxy_uri.getHost(), proxy_uri.getPort()); if (!proxy_uri.getUserInfo().empty()) { Poco::Net::HTTPCredentials credentials; credentials.fromUserInfo(proxy_uri.getUserInfo()); session->setProxyCredentials( credentials.getUsername(), credentials.getPassword()); logger.debug("Proxy credentials detected username=" + credentials.getUsername()); } } // Try to use user-configured proxy if (proxy_url.empty() && HTTPSClient::Config.UseProxy && HTTPSClient::Config.ProxySettings.IsConfigured()) { session->setProxy( HTTPSClient::Config.ProxySettings.Host(), static_cast<Poco::UInt16>( HTTPSClient::Config.ProxySettings.Port())); std::stringstream ss; ss << "Proxy configured " << " host=" << HTTPSClient::Config.ProxySettings.Host() << " port=" << HTTPSClient::Config.ProxySettings.Port(); logger.debug(ss.str()); if (HTTPSClient::Config.ProxySettings.HasCredentials()) { session->setProxyCredentials( HTTPSClient::Config.ProxySettings.Username(), HTTPSClient::Config.ProxySettings.Password()); logger.debug("Proxy credentials configured username=" + HTTPSClient::Config.ProxySettings.Username()); } } return noError; } } // namespace toggl
// Copyright 2015 Toggl Desktop developers. #include "../src/netconf.h" #include <string> #include <sstream> #include "./https_client.h" #include "Poco/Environment.h" #include "Poco/Logger.h" #include "Poco/Net/HTTPCredentials.h" #include "Poco/Net/HTTPSClientSession.h" #include "Poco/URI.h" #include "Poco/UnicodeConverter.h" #ifdef __MACH__ #include <CoreFoundation/CoreFoundation.h> // NOLINT #include <CoreServices/CoreServices.h> // NOLINT #endif #ifdef _WIN32 #include <winhttp.h> #pragma comment(lib, "winhttp") #endif namespace toggl { error Netconf::autodetectProxy( const std::string encoded_url, std::string *proxy_url) { *proxy_url = ""; if (encoded_url.empty()) { return noError; } #ifdef _WIN32 WINHTTP_CURRENT_USER_IE_PROXY_CONFIG ie_config = { 0 }; if (!WinHttpGetIEProxyConfigForCurrentUser(&ie_config)) { std::stringstream ss; ss << "WinHttpGetIEProxyConfigForCurrentUser error: " << GetLastError(); return ss.str(); } if (ie_config.lpszProxy) { std::wstring proxy_url_wide(ie_config.lpszProxy); std::string s(""); Poco::UnicodeConverter::toUTF8(proxy_url_wide, s); *proxy_url = s; } #endif // Inspired by VLC source code // https://github.com/videolan/vlc/blob/master/src/darwin/netconf.c #ifdef __MACH__ CFDictionaryRef dicRef = CFNetworkCopySystemProxySettings(); if (NULL != dicRef) { const CFStringRef proxyCFstr = (const CFStringRef)CFDictionaryGetValue( dicRef, (const void*)kCFNetworkProxiesHTTPProxy); const CFNumberRef portCFnum = (const CFNumberRef)CFDictionaryGetValue( dicRef, (const void*)kCFNetworkProxiesHTTPPort); if (NULL != proxyCFstr && NULL != portCFnum) { int port = 0; if (!CFNumberGetValue(portCFnum, kCFNumberIntType, &port)) { CFRelease(dicRef); return noError; } const std::size_t kBufsize(4096); char host_buffer[kBufsize]; memset(host_buffer, 0, sizeof(host_buffer)); if (CFStringGetCString(proxyCFstr, host_buffer, sizeof(host_buffer) - 1, kCFStringEncodingUTF8)) { char buffer[kBufsize]; snprintf(buffer, kBufsize, "%s:%d", host_buffer, port); *proxy_url = std::string(buffer); } } CFRelease(dicRef); } #endif return noError; } error Netconf::ConfigureProxy( const std::string encoded_url, Poco::Net::HTTPSClientSession *session) { Poco::Logger &logger = Poco::Logger::get("ConfigureProxy"); std::string proxy_url(""); if (HTTPSClient::Config.AutodetectProxy) { if (Poco::Environment::has("HTTP_PROXY")) { proxy_url = Poco::Environment::get("HTTP_PROXY"); } if (Poco::Environment::has("http_proxy")) { proxy_url = Poco::Environment::get("http_proxy"); } if (proxy_url.empty()) { error err = autodetectProxy(encoded_url, &proxy_url); if (err != noError) { return err; } } if (proxy_url.find("://") == std::string::npos) { proxy_url = "http://" + proxy_url; } Poco::URI proxy_uri(proxy_url); std::stringstream ss; ss << "Proxy detected URI=" + proxy_uri.toString() << " host=" << proxy_uri.getHost() << " port=" << proxy_uri.getPort(); logger.debug(ss.str()); session->setProxy( proxy_uri.getHost(), proxy_uri.getPort()); if (!proxy_uri.getUserInfo().empty()) { Poco::Net::HTTPCredentials credentials; credentials.fromUserInfo(proxy_uri.getUserInfo()); session->setProxyCredentials( credentials.getUsername(), credentials.getPassword()); logger.debug("Proxy credentials detected username=" + credentials.getUsername()); } } // Try to use user-configured proxy if (proxy_url.empty() && HTTPSClient::Config.UseProxy && HTTPSClient::Config.ProxySettings.IsConfigured()) { session->setProxy( HTTPSClient::Config.ProxySettings.Host(), static_cast<Poco::UInt16>( HTTPSClient::Config.ProxySettings.Port())); std::stringstream ss; ss << "Proxy configured " << " host=" << HTTPSClient::Config.ProxySettings.Host() << " port=" << HTTPSClient::Config.ProxySettings.Port(); logger.debug(ss.str()); if (HTTPSClient::Config.ProxySettings.HasCredentials()) { session->setProxyCredentials( HTTPSClient::Config.ProxySettings.Username(), HTTPSClient::Config.ProxySettings.Password()); logger.debug("Proxy credentials configured username=" + HTTPSClient::Config.ProxySettings.Username()); } } return noError; } } // namespace toggl
use http_proxy env variable (lib)
use http_proxy env variable (lib)
C++
bsd-3-clause
codeman38/toggldesktop,codeman38/toggldesktop,codeman38/toggldesktop,codeman38/toggldesktop,codeman38/toggldesktop,codeman38/toggldesktop
6faf48a6004279c165f5ab0d2efa0de8c82e8eac
src/socket.cxx
src/socket.cxx
// Module: Log4CPLUS // File: socket-win32.cxx // Created: 4/2003 // Author: Tad E. Smith // // // Copyright 2003-2014 Tad E. Smith // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <log4cplus/helpers/loglog.h> #include <log4cplus/internal/socket.h> namespace log4cplus { namespace helpers { extern LOG4CPLUS_EXPORT SOCKET_TYPE const INVALID_SOCKET_VALUE #if defined(_WIN32) = static_cast<SOCKET_TYPE>(INVALID_SOCKET); #else = static_cast<SOCKET_TYPE>(-1); #endif ////////////////////////////////////////////////////////////////////////////// // AbstractSocket ctors and dtor ////////////////////////////////////////////////////////////////////////////// AbstractSocket::AbstractSocket() : sock(INVALID_SOCKET_VALUE), state(not_opened), err(0) { } AbstractSocket::AbstractSocket(SOCKET_TYPE sock_, SocketState state_, int err_) : sock(sock_), state(state_), err(err_) { } AbstractSocket::AbstractSocket(AbstractSocket && rhs) : AbstractSocket () { swap (rhs); } AbstractSocket::~AbstractSocket() { close(); } ////////////////////////////////////////////////////////////////////////////// // AbstractSocket methods ////////////////////////////////////////////////////////////////////////////// void AbstractSocket::close() { if (sock != INVALID_SOCKET_VALUE) { closeSocket(sock); sock = INVALID_SOCKET_VALUE; state = not_opened; } } void AbstractSocket::shutdown() { if (sock != INVALID_SOCKET_VALUE) shutdownSocket(sock); } bool AbstractSocket::isOpen() const { return sock != INVALID_SOCKET_VALUE; } AbstractSocket & AbstractSocket::operator = (AbstractSocket && rhs) { swap (rhs); return *this; } void AbstractSocket::swap (AbstractSocket & rhs) { using std::swap; swap (sock, rhs.sock); swap (state, rhs.state); swap (err, rhs.err); } ////////////////////////////////////////////////////////////////////////////// // Socket ctors and dtor ////////////////////////////////////////////////////////////////////////////// Socket::Socket() : AbstractSocket() { } Socket::Socket(const tstring& address, unsigned short port, bool udp /*= false*/) : AbstractSocket() { sock = connectSocket(address, port, udp, state); if (sock == INVALID_SOCKET_VALUE) goto error; if (! udp && setTCPNoDelay (sock, true) != 0) goto error; return; error: err = get_last_socket_error (); } Socket::Socket(SOCKET_TYPE sock_, SocketState state_, int err_) : AbstractSocket(sock_, state_, err_) { } Socket::Socket (Socket && other) : AbstractSocket (std::move (other)) { } Socket::~Socket() { } Socket & Socket::operator = (Socket && other) { swap (other); return *this; } ////////////////////////////////////////////////////////////////////////////// // Socket methods ////////////////////////////////////////////////////////////////////////////// bool Socket::read(SocketBuffer& buffer) { long retval = helpers::read(sock, buffer); if(retval <= 0) { close(); } else { buffer.setSize(retval); } return (retval > 0); } bool Socket::write(const SocketBuffer& buffer) { long retval = helpers::write(sock, buffer); if(retval <= 0) { close(); } return (retval > 0); } bool Socket::write(const std::string & buffer) { long retval = helpers::write (sock, buffer); if (retval <= 0) close(); return retval > 0; } // // // ServerSocket::ServerSocket (ServerSocket && other) : AbstractSocket (std::move (other)) { interruptHandles[0] = -1; interruptHandles[1] = -1; interruptHandles.swap (other.interruptHandles); } ServerSocket & ServerSocket::operator = (ServerSocket && other) { swap (other); return *this; } void ServerSocket::swap (ServerSocket & other) { AbstractSocket::swap (other); interruptHandles.swap (other.interruptHandles); } } } // namespace log4cplus { namespace helpers {
// Module: Log4CPLUS // File: socket.cxx // Created: 4/2003 // Author: Tad E. Smith // // // Copyright 2003-2014 Tad E. Smith // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <log4cplus/helpers/loglog.h> #include <log4cplus/internal/socket.h> namespace log4cplus { namespace helpers { extern LOG4CPLUS_EXPORT SOCKET_TYPE const INVALID_SOCKET_VALUE #if defined(_WIN32) = static_cast<SOCKET_TYPE>(INVALID_SOCKET); #else = static_cast<SOCKET_TYPE>(-1); #endif ////////////////////////////////////////////////////////////////////////////// // AbstractSocket ctors and dtor ////////////////////////////////////////////////////////////////////////////// AbstractSocket::AbstractSocket() : sock(INVALID_SOCKET_VALUE), state(not_opened), err(0) { } AbstractSocket::AbstractSocket(SOCKET_TYPE sock_, SocketState state_, int err_) : sock(sock_), state(state_), err(err_) { } AbstractSocket::AbstractSocket(AbstractSocket && rhs) : AbstractSocket () { swap (rhs); } AbstractSocket::~AbstractSocket() { close(); } ////////////////////////////////////////////////////////////////////////////// // AbstractSocket methods ////////////////////////////////////////////////////////////////////////////// void AbstractSocket::close() { if (sock != INVALID_SOCKET_VALUE) { closeSocket(sock); sock = INVALID_SOCKET_VALUE; state = not_opened; } } void AbstractSocket::shutdown() { if (sock != INVALID_SOCKET_VALUE) shutdownSocket(sock); } bool AbstractSocket::isOpen() const { return sock != INVALID_SOCKET_VALUE; } AbstractSocket & AbstractSocket::operator = (AbstractSocket && rhs) { swap (rhs); return *this; } void AbstractSocket::swap (AbstractSocket & rhs) { using std::swap; swap (sock, rhs.sock); swap (state, rhs.state); swap (err, rhs.err); } ////////////////////////////////////////////////////////////////////////////// // Socket ctors and dtor ////////////////////////////////////////////////////////////////////////////// Socket::Socket() : AbstractSocket() { } Socket::Socket(const tstring& address, unsigned short port, bool udp /*= false*/) : AbstractSocket() { sock = connectSocket(address, port, udp, state); if (sock == INVALID_SOCKET_VALUE) goto error; if (! udp && setTCPNoDelay (sock, true) != 0) goto error; return; error: err = get_last_socket_error (); } Socket::Socket(SOCKET_TYPE sock_, SocketState state_, int err_) : AbstractSocket(sock_, state_, err_) { } Socket::Socket (Socket && other) : AbstractSocket (std::move (other)) { } Socket::~Socket() { } Socket & Socket::operator = (Socket && other) { swap (other); return *this; } ////////////////////////////////////////////////////////////////////////////// // Socket methods ////////////////////////////////////////////////////////////////////////////// bool Socket::read(SocketBuffer& buffer) { long retval = helpers::read(sock, buffer); if(retval <= 0) { close(); } else { buffer.setSize(retval); } return (retval > 0); } bool Socket::write(const SocketBuffer& buffer) { long retval = helpers::write(sock, buffer); if(retval <= 0) { close(); } return (retval > 0); } bool Socket::write(const std::string & buffer) { long retval = helpers::write (sock, buffer); if (retval <= 0) close(); return retval > 0; } // // // ServerSocket::ServerSocket (ServerSocket && other) : AbstractSocket (std::move (other)) { interruptHandles[0] = -1; interruptHandles[1] = -1; interruptHandles.swap (other.interruptHandles); } ServerSocket & ServerSocket::operator = (ServerSocket && other) { swap (other); return *this; } void ServerSocket::swap (ServerSocket & other) { AbstractSocket::swap (other); interruptHandles.swap (other.interruptHandles); } } } // namespace log4cplus { namespace helpers {
Fix comment typo.
Fix comment typo.
C++
apache-2.0
csuideal/log4cplus,csuideal/log4cplus,ccpaging/log4cplus,csuideal/log4cplus,csuideal/log4cplus,ccpaging/log4cplus,ccpaging/log4cplus,ccpaging/log4cplus
34c2ebd33306707d0511cb49640edcfd4b00575b
src/symbol.hpp
src/symbol.hpp
#ifndef SYMBOL_HPP_ #define SYMBOL_HPP_ #include <boost/variant.hpp> #include "source_location.hpp" class symbol { public: typedef std::string literal; struct reference { reference() : refered(nullptr) {} std::string identifier; symbol* refered; }; typedef std::vector<symbol> list; boost::variant<boost::blank, source_range> source; boost::variant<literal, reference, list> content; }; namespace symbol_building { inline symbol lit(std::string str) { return symbol{boost::blank(), std::move(str)}; } inline symbol ref(std::string identifier) { return symbol{boost::blank(), std::move(identifier)}; } inline symbol list(symbol::list list) { return symbol{boost::blank(), std::move(list)}; } } #endif
#ifndef SYMBOL_HPP_ #define SYMBOL_HPP_ #include <boost/variant.hpp> #include "source_location.hpp" class symbol { public: typedef std::string literal; struct reference { reference() : refered(nullptr) {} std::string identifier; const symbol* refered; }; typedef std::vector<symbol> list; boost::variant<boost::blank, source_range> source; boost::variant<literal, reference, list> content; literal* cast_literal() { return boost::get<literal*>(content); } reference* cast_reference() { return boost::get<reference*>(content); } list* cast_list() { return boost::get<list*>(content); } const literal* cast_literal() const { return boost::get<literal*>(content); } const reference* cast_reference() const { return boost::get<reference*>(content); } const list* cast_list() const { return boost::get<list*>(content); } }; namespace symbol_building { inline symbol lit(std::string str) { return symbol{boost::blank(), std::move(str)}; } inline symbol ref(std::string identifier) { return symbol{boost::blank(), std::move(identifier)}; } inline symbol list(symbol::list list) { return symbol{boost::blank(), std::move(list)}; } } #endif
add convenience retrieval functions
add convenience retrieval functions
C++
mit
mbid/asm-lisp
060a5ccd62c47faed35dfe651cf0b4cb36bcc815
src/system.cpp
src/system.cpp
/* system.cpp Classic Invaders Copyright (c) 2013, Simon Que 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 No Quarter Arcade (http://www.noquarterarcade.com/) nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "system.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #ifndef __AVR__ #include <SDL/SDL.h> #else ///////////// Begin embedded system definitions //////////////// #include <avr/io.h> #include <avr/interrupt.h> #include "spipad.h" #define FOSC 8000000 #define BAUD 57600 #define MYUBRR 16 static int uart_putchar(char c, FILE *stream); static int uart_getchar(FILE *stream); static void init_fdev(FILE* stream, int (*put_func)(char, FILE*), int (*get_func)(FILE*), int flags) { stream->flags = flags; stream->put = put_func; stream->get = get_func; stream->udata = NULL; } static FILE mystdout; static FILE mystdin; static int uart_putchar(char c, FILE *stream) { if (c == '\n') uart_putchar('\r', stream); loop_until_bit_is_set(UCSR0A, UDRE0); UDR0 = c; return 0; } static int uart_getchar(FILE *stream) { while( !(UCSR0A & (1<<RXC0)) ); return(UDR0); } // Initializes AVR UART. static void init_uart() { UBRR0H = MYUBRR >> 8; UBRR0L = MYUBRR; UCSR0A = (1<<U2X0); UCSR0B = (1<<TXEN0); UCSR0C = (1<<UCSZ00)|(1<<UCSZ01); DDRE = (1<<PORTE1); stdout = &mystdout; // Required for printf over UART. stderr = &mystdout; // Required for fprintf(stderr) over UART. stdin = &mystdin; // Required for scanf over UART. } // This gets incremented every millisecond by the timer ISR. static volatile uint32_t ms_counter; // AVR timer interrupt handler. ISR(TIMER1_COMPA_vect) { ++ms_counter; } // Initializes AVR timer. static void init_timer() { TCCR1B |= (1 << WGM12); // Configure timer 1 for CTC mode TIMSK |= (1 << OCIE1A); // Enable CTC interrupt sei(); // Enable global interrupts OCR1A = 125; // Set CTC compare value to trigger at 1 kHz given // an 8-MHz clock with prescaler of 64. TCCR1B |= ((1 << CS11) | (1 << CS10)); // Start timer at Fcpu/64 ms_counter = 0; // Reset millisecond counter } // Initializes AVR external memory. static void init_external_memory() { MCUCR = (1<<SRE); XMCRB = (1<<XMBK) | (1<<XMM0); DDRC = 0xff; PORTC = 0; } static void system_init() { init_fdev(&mystdout, uart_putchar, NULL, _FDEV_SETUP_WRITE); init_fdev(&mystdin, NULL, uart_getchar, _FDEV_SETUP_READ); init_uart(); init_timer(); init_external_memory(); } #endif // !defined(__AVR__) ///////////// End embedded system definitions //////////////// namespace System { bool init() { #ifndef __AVR__ atexit(SDL_Quit); if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_AUDIO) < 0) { fprintf(stderr, "Unable to initialize SDL: %s\n", SDL_GetError()); return false; } #else system_init(); spipad_init(); #endif return true; } KeyState get_key_state() { KeyState key_state; memset(&key_state, 0, sizeof(key_state)); #ifndef __AVR__ // Get the current keys from SDL. Call SDL_PollEvent() to update the // key array with the latest values. Uint8* keys = SDL_GetKeyState(NULL); SDL_Event event; while(SDL_PollEvent(&event)); if (keys[SDLK_ESCAPE]) key_state.quit = 1; if (keys[SDLK_p]) key_state.pause = 1; if (keys[SDLK_LEFT]) key_state.left = 1; if (keys[SDLK_RIGHT]) key_state.right = 1; if (keys[SDLK_SPACE]) key_state.fire = 1; #else SpiPadButtons buttons = spipad_read(); if (buttons.A) key_state.quit = 1; if (buttons.START) key_state.pause = 1; if (buttons.LEFT) key_state.left = 1; if (buttons.RIGHT) key_state.right = 1; if (buttons.B) key_state.fire = 1; #endif // !defined(__AVR__) return key_state; } // This is just a wrapper around SDL_GetTicks. As part of the embedded port, // its contents will eventually be replaced with something else. uint32_t get_ticks() { #ifndef __AVR__ return SDL_GetTicks(); #else return ms_counter; #endif } void delay(uint16_t num_ticks) { #ifndef __AVR__ SDL_Delay(num_ticks); #else uint32_t final_time = get_ticks() + num_ticks; while (get_ticks() != final_time); #endif } }
/* system.cpp Classic Invaders Copyright (c) 2013, Simon Que 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 No Quarter Arcade (http://www.noquarterarcade.com/) nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "system.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <Arduino.h> #include <DuinoCube.h> namespace System { bool init() { return true; } KeyState get_key_state() { KeyState key_state; memset(&key_state, 0, sizeof(key_state)); GamepadState gamepad = DC.Gamepad.readGamepad(); if (gamepad.buttons & (1 << GAMEPAD_BUTTON_4) key_state.quit = 1; if (gamepad.buttons & (1 << GAMEPAD_BUTTON_2) key_state.pause = 1; if (gamepad.x == 0) key_state.left = 1; if (gamepad.x == UINT8_MAX) key_state.right = 1; if (buttons.buttons & (1 << GAMEPAD_BUTTON_1) key_state.fire = 1; return key_state; } // This is just a wrapper around SDL_GetTicks. As part of the embedded port, // its contents will eventually be replaced with something else. uint32_t get_ticks() { return millis(); } void delay(uint16_t num_ticks) { uint32_t final_time = get_ticks() + num_ticks; while (get_ticks() != final_time); } }
convert to Arduino
system: convert to Arduino
C++
bsd-3-clause
eecsninja/invaders,eecsninja/invaders
275814546965c278eba2caa9404094a595efc872
src/parser.cpp
src/parser.cpp
// Copyright (c) 2013-2014, Alberto Corona <[email protected]> // All rights reserved. This file is part of yabs, distributed under the BSD // 3-Clause license. For full terms please see the LICENSE file. #include <sys/types.h> #include <dirent.h> #include <fstream> #include <yaml.h> #include "parser.h" #include "gen.h" Parser::Parser(){}; Parser::~Parser(){}; int Parser::OpenConfig(const char *build_file) { if (AssertYML(build_file) == 1) { conf = fopen(build_file, "r"); if (conf == NULL) { printf("Error: No file named %s\n", build_file); return -2; } ParseConfig(); ParseValues(); CloseConfig(); return 1; } else { return -1; } return 0; } int Parser::ParseConfig() { if (conf != NULL) { yaml_parser_initialize(&parser); yaml_parser_set_input_file(&parser, conf); return 1; } return 0; } int Parser::CloseConfig() { if ((&parser != NULL) && (conf != NULL)) { yaml_parser_delete(&parser); yaml_token_delete(&token); fclose(conf); return 1; } else { return -1; } return 0; } int Parser::AssertYML(const char *build_file) { const char *ext; ext = strrchr(build_file, '.'); if (opendir(build_file) != NULL) { printf("Error: %s is a directory\n", build_file); return -3; } if (!ext) { printf("Error: %s has no extension\n", build_file); return -1; } if ((strcasecmp(ext + 1, "yml") == 0) || (strcasecmp(ext + 1, "yaml") == 0) || (strcasecmp(ext + 1, "ybf") == 0)) { return 1; } else { printf("Error: %s is not a valid build file\n", build_file); return -2; } return 0; } const char *Parser::ParseValues() { do { ReadValues(); } while (token_return != 0); return NULL; } const char *Parser::ReadValues() { do { yaml_parser_scan(&parser, &token); switch (token.type) { case YAML_VERSION_DIRECTIVE_TOKEN: break; case YAML_NO_TOKEN: break; case YAML_STREAM_START_TOKEN: break; case YAML_STREAM_END_TOKEN: break; case YAML_KEY_TOKEN: prs = key; break; case YAML_VALUE_TOKEN: prs = value; break; case YAML_TAG_DIRECTIVE_TOKEN: printf("Tag directive: %s\n", token.data.scalar.value); break; case YAML_DOCUMENT_START_TOKEN: IncDocNum(); break; case YAML_DOCUMENT_END_TOKEN: printf("...\n"); break; case YAML_BLOCK_SEQUENCE_START_TOKEN: printf("Block Seq Start\n"); break; case YAML_BLOCK_END_TOKEN: break; case YAML_BLOCK_MAPPING_START_TOKEN: break; case YAML_BLOCK_ENTRY_TOKEN: prs = block_entry; break; case YAML_FLOW_SEQUENCE_START_TOKEN: break; case YAML_FLOW_SEQUENCE_END_TOKEN: break; case YAML_FLOW_MAPPING_START_TOKEN: break; case YAML_FLOW_MAPPING_END_TOKEN: break; case YAML_FLOW_ENTRY_TOKEN: break; case YAML_ALIAS_TOKEN: printf("Alias token: %s\n", token.data.scalar.value); break; case YAML_ANCHOR_TOKEN: printf("Anchor token: %s\n", token.data.scalar.value); break; case YAML_TAG_TOKEN: printf("Tag token: %s\n", token.data.scalar.value); break; case YAML_SCALAR_TOKEN: switch (prs) { case error: break; case key: printf("%s: ", token.data.scalar.value); if (CompValid(token.data.scalar.value) == 1) { key_value = ConvValue(token.data.scalar.value); token_return = key; break; } else { printf("Error: '%s' is not a valid configuration option\n", token.data.scalar.value); token_return = error; token.type = YAML_STREAM_END_TOKEN; break; } break; case block_entry: printf(" - %s\n", token.data.scalar.value); PopValidValue(key_value, ConvValue(token.data.scalar.value)); token_return = block_entry; break; case value: printf("%s\n", token.data.scalar.value); PopValidValue(key_value, ConvValue(token.data.scalar.value)); printf("Key Value: %s\n", key_value.c_str()); token_return = value; break; default: printf("%s\n", token.data.scalar.value); break; } break; } } while (token.type != YAML_STREAM_END_TOKEN); token_return = error; return NULL; }
// Copyright (c) 2013-2014, Alberto Corona <[email protected]> // All rights reserved. This file is part of yabs, distributed under the BSD // 3-Clause license. For full terms please see the LICENSE file. #include <sys/types.h> #include <dirent.h> #include <fstream> #include <yaml.h> #include "parser.h" #include "gen.h" Parser::Parser(){}; Parser::~Parser(){}; int Parser::OpenConfig(const char *build_file) { if (AssertYML(build_file) == 1) { conf = fopen(build_file, "r"); if (conf == NULL) { printf("Error: No file named %s\n", build_file); return -2; } ParseConfig(); ParseValues(); CloseConfig(); return 1; } else { return -1; } return 0; } int Parser::ParseConfig() { if (conf != NULL) { yaml_parser_initialize(&parser); yaml_parser_set_input_file(&parser, conf); return 1; } return 0; } int Parser::CloseConfig() { if ((&parser != NULL) && (conf != NULL)) { yaml_parser_delete(&parser); yaml_token_delete(&token); fclose(conf); return 1; } else { return -1; } return 0; } int Parser::AssertYML(const char *build_file) { const char *ext; ext = strrchr(build_file, '.'); if (opendir(build_file) != NULL) { printf("Error: %s is a directory\n", build_file); return -3; } if (!ext) { printf("Error: %s has no extension\n", build_file); return -1; } if ((strcasecmp(ext + 1, "yml") == 0) || (strcasecmp(ext + 1, "yaml") == 0) || (strcasecmp(ext + 1, "ybf") == 0)) { return 1; } else { printf("Error: %s is not a valid build file\n", build_file); return -2; } return 0; } const char *Parser::ParseValues() { do { ReadValues(); } while (token_return != 0); return NULL; } const char *Parser::ReadValues() { do { yaml_parser_scan(&parser, &token); switch (token.type) { case YAML_VERSION_DIRECTIVE_TOKEN: break; case YAML_NO_TOKEN: break; case YAML_STREAM_START_TOKEN: break; case YAML_STREAM_END_TOKEN: break; case YAML_KEY_TOKEN: prs = key; break; case YAML_VALUE_TOKEN: prs = value; break; case YAML_TAG_DIRECTIVE_TOKEN: printf("Tag directive: %s\n", token.data.scalar.value); break; case YAML_DOCUMENT_START_TOKEN: IncDocNum(); break; case YAML_DOCUMENT_END_TOKEN: printf("...\n"); break; case YAML_BLOCK_SEQUENCE_START_TOKEN: printf("\n"); break; case YAML_BLOCK_END_TOKEN: break; case YAML_BLOCK_MAPPING_START_TOKEN: break; case YAML_BLOCK_ENTRY_TOKEN: prs = block_entry; break; case YAML_FLOW_SEQUENCE_START_TOKEN: break; case YAML_FLOW_SEQUENCE_END_TOKEN: break; case YAML_FLOW_MAPPING_START_TOKEN: break; case YAML_FLOW_MAPPING_END_TOKEN: break; case YAML_FLOW_ENTRY_TOKEN: break; case YAML_ALIAS_TOKEN: printf("Alias token: %s\n", token.data.scalar.value); break; case YAML_ANCHOR_TOKEN: printf("Anchor token: %s\n", token.data.scalar.value); break; case YAML_TAG_TOKEN: printf("Tag token: %s\n", token.data.scalar.value); break; case YAML_SCALAR_TOKEN: switch (prs) { case error: break; case key: printf("%s: ", token.data.scalar.value); if (CompValid(token.data.scalar.value) == 1) { key_value = ConvValue(token.data.scalar.value); token_return = key; break; } else { printf("Error: '%s' is not a valid configuration option\n", token.data.scalar.value); token_return = error; token.type = YAML_STREAM_END_TOKEN; break; } break; case block_entry: printf(" - %s\n", token.data.scalar.value); PopValidValue(key_value, ConvValue(token.data.scalar.value)); token_return = block_entry; break; case value: printf("%s\n", token.data.scalar.value); PopValidValue(key_value, ConvValue(token.data.scalar.value)); token_return = value; break; default: printf("%s\n", token.data.scalar.value); break; } break; } } while (token.type != YAML_STREAM_END_TOKEN); token_return = error; return NULL; }
remove verbosity in printing build file
parser: remove verbosity in printing build file Signed-off-by: Alberto Corona <[email protected]>
C++
bsd-3-clause
0X1A/yabs,0X1A/yabs,0X1A/yabs,0X1A/yabs
984a29e600a3cf8536d0716a3b7f0c4a678cd2f2
src/transp.cpp
src/transp.cpp
#include <stdio.h> #include <stdlib.h> #include "field_descriptor.hpp" int myrank, nprocs; int main(int argc, char *argv[]) { MPI_Init(&argc, &argv); MPI_Comm_rank(MPI_COMM_WORLD, &myrank); MPI_Comm_size(MPI_COMM_WORLD, &nprocs); int n[3]; field_descriptor *f0, *f1; switch(argc) { case 3: n[0] = atoi(argv[1]); n[1] = atoi(argv[2]); break; case 4: n[0] = atoi(argv[1]); n[1] = atoi(argv[2]); n[2] = atoi(argv[3]); break; default: printf("you messed up the parameters, I'm not doing anything.\n"); MPI_Finalize(); return EXIT_SUCCESS; break; } if (myrank == 0) printf( "transposing %dD array from \"data0\" into \"data1\"" " with %d processes.\n", argc - 1, nprocs); f0 = new field_descriptor(argc - 1, n, MPI_FLOAT); f1 = f0->get_transpose(); float *a0, *a1; a0 = (float*)malloc(f0->local_size*sizeof(float)); a1 = (float*)malloc(f1->local_size*sizeof(float)); f0->read("data0", (void*)a0); f0->transpose(a0, a1); f1->write("data1", (void*)a1); free(a0); free(a1); delete f0; delete f1; MPI_Finalize(); return EXIT_SUCCESS; }
#include <stdio.h> #include <stdlib.h> #include "field_descriptor.hpp" int myrank, nprocs; int main(int argc, char *argv[]) { MPI_Init(&argc, &argv); MPI_Comm_rank(MPI_COMM_WORLD, &myrank); MPI_Comm_size(MPI_COMM_WORLD, &nprocs); int n[3]; field_descriptor *f0, *f1; switch(argc) { case 3: n[0] = atoi(argv[1]); n[1] = atoi(argv[2]); break; case 4: n[0] = atoi(argv[1]); n[1] = atoi(argv[2]); n[2] = atoi(argv[3]); break; default: printf("you messed up the parameters, I'm not doing anything.\n"); MPI_Finalize(); return EXIT_SUCCESS; break; } if (myrank == 0) printf( "transposing %dD array from \"data0\" into \"data1\"" " with %d processes.\n", argc - 1, nprocs); f0 = new field_descriptor(argc - 1, n, MPI_FLOAT); f1 = f0->get_transpose(); float *a0, *a1; a0 = fftwf_alloc_real(f0->local_size); a1 = fftwf_alloc_real(f1->local_size); f0->read("data0", (void*)a0); f0->transpose(a0, a1); f1->write("data1", (void*)a1); fftw_free(a0); fftw_free(a1); delete f0; delete f1; MPI_Finalize(); return EXIT_SUCCESS; }
use fftw_malloc calls instead of malloc
use fftw_malloc calls instead of malloc
C++
apache-2.0
idies/MPIArrayTools,idies/MPIArrayTools
09994a12866d9edacfec0187faca5a9d27e96000
src/random.cpp
src/random.cpp
/* Copyright (c) 2014-2016 DataStax Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #if defined(_WIN32) #ifndef _WINSOCKAPI_ #define _WINSOCKAPI_ #endif #include <Windows.h> #include <WinCrypt.h> #else #include <errno.h> #include <fcntl.h> #include <unistd.h> #include <string.h> #include <sys/types.h> #include <sys/uio.h> #endif #include "logger.hpp" namespace cass { #if defined(_WIN32) uint64_t get_random_seed(uint64_t seed) { HCRYPTPROV provider; if (!CryptAcquireContext(&provider, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT | CRYPT_SILENT)) { LOG_CRITICAL("Unable to aqcuire cryptographic provider: 0x%x", GetLastError()); return seed; } if (!CryptGenRandom(provider, sizeof(seed), (BYTE*)&seed)) { LOG_CRITICAL("An error occurred attempting to generate random data: 0x%x", GetLastError()); return seed; } CryptReleaseContext(provider, 0); return seed; } #else #define STRERROR_BUFSIZE_ 256 #if defined(__APPLE__) || defined(__FreeBSD__) #define STRERROR_R_(errno, buf, bufsize) (strerror_r(errno, buf, bufsize), buf) #else #define STRERROR_R_(errno, buf, bufsize) strerror_r(errno, buf, bufsize) #endif uint64_t get_random_seed(uint64_t seed) { static const char* device = "/dev/urandom"; int fd = open(device, O_RDONLY); if (fd < 0) { char buf[STRERROR_BUFSIZE_]; char* err = STRERROR_R_(errno, buf, sizeof(buf)); LOG_CRITICAL("Unable to open random device (%s): %s", device, err); return seed; } ssize_t num_bytes = read(fd, reinterpret_cast<char*>(&seed), sizeof(seed)); if (num_bytes < 0) { char buf[STRERROR_BUFSIZE_]; char* err = STRERROR_R_(errno, buf, sizeof(buf)); LOG_CRITICAL("Unable to read from random device (%s): %s", device, err); } else if (num_bytes != sizeof(seed)) { char buf[STRERROR_BUFSIZE_]; char* err = STRERROR_R_(errno, buf, sizeof(buf)); LOG_CRITICAL("Unable to read full seed value (expected: %u read: %u) " "from random device (%s): %s", static_cast<unsigned int>(sizeof(seed)), static_cast<unsigned int>(num_bytes), device, err); } close(fd); return seed; } #endif } // namespace cass
/* Copyright (c) 2014-2016 DataStax Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #if defined(_WIN32) #ifndef _WINSOCKAPI_ #define _WINSOCKAPI_ #endif #include <Windows.h> #include <WinCrypt.h> #else #include <errno.h> #include <fcntl.h> #include <unistd.h> #include <string.h> #include <sys/types.h> #include <sys/uio.h> #endif #include "logger.hpp" namespace cass { #if defined(_WIN32) uint64_t get_random_seed(uint64_t seed) { HCRYPTPROV provider; if (!CryptAcquireContext(&provider, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT | CRYPT_SILENT)) { LOG_CRITICAL("Unable to aqcuire cryptographic provider: 0x%x", GetLastError()); return seed; } if (!CryptGenRandom(provider, sizeof(seed), (BYTE*)&seed)) { LOG_CRITICAL("An error occurred attempting to generate random data: 0x%x", GetLastError()); return seed; } CryptReleaseContext(provider, 0); return seed; } #else #define STRERROR_BUFSIZE_ 256 #if defined(__APPLE__) || defined(__FreeBSD__) || !defined(_GNU_SOURCE) || !defined(__GLIBC__) #define STRERROR_R_(errno, buf, bufsize) (strerror_r(errno, buf, bufsize), buf) #else #define STRERROR_R_(errno, buf, bufsize) strerror_r(errno, buf, bufsize) #endif uint64_t get_random_seed(uint64_t seed) { static const char* device = "/dev/urandom"; int fd = open(device, O_RDONLY); if (fd < 0) { char buf[STRERROR_BUFSIZE_]; char* err = STRERROR_R_(errno, buf, sizeof(buf)); LOG_CRITICAL("Unable to open random device (%s): %s", device, err); return seed; } ssize_t num_bytes = read(fd, reinterpret_cast<char*>(&seed), sizeof(seed)); if (num_bytes < 0) { char buf[STRERROR_BUFSIZE_]; char* err = STRERROR_R_(errno, buf, sizeof(buf)); LOG_CRITICAL("Unable to read from random device (%s): %s", device, err); } else if (num_bytes != sizeof(seed)) { char buf[STRERROR_BUFSIZE_]; char* err = STRERROR_R_(errno, buf, sizeof(buf)); LOG_CRITICAL("Unable to read full seed value (expected: %u read: %u) " "from random device (%s): %s", static_cast<unsigned int>(sizeof(seed)), static_cast<unsigned int>(num_bytes), device, err); } close(fd); return seed; } #endif } // namespace cass
Handle permissive errors for non GNU compilers
fix: Handle permissive errors for non GNU compilers
C++
apache-2.0
flightaware/cpp-driver,mpenick/cpp-driver,mikefero/cpp-driver,datastax/cpp-driver,hpcc-systems/cpp-driver,mpenick/cpp-driver,mikefero/cpp-driver,hpcc-systems/cpp-driver,flightaware/cpp-driver,flightaware/cpp-driver,mikefero/cpp-driver,mpenick/cpp-driver,hpcc-systems/cpp-driver,datastax/cpp-driver,mpenick/cpp-driver,datastax/cpp-driver,mikefero/cpp-driver,hpcc-systems/cpp-driver,datastax/cpp-driver,mikefero/cpp-driver,flightaware/cpp-driver
f6f0ef3ac8745a0ef90ca53eca1321a9eef2fddc
src/random.cpp
src/random.cpp
#include "random.h" #include "compiler.h" // The algorithm is D1(A1r), aka Ranq1, from Numerical Recipes. void rng_t::initialize (std::uint64_t seed) { state = 4101842887655102017ull; state ^= seed; state = get (); } NOINLINE std::uint64_t rng_t::get () { state ^= state >> 21; state ^= state << 35; state ^= state >> 4; return state * 2685821657736338717ull; } #include "random-util.h" // Random floating-point number uniformly distributed on the interval [a, b). float get_float (rng_t & rng, float a, float b) { return a + 0x1.0p-64f * rng.get () * (b - a); } // Return a random vector uniformly distributed in // the interior of a sphere centre the origin. v4f get_vector_in_ball (rng_t & rng, float radius) { union { __m128i i128; std::uint64_t u64 [2]; }; v4f v, vsq; v4f lim = { 0x1.0p62f, 0.0f, 0.0f, 0.0f, }; do { u64 [0] = rng.get (); u64 [1] = rng.get () & 0xffffffffull; v = _mm_cvtepi32_ps (i128); vsq = dot (v, v); } while (_mm_comige_ss (vsq, lim)); float rs = 0x1.0p-31f * radius; v4f k = { rs, rs, rs, 0.0f, }; return k * v; } // Return a random vector uniformly distributed in // the box [0,1)^3. v4f get_vector_in_box (rng_t & rng) { union { __m128i i128; std::uint64_t u64 [2]; }; u64 [0] = rng.get () & 0x7fffffff7fffffffull; u64 [1] = rng.get () & 0x7fffffffull; v4f v = _mm_cvtepi32_ps (i128); v4f k = { 0x1.0p-31f, 0x1.0p-31f, 0x1.0p-31f, 0.0f }; return k * v; }
#include "random.h" #include "compiler.h" // The xorshift family of PRNGs was introduced in [1]. // This particular generator, "xorshift64* A_1(12; 25; 27).M_32", is suggested in [2]. // [1] George Marsaglia (2003) http://www.jstatsoft.org/article/view/v008i14/xorshift.pdf // [2] Sebastiano Vigna (2014) http://arxiv.org/abs/1402.6246 void rng_t::initialize (std::uint64_t seed) { state = 4101842887655102017ull; state ^= seed; state = get (); } NOINLINE std::uint64_t rng_t::get () { state ^= state >> 12; state ^= state << 25; state ^= state >> 27; return state * 2685821657736338717ull; } #include "random-util.h" // Random floating-point number uniformly distributed on the interval [a, b). float get_float (rng_t & rng, float a, float b) { return a + 0x1.0p-64f * rng.get () * (b - a); } // Return a random vector uniformly distributed in // the interior of a sphere centre the origin. v4f get_vector_in_ball (rng_t & rng, float radius) { union { __m128i i128; std::uint64_t u64 [2]; }; v4f v, vsq; v4f lim = { 0x1.0p62f, 0.0f, 0.0f, 0.0f, }; do { u64 [0] = rng.get (); u64 [1] = rng.get () & 0xffffffffull; v = _mm_cvtepi32_ps (i128); vsq = dot (v, v); } while (_mm_comige_ss (vsq, lim)); float rs = 0x1.0p-31f * radius; v4f k = { rs, rs, rs, 0.0f, }; return k * v; } // Return a random vector uniformly distributed in // the box [0,1)^3. v4f get_vector_in_box (rng_t & rng) { union { __m128i i128; std::uint64_t u64 [2]; }; u64 [0] = rng.get () & 0x7fffffff7fffffffull; u64 [1] = rng.get () & 0x7fffffffull; v4f v = _mm_cvtepi32_ps (i128); v4f k = { 0x1.0p-31f, 0x1.0p-31f, 0x1.0p-31f, 0.0f }; return k * v; }
use a different xorshift64* generator.
random.cpp: use a different xorshift64* generator.
C++
apache-2.0
bustercopley/polymorph,bustercopley/polymorph
75df705108c8091b633e7c69884428900b8a396c
src/weakref.cc
src/weakref.cc
/* * Copyright (c) 2011, Ben Noordhuis <[email protected]> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <stdlib.h> #include "node.h" #include "nan.h" using namespace v8; using namespace node; namespace { typedef struct proxy_container { Persistent<Object> proxy; Persistent<Object> target; Persistent<Object> emitter; } proxy_container; Persistent<ObjectTemplate> proxyClass; NanCallback *globalCallback; bool IsDead(Handle<Object> proxy) { assert(proxy->InternalFieldCount() == 1); proxy_container *cont = reinterpret_cast<proxy_container*>( NanGetInternalFieldPointer(proxy, 0) ); return cont == NULL || cont->target.IsEmpty(); } Handle<Object> Unwrap(Handle<Object> proxy) { assert(!IsDead(proxy)); proxy_container *cont = reinterpret_cast<proxy_container*>( NanGetInternalFieldPointer(proxy, 0) ); return NanPersistentToLocal(cont->target); } Handle<Object> GetEmitter(Handle<Object> proxy) { proxy_container *cont = reinterpret_cast<proxy_container*>( NanGetInternalFieldPointer(proxy, 0) ); assert(cont != NULL); return NanPersistentToLocal(cont->emitter); } #define UNWRAP \ NanScope(); \ Handle<Object> obj; \ const bool dead = IsDead(args.This()); \ if (!dead) obj = Unwrap(args.This()); \ NAN_PROPERTY_GETTER(WeakNamedPropertyGetter) { UNWRAP NanReturnValue(dead ? Local<Value>() : obj->Get(property)); } NAN_PROPERTY_SETTER(WeakNamedPropertySetter) { UNWRAP if (!dead) obj->Set(property, value); NanReturnValue(value); } NAN_PROPERTY_QUERY(WeakNamedPropertyQuery) { NanScope(); NanReturnValue(Integer::New(None)); } NAN_PROPERTY_DELETER(WeakNamedPropertyDeleter) { UNWRAP NanReturnValue(Boolean::New(!dead && obj->Delete(property))); } NAN_INDEX_GETTER(WeakIndexedPropertyGetter) { UNWRAP NanReturnValue(dead ? Local<Value>() : obj->Get(index)); } NAN_INDEX_SETTER(WeakIndexedPropertySetter) { UNWRAP if (!dead) obj->Set(index, value); NanReturnValue(value); } NAN_INDEX_QUERY(WeakIndexedPropertyQuery) { NanScope(); NanReturnValue(Integer::New(None)); } NAN_INDEX_DELETER(WeakIndexedPropertyDeleter) { UNWRAP NanReturnValue(Boolean::New(!dead && obj->Delete(index))); } /** * Only one "enumerator" function needs to be defined. This function is used for * both the property and indexed enumerator functions. */ NAN_PROPERTY_ENUMERATOR(WeakPropertyEnumerator) { UNWRAP NanReturnValue(dead ? Array::New(0) : obj->GetPropertyNames()); } /** * Weakref callback function. Invokes the "global" callback function. */ NAN_WEAK_CALLBACK(void*, TargetCallback) { NanScope(); assert(NAN_WEAK_CALLBACK_OBJECT.IsNearDeath()); void* arg = NAN_WEAK_CALLBACK_DATA(void *); proxy_container *cont = reinterpret_cast<proxy_container *>(arg); // invoke global callback function Local<Value> argv[] = { NanPersistentToLocal(NAN_WEAK_CALLBACK_OBJECT), NanPersistentToLocal(cont->emitter) }; globalCallback->Call(2, argv); // clean everything up NanSetInternalFieldPointer(NanPersistentToLocal(cont->proxy), 0, NULL); NanDispose(cont->proxy); NanDispose(cont->target); NanDispose(cont->emitter); free(cont); } /** * `_create(obj, emitter)` JS function. */ NAN_METHOD(Create) { NanScope(); if (!args[0]->IsObject()) return NanThrowTypeError("Object expected"); proxy_container *cont = (proxy_container *) malloc(sizeof(proxy_container)); NanAssignPersistent(Object, cont->proxy, NanPersistentToLocal(proxyClass)->NewInstance()); NanAssignPersistent(Object, cont->target, args[0]->ToObject()); NanAssignPersistent(Object, cont->emitter, args[1]->ToObject()); NanSetInternalFieldPointer(NanPersistentToLocal(cont->proxy), 0, cont); NanMakeWeak(cont->target, reinterpret_cast<void *>(cont), TargetCallback); NanReturnValue(NanPersistentToLocal(cont->proxy)); } /** * TODO: Make this better. */ bool isWeakRef (Handle<Value> val) { return val->IsObject() && val->ToObject()->InternalFieldCount() == 1; } /** * `isWeakRef()` JS function. */ NAN_METHOD(IsWeakRef) { NanScope(); NanReturnValue(Boolean::New(isWeakRef(args[0]))); } #define WEAKREF_FIRST_ARG \ if (!isWeakRef(args[0])) { \ return NanThrowTypeError("Weakref instance expected"); \ } \ Local<Object> proxy = args[0]->ToObject(); /** * `get(weakref)` JS function. */ NAN_METHOD(Get) { NanScope(); WEAKREF_FIRST_ARG if (IsDead(proxy)) NanReturnUndefined(); NanReturnValue(Unwrap(proxy)); } /** * `isNearDeath(weakref)` JS function. */ NAN_METHOD(IsNearDeath) { NanScope(); WEAKREF_FIRST_ARG proxy_container *cont = reinterpret_cast<proxy_container*>( NanGetInternalFieldPointer(proxy, 0) ); assert(cont != NULL); Handle<Boolean> rtn = Boolean::New(cont->target.IsNearDeath()); NanReturnValue(rtn); } /** * `isDead(weakref)` JS function. */ NAN_METHOD(IsDead) { NanScope(); WEAKREF_FIRST_ARG NanReturnValue(Boolean::New(IsDead(proxy))); } /** * `_getEmitter(weakref)` JS function. */ NAN_METHOD(GetEmitter) { NanScope(); WEAKREF_FIRST_ARG NanReturnValue(GetEmitter(proxy)); } /** * Sets the global weak callback function. */ NAN_METHOD(SetCallback) { Local<Function> callbackHandle = args[0].As<Function>(); globalCallback = new NanCallback(callbackHandle); NanReturnUndefined(); } /** * Init function. */ void Initialize(Handle<Object> exports) { NanScope(); Handle<ObjectTemplate> p = ObjectTemplate::New(); NanAssignPersistent(ObjectTemplate, proxyClass, p); p->SetNamedPropertyHandler(WeakNamedPropertyGetter, WeakNamedPropertySetter, WeakNamedPropertyQuery, WeakNamedPropertyDeleter, WeakPropertyEnumerator); p->SetIndexedPropertyHandler(WeakIndexedPropertyGetter, WeakIndexedPropertySetter, WeakIndexedPropertyQuery, WeakIndexedPropertyDeleter, WeakPropertyEnumerator); p->SetInternalFieldCount(1); NODE_SET_METHOD(exports, "get", Get); NODE_SET_METHOD(exports, "isWeakRef", IsWeakRef); NODE_SET_METHOD(exports, "isNearDeath", IsNearDeath); NODE_SET_METHOD(exports, "isDead", IsDead); NODE_SET_METHOD(exports, "_create", Create); NODE_SET_METHOD(exports, "_getEmitter", GetEmitter); NODE_SET_METHOD(exports, "_setCallback", SetCallback); } } // anonymous namespace NODE_MODULE(weakref, Initialize);
/* * Copyright (c) 2011, Ben Noordhuis <[email protected]> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <stdlib.h> #include "node.h" #include "nan.h" using namespace v8; using namespace node; namespace { typedef struct proxy_container { Persistent<Object> proxy; Persistent<Object> target; Persistent<Object> emitter; } proxy_container; Persistent<ObjectTemplate> proxyClass; NanCallback *globalCallback; bool IsDead(Handle<Object> proxy) { assert(proxy->InternalFieldCount() == 1); proxy_container *cont = reinterpret_cast<proxy_container*>( NanGetInternalFieldPointer(proxy, 0) ); return cont == NULL || cont->target.IsEmpty(); } Handle<Object> Unwrap(Handle<Object> proxy) { assert(!IsDead(proxy)); proxy_container *cont = reinterpret_cast<proxy_container*>( NanGetInternalFieldPointer(proxy, 0) ); return NanPersistentToLocal(cont->target); } Handle<Object> GetEmitter(Handle<Object> proxy) { proxy_container *cont = reinterpret_cast<proxy_container*>( NanGetInternalFieldPointer(proxy, 0) ); assert(cont != NULL); return NanPersistentToLocal(cont->emitter); } #define UNWRAP \ NanScope(); \ Handle<Object> obj; \ const bool dead = IsDead(args.This()); \ if (!dead) obj = Unwrap(args.This()); \ NAN_PROPERTY_GETTER(WeakNamedPropertyGetter) { UNWRAP NanReturnValue(dead ? Local<Value>() : obj->Get(property)); } NAN_PROPERTY_SETTER(WeakNamedPropertySetter) { UNWRAP if (!dead) obj->Set(property, value); NanReturnValue(value); } NAN_PROPERTY_QUERY(WeakNamedPropertyQuery) { NanScope(); NanReturnValue(Integer::New(None)); } NAN_PROPERTY_DELETER(WeakNamedPropertyDeleter) { UNWRAP NanReturnValue(Boolean::New(!dead && obj->Delete(property))); } NAN_INDEX_GETTER(WeakIndexedPropertyGetter) { UNWRAP NanReturnValue(dead ? Local<Value>() : obj->Get(index)); } NAN_INDEX_SETTER(WeakIndexedPropertySetter) { UNWRAP if (!dead) obj->Set(index, value); NanReturnValue(value); } NAN_INDEX_QUERY(WeakIndexedPropertyQuery) { NanScope(); NanReturnValue(Integer::New(None)); } NAN_INDEX_DELETER(WeakIndexedPropertyDeleter) { UNWRAP NanReturnValue(Boolean::New(!dead && obj->Delete(index))); } /** * Only one "enumerator" function needs to be defined. This function is used for * both the property and indexed enumerator functions. */ NAN_PROPERTY_ENUMERATOR(WeakPropertyEnumerator) { UNWRAP NanReturnValue(dead ? Array::New(0) : obj->GetPropertyNames()); } /** * Weakref callback function. Invokes the "global" callback function. */ NAN_WEAK_CALLBACK(void*, TargetCallback) { NanScope(); assert(NAN_WEAK_CALLBACK_OBJECT.IsNearDeath()); void* arg = NAN_WEAK_CALLBACK_DATA(void *); proxy_container *cont = reinterpret_cast<proxy_container *>(arg); // invoke global callback function Local<Value> argv[] = { NanPersistentToLocal(NAN_WEAK_CALLBACK_OBJECT), NanPersistentToLocal(cont->emitter) }; globalCallback->Call(2, argv); // clean everything up NanSetInternalFieldPointer(NanPersistentToLocal(cont->proxy), 0, NULL); NanDispose(cont->proxy); NanDispose(cont->target); NanDispose(cont->emitter); free(cont); } /** * `_create(obj, emitter)` JS function. */ NAN_METHOD(Create) { NanScope(); if (!args[0]->IsObject()) return NanThrowTypeError("Object expected"); proxy_container *cont = (proxy_container *) malloc(sizeof(proxy_container)); Local<Object> proxy = NanPersistentToLocal(proxyClass)->NewInstance(); NanAssignPersistent(Object, cont->proxy, proxy); NanAssignPersistent(Object, cont->target, args[0]->ToObject()); NanAssignPersistent(Object, cont->emitter, args[1]->ToObject()); NanSetInternalFieldPointer(NanPersistentToLocal(cont->proxy), 0, cont); NanMakeWeak(cont->target, reinterpret_cast<void *>(cont), TargetCallback); NanReturnValue(proxy); } /** * TODO: Make this better. */ bool isWeakRef (Handle<Value> val) { return val->IsObject() && val->ToObject()->InternalFieldCount() == 1; } /** * `isWeakRef()` JS function. */ NAN_METHOD(IsWeakRef) { NanScope(); NanReturnValue(Boolean::New(isWeakRef(args[0]))); } #define WEAKREF_FIRST_ARG \ if (!isWeakRef(args[0])) { \ return NanThrowTypeError("Weakref instance expected"); \ } \ Local<Object> proxy = args[0]->ToObject(); /** * `get(weakref)` JS function. */ NAN_METHOD(Get) { NanScope(); WEAKREF_FIRST_ARG if (IsDead(proxy)) NanReturnUndefined(); NanReturnValue(Unwrap(proxy)); } /** * `isNearDeath(weakref)` JS function. */ NAN_METHOD(IsNearDeath) { NanScope(); WEAKREF_FIRST_ARG proxy_container *cont = reinterpret_cast<proxy_container*>( NanGetInternalFieldPointer(proxy, 0) ); assert(cont != NULL); Handle<Boolean> rtn = Boolean::New(cont->target.IsNearDeath()); NanReturnValue(rtn); } /** * `isDead(weakref)` JS function. */ NAN_METHOD(IsDead) { NanScope(); WEAKREF_FIRST_ARG NanReturnValue(Boolean::New(IsDead(proxy))); } /** * `_getEmitter(weakref)` JS function. */ NAN_METHOD(GetEmitter) { NanScope(); WEAKREF_FIRST_ARG NanReturnValue(GetEmitter(proxy)); } /** * Sets the global weak callback function. */ NAN_METHOD(SetCallback) { Local<Function> callbackHandle = args[0].As<Function>(); globalCallback = new NanCallback(callbackHandle); NanReturnUndefined(); } /** * Init function. */ void Initialize(Handle<Object> exports) { NanScope(); Handle<ObjectTemplate> p = ObjectTemplate::New(); NanAssignPersistent(ObjectTemplate, proxyClass, p); p->SetNamedPropertyHandler(WeakNamedPropertyGetter, WeakNamedPropertySetter, WeakNamedPropertyQuery, WeakNamedPropertyDeleter, WeakPropertyEnumerator); p->SetIndexedPropertyHandler(WeakIndexedPropertyGetter, WeakIndexedPropertySetter, WeakIndexedPropertyQuery, WeakIndexedPropertyDeleter, WeakPropertyEnumerator); p->SetInternalFieldCount(1); NODE_SET_METHOD(exports, "get", Get); NODE_SET_METHOD(exports, "isWeakRef", IsWeakRef); NODE_SET_METHOD(exports, "isNearDeath", IsNearDeath); NODE_SET_METHOD(exports, "isDead", IsDead); NODE_SET_METHOD(exports, "_create", Create); NODE_SET_METHOD(exports, "_getEmitter", GetEmitter); NODE_SET_METHOD(exports, "_setCallback", SetCallback); } } // anonymous namespace NODE_MODULE(weakref, Initialize);
save the weakref proxy instance as a Local ref
weakref: save the weakref proxy instance as a Local ref
C++
isc
fastest963/node-weak,unbornchikken/node-weak,TooTallNate/node-weak,robcolburn/node-weak,TooTallNate/node-weak,EvolveLabs/electron-weak,kkoopa/node-weak,EvolveLabs/electron-weak,fastest963/node-weak,EvolveLabs/electron-weak,robcolburn/node-weak,kkoopa/node-weak,kkoopa/node-weak,KenanSulayman/node-weak,TooTallNate/node-weak,unbornchikken/node-weak,robcolburn/node-weak,fastest963/node-weak,KenanSulayman/node-weak,KenanSulayman/node-weak,unbornchikken/node-weak
1f5ec2d26dc229b58b99864278fdfb2ff1a27d83
src/sm4_ofb.cc
src/sm4_ofb.cc
/****************************************************************************** * Copyright (c) 2015 Jamis Hoo * Distributed under the MIT license * (See accompanying file LICENSE or copy at http://opensource.org/licenses/MIT) * * Project: * Filename: sm4_ofb.cc * Version: 1.0 * Author: Jamis Hoo * E-mail: [email protected] * Date: May 16, 2015 * Time: 17:01:33 * Description: SM4(128 bit) Output Feedback Block(in 8 bit) Mode (OFB) *****************************************************************************/ #include <cstdio> #include <iostream> #include <fstream> #include <cinttypes> #include <vector> inline uint32_t left_rotate(const uint32_t x, const size_t i) { return x << i | (x >> (sizeof(uint32_t) * 8 - i)); } inline uint32_t tauTransformation(const uint32_t x) { constexpr uint8_t Sbox[256] = { 0xd6, 0x90, 0xe9, 0xfe, 0xcc, 0xe1, 0x3d, 0xb7, 0x16, 0xb6, 0x14, 0xc2, 0x28, 0xfb, 0x2c, 0x05, 0x2b, 0x67, 0x9a, 0x76, 0x2a, 0xbe, 0x04, 0xc3, 0xaa, 0x44, 0x13, 0x26, 0x49, 0x86, 0x06, 0x99, 0x9c, 0x42, 0x50, 0xf4, 0x91, 0xef, 0x98, 0x7a, 0x33, 0x54, 0x0b, 0x43, 0xed, 0xcf, 0xac, 0x62, 0xe4, 0xb3, 0x1c, 0xa9, 0xc9, 0x08, 0xe8, 0x95, 0x80, 0xdf, 0x94, 0xfa, 0x75, 0x8f, 0x3f, 0xa6, 0x47, 0x07, 0xa7, 0xfc, 0xf3, 0x73, 0x17, 0xba, 0x83, 0x59, 0x3c, 0x19, 0xe6, 0x85, 0x4f, 0xa8, 0x68, 0x6b, 0x81, 0xb2, 0x71, 0x64, 0xda, 0x8b, 0xf8, 0xeb, 0x0f, 0x4b, 0x70, 0x56, 0x9d, 0x35, 0x1e, 0x24, 0x0e, 0x5e, 0x63, 0x58, 0xd1, 0xa2, 0x25, 0x22, 0x7c, 0x3b, 0x01, 0x21, 0x78, 0x87, 0xd4, 0x00, 0x46, 0x57, 0x9f, 0xd3, 0x27, 0x52, 0x4c, 0x36, 0x02, 0xe7, 0xa0, 0xc4, 0xc8, 0x9e, 0xea, 0xbf, 0x8a, 0xd2, 0x40, 0xc7, 0x38, 0xb5, 0xa3, 0xf7, 0xf2, 0xce, 0xf9, 0x61, 0x15, 0xa1, 0xe0, 0xae, 0x5d, 0xa4, 0x9b, 0x34, 0x1a, 0x55, 0xad, 0x93, 0x32, 0x30, 0xf5, 0x8c, 0xb1, 0xe3, 0x1d, 0xf6, 0xe2, 0x2e, 0x82, 0x66, 0xca, 0x60, 0xc0, 0x29, 0x23, 0xab, 0x0d, 0x53, 0x4e, 0x6f, 0xd5, 0xdb, 0x37, 0x45, 0xde, 0xfd, 0x8e, 0x2f, 0x03, 0xff, 0x6a, 0x72, 0x6d, 0x6c, 0x5b, 0x51, 0x8d, 0x1b, 0xaf, 0x92, 0xbb, 0xdd, 0xbc, 0x7f, 0x11, 0xd9, 0x5c, 0x41, 0x1f, 0x10, 0x5a, 0xd8, 0x0a, 0xc1, 0x31, 0x88, 0xa5, 0xcd, 0x7b, 0xbd, 0x2d, 0x74, 0xd0, 0x12, 0xb8, 0xe5, 0xb4, 0xb0, 0x89, 0x69, 0x97, 0x4a, 0x0c, 0x96, 0x77, 0x7e, 0x65, 0xb9, 0xf1, 0x09, 0xc5, 0x6e, 0xc6, 0x84, 0x18, 0xf0, 0x7d, 0xec, 0x3a, 0xdc, 0x4d, 0x20, 0x79, 0xee, 0x5f, 0x3e, 0xd7, 0xcb, 0x39, 0x48 }; uint32_t val; val = Sbox[x >> 0 & 0xff] << 0 | Sbox[x >> 8 & 0xff] << 8 | Sbox[x >> 16 & 0xff] << 16 | Sbox[x >> 24 & 0xff] << 24; return val; } inline uint32_t endianConvert(const uint32_t x) { return (x << 24 & 0xff000000) | (x << 8 & 0x00ff0000) | (x >> 8 & 0x0000ff00) | (x >> 24 & 0x000000ff); } inline uint32_t LTransformation(const uint32_t x) { return x ^ left_rotate(x, 2) ^ left_rotate(x, 10) ^ left_rotate(x, 18) ^ left_rotate(x, 24); } inline uint32_t L1Transformation(const uint32_t x) { return x ^ left_rotate(x, 13) ^ left_rotate(x, 23); } inline uint32_t TTransformation(const uint32_t x) { return LTransformation(tauTransformation(x)); } inline uint32_t FFunction(const uint32_t x[], const uint32_t rkey) { return x[0] ^ TTransformation(x[1] ^ x[2] ^ x[3] ^ rkey); } // key: 16 bytes // keys: 32 * 4 bytes void keyExpansion(const uint8_t key[], uint32_t keys[]) { uint32_t mk[4]; mk[0] = key[ 0] << 24 | key[ 1] << 16 | key[ 2] << 8 | key[ 3] << 0; mk[1] = key[ 4] << 24 | key[ 5] << 16 | key[ 6] << 8 | key[ 7] << 0; mk[2] = key[ 8] << 24 | key[ 9] << 16 | key[10] << 8 | key[11] << 0; mk[3] = key[12] << 24 | key[13] << 16 | key[14] << 8 | key[15] << 0; constexpr uint32_t FK[4] = { 0xA3B1BAC6, 0x56AA3350, 0x677D9197, 0xB27022DC }; constexpr uint32_t CK[32] = { 0x00070e15, 0x1c232a31, 0x383f464d, 0x545b6269, 0x70777e85, 0x8c939aa1, 0xa8afb6bd, 0xc4cbd2d9, 0xe0e7eef5, 0xfc030a11, 0x181f262d, 0x343b4249, 0x50575e65, 0x6c737a81, 0x888f969d, 0xa4abb2b9, 0xc0c7ced5, 0xdce3eaf1, 0xf8ff060d, 0x141b2229, 0x30373e45, 0x4c535a61, 0x686f767d, 0x848b9299, 0xa0a7aeb5, 0xbcc3cad1, 0xd8dfe6ed, 0xf4fb0209, 0x10171e25, 0x2c333a41, 0x484f565d, 0x646b7279 }; uint32_t k[36]; k[0] = mk[0] ^ FK[0], k[1] = mk[1] ^ FK[1], k[2] = mk[2] ^ FK[2], k[3] = mk[3] ^ FK[3]; for (size_t i = 0; i < 32; ++i) keys[i] = k[i + 4] = k[i] ^ L1Transformation(tauTransformation(k[i + 1] ^ k[i + 2] ^ k[i + 3] ^ CK[i])); } void sm4Iteration(const uint32_t plain[], const uint32_t keys[], uint32_t cipher[]) { uint32_t x[36]; x[0] = endianConvert(plain[0]); x[1] = endianConvert(plain[1]); x[2] = endianConvert(plain[2]); x[3] = endianConvert(plain[3]); for (size_t i = 0; i < 32; ++i) x[i + 4] = FFunction(x + i, keys[i]); cipher[0] = endianConvert(x[35]); cipher[1] = endianConvert(x[34]); cipher[2] = endianConvert(x[33]); cipher[3] = endianConvert(x[32]); } void sm4_ofb(const void* plain, const size_t length, const void* key, const void* IV, void* cipher) { // I cannot guarantee this is correct. // The endian of SM4 is way too complicated const uint8_t* plain_ = (const uint8_t*)(plain); uint8_t* cipher_ = (uint8_t*)(cipher); uint32_t keys[32]; keyExpansion((const uint8_t*)(key), keys); uint8_t buffer[16]; memcpy(buffer, IV, 16); for (size_t i = 0; i < length; ++i) { sm4Iteration((const uint32_t*)buffer, keys, (uint32_t*)(cipher_ + i)); for (size_t j = 0; j < 15; ++j) buffer[j] = buffer[j + 1]; buffer[15] = cipher_[i]; cipher_[i] ^= plain_[i]; } } int main(int argc, char** argv) { if (argc == 1) return 0; std::ifstream fin(argv[1]); fin.seekg(0, std::ios::end); std::string buffer; size_t len = fin.tellg(); buffer.reserve(len); fin.seekg(0, std::ios::beg); buffer.assign((std::istreambuf_iterator<char>(fin)), std::istreambuf_iterator<char>()); fin.close(); // 128 bit key size unsigned char key[16] = { 0 }; unsigned char IV[16] = { 0 }; if (argc == 3) { fin.open(argv[2]); fin.seekg(0, std::ios::beg); char buffer[3] = { 0 }; for (size_t i = 0; i < 16; ++i) { fin.read(buffer, 2); key[i] = std::stoi(buffer, 0, 16); } fin.close(); } std::vector<char> cipher(buffer.length() + 16, 0); sm4_ofb(buffer.data(), buffer.length(), key, IV, &cipher[0]); for (size_t i = 0; i < buffer.length(); ++i) printf("%02x", int(cipher[i]) & 0xff); printf("\n"); }
/****************************************************************************** * Copyright (c) 2015 Jamis Hoo * Distributed under the MIT license * (See accompanying file LICENSE or copy at http://opensource.org/licenses/MIT) * * Project: * Filename: sm4_ofb.cc * Version: 1.0 * Author: Jamis Hoo * E-mail: [email protected] * Date: May 16, 2015 * Time: 17:01:33 * Description: SM4(128 bit) Output Feedback Block(in 8 bit) Mode (OFB) *****************************************************************************/ #include <cstdio> #include <iostream> #include <fstream> #include <cinttypes> #include <vector> inline uint32_t left_rotate(const uint32_t x, const size_t i) { return x << i | (x >> (sizeof(uint32_t) * 8 - i)); } inline uint32_t tauTransformation(const uint32_t x) { constexpr uint8_t Sbox[256] = { 0xd6, 0x90, 0xe9, 0xfe, 0xcc, 0xe1, 0x3d, 0xb7, 0x16, 0xb6, 0x14, 0xc2, 0x28, 0xfb, 0x2c, 0x05, 0x2b, 0x67, 0x9a, 0x76, 0x2a, 0xbe, 0x04, 0xc3, 0xaa, 0x44, 0x13, 0x26, 0x49, 0x86, 0x06, 0x99, 0x9c, 0x42, 0x50, 0xf4, 0x91, 0xef, 0x98, 0x7a, 0x33, 0x54, 0x0b, 0x43, 0xed, 0xcf, 0xac, 0x62, 0xe4, 0xb3, 0x1c, 0xa9, 0xc9, 0x08, 0xe8, 0x95, 0x80, 0xdf, 0x94, 0xfa, 0x75, 0x8f, 0x3f, 0xa6, 0x47, 0x07, 0xa7, 0xfc, 0xf3, 0x73, 0x17, 0xba, 0x83, 0x59, 0x3c, 0x19, 0xe6, 0x85, 0x4f, 0xa8, 0x68, 0x6b, 0x81, 0xb2, 0x71, 0x64, 0xda, 0x8b, 0xf8, 0xeb, 0x0f, 0x4b, 0x70, 0x56, 0x9d, 0x35, 0x1e, 0x24, 0x0e, 0x5e, 0x63, 0x58, 0xd1, 0xa2, 0x25, 0x22, 0x7c, 0x3b, 0x01, 0x21, 0x78, 0x87, 0xd4, 0x00, 0x46, 0x57, 0x9f, 0xd3, 0x27, 0x52, 0x4c, 0x36, 0x02, 0xe7, 0xa0, 0xc4, 0xc8, 0x9e, 0xea, 0xbf, 0x8a, 0xd2, 0x40, 0xc7, 0x38, 0xb5, 0xa3, 0xf7, 0xf2, 0xce, 0xf9, 0x61, 0x15, 0xa1, 0xe0, 0xae, 0x5d, 0xa4, 0x9b, 0x34, 0x1a, 0x55, 0xad, 0x93, 0x32, 0x30, 0xf5, 0x8c, 0xb1, 0xe3, 0x1d, 0xf6, 0xe2, 0x2e, 0x82, 0x66, 0xca, 0x60, 0xc0, 0x29, 0x23, 0xab, 0x0d, 0x53, 0x4e, 0x6f, 0xd5, 0xdb, 0x37, 0x45, 0xde, 0xfd, 0x8e, 0x2f, 0x03, 0xff, 0x6a, 0x72, 0x6d, 0x6c, 0x5b, 0x51, 0x8d, 0x1b, 0xaf, 0x92, 0xbb, 0xdd, 0xbc, 0x7f, 0x11, 0xd9, 0x5c, 0x41, 0x1f, 0x10, 0x5a, 0xd8, 0x0a, 0xc1, 0x31, 0x88, 0xa5, 0xcd, 0x7b, 0xbd, 0x2d, 0x74, 0xd0, 0x12, 0xb8, 0xe5, 0xb4, 0xb0, 0x89, 0x69, 0x97, 0x4a, 0x0c, 0x96, 0x77, 0x7e, 0x65, 0xb9, 0xf1, 0x09, 0xc5, 0x6e, 0xc6, 0x84, 0x18, 0xf0, 0x7d, 0xec, 0x3a, 0xdc, 0x4d, 0x20, 0x79, 0xee, 0x5f, 0x3e, 0xd7, 0xcb, 0x39, 0x48 }; uint32_t val; val = Sbox[x >> 0 & 0xff] << 0 | Sbox[x >> 8 & 0xff] << 8 | Sbox[x >> 16 & 0xff] << 16 | Sbox[x >> 24 & 0xff] << 24; return val; } inline uint32_t endianConvert(const uint32_t x) { return (x << 24 & 0xff000000) | (x << 8 & 0x00ff0000) | (x >> 8 & 0x0000ff00) | (x >> 24 & 0x000000ff); } inline uint32_t LTransformation(const uint32_t x) { return x ^ left_rotate(x, 2) ^ left_rotate(x, 10) ^ left_rotate(x, 18) ^ left_rotate(x, 24); } inline uint32_t L1Transformation(const uint32_t x) { return x ^ left_rotate(x, 13) ^ left_rotate(x, 23); } inline uint32_t TTransformation(const uint32_t x) { return LTransformation(tauTransformation(x)); } inline uint32_t FFunction(const uint32_t x[], const uint32_t rkey) { return x[0] ^ TTransformation(x[1] ^ x[2] ^ x[3] ^ rkey); } // key: 16 bytes // keys: 32 * 4 bytes void keyExpansion(const uint8_t key[], uint32_t keys[]) { uint32_t mk[4]; mk[0] = key[ 0] << 24 | key[ 1] << 16 | key[ 2] << 8 | key[ 3] << 0; mk[1] = key[ 4] << 24 | key[ 5] << 16 | key[ 6] << 8 | key[ 7] << 0; mk[2] = key[ 8] << 24 | key[ 9] << 16 | key[10] << 8 | key[11] << 0; mk[3] = key[12] << 24 | key[13] << 16 | key[14] << 8 | key[15] << 0; constexpr uint32_t FK[4] = { 0xA3B1BAC6, 0x56AA3350, 0x677D9197, 0xB27022DC }; constexpr uint32_t CK[32] = { 0x00070e15, 0x1c232a31, 0x383f464d, 0x545b6269, 0x70777e85, 0x8c939aa1, 0xa8afb6bd, 0xc4cbd2d9, 0xe0e7eef5, 0xfc030a11, 0x181f262d, 0x343b4249, 0x50575e65, 0x6c737a81, 0x888f969d, 0xa4abb2b9, 0xc0c7ced5, 0xdce3eaf1, 0xf8ff060d, 0x141b2229, 0x30373e45, 0x4c535a61, 0x686f767d, 0x848b9299, 0xa0a7aeb5, 0xbcc3cad1, 0xd8dfe6ed, 0xf4fb0209, 0x10171e25, 0x2c333a41, 0x484f565d, 0x646b7279 }; uint32_t k[36]; k[0] = mk[0] ^ FK[0], k[1] = mk[1] ^ FK[1], k[2] = mk[2] ^ FK[2], k[3] = mk[3] ^ FK[3]; for (size_t i = 0; i < 32; ++i) keys[i] = k[i + 4] = k[i] ^ L1Transformation(tauTransformation(k[i + 1] ^ k[i + 2] ^ k[i + 3] ^ CK[i])); } void sm4Iteration(const uint32_t plain[], const uint32_t keys[], uint32_t cipher[]) { uint32_t x[36]; x[0] = endianConvert(plain[0]); x[1] = endianConvert(plain[1]); x[2] = endianConvert(plain[2]); x[3] = endianConvert(plain[3]); for (size_t i = 0; i < 32; ++i) x[i + 4] = FFunction(x + i, keys[i]); cipher[0] = endianConvert(x[35]); cipher[1] = endianConvert(x[34]); cipher[2] = endianConvert(x[33]); cipher[3] = endianConvert(x[32]); } void sm4_ofb(const void* plain, const size_t length, const void* key, const void* IV, void* cipher) { // I cannot guarantee this is correct. // The endian of SM4 is way too complicated // nor can I find any documentation about SM4 OFB mode const uint8_t* plain_ = (const uint8_t*)(plain); uint8_t* cipher_ = (uint8_t*)(cipher); uint32_t keys[32]; keyExpansion((const uint8_t*)(key), keys); uint8_t buffer[16]; memcpy(buffer, IV, 16); for (size_t i = 0; i < length; ++i) { sm4Iteration((const uint32_t*)buffer, keys, (uint32_t*)(cipher_ + i)); for (size_t j = 0; j < 15; ++j) buffer[j] = buffer[j + 1]; buffer[15] = cipher_[i]; cipher_[i] ^= plain_[i]; } } int main(int argc, char** argv) { if (argc == 1) return 0; std::ifstream fin(argv[1]); fin.seekg(0, std::ios::end); std::string buffer; size_t len = fin.tellg(); buffer.reserve(len); fin.seekg(0, std::ios::beg); buffer.assign((std::istreambuf_iterator<char>(fin)), std::istreambuf_iterator<char>()); fin.close(); // 128 bit key size unsigned char key[16] = { 0 }; unsigned char IV[16] = { 0 }; if (argc == 3) { fin.open(argv[2]); fin.seekg(0, std::ios::beg); char buffer[3] = { 0 }; for (size_t i = 0; i < 16; ++i) { fin.read(buffer, 2); key[i] = std::stoi(buffer, 0, 16); } fin.close(); } std::vector<char> cipher(buffer.length() + 16, 0); sm4_ofb(buffer.data(), buffer.length(), key, IV, &cipher[0]); for (size_t i = 0; i < buffer.length(); ++i) printf("%02x", int(cipher[i]) & 0xff); printf("\n"); }
add comment
add comment
C++
mit
JamisHoo/Cryptographic-Algorithms
37af789afe731eccf29b33db93ff0fd01a3cf1ca
src/socket.cpp
src/socket.cpp
#include "socket.h" Socket::Socket() : socketfd(socket(AF_INET, SOCK_STREAM, 0)), connected(false) { socketAddr.sin_family = AF_INET; fcntl(socketfd, F_SETFL, O_NONBLOCK); } Socket::~Socket() { closeConnection(); } bool Socket::bindSocket(std::string address) { return false; } void Socket::closeConnection() {} bool Socket::isConnected() { return connected; } bool Socket::sendData(std::string message) { return false; } std::string Socket::receive() { return ""; }
#include "socket.h" Socket::Socket() : socketfd(socket(AF_INET, SOCK_STREAM, 0)), connected(false) { socketAddr.sin_family = AF_INET; fcntl(socketfd, F_SETFL, O_NONBLOCK); } Socket::~Socket() { closeConnection(); } bool Socket::bindSocket(std::string address) { return false; } void Socket::closeConnection() {} bool Socket::isConnected() { return connected; } bool Socket::sendData(std::string message) { return false; } std::string Socket::receive() { return ""; } void Socket::connectServer(std::string address, unsigned short port) {}
Define default Socket::connectServer function
Define default Socket::connectServer function
C++
mit
ElementalAlchemist/RoBoBo,ElementalAlchemist/RoBoBo
e06ae61a133e1c3b156a32a1b33e7514b645ea38
src/solver.cpp
src/solver.cpp
/** * solver.cpp * * by Mohammad Elmi * Created on 24 Oct 2013 */ #include "solver.h" #include "gradient.h" #include <iostream> #include <iomanip> namespace aban2 { void solver::write_step(size_t step) { std::stringstream s; s << out_path << std::setfill('0') << std::setw(6) << step << ".vtk"; d->write_vtk(s.str()); } solver::solver(domain *_d, std::string _out_path): d(_d), out_path(_out_path) { projector = new projection(d); _vof = new vof(d); diffusor = new diffusion(d); } solver::~solver() { delete projector; delete _vof; delete diffusor; } void solver::step() { for (int i = 0; i < NDIRS; ++i) std::copy_n(d->u[i], d->n, d->ustar[i]); std::cout << " advection " << std::endl; _vof->advect(); for (size_t i = 0; i < d->n; ++i) d->nu[i] = d->nu_bar(d->vof[i]); std::cout << " diffusion " << std::endl; diffusor->diffuse_ustar(); std::cout << " source terms " << std::endl; apply_source_terms(); std::cout << " pressure " << std::endl; projector->solve_p(); std::cout << " updating " << std::endl; projector->update_u(); std::cout << " calculating uf " << std::endl; projector->update_uf(); std::cout //<< std::scientific << " divergance: " << divergance() << std::endl; d->t += d->dt; } double solver::divergance() { auto grad_uf = gradient::of_uf(d); double result = 0; for (size_t i = 0; i < d->n; ++i) #ifdef THREE_D result += std::abs(grad_uf[0][0][i] + grad_uf[1][1][i] + grad_uf[2][2][i]); #else result += std::abs(grad_uf[0][0][i] + grad_uf[1][1][i]); #endif domain::delete_var(3, grad_uf); return result; } void solver::run(size_t nsteps) { for (size_t i = 0; i < d->n; ++i) d->rho[i] = d->rho_bar(d->vof[i]); write_step(0); for (size_t it = 0; it < nsteps; ++it) { std::cout << "running step " << it + 1 << std::endl << std::flush; step(); if ((it + 1) % d->write_interval == 0) write_step((it + 1) / d->write_interval); } } void solver::apply_source_terms() { for (size_t i = 0; i < d->n; ++i) { d->ustar[0][i] += d->g.cmpnt[0] * d->dt; d->ustar[1][i] += d->g.cmpnt[1] * d->dt; d->ustar[2][i] += d->g.cmpnt[2] * d->dt; } } }
/** * solver.cpp * * by Mohammad Elmi * Created on 24 Oct 2013 */ #include "solver.h" #include "gradient.h" #include <iostream> #include <cmath> #include <iomanip> namespace aban2 { void solver::write_step(size_t step) { std::stringstream s; s << out_path << std::setfill('0') << std::setw(6) << step << ".vtk"; d->write_vtk(s.str()); } solver::solver(domain *_d, std::string _out_path): d(_d), out_path(_out_path) { projector = new projection(d); _vof = new vof(d); diffusor = new diffusion(d); } solver::~solver() { delete projector; delete _vof; delete diffusor; } void solver::step() { for (int i = 0; i < NDIRS; ++i) std::copy_n(d->u[i], d->n, d->ustar[i]); std::cout << " advection " << std::endl; _vof->advect(); for (size_t i = 0; i < d->n; ++i) d->nu[i] = d->nu_bar(d->vof[i]); std::cout << " diffusion " << std::endl; diffusor->diffuse_ustar(); std::cout << " source terms " << std::endl; apply_source_terms(); std::cout << " pressure " << std::endl; projector->solve_p(); std::cout << " updating " << std::endl; projector->update_u(); std::cout << " calculating uf " << std::endl; projector->update_uf(); std::cout //<< std::scientific << " divergance: " << divergance() << std::endl; d->t += d->dt; } double solver::divergance() { auto grad_uf = gradient::of_uf(d); double result = 0; for (size_t i = 0; i < d->n; ++i) #ifdef THREE_D result += std::abs(grad_uf[0][0][i] + grad_uf[1][1][i] + grad_uf[2][2][i]); #else result += std::abs(grad_uf[0][0][i] + grad_uf[1][1][i]); #endif domain::delete_var(3, grad_uf); return result; } void solver::run(size_t nsteps) { for (size_t i = 0; i < d->n; ++i) d->rho[i] = d->rho_bar(d->vof[i]); write_step(0); for (size_t it = 0; it < nsteps; ++it) { std::cout << "running step " << it + 1 << std::endl << std::flush; step(); if ((it + 1) % d->write_interval == 0) write_step((it + 1) / d->write_interval); } } void solver::apply_source_terms() { for (size_t i = 0; i < d->n; ++i) { d->ustar[0][i] += d->g.cmpnt[0] * d->dt; d->ustar[1][i] += d->g.cmpnt[1] * d->dt; d->ustar[2][i] += d->g.cmpnt[2] * d->dt; } } }
include cmath added
include cmath added
C++
mit
melmi/aban2,melmi/aban2
07db5c3165ff49edecb8c1dc9891664711cd5c05
src/taglib2.cc
src/taglib2.cc
#include <errno.h> #include <string.h> #include <v8.h> #include <nan.h> #include <node.h> #include <node_buffer.h> #include <fstream> #include <cctype> #include <iostream> #include <iomanip> #include <sstream> #include <string.h> #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <stdlib.h> #define NDEBUG #define TAGLIB_STATIC #include <taglib/tag.h> #include <taglib/tlist.h> #include <taglib/fileref.h> #include <taglib/tfile.h> #include <taglib/flacfile.h> #include <taglib/mp4tag.h> #include <taglib/mp4atom.h> #include <taglib/mp4file.h> #include <taglib/tpicturemap.h> #include <taglib/tpropertymap.h> #include <taglib/tbytevector.h> #include <taglib/tbytevectorlist.h> using namespace std; using namespace v8; using namespace node; Local<Value> TagLibStringToString(TagLib::String s) { if (s.isEmpty()) return Nan::Null(); TagLib::ByteVector str = s.data(TagLib::String::UTF16); return Nan::New<v8::String>( (uint16_t *) str.mid(2, str.size()-2).data(), s.size() ).ToLocalChecked(); } TagLib::String StringToTagLibString(std::string s) { return TagLib::String(s, TagLib::String::UTF8); } bool isFile(const char *s) { struct stat st; #ifdef _WIN32 return ::stat(s, &st) == 0 && (st.st_mode & (S_IFREG)); #else return ::stat(s, &st) == 0 && (st.st_mode & (S_IFREG | S_IFLNK)); #endif } NAN_METHOD(writeTagsSync) { Nan::HandleScope scope; Local<v8::Object> options; if (info.Length() < 2) { Nan::ThrowTypeError("Expected 2 arguments"); return; } if (!info[0]->IsString()) { Nan::ThrowTypeError("Expected a path to audio file"); return; } if (!info[1]->IsObject()) return; options = v8::Local<v8::Object>::Cast(info[1]); std::string audio_file = *v8::String::Utf8Value(info[0]->ToString()); if (!isFile(audio_file.c_str())) { Nan::ThrowTypeError("Audio file not found"); return; } TagLib::FileRef f(audio_file.c_str()); TagLib::Tag *tag = f.tag(); TagLib::PropertyMap map = f.properties(); if (!tag) { Nan::ThrowTypeError("Could not parse file"); return; } bool hasProps = false; auto hasOption = [&]( Local<v8::Object> o, const std::string name) -> bool { return o->Has(Nan::New(name).ToLocalChecked()); }; auto getOptionString = [&]( Local<v8::Object> o, const std::string name) -> TagLib::String { auto r = o->Get(Nan::New(name).ToLocalChecked()); std::string s = *v8::String::Utf8Value(r); return StringToTagLibString(s); }; auto getOptionInt = [&]( Local<v8::Object> o, const std::string name) -> int { return o->Get(Nan::New(name).ToLocalChecked())->Int32Value(); }; if (hasOption(options, "albumartist")) { hasProps = true; TagLib::String value = getOptionString(options, "albumartist"); map.erase(TagLib::String("ALBUMARTIST")); map.insert(TagLib::String("ALBUMARTIST"), value); } if (hasOption(options, "discnumber")) { hasProps = true; TagLib::String value = getOptionString(options, "discnumber"); map.erase(TagLib::String("DISCNUMBER")); map.insert(TagLib::String("DISCNUMBER"), value); } if (hasOption(options, "tracknumber")) { hasProps = true; TagLib::String value = getOptionString(options, "tracknumber"); map.erase(TagLib::String("TRACKNUMBER")); map.insert(TagLib::String("TRACKNUMBER"), value); } if (hasOption(options, "composer")) { hasProps = true; TagLib::String value = getOptionString(options, "composer"); map.erase(TagLib::String("COMPOSER")); map.insert(TagLib::String("COMPOSER"), value); } if (hasOption(options, "id")) { hasProps = true; TagLib::String value = getOptionString(options, "id"); map.erase(TagLib::String("ID")); map.insert(TagLib::String("ID"), value); } if (hasOption(options, "bpm")) { hasProps = true; TagLib::String value = getOptionString(options, "bpm"); map.erase(TagLib::String("BPM")); map.insert(TagLib::String("BPM"), value); } if (hasProps) { f.setProperties(map); } if (hasOption(options, "artist")) { tag->setArtist(getOptionString(options, "artist")); } if (hasOption(options, "title")) { tag->setTitle(getOptionString(options, "title")); } if (hasOption(options, "album")) { tag->setAlbum(getOptionString(options, "album")); } if (hasOption(options, "comment")) { tag->setComment(getOptionString(options, "comment")); } if (hasOption(options, "genre")) { tag->setGenre(getOptionString(options, "genre")); } if (hasOption(options, "year")) { tag->setYear(getOptionInt(options, "year")); } if (hasOption(options, "track")) { tag->setTrack(getOptionInt(options, "track")); } if (hasOption(options, "pictures")) { auto pictures = options->Get(Nan::New("pictures").ToLocalChecked()); Local<Array> pics = Local<Array>::Cast(pictures); unsigned int plen = pics->Length(); TagLib::PictureMap picMap; bool hasPics = false; for (unsigned int i = 0; i < plen; i++) { Local<v8::Object> imgObj = Handle<Object>::Cast(pics->Get(i)); if (!hasOption(imgObj, "mimetype")) { Nan::ThrowTypeError("mimetype required for each picture"); return; } if (!hasOption(imgObj, "picture")) { Nan::ThrowTypeError("picture required for each item in pictures array"); return; } auto mimetype = getOptionString(imgObj, "mimetype"); auto picture = imgObj->Get(Nan::New("picture").ToLocalChecked()); if (!picture.IsEmpty() && node::Buffer::HasInstance(picture->ToObject())) { char* buffer = node::Buffer::Data(picture->ToObject()); const size_t blen = node::Buffer::Length(picture->ToObject()); TagLib::ByteVector data(buffer, blen); TagLib::Picture pic(data, TagLib::Picture::FrontCover, mimetype, "Added with node-taglib2"); picMap.insert(pic); hasPics = true; } } if (hasPics) { tag->setPictures(picMap); } } f.save(); info.GetReturnValue().Set(Nan::True()); } NAN_METHOD(readTagsSync) { Nan::HandleScope scope; if (!info[0]->IsString()) { Nan::ThrowTypeError("Expected a path to audio file"); return; } std::string audio_file = *v8::String::Utf8Value(info[0]->ToString()); if (!isFile(audio_file.c_str())) { Nan::ThrowTypeError("Audio file not found"); return; } string ext; const size_t pos = audio_file.find_last_of("."); if (pos != -1) { ext = audio_file.substr(pos + 1); for (std::string::size_type i = 0; i < ext.length(); ++i) ext[i] = std::toupper(ext[i]); } TagLib::FileRef f(audio_file.c_str()); TagLib::Tag *tag = f.tag(); TagLib::PropertyMap map = f.properties(); if (!tag || f.isNull()) { Nan::ThrowTypeError("Could not parse file"); return; } v8::Local<v8::Object> obj = Nan::New<v8::Object>(); !tag->title().isEmpty() && obj->Set( Nan::New("title").ToLocalChecked(), TagLibStringToString(tag->title()) ); !tag->artist().isEmpty() && obj->Set( Nan::New("artist").ToLocalChecked(), TagLibStringToString(tag->artist()) ); if (map.contains("COMPILATION")) { obj->Set( Nan::New("compilation").ToLocalChecked(), TagLibStringToString(map["COMPILATION"].toString(",")) ); } if (map.contains("ID")) { obj->Set( Nan::New("id").ToLocalChecked(), TagLibStringToString(map["ID"].toString(",")) ); } if (map.contains("ALBUMARTIST")) { obj->Set( Nan::New("albumartist").ToLocalChecked(), TagLibStringToString(map["ALBUMARTIST"].toString(",")) ); } if (map.contains("DISCNUMBER")) { obj->Set( Nan::New("discnumber").ToLocalChecked(), TagLibStringToString(map["DISCNUMBER"].toString(",")) ); } if (map.contains("TRACKNUMBER")) { obj->Set( Nan::New("tracknumber").ToLocalChecked(), TagLibStringToString(map["TRACKNUMBER"].toString(",")) ); } if (map.contains("BPM")) { TagLib::String sl = map["BPM"].toString(""); TagLib::ByteVector vec = sl.data(TagLib::String::UTF8); char* s = vec.data(); int i = 0; if (s) { i = atoi(s); } obj->Set( Nan::New("bpm").ToLocalChecked(), Nan::New<v8::Integer>(i) ); } if (map.contains("COMPOSER")) { obj->Set( Nan::New("composer").ToLocalChecked(), TagLibStringToString(map["COMPOSER"].toString(",")) ); } !tag->album().isEmpty() && obj->Set( Nan::New("album").ToLocalChecked(), TagLibStringToString(tag->album()) ); !tag->comment().isEmpty() && obj->Set( Nan::New("comment").ToLocalChecked(), TagLibStringToString(tag->comment()) ); !tag->genre().isEmpty() && obj->Set( Nan::New("genre").ToLocalChecked(), TagLibStringToString(tag->genre()) ); obj->Set( // is always at least 0 Nan::New("track").ToLocalChecked(), Nan::New<v8::Integer>(tag->track()) ); obj->Set( // is always at least 0 Nan::New("year").ToLocalChecked(), Nan::New<v8::Integer>(tag->year()) ); // Ok, this was a quick fix. And I'll admit, opening another handle to the // file is not the greatest way to get the pictures for flac files. It seems // like this should be managed by the tag->pictures() method on FileRef, but // isn't, open to changes here. if (audio_file.find(".flac") != std::string::npos) { TagLib::FLAC::File flacfile(audio_file.c_str()); TagLib::List<TagLib::FLAC::Picture *> list = flacfile.pictureList(); size_t arraySize = list.size(); v8::Local<v8::Array> pictures = Nan::New<v8::Array>(arraySize); int picIndex = 0; for (auto& p : list) { v8::Local<v8::Object> imgObj = Nan::New<v8::Object>(); auto data = p->data(); auto datasize = data.size(); const char* rawdata = data.data(); v8::Local<v8::Object> buf = Nan::NewBuffer(datasize).ToLocalChecked(); memcpy(node::Buffer::Data(buf), rawdata, datasize); imgObj->Set( Nan::New("mimetype").ToLocalChecked(), TagLibStringToString(p->mimeType()) ); imgObj->Set( Nan::New("picture").ToLocalChecked(), buf ); pictures->Set(picIndex++, imgObj); } obj->Set(Nan::New("pictures").ToLocalChecked(), pictures); } else if (!tag->pictures().isEmpty()) { size_t arraySize = tag->pictures().size(); v8::Local<v8::Array> pictures = Nan::New<v8::Array>(arraySize); int picIndex = 0; for (auto& p : tag->pictures()) { v8::Local<v8::Object> imgObj = Nan::New<v8::Object>(); auto data = p.second[0].data(); auto datasize = data.size(); const char* rawdata = data.data(); v8::Local<v8::Object> buf = Nan::NewBuffer(datasize).ToLocalChecked(); memcpy(node::Buffer::Data(buf), rawdata, datasize); imgObj->Set( Nan::New("mimetype").ToLocalChecked(), TagLibStringToString(p.second[0].mime()) ); imgObj->Set( Nan::New("picture").ToLocalChecked(), buf ); pictures->Set(picIndex++, imgObj); } obj->Set(Nan::New("pictures").ToLocalChecked(), pictures); } if (f.audioProperties()) { TagLib::AudioProperties *properties = f.audioProperties(); int seconds = properties->length() % 60; int minutes = (properties->length() - seconds) / 60; obj->Set( Nan::New("bitrate").ToLocalChecked(), Nan::New<v8::Integer>(properties->bitrate()) ); obj->Set( Nan::New("samplerate").ToLocalChecked(), Nan::New<v8::Integer>(properties->sampleRate()) ); obj->Set( Nan::New("channels").ToLocalChecked(), Nan::New<v8::Integer>(properties->channels()) ); // this is the same hackery, a second read, is required to get the codec // since codec isn't always a member of audioProperties. There should be // a better way of getting properties that are unique to each format. if (ext == "M4A" || ext == "MP4") { TagLib::MP4::File mp4file(audio_file.c_str()); if (mp4file.audioProperties()) { auto codec = mp4file.audioProperties()->codec(); string encoding = codec == 2 ? "alac" : "aac"; obj->Set( Nan::New("codec").ToLocalChecked(), Nan::New<v8::String>(encoding).ToLocalChecked() ); } } stringstream ss; ss << minutes << ":" << setfill('0') << setw(2) << seconds; string s = ss.str(); auto time = Nan::New<v8::String>(s.c_str(), s.size()).ToLocalChecked(); obj->Set(Nan::New("time").ToLocalChecked(), time); obj->Set( Nan::New("length").ToLocalChecked(), Nan::New<v8::Integer>(properties->length()) ); } info.GetReturnValue().Set(obj); } void Init(v8::Local<v8::Object> exports, v8::Local<v8::Value> module, void *) { exports->Set(Nan::New("writeTagsSync").ToLocalChecked(), Nan::New<v8::FunctionTemplate>(writeTagsSync)->GetFunction()); exports->Set(Nan::New("readTagsSync").ToLocalChecked(), Nan::New<v8::FunctionTemplate>(readTagsSync)->GetFunction()); } NODE_MODULE(taglib2, Init)
#include <errno.h> #include <string.h> #include <v8.h> #include <nan.h> #include <node.h> #include <node_buffer.h> #include <fstream> #include <cctype> #include <iostream> #include <iomanip> #include <sstream> #include <string.h> #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <stdlib.h> #define NDEBUG #define TAGLIB_STATIC #include <taglib/tag.h> #include <taglib/tlist.h> #include <taglib/fileref.h> #include <taglib/tfile.h> #include <taglib/flacfile.h> #include <taglib/mp4tag.h> #include <taglib/mp4atom.h> #include <taglib/mp4file.h> #include <taglib/tpicturemap.h> #include <taglib/tpropertymap.h> #include <taglib/tbytevector.h> #include <taglib/tbytevectorlist.h> using namespace std; using namespace v8; using namespace node; Local<Value> TagLibStringToString(TagLib::String s) { if (s.isEmpty()) return Nan::Null(); TagLib::ByteVector str = s.data(TagLib::String::UTF16); return Nan::New<v8::String>( (uint16_t *) str.mid(2, str.size()-2).data(), s.size() ).ToLocalChecked(); } TagLib::String StringToTagLibString(std::string s) { return TagLib::String(s, TagLib::String::UTF8); } bool isFile(const char *s) { struct stat st; #ifdef _WIN32 return ::stat(s, &st) == 0 && (st.st_mode & (S_IFREG)); #else return ::stat(s, &st) == 0 && (st.st_mode & (S_IFREG | S_IFLNK)); #endif } NAN_METHOD(writeTagsSync) { Nan::HandleScope scope; Local<v8::Object> options; if (info.Length() < 2) { Nan::ThrowTypeError("Expected 2 arguments"); return; } if (!info[0]->IsString()) { Nan::ThrowTypeError("Expected a path to audio file"); return; } if (!info[1]->IsObject()) return; options = v8::Local<v8::Object>::Cast(info[1]); std::string audio_file = *v8::String::Utf8Value(info[0]->ToString()); if (!isFile(audio_file.c_str())) { Nan::ThrowTypeError("Audio file not found"); return; } TagLib::FileRef f(audio_file.c_str()); TagLib::Tag *tag = f.tag(); TagLib::PropertyMap map = f.properties(); if (!tag) { Nan::ThrowTypeError("Could not parse file"); return; } bool hasProps = false; auto hasOption = [&]( Local<v8::Object> o, const std::string name) -> bool { return o->Has(Nan::New(name).ToLocalChecked()); }; auto getOptionString = [&]( Local<v8::Object> o, const std::string name) -> TagLib::String { auto r = o->Get(Nan::New(name).ToLocalChecked()); std::string s = *v8::String::Utf8Value(r); return StringToTagLibString(s); }; auto getOptionInt = [&]( Local<v8::Object> o, const std::string name) -> int { return o->Get(Nan::New(name).ToLocalChecked())->Int32Value(); }; if (hasOption(options, "albumartist")) { hasProps = true; TagLib::String value = getOptionString(options, "albumartist"); map.erase(TagLib::String("ALBUMARTIST")); map.insert(TagLib::String("ALBUMARTIST"), value); } if (hasOption(options, "discnumber")) { hasProps = true; TagLib::String value = getOptionString(options, "discnumber"); map.erase(TagLib::String("DISCNUMBER")); map.insert(TagLib::String("DISCNUMBER"), value); } if (hasOption(options, "tracknumber")) { hasProps = true; TagLib::String value = getOptionString(options, "tracknumber"); map.erase(TagLib::String("TRACKNUMBER")); map.insert(TagLib::String("TRACKNUMBER"), value); } if (hasOption(options, "composer")) { hasProps = true; TagLib::String value = getOptionString(options, "composer"); map.erase(TagLib::String("COMPOSER")); map.insert(TagLib::String("COMPOSER"), value); } if (hasOption(options, "id")) { hasProps = true; TagLib::String value = getOptionString(options, "id"); map.erase(TagLib::String("ID")); map.insert(TagLib::String("ID"), value); } if (hasOption(options, "bpm")) { hasProps = true; TagLib::String value = getOptionString(options, "bpm"); map.erase(TagLib::String("BPM")); map.insert(TagLib::String("BPM"), value); } if (hasProps) { f.setProperties(map); } if (hasOption(options, "artist")) { tag->setArtist(getOptionString(options, "artist")); } if (hasOption(options, "title")) { tag->setTitle(getOptionString(options, "title")); } if (hasOption(options, "album")) { tag->setAlbum(getOptionString(options, "album")); } if (hasOption(options, "comment")) { tag->setComment(getOptionString(options, "comment")); } if (hasOption(options, "genre")) { tag->setGenre(getOptionString(options, "genre")); } if (hasOption(options, "year")) { tag->setYear(getOptionInt(options, "year")); } if (hasOption(options, "track")) { tag->setTrack(getOptionInt(options, "track")); } if (hasOption(options, "pictures")) { auto pictures = options->Get(Nan::New("pictures").ToLocalChecked()); Local<Array> pics = Local<Array>::Cast(pictures); unsigned int plen = pics->Length(); TagLib::PictureMap picMap; bool hasPics = false; for (unsigned int i = 0; i < plen; i++) { Local<v8::Object> imgObj = Handle<Object>::Cast(pics->Get(i)); if (!hasOption(imgObj, "mimetype")) { Nan::ThrowTypeError("mimetype required for each picture"); return; } if (!hasOption(imgObj, "picture")) { Nan::ThrowTypeError("picture required for each item in pictures array"); return; } auto mimetype = getOptionString(imgObj, "mimetype"); auto picture = imgObj->Get(Nan::New("picture").ToLocalChecked()); if (!picture.IsEmpty() && node::Buffer::HasInstance(picture->ToObject())) { char* buffer = node::Buffer::Data(picture->ToObject()); const size_t blen = node::Buffer::Length(picture->ToObject()); TagLib::ByteVector data(buffer, blen); TagLib::Picture pic(data, TagLib::Picture::FrontCover, mimetype, "Added with node-taglib2"); picMap.insert(pic); hasPics = true; } } if (hasPics) { tag->setPictures(picMap); } } f.save(); info.GetReturnValue().Set(Nan::True()); } NAN_METHOD(readTagsSync) { Nan::HandleScope scope; if (!info[0]->IsString()) { Nan::ThrowTypeError("Expected a path to audio file"); return; } std::string audio_file = *v8::String::Utf8Value(info[0]->ToString()); if (!isFile(audio_file.c_str())) { Nan::ThrowTypeError("Audio file not found"); return; } string ext; const size_t pos = audio_file.find_last_of("."); if (pos != -1) { ext = audio_file.substr(pos + 1); for (std::string::size_type i = 0; i < ext.length(); ++i) ext[i] = std::toupper(ext[i]); } TagLib::FileRef f(audio_file.c_str()); TagLib::Tag *tag = f.tag(); TagLib::PropertyMap map = f.properties(); if (!tag || f.isNull()) { Nan::ThrowTypeError("Could not parse file"); return; } v8::Local<v8::Object> obj = Nan::New<v8::Object>(); !tag->title().isEmpty() && obj->Set( Nan::New("title").ToLocalChecked(), TagLibStringToString(tag->title()) ); !tag->artist().isEmpty() && obj->Set( Nan::New("artist").ToLocalChecked(), TagLibStringToString(tag->artist()) ); if (map.contains("COMPILATION")) { obj->Set( Nan::New("compilation").ToLocalChecked(), TagLibStringToString(map["COMPILATION"].toString(",")) ); } if (map.contains("ID")) { obj->Set( Nan::New("id").ToLocalChecked(), TagLibStringToString(map["ID"].toString(",")) ); } if (map.contains("ALBUMARTIST")) { obj->Set( Nan::New("albumartist").ToLocalChecked(), TagLibStringToString(map["ALBUMARTIST"].toString(",")) ); } if (map.contains("DISCNUMBER")) { obj->Set( Nan::New("discnumber").ToLocalChecked(), TagLibStringToString(map["DISCNUMBER"].toString(",")) ); } if (map.contains("TRACKNUMBER")) { obj->Set( Nan::New("tracknumber").ToLocalChecked(), TagLibStringToString(map["TRACKNUMBER"].toString(",")) ); } if (map.contains("BPM")) { TagLib::String sl = map["BPM"].toString(""); TagLib::ByteVector vec = sl.data(TagLib::String::UTF8); char* s = vec.data(); int i = 0; if (s) { i = atoi(s); } obj->Set( Nan::New("bpm").ToLocalChecked(), Nan::New<v8::Integer>(i) ); } if (map.contains("COMPOSER")) { obj->Set( Nan::New("composer").ToLocalChecked(), TagLibStringToString(map["COMPOSER"].toString(",")) ); } !tag->album().isEmpty() && obj->Set( Nan::New("album").ToLocalChecked(), TagLibStringToString(tag->album()) ); !tag->comment().isEmpty() && obj->Set( Nan::New("comment").ToLocalChecked(), TagLibStringToString(tag->comment()) ); !tag->genre().isEmpty() && obj->Set( Nan::New("genre").ToLocalChecked(), TagLibStringToString(tag->genre()) ); obj->Set( // is always at least 0 Nan::New("track").ToLocalChecked(), Nan::New<v8::Integer>(tag->track()) ); obj->Set( // is always at least 0 Nan::New("year").ToLocalChecked(), Nan::New<v8::Integer>(tag->year()) ); // Ok, this was a quick fix. And I'll admit, opening another handle to the // file is not the greatest way to get the pictures for flac files. It seems // like this should be managed by the tag->pictures() method on FileRef, but // isn't, open to changes here. if (audio_file.find(".flac") != std::string::npos) { TagLib::FLAC::File flacfile(audio_file.c_str()); TagLib::List<TagLib::FLAC::Picture *> list = flacfile.pictureList(); size_t arraySize = list.size(); v8::Local<v8::Array> pictures = Nan::New<v8::Array>(arraySize); int picIndex = 0; for (auto& p : list) { v8::Local<v8::Object> imgObj = Nan::New<v8::Object>(); auto data = p->data(); auto datasize = data.size(); const char* rawdata = data.data(); v8::Local<v8::Object> buf = Nan::NewBuffer(datasize).ToLocalChecked(); memcpy(node::Buffer::Data(buf), rawdata, datasize); imgObj->Set( Nan::New("mimetype").ToLocalChecked(), TagLibStringToString(p->mimeType()) ); imgObj->Set( Nan::New("picture").ToLocalChecked(), buf ); pictures->Set(picIndex++, imgObj); } obj->Set(Nan::New("pictures").ToLocalChecked(), pictures); } else if (!tag->pictures().isEmpty()) { size_t arraySize = tag->pictures().size(); v8::Local<v8::Array> pictures = Nan::New<v8::Array>(arraySize); int picIndex = 0; for (auto& p : tag->pictures()) { v8::Local<v8::Object> imgObj = Nan::New<v8::Object>(); auto data = p.second[0].data(); auto datasize = data.size(); const char* rawdata = data.data(); v8::Local<v8::Object> buf = Nan::NewBuffer(datasize).ToLocalChecked(); memcpy(node::Buffer::Data(buf), rawdata, datasize); imgObj->Set( Nan::New("mimetype").ToLocalChecked(), TagLibStringToString(p.second[0].mime()) ); imgObj->Set( Nan::New("picture").ToLocalChecked(), buf ); pictures->Set(picIndex++, imgObj); } obj->Set(Nan::New("pictures").ToLocalChecked(), pictures); } if (f.audioProperties()) { TagLib::AudioProperties *properties = f.audioProperties(); int seconds = properties->length() % 60; int minutes = (properties->length() - seconds) / 60; int hours = (properties->length() - minutes * 60) / 60; obj->Set( Nan::New("bitrate").ToLocalChecked(), Nan::New<v8::Integer>(properties->bitrate()) ); obj->Set( Nan::New("samplerate").ToLocalChecked(), Nan::New<v8::Integer>(properties->sampleRate()) ); obj->Set( Nan::New("channels").ToLocalChecked(), Nan::New<v8::Integer>(properties->channels()) ); // this is the same hackery, a second read, is required to get the codec // since codec isn't always a member of audioProperties. There should be // a better way of getting properties that are unique to each format. if (ext == "M4A" || ext == "MP4") { TagLib::MP4::File mp4file(audio_file.c_str()); if (mp4file.audioProperties()) { auto codec = mp4file.audioProperties()->codec(); string encoding = codec == 2 ? "alac" : "aac"; obj->Set( Nan::New("codec").ToLocalChecked(), Nan::New<v8::String>(encoding).ToLocalChecked() ); } } stringstream ss; if (hours > 0) { ss << hours << ":" << setfill('0') << setw(2); } ss << minutes << ":" << setfill('0') << setw(2) << seconds; string s = ss.str(); auto time = Nan::New<v8::String>(s.c_str(), s.size()).ToLocalChecked(); obj->Set(Nan::New("time").ToLocalChecked(), time); obj->Set( Nan::New("length").ToLocalChecked(), Nan::New<v8::Integer>(properties->length()) ); } info.GetReturnValue().Set(obj); } void Init(v8::Local<v8::Object> exports, v8::Local<v8::Value> module, void *) { exports->Set(Nan::New("writeTagsSync").ToLocalChecked(), Nan::New<v8::FunctionTemplate>(writeTagsSync)->GetFunction()); exports->Set(Nan::New("readTagsSync").ToLocalChecked(), Nan::New<v8::FunctionTemplate>(readTagsSync)->GetFunction()); } NODE_MODULE(taglib2, Init)
fix hour in .time
fix hour in .time
C++
mit
voltraco/node-taglib2,voltraco/node-taglib2
6fda23d34dc03a47cca1bd231972fa6737367054
src/version.cc
src/version.cc
// Copyright 2012 the V8 project 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 "src/v8.h" #include "src/version.h" // These macros define the version number for the current version. // NOTE these macros are used by some of the tool scripts and the build // system so their names cannot be changed without changing the scripts. #define MAJOR_VERSION 3 #define MINOR_VERSION 28 #define BUILD_NUMBER 42 #define PATCH_LEVEL 0 // Use 1 for candidates and 0 otherwise. // (Boolean macro values are not supported by all preprocessors.) #define IS_CANDIDATE_VERSION 1 // Define SONAME to have the build system put a specific SONAME into the // shared library instead the generic SONAME generated from the V8 version // number. This define is mainly used by the build system script. #define SONAME "" #if IS_CANDIDATE_VERSION #define CANDIDATE_STRING " (candidate)" #else #define CANDIDATE_STRING "" #endif #define SX(x) #x #define S(x) SX(x) #if PATCH_LEVEL > 0 #define VERSION_STRING \ S(MAJOR_VERSION) "." S(MINOR_VERSION) "." S(BUILD_NUMBER) "." \ S(PATCH_LEVEL) CANDIDATE_STRING #else #define VERSION_STRING \ S(MAJOR_VERSION) "." S(MINOR_VERSION) "." S(BUILD_NUMBER) \ CANDIDATE_STRING #endif namespace v8 { namespace internal { int Version::major_ = MAJOR_VERSION; int Version::minor_ = MINOR_VERSION; int Version::build_ = BUILD_NUMBER; int Version::patch_ = PATCH_LEVEL; bool Version::candidate_ = (IS_CANDIDATE_VERSION != 0); const char* Version::soname_ = SONAME; const char* Version::version_string_ = VERSION_STRING; // Calculate the V8 version string. void Version::GetString(Vector<char> str) { const char* candidate = IsCandidate() ? " (candidate)" : ""; #ifdef USE_SIMULATOR const char* is_simulator = " SIMULATOR"; #else const char* is_simulator = ""; #endif // USE_SIMULATOR if (GetPatch() > 0) { SNPrintF(str, "%d.%d.%d.%d%s%s", GetMajor(), GetMinor(), GetBuild(), GetPatch(), candidate, is_simulator); } else { SNPrintF(str, "%d.%d.%d%s%s", GetMajor(), GetMinor(), GetBuild(), candidate, is_simulator); } } // Calculate the SONAME for the V8 shared library. void Version::GetSONAME(Vector<char> str) { if (soname_ == NULL || *soname_ == '\0') { // Generate generic SONAME if no specific SONAME is defined. const char* candidate = IsCandidate() ? "-candidate" : ""; if (GetPatch() > 0) { SNPrintF(str, "libv8-%d.%d.%d.%d%s.so", GetMajor(), GetMinor(), GetBuild(), GetPatch(), candidate); } else { SNPrintF(str, "libv8-%d.%d.%d%s.so", GetMajor(), GetMinor(), GetBuild(), candidate); } } else { // Use specific SONAME. SNPrintF(str, "%s", soname_); } } } } // namespace v8::internal
// Copyright 2012 the V8 project 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 "src/v8.h" #include "src/version.h" // These macros define the version number for the current version. // NOTE these macros are used by some of the tool scripts and the build // system so their names cannot be changed without changing the scripts. #define MAJOR_VERSION 3 #define MINOR_VERSION 28 #define BUILD_NUMBER 44 #define PATCH_LEVEL 0 // Use 1 for candidates and 0 otherwise. // (Boolean macro values are not supported by all preprocessors.) #define IS_CANDIDATE_VERSION 1 // Define SONAME to have the build system put a specific SONAME into the // shared library instead the generic SONAME generated from the V8 version // number. This define is mainly used by the build system script. #define SONAME "" #if IS_CANDIDATE_VERSION #define CANDIDATE_STRING " (candidate)" #else #define CANDIDATE_STRING "" #endif #define SX(x) #x #define S(x) SX(x) #if PATCH_LEVEL > 0 #define VERSION_STRING \ S(MAJOR_VERSION) "." S(MINOR_VERSION) "." S(BUILD_NUMBER) "." \ S(PATCH_LEVEL) CANDIDATE_STRING #else #define VERSION_STRING \ S(MAJOR_VERSION) "." S(MINOR_VERSION) "." S(BUILD_NUMBER) \ CANDIDATE_STRING #endif namespace v8 { namespace internal { int Version::major_ = MAJOR_VERSION; int Version::minor_ = MINOR_VERSION; int Version::build_ = BUILD_NUMBER; int Version::patch_ = PATCH_LEVEL; bool Version::candidate_ = (IS_CANDIDATE_VERSION != 0); const char* Version::soname_ = SONAME; const char* Version::version_string_ = VERSION_STRING; // Calculate the V8 version string. void Version::GetString(Vector<char> str) { const char* candidate = IsCandidate() ? " (candidate)" : ""; #ifdef USE_SIMULATOR const char* is_simulator = " SIMULATOR"; #else const char* is_simulator = ""; #endif // USE_SIMULATOR if (GetPatch() > 0) { SNPrintF(str, "%d.%d.%d.%d%s%s", GetMajor(), GetMinor(), GetBuild(), GetPatch(), candidate, is_simulator); } else { SNPrintF(str, "%d.%d.%d%s%s", GetMajor(), GetMinor(), GetBuild(), candidate, is_simulator); } } // Calculate the SONAME for the V8 shared library. void Version::GetSONAME(Vector<char> str) { if (soname_ == NULL || *soname_ == '\0') { // Generate generic SONAME if no specific SONAME is defined. const char* candidate = IsCandidate() ? "-candidate" : ""; if (GetPatch() > 0) { SNPrintF(str, "libv8-%d.%d.%d.%d%s.so", GetMajor(), GetMinor(), GetBuild(), GetPatch(), candidate); } else { SNPrintF(str, "libv8-%d.%d.%d%s.so", GetMajor(), GetMinor(), GetBuild(), candidate); } } else { // Use specific SONAME. SNPrintF(str, "%s", soname_); } } } } // namespace v8::internal
Bump up version to 3.28.44.0
[Auto-roll] Bump up version to 3.28.44.0 [email protected] Review URL: https://codereview.chromium.org/422003002 git-svn-id: f98b9d40cb02301bc76fa9e1b46ee668158567fd@22639 ce2b1a6d-e550-0410-aec6-3dcde31c8c00
C++
mit
UniversalFuture/moosh,UniversalFuture/moosh,UniversalFuture/moosh,UniversalFuture/moosh
c2bd4b100aa887e950edd261262cf89923f15dff
src/wrapper.cc
src/wrapper.cc
#include "wrapper.hh" #include <stdexcept> Wrapper::Wrapper(v8::Local<v8::Object> options) { v8::Local<v8::Value> options_device_value = Nan::Get(options, Nan::New("device").ToLocalChecked()).ToLocalChecked(); if(!options_device_value->IsString()) { throw std::invalid_argument("Options should have string device property"); } v8::Local<v8::Value> options_onRecv_value = Nan::Get(options, Nan::New("onRecv").ToLocalChecked()).ToLocalChecked(); if(!options_onRecv_value->IsFunction()) { throw std::invalid_argument("Options should have callback onRecv property"); } v8::Local<v8::Value> options_onSend_value = Nan::Get(options, Nan::New("onSend").ToLocalChecked()).ToLocalChecked(); if(!options_onSend_value->IsFunction()) { throw std::invalid_argument("Options should have callback onSend property"); } Nan::Utf8String device_string(options_device_value); socket = new Socket(*device_string); } Wrapper::~Wrapper() { delete socket; } Nan::Persistent<v8::Function> Wrapper::constructor; #include <cstdio> NAN_MODULE_INIT(Wrapper::Init) { v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New); tpl->SetClassName(Nan::New("Wrapper").ToLocalChecked()); tpl->InstanceTemplate()->SetInternalFieldCount(1); Nan::SetPrototypeMethod(tpl, "AddMembership", AddMembership); Nan::SetPrototypeMethod(tpl, "DropMembership", DropMembership); Nan::SetPrototypeMethod(tpl, "Send", Send); Nan::SetPrototypeMethod(tpl, "Receive", Receive); constructor.Reset(Nan::GetFunction(tpl).ToLocalChecked()); Nan::Set(target, Nan::New("Wrapper").ToLocalChecked(), Nan::GetFunction(tpl).ToLocalChecked()); } NAN_METHOD(Wrapper::New) { if(info.IsConstructCall()) { Nan::MaybeLocal<v8::Object> options_object_maybe = Nan::To<v8::Object>(info[0]); if(options_object_maybe.IsEmpty()) return Nan::ThrowError("Missing options object"); v8::Local<v8::Object> options_object = options_object_maybe.ToLocalChecked(); if(!Nan::HasOwnProperty(options_object, Nan::New("device").ToLocalChecked()).FromMaybe(false)) { return Nan::ThrowTypeError("Options should have device property"); } if(!Nan::HasOwnProperty(options_object, Nan::New("onRecv").ToLocalChecked()).FromMaybe(false)) { return Nan::ThrowTypeError("Options should have onRecv property"); } if(!Nan::HasOwnProperty(options_object, Nan::New("onSend").ToLocalChecked()).FromMaybe(false)) { return Nan::ThrowTypeError("Options should have onSend property"); } try { Wrapper *object = new Wrapper(options_object); object->Wrap(info.This()); } catch(const std::exception &e) { return Nan::ThrowError(e.what()); } info.GetReturnValue().Set(info.This()); } else { const int argc = 1; v8::Local<v8::Value> argv[argc] = {info[0]}; v8::Local<v8::Function> emulate_constructor = Nan::New(constructor); Nan::TryCatch trycatch; Nan::MaybeLocal<v8::Object> constructed_object = Nan::NewInstance(emulate_constructor, argc, argv); if(trycatch.HasCaught()) { trycatch.ReThrow(); return; } info.GetReturnValue().Set(constructed_object.ToLocalChecked()); } } void Wrapper::ParseMembershipArguments( Nan::NAN_METHOD_ARGS_TYPE info, Socket::MembershipType *type, unsigned char **address) { Nan::HandleScope scope; Nan::MaybeLocal<v8::Value> type_or_addr_maybe = info[0]; if(info.Length() == 0 || type_or_addr_maybe.IsEmpty()) throw std::invalid_argument("Missing type or address argument"); v8::Local<v8::Value> type_or_addr = type_or_addr_maybe.ToLocalChecked(); if(node::Buffer::HasInstance(type_or_addr)) { if(node::Buffer::Length(type_or_addr) < Socket::ADDRESS_LENGHT) throw std::invalid_argument("Invalid address length"); *address = reinterpret_cast<unsigned char *>(node::Buffer::Data(type_or_addr)); } else if(type_or_addr->IsNumber()) { *type = static_cast<Socket::MembershipType>(Nan::To<int>(type_or_addr).FromJust()); } else { throw std::invalid_argument("Invalid address length"); } } NAN_METHOD(Wrapper::AddMembership) { Wrapper *obj = Nan::ObjectWrap::Unwrap<Wrapper>(info.Holder()); Socket::MembershipType type = Socket::MULTICAST; unsigned char *address = NULL; try { ParseMembershipArguments(info, &type, &address); obj->socket->add_membership(type, address); } catch(const std::exception &e) { return Nan::ThrowError(e.what()); } } NAN_METHOD(Wrapper::DropMembership) { Wrapper *obj = Nan::ObjectWrap::Unwrap<Wrapper>(info.Holder()); Socket::MembershipType type = Socket::MULTICAST; unsigned char *address = NULL; try { ParseMembershipArguments(info, &type, &address); obj->socket->drop_membership(type, address); } catch(const std::exception &e) { return Nan::ThrowError(e.what()); } } NAN_METHOD(Wrapper::Receive) { Wrapper *obj = Nan::ObjectWrap::Unwrap<Wrapper>(info.Holder()); if(info.Length() != 1) return Nan::ThrowError("One argument required"); if(!info[0]->IsFunction()) return Nan::ThrowTypeError("Callback argument has to be function"); v8::Local<v8::Function> callback = info[0].As<v8::Function>(); int received_bytes = -1; unsigned char *source_address = reinterpret_cast<unsigned char *>(malloc(Socket::ADDRESS_LENGHT)); if(!source_address) return Nan::ThrowError("Memory allocation for source address failed"); unsigned char *destination_address = reinterpret_cast<unsigned char *>(malloc(Socket::ADDRESS_LENGHT)); if(!destination_address) { free(source_address); return Nan::ThrowError("Memory allocation for destination address failed"); } char *message_buffer = reinterpret_cast<char *>(malloc(Wrapper::MAX_RECEIVE_BUFFER_SIZE)); if(!message_buffer) { free(source_address); free(destination_address); return Nan::ThrowError("Memory allocation for buffer failed"); } try { received_bytes = obj->socket->receive_message( source_address, destination_address, message_buffer, Wrapper::MAX_RECEIVE_BUFFER_SIZE); } catch(const std::exception &e) { free(destination_address); free(source_address); free(message_buffer); return Nan::ThrowError(e.what()); } char *tmp_buff = reinterpret_cast<char *>(realloc(message_buffer, received_bytes)); if(tmp_buff) message_buffer = tmp_buff; Nan::MaybeLocal<v8::Object> source_address_node_buffer = Nan::NewBuffer((char *)source_address, Socket::ADDRESS_LENGHT); Nan::MaybeLocal<v8::Object> destination_address_node_buffer = Nan::NewBuffer((char *)destination_address, Socket::ADDRESS_LENGHT); Nan::MaybeLocal<v8::Object> message_node_buffer = Nan::NewBuffer(message_buffer, received_bytes); if(source_address_node_buffer.IsEmpty() || destination_address_node_buffer.IsEmpty() || message_node_buffer.IsEmpty()) { return Nan::ThrowError("Failed to create buffer object"); } const int argc = 3; v8::Local<v8::Value> argv[argc] = { source_address_node_buffer.ToLocalChecked(), destination_address_node_buffer.ToLocalChecked(), message_node_buffer.ToLocalChecked() }; Nan::MakeCallback(Nan::GetCurrentContext()->Global(), callback, argc, argv); } NAN_METHOD(Wrapper::Send) { Wrapper *obj = Nan::ObjectWrap::Unwrap<Wrapper>(info.Holder()); if(info.Length() != 3) return Nan::ThrowError("Three arguments required"); v8::Local<v8::Value> message_to_send = info[0]; if(!node::Buffer::HasInstance(message_to_send)) return Nan::ThrowTypeError("Message argument has to be buffer"); v8::Local<v8::Value> destination_address = info[1]; if(!node::Buffer::HasInstance(destination_address)) return Nan::ThrowTypeError("Address argument has to be buffer"); if(node::Buffer::Length(destination_address) != Socket::ADDRESS_LENGHT) return Nan::ThrowTypeError("Address argument invalid length"); if(!info[2]->IsFunction()) return Nan::ThrowTypeError("Callback argument has to be function"); v8::Local<v8::Function> callback = info[2].As<v8::Function>(); int send_bytes = -1; try { send_bytes = obj->socket->send_message( reinterpret_cast<unsigned char *>(node::Buffer::Data(destination_address)), node::Buffer::Data(message_to_send), node::Buffer::Length(message_to_send)); } catch(const std::exception &e) { return Nan::ThrowError(e.what()); } const int argc = 1; v8::Local<v8::Value> argv[argc] = { Nan::New(send_bytes) }; Nan::MakeCallback(Nan::GetCurrentContext()->Global(), callback, argc, argv); } NODE_MODULE(packet_socket_addon, Wrapper::Init);
#include "wrapper.hh" #include <stdexcept> Wrapper::Wrapper(v8::Local<v8::Object> options) { v8::Local<v8::Value> options_device_value = Nan::Get(options, Nan::New("device").ToLocalChecked()).ToLocalChecked(); if(!options_device_value->IsString()) { throw std::invalid_argument("Options should have string device property"); } v8::Local<v8::Value> options_onRecv_value = Nan::Get(options, Nan::New("onRecv").ToLocalChecked()).ToLocalChecked(); if(!options_onRecv_value->IsFunction()) { throw std::invalid_argument("Options should have callback onRecv property"); } v8::Local<v8::Value> options_onSend_value = Nan::Get(options, Nan::New("onSend").ToLocalChecked()).ToLocalChecked(); if(!options_onSend_value->IsFunction()) { throw std::invalid_argument("Options should have callback onSend property"); } onRecvCallback.Reset(options_onRecv_value.As<v8::Function>()); onSendCallback.Reset(options_onSend_value.As<v8::Function>()); Nan::Utf8String device_string(options_device_value); socket = new Socket(*device_string); } Wrapper::~Wrapper() { onRecvCallback.Reset(); onSendCallback.Reset(); delete socket; } Nan::Persistent<v8::Function> Wrapper::constructor; #include <cstdio> NAN_MODULE_INIT(Wrapper::Init) { v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New); tpl->SetClassName(Nan::New("Wrapper").ToLocalChecked()); tpl->InstanceTemplate()->SetInternalFieldCount(1); Nan::SetPrototypeMethod(tpl, "AddMembership", AddMembership); Nan::SetPrototypeMethod(tpl, "DropMembership", DropMembership); Nan::SetPrototypeMethod(tpl, "Send", Send); Nan::SetPrototypeMethod(tpl, "Receive", Receive); constructor.Reset(Nan::GetFunction(tpl).ToLocalChecked()); Nan::Set(target, Nan::New("Wrapper").ToLocalChecked(), Nan::GetFunction(tpl).ToLocalChecked()); } NAN_METHOD(Wrapper::New) { if(info.IsConstructCall()) { Nan::MaybeLocal<v8::Object> options_object_maybe = Nan::To<v8::Object>(info[0]); if(options_object_maybe.IsEmpty()) return Nan::ThrowError("Missing options object"); v8::Local<v8::Object> options_object = options_object_maybe.ToLocalChecked(); if(!Nan::HasOwnProperty(options_object, Nan::New("device").ToLocalChecked()).FromMaybe(false)) { return Nan::ThrowTypeError("Options should have device property"); } if(!Nan::HasOwnProperty(options_object, Nan::New("onRecv").ToLocalChecked()).FromMaybe(false)) { return Nan::ThrowTypeError("Options should have onRecv property"); } if(!Nan::HasOwnProperty(options_object, Nan::New("onSend").ToLocalChecked()).FromMaybe(false)) { return Nan::ThrowTypeError("Options should have onSend property"); } try { Wrapper *object = new Wrapper(options_object); object->Wrap(info.This()); } catch(const std::exception &e) { return Nan::ThrowError(e.what()); } info.GetReturnValue().Set(info.This()); } else { const int argc = 1; v8::Local<v8::Value> argv[argc] = {info[0]}; v8::Local<v8::Function> emulate_constructor = Nan::New(constructor); Nan::TryCatch trycatch; Nan::MaybeLocal<v8::Object> constructed_object = Nan::NewInstance(emulate_constructor, argc, argv); if(trycatch.HasCaught()) { trycatch.ReThrow(); return; } info.GetReturnValue().Set(constructed_object.ToLocalChecked()); } } void Wrapper::ParseMembershipArguments( Nan::NAN_METHOD_ARGS_TYPE info, Socket::MembershipType *type, unsigned char **address) { Nan::HandleScope scope; Nan::MaybeLocal<v8::Value> type_or_addr_maybe = info[0]; if(info.Length() == 0 || type_or_addr_maybe.IsEmpty()) throw std::invalid_argument("Missing type or address argument"); v8::Local<v8::Value> type_or_addr = type_or_addr_maybe.ToLocalChecked(); if(node::Buffer::HasInstance(type_or_addr)) { if(node::Buffer::Length(type_or_addr) < Socket::ADDRESS_LENGHT) throw std::invalid_argument("Invalid address length"); *address = reinterpret_cast<unsigned char *>(node::Buffer::Data(type_or_addr)); } else if(type_or_addr->IsNumber()) { *type = static_cast<Socket::MembershipType>(Nan::To<int>(type_or_addr).FromJust()); } else { throw std::invalid_argument("Invalid address length"); } } NAN_METHOD(Wrapper::AddMembership) { Wrapper *obj = Nan::ObjectWrap::Unwrap<Wrapper>(info.Holder()); Socket::MembershipType type = Socket::MULTICAST; unsigned char *address = NULL; try { ParseMembershipArguments(info, &type, &address); obj->socket->add_membership(type, address); } catch(const std::exception &e) { return Nan::ThrowError(e.what()); } } NAN_METHOD(Wrapper::DropMembership) { Wrapper *obj = Nan::ObjectWrap::Unwrap<Wrapper>(info.Holder()); Socket::MembershipType type = Socket::MULTICAST; unsigned char *address = NULL; try { ParseMembershipArguments(info, &type, &address); obj->socket->drop_membership(type, address); } catch(const std::exception &e) { return Nan::ThrowError(e.what()); } } NAN_METHOD(Wrapper::Receive) { Wrapper *obj = Nan::ObjectWrap::Unwrap<Wrapper>(info.Holder()); if(info.Length() != 1) return Nan::ThrowError("One argument required"); if(!info[0]->IsFunction()) return Nan::ThrowTypeError("Callback argument has to be function"); v8::Local<v8::Function> callback = info[0].As<v8::Function>(); int received_bytes = -1; unsigned char *source_address = reinterpret_cast<unsigned char *>(malloc(Socket::ADDRESS_LENGHT)); if(!source_address) return Nan::ThrowError("Memory allocation for source address failed"); unsigned char *destination_address = reinterpret_cast<unsigned char *>(malloc(Socket::ADDRESS_LENGHT)); if(!destination_address) { free(source_address); return Nan::ThrowError("Memory allocation for destination address failed"); } char *message_buffer = reinterpret_cast<char *>(malloc(Wrapper::MAX_RECEIVE_BUFFER_SIZE)); if(!message_buffer) { free(source_address); free(destination_address); return Nan::ThrowError("Memory allocation for buffer failed"); } try { received_bytes = obj->socket->receive_message( source_address, destination_address, message_buffer, Wrapper::MAX_RECEIVE_BUFFER_SIZE); } catch(const std::exception &e) { free(destination_address); free(source_address); free(message_buffer); return Nan::ThrowError(e.what()); } char *tmp_buff = reinterpret_cast<char *>(realloc(message_buffer, received_bytes)); if(tmp_buff) message_buffer = tmp_buff; Nan::MaybeLocal<v8::Object> source_address_node_buffer = Nan::NewBuffer((char *)source_address, Socket::ADDRESS_LENGHT); Nan::MaybeLocal<v8::Object> destination_address_node_buffer = Nan::NewBuffer((char *)destination_address, Socket::ADDRESS_LENGHT); Nan::MaybeLocal<v8::Object> message_node_buffer = Nan::NewBuffer(message_buffer, received_bytes); if(source_address_node_buffer.IsEmpty() || destination_address_node_buffer.IsEmpty() || message_node_buffer.IsEmpty()) { return Nan::ThrowError("Failed to create buffer object"); } const int argc = 3; v8::Local<v8::Value> argv[argc] = { source_address_node_buffer.ToLocalChecked(), destination_address_node_buffer.ToLocalChecked(), message_node_buffer.ToLocalChecked() }; Nan::MakeCallback(Nan::GetCurrentContext()->Global(), callback, argc, argv); } NAN_METHOD(Wrapper::Send) { Wrapper *obj = Nan::ObjectWrap::Unwrap<Wrapper>(info.Holder()); if(info.Length() != 3) return Nan::ThrowError("Three arguments required"); v8::Local<v8::Value> message_to_send = info[0]; if(!node::Buffer::HasInstance(message_to_send)) return Nan::ThrowTypeError("Message argument has to be buffer"); v8::Local<v8::Value> destination_address = info[1]; if(!node::Buffer::HasInstance(destination_address)) return Nan::ThrowTypeError("Address argument has to be buffer"); if(node::Buffer::Length(destination_address) != Socket::ADDRESS_LENGHT) return Nan::ThrowTypeError("Address argument invalid length"); if(!info[2]->IsFunction()) return Nan::ThrowTypeError("Callback argument has to be function"); v8::Local<v8::Function> callback = info[2].As<v8::Function>(); int send_bytes = -1; try { send_bytes = obj->socket->send_message( reinterpret_cast<unsigned char *>(node::Buffer::Data(destination_address)), node::Buffer::Data(message_to_send), node::Buffer::Length(message_to_send)); } catch(const std::exception &e) { return Nan::ThrowError(e.what()); } const int argc = 1; v8::Local<v8::Value> argv[argc] = { Nan::New(send_bytes) }; Nan::MakeCallback(Nan::GetCurrentContext()->Global(), callback, argc, argv); } NODE_MODULE(packet_socket_addon, Wrapper::Init);
Add storing onRecv and onSend callbacks passed in constructor
Add storing onRecv and onSend callbacks passed in constructor
C++
mit
piskorzj/node-packet-socket,piskorzj/node-packet-socket,piskorzj/node-packet-socket
df2c8fbc01b88d7afbe693e3371deb8ca8e0a30b
src/ycursor.cc
src/ycursor.cc
/* * IceWM - Colored cursor support * * Copyright (C) 2001 The Authors of IceWM * * initially by Oleastre * C++ style implementation by tbf */ #include "config.h" #include "default.h" #include "yfull.h" #include "yapp.h" #include "wmprog.h" #ifndef LITE #include <limits.h> #include <stdlib.h> #ifdef CONFIG_XPM #include "X11/xpm.h" #endif #ifdef CONFIG_IMLIB #include <Imlib.h> extern ImlibData *hImlib; #endif #include "ycursor.h" #include "intl.h" class YCursorPixmap { public: YCursorPixmap(char const *path); ~YCursorPixmap(); Pixmap pixmap() const { return fPixmap; } Pixmap mask() const { return fMask; } const XColor& background() const { return fBackground; } const XColor& foreground() const { return fForeground; } #ifdef CONFIG_XPM operator bool () { return fValid; } unsigned int width() const { return fAttributes.width; } unsigned int height() const { return fAttributes.height; } unsigned int hotspotX() const { return fAttributes.x_hotspot; } unsigned int hotspotY() const { return fAttributes.y_hotspot; } #endif #ifdef CONFIG_IMLIB operator bool () { return fImage; } unsigned int width() const { return fImage ? fImage->rgb_width : 0; } unsigned int height() const { return fImage ? fImage->rgb_height : 0; } unsigned int hotspotX() const { return fHotspotX; } unsigned int hotspotY() const { return fHotspotY; } #endif private: Pixmap fPixmap, fMask; XColor fForeground, fBackground; #ifdef CONFIG_XPM bool fValid; XpmAttributes fAttributes; #endif #ifdef CONFIG_IMLIB unsigned int fHotspotX, fHotspotY; ImlibImage *fImage; #endif }; #ifdef CONFIG_XPM // ================== use libXpm to load the cursor pixmap === YCursorPixmap::YCursorPixmap(char const *path): fValid(false) { fAttributes.colormap = app->colormap(); fAttributes.closeness = 65535; fAttributes.valuemask = XpmColormap|XpmCloseness| XpmReturnPixels|XpmSize|XpmHotspot; fAttributes.x_hotspot = 0; fAttributes.y_hotspot = 0; int const rc(XpmReadFileToPixmap(app->display(), desktop->handle(), (char *)REDIR_ROOT(path), // !!! &fPixmap, &fMask, &fAttributes)); if (rc != XpmSuccess) warn(_("Loading of pixmap \"%s\" failed: %s"), path, XpmGetErrorString(rc)); else if (fAttributes.npixels != 2) warn(_("Invalid cursor pixmap: \"%s\" contains too many unique colors"), path); else { fBackground.pixel = fAttributes.pixels[0]; fForeground.pixel = fAttributes.pixels[1]; XQueryColor (app->display(), app->colormap(), &fBackground); XQueryColor (app->display(), app->colormap(), &fForeground); fValid = true; } } #endif #ifdef CONFIG_IMLIB // ================= use Imlib to load the cursor pixmap === YCursorPixmap::YCursorPixmap(char const *path): fHotspotX(0), fHotspotY(0) { fImage = Imlib_load_image(hImlib, (char *)REDIR_ROOT(path)); if (fImage == NULL) { warn(_("Loading of pixmap \"%s\" failed"), path); return; } Imlib_render(hImlib, fImage, fImage->rgb_width, fImage->rgb_height); fPixmap = (Pixmap)Imlib_move_image(hImlib, fImage); fMask = (Pixmap)Imlib_move_mask(hImlib, fImage); struct Pixel { // ----------------- find the background/foreground color --- bool operator!= (const Pixel& o) { return (r != o.r || g != o.g || b != o.b); } bool operator!= (const ImlibColor& o) { return (r != o.r || g != o.g || b != o.b); } unsigned char r,g,b; }; Pixel fg, bg, *pp((Pixel*) fImage->rgb_data); unsigned ccnt = 0; for (unsigned n = fImage->rgb_width * fImage->rgb_height; n > 0; --n, ++pp) if (*pp != fImage->shape_color) switch (ccnt) { case 0: bg = *pp; ++ccnt; break; case 1: if (*pp != bg) { fg = *pp; ++ccnt; } break; default: if (*pp != bg && *pp != fg) { warn(_("Invalid cursor pixmap: \"%s\" contains too " "much unique colors"), path); Imlib_destroy_image(hImlib, fImage); fImage = NULL; return; } } fForeground.red = fg.r << 8; // -- alloc the background/foreground color --- fForeground.green = fg.g << 8; fForeground.blue = fg.b << 8; XAllocColor(app->display(), app->colormap(), &fForeground); fBackground.red = bg.r << 8; fBackground.green = bg.g << 8; fBackground.blue = bg.b << 8; XAllocColor(app->display(), app->colormap(), &fBackground); // ----------------- find the hotspot by reading the xpm header manually --- FILE *xpm = fopen((char *)REDIR_ROOT(path), "rb"); if (xpm == NULL) warn(_("BUG? Imlib was able to read \"%s\""), path); else { while (fgetc(xpm) != '{'); // ----- that's safe since imlib accepted --- for (int c;;) switch (c = fgetc(xpm)) { case '/': if ((c == fgetc(xpm)) == '/') // ------ eat C++ line comment --- while (fgetc(xpm) != '\n'); else { // -------------------------------- eat block comment --- int pc; do { pc = c; c = fgetc(xpm); } while (c != '/' && pc != '*'); } break; case ' ': case '\t': case '\r': case '\n': // ------- whitespace --- break; case '"': { // ---------------------------------- the XPM header --- unsigned foo; int x, y; int tokens = fscanf(xpm, "%u %u %u %u %u %u", &foo, &foo, &foo, &foo, &x, &y); if (tokens == 6) { fHotspotX = (x < 0 ? 0 : x); fHotspotY = (y < 0 ? 0 : y); } else if (tokens != 4) warn(_("BUG? Malformed XPM header but Imlib " "was able to parse \"%s\""), path); fclose(xpm); return; } default: if (c == EOF) warn(_("BUG? Unexpected end of XPM file but Imlib " "was able to parse \"%s\""), path); else warn(_("BUG? Unexpected characted but Imlib " "was able to parse \"%s\""), path); fclose(xpm); return; } } } #endif YCursorPixmap::~YCursorPixmap() { XFreePixmap(app->display(), fPixmap); XFreePixmap(app->display(), fMask); #ifdef CONFIG_XPM XpmFreeAttributes(&fAttributes); #endif #ifdef CONFIG_IMLIB Imlib_destroy_image(hImlib, fImage); #endif } #endif YCursor::~YCursor() { if(fOwned && fCursor && app) XFreeCursor(app->display(), fCursor); } #ifndef LITE void YCursor::load(char const *path) { YCursorPixmap pixmap(path); if (pixmap) { // ============ convert coloured pixmap into a bilevel one === Pixmap bilevel(YPixmap::createMask(pixmap.width(), pixmap.height())); // -------------------------- figure out which plane we have to copy --- unsigned long pmask(1 << (app->depth())); if (pixmap.foreground().pixel && pixmap.foreground().pixel != pixmap.background().pixel) while ((pixmap.foreground().pixel & pmask) == (pixmap.background().pixel & pmask)) pmask >>= 1; else if (pixmap.background().pixel) while ((pixmap.background().pixel & pmask) == 0) pmask >>= 1; GC gc; XGCValues gcv; // ------ copy one plane by using a bilevel GC --- gcv.function = (pixmap.foreground().pixel && (pixmap.foreground().pixel & pmask)) ? GXcopyInverted : GXcopy; gc = XCreateGC (app->display(), bilevel, GCFunction, &gcv); XFillRectangle(app->display(), bilevel, gc, 0, 0, pixmap.width(), pixmap.height()); XCopyPlane(app->display(), pixmap.pixmap(), bilevel, gc, 0, 0, pixmap.width(), pixmap.height(), 0, 0, pmask); XFreeGC(app->display(), gc); // ==================================== allocate a new pixmap cursor === XColor foreground(pixmap.foreground()), background(pixmap.background()); fCursor = XCreatePixmapCursor(app->display(), bilevel, pixmap.mask(), &foreground, &background, pixmap.hotspotX(), pixmap.hotspotY()); XFreePixmap(app->display(), bilevel); } } #endif #ifndef LITE void YCursor::load(char const *name, unsigned int fallback) { #else void YCursor::load(char const */*name*/, unsigned int fallback) { #endif if(fCursor && fOwned) XFreeCursor(app->display(), fCursor); #ifndef LITE static char const *cursors = "cursors/"; YResourcePaths paths(cursors); for (YPathElement const * pe(paths); pe->root && fCursor == None; pe++) { char *path(pe->joinPath(cursors, name)); if (isreg(path)) load(path); delete path; } if (fCursor == None) #endif fCursor = XCreateFontCursor(app->display(), fallback); fOwned = true; }
/* * IceWM - Colored cursor support * * Copyright (C) 2001 The Authors of IceWM * * initially by Oleastre * C++ style implementation by tbf */ #include "config.h" #include "default.h" #include "yfull.h" #include "yapp.h" #include "wmprog.h" #ifndef LITE #include <limits.h> #include <stdlib.h> #ifdef CONFIG_XPM #include "X11/xpm.h" #endif #ifdef CONFIG_IMLIB #include <Imlib.h> extern ImlibData *hImlib; #endif #include "ycursor.h" #include "intl.h" class YCursorPixmap { public: YCursorPixmap(char const *path); ~YCursorPixmap(); Pixmap pixmap() const { return fPixmap; } Pixmap mask() const { return fMask; } const XColor& background() const { return fBackground; } const XColor& foreground() const { return fForeground; } #ifdef CONFIG_XPM operator bool () { return fValid; } unsigned int width() const { return fAttributes.width; } unsigned int height() const { return fAttributes.height; } unsigned int hotspotX() const { return fAttributes.x_hotspot; } unsigned int hotspotY() const { return fAttributes.y_hotspot; } #endif #ifdef CONFIG_IMLIB operator bool () { return fImage; } unsigned int width() const { return fImage ? fImage->rgb_width : 0; } unsigned int height() const { return fImage ? fImage->rgb_height : 0; } unsigned int hotspotX() const { return fHotspotX; } unsigned int hotspotY() const { return fHotspotY; } #endif private: Pixmap fPixmap, fMask; XColor fForeground, fBackground; #ifdef CONFIG_XPM bool fValid; XpmAttributes fAttributes; #endif #ifdef CONFIG_IMLIB unsigned int fHotspotX, fHotspotY; ImlibImage *fImage; #endif }; #ifdef CONFIG_XPM // ================== use libXpm to load the cursor pixmap === YCursorPixmap::YCursorPixmap(char const *path): fValid(false) { fAttributes.colormap = app->colormap(); fAttributes.closeness = 65535; fAttributes.valuemask = XpmColormap|XpmCloseness| XpmReturnPixels|XpmSize|XpmHotspot; fAttributes.x_hotspot = 0; fAttributes.y_hotspot = 0; int const rc(XpmReadFileToPixmap(app->display(), desktop->handle(), (char *)REDIR_ROOT(path), // !!! &fPixmap, &fMask, &fAttributes)); if (rc != XpmSuccess) warn(_("Loading of pixmap \"%s\" failed: %s"), path, XpmGetErrorString(rc)); else if (fAttributes.npixels != 2) warn(_("Invalid cursor pixmap: \"%s\" contains too many unique colors"), path); else { fBackground.pixel = fAttributes.pixels[0]; fForeground.pixel = fAttributes.pixels[1]; XQueryColor (app->display(), app->colormap(), &fBackground); XQueryColor (app->display(), app->colormap(), &fForeground); fValid = true; } } #endif #ifdef CONFIG_IMLIB // ================= use Imlib to load the cursor pixmap === YCursorPixmap::YCursorPixmap(char const *path): fHotspotX(0), fHotspotY(0) { fImage = Imlib_load_image(hImlib, (char *)REDIR_ROOT(path)); if (fImage == NULL) { warn(_("Loading of pixmap \"%s\" failed"), path); return; } Imlib_render(hImlib, fImage, fImage->rgb_width, fImage->rgb_height); fPixmap = (Pixmap)Imlib_move_image(hImlib, fImage); fMask = (Pixmap)Imlib_move_mask(hImlib, fImage); struct Pixel { // ----------------- find the background/foreground color --- bool operator!= (const Pixel& o) { return (r != o.r || g != o.g || b != o.b); } bool operator!= (const ImlibColor& o) { return (r != o.r || g != o.g || b != o.b); } unsigned char r,g,b; }; Pixel fg, bg, *pp((Pixel*) fImage->rgb_data); unsigned ccnt = 0; for (unsigned n = fImage->rgb_width * fImage->rgb_height; n > 0; --n, ++pp) if (*pp != fImage->shape_color) switch (ccnt) { case 0: bg = *pp; ++ccnt; break; case 1: if (*pp != bg) { fg = *pp; ++ccnt; } break; default: if (*pp != bg && *pp != fg) { warn(_("Invalid cursor pixmap: \"%s\" contains too " "much unique colors"), path); Imlib_destroy_image(hImlib, fImage); fImage = NULL; return; } } fForeground.red = fg.r << 8; // -- alloc the background/foreground color --- fForeground.green = fg.g << 8; fForeground.blue = fg.b << 8; XAllocColor(app->display(), app->colormap(), &fForeground); fBackground.red = bg.r << 8; fBackground.green = bg.g << 8; fBackground.blue = bg.b << 8; XAllocColor(app->display(), app->colormap(), &fBackground); // ----------------- find the hotspot by reading the xpm header manually --- FILE *xpm = fopen((char *)REDIR_ROOT(path), "rb"); if (xpm == NULL) warn(_("BUG? Imlib was able to read \"%s\""), path); else { while (fgetc(xpm) != '{'); // ----- that's safe since imlib accepted --- for (int c;;) switch (c = fgetc(xpm)) { case '/': if ((c == fgetc(xpm)) == '/') // ------ eat C++ line comment --- while (fgetc(xpm) != '\n'); else { // -------------------------------- eat block comment --- int pc; do { pc = c; c = fgetc(xpm); } while (c != '/' && pc != '*'); } break; case ' ': case '\t': case '\r': case '\n': // ------- whitespace --- break; case '"': { // ---------------------------------- the XPM header --- unsigned foo; int x, y; int tokens = fscanf(xpm, "%u %u %u %u %u %u", &foo, &foo, &foo, &foo, &x, &y); if (tokens == 6) { fHotspotX = (x < 0 ? 0 : x); fHotspotY = (y < 0 ? 0 : y); } else if (tokens != 4) warn(_("BUG? Malformed XPM header but Imlib " "was able to parse \"%s\""), path); fclose(xpm); return; } default: if (c == EOF) warn(_("BUG? Unexpected end of XPM file but Imlib " "was able to parse \"%s\""), path); else warn(_("BUG? Unexpected characted but Imlib " "was able to parse \"%s\""), path); fclose(xpm); return; } } } #endif YCursorPixmap::~YCursorPixmap() { XFreePixmap(app->display(), fPixmap); XFreePixmap(app->display(), fMask); #ifdef CONFIG_XPM XpmFreeAttributes(&fAttributes); #endif #ifdef CONFIG_IMLIB Imlib_destroy_image(hImlib, fImage); #endif } #endif YCursor::~YCursor() { if(fOwned && fCursor && app) XFreeCursor(app->display(), fCursor); } #ifndef LITE void YCursor::load(char const *path) { YCursorPixmap pixmap(path); if (pixmap) { // ============ convert coloured pixmap into a bilevel one === Pixmap bilevel(YPixmap::createMask(pixmap.width(), pixmap.height())); // -------------------------- figure out which plane we have to copy --- unsigned long pmask(1 << (app->depth() - 1)); if (pixmap.foreground().pixel && pixmap.foreground().pixel != pixmap.background().pixel) while ((pixmap.foreground().pixel & pmask) == (pixmap.background().pixel & pmask)) pmask >>= 1; else if (pixmap.background().pixel) while ((pixmap.background().pixel & pmask) == 0) pmask >>= 1; GC gc; XGCValues gcv; // ------ copy one plane by using a bilevel GC --- gcv.function = (pixmap.foreground().pixel && (pixmap.foreground().pixel & pmask)) ? GXcopyInverted : GXcopy; gc = XCreateGC (app->display(), bilevel, GCFunction, &gcv); XFillRectangle(app->display(), bilevel, gc, 0, 0, pixmap.width(), pixmap.height()); XCopyPlane(app->display(), pixmap.pixmap(), bilevel, gc, 0, 0, pixmap.width(), pixmap.height(), 0, 0, pmask); XFreeGC(app->display(), gc); // ==================================== allocate a new pixmap cursor === XColor foreground(pixmap.foreground()), background(pixmap.background()); fCursor = XCreatePixmapCursor(app->display(), bilevel, pixmap.mask(), &foreground, &background, pixmap.hotspotX(), pixmap.hotspotY()); XFreePixmap(app->display(), bilevel); } } #endif #ifndef LITE void YCursor::load(char const *name, unsigned int fallback) { #else void YCursor::load(char const */*name*/, unsigned int fallback) { #endif if(fCursor && fOwned) XFreeCursor(app->display(), fCursor); #ifndef LITE static char const *cursors = "cursors/"; YResourcePaths paths(cursors); for (YPathElement const * pe(paths); pe->root && fCursor == None; pe++) { char *path(pe->joinPath(cursors, name)); if (isreg(path)) load(path); delete path; } if (fCursor == None) #endif fCursor = XCreateFontCursor(app->display(), fallback); fOwned = true; }
fix bug: 520788 freeze with 32 bit deep display fix tested on xfree86 - win32
fix bug: 520788 freeze with 32 bit deep display fix tested on xfree86 - win32
C++
lgpl-2.1
bedna-KU/icewm,bedna-KU/icewm,bedna-KU/icewm,jinn-alt/icewm,dicej/icewm,jinn-alt/icewm,dicej/icewm,dicej/icewm,jinn-alt/icewm,dicej/icewm
1c836ceede7b5bb70f681dc7b54aa261c97e95ef
content/browser/appcache/appcache_ui_test.cc
content/browser/appcache/appcache_ui_test.cc
// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/file_path.h" #include "chrome/test/layout_test_http_server.h" #include "chrome/test/ui/ui_layout_test.h" class AppCacheUITest : public UILayoutTest { public: void RunAppCacheTests(const char* tests[], int num_tests) { FilePath http_test_dir; http_test_dir = http_test_dir.AppendASCII("http"); http_test_dir = http_test_dir.AppendASCII("tests"); FilePath appcache_test_dir; appcache_test_dir = appcache_test_dir.AppendASCII("appcache"); InitializeForLayoutTest(http_test_dir, appcache_test_dir, kHttpPort); LayoutTestHttpServer http_server(new_http_root_dir_, kHttpPort); ASSERT_TRUE(http_server.Start()); for (int i = 0; i < num_tests; ++i) RunLayoutTest(tests[i], kHttpPort); ASSERT_TRUE(http_server.Stop()); } protected: virtual ~AppCacheUITest() {} }; // Flaky: http://crbug.com/54717 // The tests that don't depend on PHP should be less flaky. TEST_F(AppCacheUITest, FLAKY_AppCacheLayoutTests_NoPHP) { static const char* kNoPHPTests[] = { "404-manifest.html", "404-resource.html", "cyrillic-uri.html", "deferred-events-delete-while-raising.html", "deferred-events.html", "destroyed-frame.html", "detached-iframe.html", "different-origin-manifest.html", "different-scheme.html", "empty-manifest.html", "foreign-iframe-main.html", "insert-html-element-with-manifest.html", "insert-html-element-with-manifest-2.html", "manifest-containing-itself.html", "manifest-parsing.html", "manifest-with-empty-file.html", "progress-counter.html", "reload.html", "simple.html", "top-frame-1.html", "top-frame-2.html", "top-frame-3.html", "top-frame-4.html", "whitelist-wildcard.html", "wrong-content-type.html", "wrong-signature-2.html", "wrong-signature.html", "xhr-foreign-resource.html", }; // This test is racey. // https://bugs.webkit.org/show_bug.cgi?id=49104 // "foreign-fallback.html" RunAppCacheTests(kNoPHPTests, arraysize(kNoPHPTests)); } // Flaky: http://crbug.com/54717 // Lighty/PHP is not reliable enough on windows. TEST_F(AppCacheUITest, FLAKY_AppCacheLayoutTests_PHP) { static const char* kPHPTests[] = { "auth.html", "fallback.html", "main-resource-hash.html", "manifest-redirect.html", "manifest-redirect-2.html", "navigating-away-while-cache-attempt-in-progress.html", "non-html.xhtml", "offline-access.html", "online-whitelist.html", "remove-cache.html", "resource-redirect.html", "resource-redirect-2.html", "update-cache.html", }; // This tests loads a data url which calls notifyDone, this just // doesn't work with the layoutTestController in this test harness. // "fail-on-update.html", // Flaky for reasons i don't yet see? // "fail-on-update2.html", // TODO(michaeln): investigate these more closely // "crash-when-navigating-away-then-back.html", // "credential-url.html", // "different-https-origin-resource-main.html", // "idempotent-update.html", not sure this is a valid test // "local-content.html", // "max-size.html", we use a different quota scheme RunAppCacheTests(kPHPTests, arraysize(kPHPTests)); }
// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/file_path.h" #include "chrome/test/layout_test_http_server.h" #include "chrome/test/ui/ui_layout_test.h" class AppCacheUITest : public UILayoutTest { public: void RunAppCacheTests(const char* tests[], int num_tests) { FilePath http_test_dir; http_test_dir = http_test_dir.AppendASCII("http"); http_test_dir = http_test_dir.AppendASCII("tests"); FilePath appcache_test_dir; appcache_test_dir = appcache_test_dir.AppendASCII("appcache"); InitializeForLayoutTest(http_test_dir, appcache_test_dir, kHttpPort); LayoutTestHttpServer http_server(new_http_root_dir_, kHttpPort); ASSERT_TRUE(http_server.Start()); for (int i = 0; i < num_tests; ++i) RunLayoutTest(tests[i], kHttpPort); ASSERT_TRUE(http_server.Stop()); } protected: virtual ~AppCacheUITest() {} }; // Flaky and slow, hence disabled: http://crbug.com/54717 // The tests that don't depend on PHP should be less flaky. TEST_F(AppCacheUITest, DISABLED_AppCacheLayoutTests_NoPHP) { static const char* kNoPHPTests[] = { "404-manifest.html", "404-resource.html", "cyrillic-uri.html", "deferred-events-delete-while-raising.html", "deferred-events.html", "destroyed-frame.html", "detached-iframe.html", "different-origin-manifest.html", "different-scheme.html", "empty-manifest.html", "foreign-iframe-main.html", "insert-html-element-with-manifest.html", "insert-html-element-with-manifest-2.html", "manifest-containing-itself.html", "manifest-parsing.html", "manifest-with-empty-file.html", "progress-counter.html", "reload.html", "simple.html", "top-frame-1.html", "top-frame-2.html", "top-frame-3.html", "top-frame-4.html", "whitelist-wildcard.html", "wrong-content-type.html", "wrong-signature-2.html", "wrong-signature.html", "xhr-foreign-resource.html", }; // This test is racey. // https://bugs.webkit.org/show_bug.cgi?id=49104 // "foreign-fallback.html" RunAppCacheTests(kNoPHPTests, arraysize(kNoPHPTests)); } // Flaky: http://crbug.com/54717 // Lighty/PHP is not reliable enough on windows. TEST_F(AppCacheUITest, FLAKY_AppCacheLayoutTests_PHP) { static const char* kPHPTests[] = { "auth.html", "fallback.html", "main-resource-hash.html", "manifest-redirect.html", "manifest-redirect-2.html", "navigating-away-while-cache-attempt-in-progress.html", "non-html.xhtml", "offline-access.html", "online-whitelist.html", "remove-cache.html", "resource-redirect.html", "resource-redirect-2.html", "update-cache.html", }; // This tests loads a data url which calls notifyDone, this just // doesn't work with the layoutTestController in this test harness. // "fail-on-update.html", // Flaky for reasons i don't yet see? // "fail-on-update2.html", // TODO(michaeln): investigate these more closely // "crash-when-navigating-away-then-back.html", // "credential-url.html", // "different-https-origin-resource-main.html", // "idempotent-update.html", not sure this is a valid test // "local-content.html", // "max-size.html", we use a different quota scheme RunAppCacheTests(kPHPTests, arraysize(kPHPTests)); }
Disable AppCacheLayoutTests_NoPHP
Disable AppCacheLayoutTests_NoPHP It takes 38 seconds to run and then fails. BUG=85865,54717 TEST=none Review URL: http://codereview.chromium.org/7300021 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@91428 0039d316-1c4b-4281-b951-d872f2087c98
C++
bsd-3-clause
adobe/chromium,yitian134/chromium,yitian134/chromium,ropik/chromium,yitian134/chromium,yitian134/chromium,yitian134/chromium,adobe/chromium,gavinp/chromium,gavinp/chromium,gavinp/chromium,adobe/chromium,adobe/chromium,yitian134/chromium,gavinp/chromium,gavinp/chromium,ropik/chromium,yitian134/chromium,ropik/chromium,gavinp/chromium,yitian134/chromium,gavinp/chromium,adobe/chromium,ropik/chromium,ropik/chromium,gavinp/chromium,yitian134/chromium,yitian134/chromium,adobe/chromium,adobe/chromium,adobe/chromium,ropik/chromium,adobe/chromium,adobe/chromium,gavinp/chromium,gavinp/chromium,adobe/chromium,ropik/chromium,ropik/chromium,ropik/chromium
79d583d04c806ae8c8bf3e90c171c9a1dfd145b0
core/dawn_player/flv_media_stream_source.cpp
core/dawn_player/flv_media_stream_source.cpp
/* * flv_media_stream_source.cpp: * * Copyright (C) 2015 limhiaoing <blog.poxiao.me> All Rights Reserved. * */ #include "pch.h" #include <algorithm> #include <memory> #include <string> #include "flv_media_stream_source.hpp" #include "flv_player.hpp" using namespace Platform::Collections; using namespace Windows::Media::MediaProperties; namespace dawn_player { flv_media_stream_source::flv_media_stream_source() { } void flv_media_stream_source::init(flv_player^ player, MediaStreamSource^ mss) { this->player = player; this->mss = mss; starting_event_token = this->mss->Starting += ref new TypedEventHandler<MediaStreamSource^, MediaStreamSourceStartingEventArgs^>(this, &flv_media_stream_source::on_starting); sample_requested_event_token = this->mss->SampleRequested += ref new TypedEventHandler<MediaStreamSource^, MediaStreamSourceSampleRequestedEventArgs^>(this, &flv_media_stream_source::on_sample_requested); } IAsyncOperation<flv_media_stream_source^>^ flv_media_stream_source::create_async(IRandomAccessStream^ random_access_stream) { auto player = ref new flv_player(); player->set_source(random_access_stream); auto media_info = ref new Map<Platform::String^, Platform::String^>(); auto shared_task = std::make_shared<concurrency::task<open_result>>(concurrency::create_task(player->open_async(media_info))); return concurrency::create_async([=]() -> flv_media_stream_source^ { auto result = shared_task->get(); if (result != open_result::ok) { player->close(); return nullptr; } auto acpd_w = media_info->Lookup(L"AudioCodecPrivateData")->ToString(); std::string acpd; std::transform(acpd_w->Begin(), acpd_w->End(), std::back_inserter(acpd), [](wchar_t ch) -> char { return static_cast<char>(ch); }); unsigned int channel_count = std::stol(acpd.substr(4, 2), 0, 16) + std::stol(acpd.substr(6, 2), 0, 16) * 0x100; unsigned int sample_rate = std::stol(acpd.substr(8, 2), 0, 16) + std::stol(acpd.substr(10, 2), 0, 16) * 0x100 + std::stol(acpd.substr(12, 2), 0, 16) * 0x10000 + std::stol(acpd.substr(14, 2), 0, 16) * 0x1000000; unsigned int bit_rate = sample_rate * (std::stol(acpd.substr(28, 2), 0, 16) + std::stol(acpd.substr(30, 2), 0, 16) * 0x100); auto aep = AudioEncodingProperties::CreateAac(sample_rate, channel_count, bit_rate); auto asd = ref new AudioStreamDescriptor(aep); auto vep = VideoEncodingProperties::CreateH264(); auto video_width = std::stoul(media_info->Lookup("Width")->ToString()->Data()); auto video_height = std::stoul(media_info->Lookup("Width")->ToString()->Data()); // It seems that H.264 only supports even numbered dimensions. vep->Width = video_width - (video_width % 2); vep->Height = video_height - (video_height % 2); auto vsd = ref new VideoStreamDescriptor(vep); auto mss = ref new MediaStreamSource(asd); mss->AddStreamDescriptor(vsd); mss->CanSeek = media_info->Lookup(L"CanSeek")->ToString() == L"True"; mss->Duration = TimeSpan{ std::stoll(media_info->Lookup(L"Duration")->ToString()->Data()) }; auto flv_mss = ref new flv_media_stream_source(); flv_mss->init(player, mss); return flv_mss; }); } MediaStreamSource^ flv_media_stream_source::unwrap() { return this->mss; } flv_media_stream_source::~flv_media_stream_source() { if (this->player) { this->player->close(); this->player = nullptr; } if (this->mss) { this->mss->Starting -= this->starting_event_token; this->mss->SampleRequested -= this->sample_requested_event_token; this->mss = nullptr; } } void flv_media_stream_source::on_starting(MediaStreamSource^ sender, MediaStreamSourceStartingEventArgs^ args) { auto request = args->Request; auto start_position = request->StartPosition; if (start_position == nullptr) { request->SetActualStartPosition(TimeSpan{ this->player->get_position() }); } else { auto deferral = request->GetDeferral(); concurrency::create_task(this->player->begin_seek(start_position->Value.Duration)).then([=](concurrency::task<std::int64_t> task) { auto seek_to_time = task.get(); if (seek_to_time == -1) { return; } request->SetActualStartPosition(TimeSpan{ seek_to_time }); deferral->Complete(); this->player->end_seek(); }); } } void flv_media_stream_source::on_sample_requested(MediaStreamSource^ sender, MediaStreamSourceSampleRequestedEventArgs^ args) { auto request = args->Request; auto deferral = request->GetDeferral(); if (request->StreamDescriptor->GetType()->FullName == AudioStreamDescriptor::typeid->FullName) { auto sample_info = ref new Map<Platform::String^, Platform::Object^>(); concurrency::create_task(this->player->get_sample_async(sample_type::audio, sample_info)).then([=](concurrency::task<get_sample_result> task) { auto result = task.get(); if (result == get_sample_result::ok) { auto sample = MediaStreamSample::CreateFromBuffer(dynamic_cast<Buffer^>(sample_info->Lookup(L"Data")), TimeSpan{ std::stoll(sample_info->Lookup(L"Timestamp")->ToString()->Data()) }); request->Sample = sample; } else if (result == get_sample_result::eos) { request->Sample = nullptr; } else if (result == get_sample_result::error) { sender->NotifyError(MediaStreamSourceErrorStatus::Other); return; } else { return; } deferral->Complete(); }); } else if (request->StreamDescriptor->GetType()->FullName == VideoStreamDescriptor::typeid->FullName) { auto sample_info = ref new Map<Platform::String^, Platform::Object^>(); concurrency::create_task(this->player->get_sample_async(sample_type::video, sample_info)).then([=](concurrency::task<get_sample_result> task) { auto result = task.get(); if (result == get_sample_result::ok) { auto sample = MediaStreamSample::CreateFromBuffer(dynamic_cast<Buffer^>(sample_info->Lookup(L"Data")), TimeSpan{ std::stoll(sample_info->Lookup(L"Timestamp")->ToString()->Data()) }); sample->DecodeTimestamp = TimeSpan{ std::stoll(sample_info->Lookup(L"DecodeTimestamp")->ToString()->Data()) }; sample->KeyFrame = sample_info->Lookup(L"KeyFrame")->ToString() == L"True"; request->Sample = sample; } else if (result == get_sample_result::eos) { request->Sample = nullptr; } else if (result == get_sample_result::error) { sender->NotifyError(MediaStreamSourceErrorStatus::Other); return; } else { return; } deferral->Complete(); }); } } } // namespace dawn_player
/* * flv_media_stream_source.cpp: * * Copyright (C) 2015 limhiaoing <blog.poxiao.me> All Rights Reserved. * */ #include "pch.h" #include <algorithm> #include <memory> #include <string> #include "flv_media_stream_source.hpp" #include "flv_player.hpp" using namespace Platform::Collections; using namespace Windows::Media::MediaProperties; namespace dawn_player { flv_media_stream_source::flv_media_stream_source() { } void flv_media_stream_source::init(flv_player^ player, MediaStreamSource^ mss) { this->player = player; this->mss = mss; starting_event_token = this->mss->Starting += ref new TypedEventHandler<MediaStreamSource^, MediaStreamSourceStartingEventArgs^>(this, &flv_media_stream_source::on_starting); sample_requested_event_token = this->mss->SampleRequested += ref new TypedEventHandler<MediaStreamSource^, MediaStreamSourceSampleRequestedEventArgs^>(this, &flv_media_stream_source::on_sample_requested); } IAsyncOperation<flv_media_stream_source^>^ flv_media_stream_source::create_async(IRandomAccessStream^ random_access_stream) { auto player = ref new flv_player(); player->set_source(random_access_stream); auto media_info = ref new Map<Platform::String^, Platform::String^>(); auto shared_task = std::make_shared<concurrency::task<open_result>>(concurrency::create_task(player->open_async(media_info))); return concurrency::create_async([=]() -> flv_media_stream_source^ { auto result = shared_task->get(); if (result != open_result::ok) { player->close(); return nullptr; } auto acpd_w = media_info->Lookup(L"AudioCodecPrivateData")->ToString(); std::string acpd; std::transform(acpd_w->Begin(), acpd_w->End(), std::back_inserter(acpd), [](wchar_t ch) -> char { return static_cast<char>(ch); }); unsigned int channel_count = std::stol(acpd.substr(4, 2), 0, 16) + std::stol(acpd.substr(6, 2), 0, 16) * 0x100; unsigned int sample_rate = std::stol(acpd.substr(8, 2), 0, 16) + std::stol(acpd.substr(10, 2), 0, 16) * 0x100 + std::stol(acpd.substr(12, 2), 0, 16) * 0x10000 + std::stol(acpd.substr(14, 2), 0, 16) * 0x1000000; unsigned int bit_rate = sample_rate * (std::stol(acpd.substr(28, 2), 0, 16) + std::stol(acpd.substr(30, 2), 0, 16) * 0x100); auto aep = AudioEncodingProperties::CreateAac(sample_rate, channel_count, bit_rate); auto asd = ref new AudioStreamDescriptor(aep); auto vep = VideoEncodingProperties::CreateH264(); auto video_width = std::stoul(media_info->Lookup("Width")->ToString()->Data()); auto video_height = std::stoul(media_info->Lookup("Width")->ToString()->Data()); // It seems that H.264 only supports even numbered dimensions. vep->Width = video_width - (video_width % 2); vep->Height = video_height - (video_height % 2); auto vsd = ref new VideoStreamDescriptor(vep); auto mss = ref new MediaStreamSource(asd); mss->AddStreamDescriptor(vsd); mss->CanSeek = media_info->Lookup(L"CanSeek")->ToString() == L"True"; // Set BufferTime to 0 to improve seek experience in Debug mode mss->BufferTime = TimeSpan { 0 }; mss->Duration = TimeSpan{ std::stoll(media_info->Lookup(L"Duration")->ToString()->Data()) }; auto flv_mss = ref new flv_media_stream_source(); flv_mss->init(player, mss); return flv_mss; }); } MediaStreamSource^ flv_media_stream_source::unwrap() { return this->mss; } flv_media_stream_source::~flv_media_stream_source() { if (this->player) { this->player->close(); this->player = nullptr; } if (this->mss) { this->mss->Starting -= this->starting_event_token; this->mss->SampleRequested -= this->sample_requested_event_token; this->mss = nullptr; } } void flv_media_stream_source::on_starting(MediaStreamSource^ sender, MediaStreamSourceStartingEventArgs^ args) { auto request = args->Request; auto start_position = request->StartPosition; if (start_position == nullptr) { request->SetActualStartPosition(TimeSpan{ this->player->get_position() }); } else { auto deferral = request->GetDeferral(); concurrency::create_task(this->player->begin_seek(start_position->Value.Duration)).then([=](concurrency::task<std::int64_t> task) { auto seek_to_time = task.get(); if (seek_to_time == -1) { return; } request->SetActualStartPosition(TimeSpan{ seek_to_time }); deferral->Complete(); this->player->end_seek(); }); } } void flv_media_stream_source::on_sample_requested(MediaStreamSource^ sender, MediaStreamSourceSampleRequestedEventArgs^ args) { auto request = args->Request; auto deferral = request->GetDeferral(); if (request->StreamDescriptor->GetType()->FullName == AudioStreamDescriptor::typeid->FullName) { auto sample_info = ref new Map<Platform::String^, Platform::Object^>(); concurrency::create_task(this->player->get_sample_async(sample_type::audio, sample_info)).then([=](concurrency::task<get_sample_result> task) { auto result = task.get(); if (result == get_sample_result::ok) { auto sample = MediaStreamSample::CreateFromBuffer(dynamic_cast<Buffer^>(sample_info->Lookup(L"Data")), TimeSpan{ std::stoll(sample_info->Lookup(L"Timestamp")->ToString()->Data()) }); request->Sample = sample; } else if (result == get_sample_result::eos) { request->Sample = nullptr; } else if (result == get_sample_result::error) { sender->NotifyError(MediaStreamSourceErrorStatus::Other); return; } else { return; } deferral->Complete(); }); } else if (request->StreamDescriptor->GetType()->FullName == VideoStreamDescriptor::typeid->FullName) { auto sample_info = ref new Map<Platform::String^, Platform::Object^>(); concurrency::create_task(this->player->get_sample_async(sample_type::video, sample_info)).then([=](concurrency::task<get_sample_result> task) { auto result = task.get(); if (result == get_sample_result::ok) { auto sample = MediaStreamSample::CreateFromBuffer(dynamic_cast<Buffer^>(sample_info->Lookup(L"Data")), TimeSpan{ std::stoll(sample_info->Lookup(L"Timestamp")->ToString()->Data()) }); sample->DecodeTimestamp = TimeSpan{ std::stoll(sample_info->Lookup(L"DecodeTimestamp")->ToString()->Data()) }; sample->KeyFrame = sample_info->Lookup(L"KeyFrame")->ToString() == L"True"; request->Sample = sample; } else if (result == get_sample_result::eos) { request->Sample = nullptr; } else if (result == get_sample_result::error) { sender->NotifyError(MediaStreamSourceErrorStatus::Other); return; } else { return; } deferral->Complete(); }); } } } // namespace dawn_player
Set MediaStreamSource::BufferTime to 0 to improve seek experience in Debug mode
flv_media_stream_source: Set MediaStreamSource::BufferTime to 0 to improve seek experience in Debug mode
C++
mit
lxrite/DawnPlayer
eb8feaf912bc21b5905b61715bac7277865540e3
samples/cpp/save_pose_into_pcd.cpp
samples/cpp/save_pose_into_pcd.cpp
/* * adds pose information given by pose_000x.txt into cloud_000x.pcd files (old dataset structure) * now we can use pcl_viewer *.pcd to show all point clouds in common coordinate system * * Created on: Dec 04, 2014 * Author: Thomas Faeulhammer * */ #include <v4r/io/filesystem.h> #include <v4r/common/faat_3d_rec_framework_defines.h> #include <pcl/console/parse.h> #include <pcl/io/pcd_io.h> #include <iostream> #include <sstream> typedef pcl::PointXYZRGB PointT; int main (int argc, char ** argv) { std::string path; bool use_indices = false; pcl::console::parse_argument (argc, argv, "-path", path); pcl::console::parse_argument (argc, argv, "-use_indices", use_indices); std::cout << "Visualizing all point clouds in folder " << path; std::vector < std::string > files_intern; if (v4r::io::getFilesInDirectory (path, files_intern, "", ".*.pcd", true) == -1) { std::cerr << "Given path: " << path << " does not exist. Usage view_all_point_clouds_in_folder -path <folder name> -rows <number of rows used for displaying files>" << std::endl; return -1; } std::vector < std::string > cloud_files; for (size_t file_id=0; file_id < files_intern.size(); file_id++) { if ( files_intern[file_id].find("indices") == std::string::npos ) { cloud_files.push_back( files_intern [file_id] ); } } std::sort(cloud_files.begin(), cloud_files.end()); for (size_t file_id=0; file_id < cloud_files.size(); file_id++) { std::stringstream full_path_ss; #ifdef _WIN32 full_path << path << "\\" << cloud_files[file_id]; #else full_path_ss << path << "/" << cloud_files[file_id]; #endif std::cout << "Checking " << full_path_ss.str() << std::endl; // Loading file and corresponding indices file (if it exists) pcl::PointCloud<PointT>::Ptr cloud (new pcl::PointCloud<PointT>); pcl::io::loadPCDFile (full_path_ss.str(), *cloud); if(use_indices) { // Check if indices file exist std::string indices_filename( cloud_files[file_id] ); boost::replace_all (indices_filename, "cloud", "object_indices"); std::stringstream full_indices_path_ss; #ifdef _WIN32 full_indices_path_ss << path << "\\" << indices_filename; #else full_indices_path_ss << path << "/" << indices_filename; #endif if( v4r::io::existsFile( full_indices_path_ss.str()) ) { pcl::PointCloud<IndexPoint> obj_indices_cloud; pcl::io::loadPCDFile(full_indices_path_ss.str(), obj_indices_cloud); pcl::PointIndices indices; indices.indices.resize(obj_indices_cloud.points.size()); for(size_t kk=0; kk < obj_indices_cloud.points.size(); kk++) indices.indices[kk] = obj_indices_cloud.points[kk].idx; pcl::copyPointCloud(*cloud, indices, *cloud); } else { std::cout << "Indices file " << full_indices_path_ss.str() << " does not exist." << std::endl; } } // Check if pose file exist std::string pose_filename( cloud_files[file_id] ); boost::replace_all (pose_filename, ".pcd", ".txt"); std::stringstream full_pose_path_ss; #ifdef USE_WILLOW_DATASET boost::replace_all (pose_filename, "cloud_", "pose_"); full_pose_path_ss << pose_filename; #else #ifdef _WIN32 full_pose_path_ss << path << "\\" << "transformation_" << pose_filename; #else full_pose_path_ss << path << "/" << "transformation_" << pose_filename; #endif #endif if( v4r::io::existsFile( full_pose_path_ss.str()) ) { std::ifstream is(full_pose_path_ss.str().c_str()); std::istream_iterator<double> start(is), end; std::vector<double> numbers(start, end); assert(numbers.size() == 16); std::cout << "Transform to world coordinate system: " << std::endl; Eigen::Matrix4f global_trans; for (size_t row=0; row <4; row++) { for(size_t col=0; col<4; col++) { global_trans(row, col) = numbers[4*row + col]; } } std::cout << global_trans << std::endl << std::endl; cloud->sensor_origin_[0] = global_trans(0,3); cloud->sensor_origin_[1] = global_trans(1,3); cloud->sensor_origin_[2] = global_trans(2,3); Eigen::Matrix3f rotation = global_trans.block<3,3>(0,0); Eigen::Quaternionf q(rotation); cloud->sensor_orientation_ = q; pcl::io::savePCDFileBinary(full_path_ss.str(), *cloud); } else { std::cout << "Pose file " << full_pose_path_ss.str() << " does not exist." << std::endl; } } }
/* * adds pose information given by pose_000x.txt into cloud_000x.pcd files (old dataset structure) * now we can use pcl_viewer *.pcd to show all point clouds in common coordinate system * * Created on: Dec 04, 2014 * Author: Thomas Faeulhammer * */ #include <v4r/io/filesystem.h> #include <v4r/common/faat_3d_rec_framework_defines.h> #include <pcl/console/parse.h> #include <pcl/io/pcd_io.h> #include <iostream> #include <sstream> typedef pcl::PointXYZRGB PointT; int main (int argc, char ** argv) { std::string path; bool use_indices = false; pcl::console::parse_argument (argc, argv, "-path", path); pcl::console::parse_argument (argc, argv, "-use_indices", use_indices); std::cout << "Visualizing all point clouds in folder " << path; std::vector < std::string > files_intern; if (v4r::io::getFilesInDirectory (path, files_intern, "", ".*.pcd", true) == -1) { std::cerr << "Given path: " << path << " does not exist. Usage view_all_point_clouds_in_folder -path <folder name> -rows <number of rows used for displaying files>" << std::endl; return -1; } std::vector < std::string > cloud_files; for (size_t file_id=0; file_id < files_intern.size(); file_id++) { if ( files_intern[file_id].find("indices") == std::string::npos ) { cloud_files.push_back( files_intern [file_id] ); } } std::sort(cloud_files.begin(), cloud_files.end()); for (size_t file_id=0; file_id < cloud_files.size(); file_id++) { std::stringstream full_path_ss; #ifdef _WIN32 full_path << path << "\\" << cloud_files[file_id]; #else full_path_ss << path << "/" << cloud_files[file_id]; #endif std::cout << "Checking " << full_path_ss.str() << std::endl; // Loading file and corresponding indices file (if it exists) pcl::PointCloud<PointT>::Ptr cloud (new pcl::PointCloud<PointT>); pcl::io::loadPCDFile (full_path_ss.str(), *cloud); if(use_indices) { // Check if indices file exist std::string indices_filename( cloud_files[file_id] ); boost::replace_all (indices_filename, "cloud", "object_indices"); std::stringstream full_indices_path_ss; #ifdef _WIN32 full_indices_path_ss << path << "\\" << indices_filename; #else full_indices_path_ss << path << "/" << indices_filename; #endif if( v4r::io::existsFile( full_indices_path_ss.str()) ) { pcl::PointCloud<IndexPoint> obj_indices_cloud; pcl::io::loadPCDFile(full_indices_path_ss.str(), obj_indices_cloud); pcl::PointIndices indices; indices.indices.resize(obj_indices_cloud.points.size()); for(size_t kk=0; kk < obj_indices_cloud.points.size(); kk++) indices.indices[kk] = obj_indices_cloud.points[kk].idx; pcl::copyPointCloud(*cloud, indices, *cloud); } else { std::cout << "Indices file " << full_indices_path_ss.str() << " does not exist." << std::endl; } } // Check if pose file exist std::string pose_filename( cloud_files[file_id] ); boost::replace_all (pose_filename, ".pcd", ".txt"); std::stringstream full_pose_path_ss; #ifdef USE_WILLOW_DATASET boost::replace_all (pose_filename, "cloud_", "pose_"); #ifdef _WIN32 full_pose_path_ss << path << "\\" << pose_filename; #else full_pose_path_ss << path << "/" << pose_filename; #endif #else #ifdef _WIN32 full_pose_path_ss << path << "\\" << "transformation_" << pose_filename; #else full_pose_path_ss << path << "/" << "transformation_" << pose_filename; #endif #endif if( v4r::io::existsFile( full_pose_path_ss.str()) ) { std::ifstream is(full_pose_path_ss.str().c_str()); std::istream_iterator<double> start(is), end; std::vector<double> numbers(start, end); assert(numbers.size() == 16); std::cout << "Transform to world coordinate system: " << std::endl; Eigen::Matrix4f global_trans; for (size_t row=0; row <4; row++) { for(size_t col=0; col<4; col++) { global_trans(row, col) = numbers[4*row + col]; } } std::cout << global_trans << std::endl << std::endl; cloud->sensor_origin_[0] = global_trans(0,3); cloud->sensor_origin_[1] = global_trans(1,3); cloud->sensor_origin_[2] = global_trans(2,3); Eigen::Matrix3f rotation = global_trans.block<3,3>(0,0); Eigen::Quaternionf q(rotation); cloud->sensor_orientation_ = q; pcl::io::savePCDFileBinary(full_path_ss.str(), *cloud); } else { std::cout << "Pose file " << full_pose_path_ss.str() << " does not exist." << std::endl; } } }
fix of last push
fix of last push
C++
mit
Cerarus/v4r,Cerarus/v4r,Cerarus/v4r
10cef959e8892e0341a0fe878a7a9c5f190015bd
Tests/lib/file_path/test.cpp
Tests/lib/file_path/test.cpp
#include <ostream> #include <gtest/gtest.h> #include "pqrs/file_path.hpp" TEST(pqrs_file_path, dirname) { EXPECT_EQ("/usr/bin", pqrs::file_path::dirname("/usr/bin/ls")); EXPECT_EQ("/usr/bin", pqrs::file_path::dirname("/usr/bin/ls/")); EXPECT_EQ("/usr/bin", pqrs::file_path::dirname("/usr/bin/l")); EXPECT_EQ("/usr/bin", pqrs::file_path::dirname("/usr/bin/l/")); EXPECT_EQ("/", pqrs::file_path::dirname("/usr")); EXPECT_EQ("/", pqrs::file_path::dirname("/")); EXPECT_EQ("usr/bin", pqrs::file_path::dirname("usr/bin/ls")); EXPECT_EQ("usr", pqrs::file_path::dirname("usr/bin/")); EXPECT_EQ(".", pqrs::file_path::dirname("usr")); EXPECT_EQ(".", pqrs::file_path::dirname("usr/")); EXPECT_EQ(".", pqrs::file_path::dirname("")); } TEST(pqrs_file_path, normalize) { std::string file_path; file_path = ""; pqrs::file_path::normalize(file_path); EXPECT_EQ(".", file_path); file_path = "."; pqrs::file_path::normalize(file_path); EXPECT_EQ(".", file_path); file_path = "./"; pqrs::file_path::normalize(file_path); EXPECT_EQ(".", file_path); file_path = ".."; pqrs::file_path::normalize(file_path); EXPECT_EQ("..", file_path); file_path = "../"; pqrs::file_path::normalize(file_path); EXPECT_EQ("../", file_path); file_path = "..//foo"; pqrs::file_path::normalize(file_path); EXPECT_EQ("../foo", file_path); file_path = "abcde"; pqrs::file_path::normalize(file_path); EXPECT_EQ("abcde", file_path); file_path = "abcde/"; pqrs::file_path::normalize(file_path); EXPECT_EQ("abcde/", file_path); file_path = "/foo//bar/../baz"; pqrs::file_path::normalize(file_path); EXPECT_EQ("/foo/baz", file_path); file_path = "/../foo//bar/../baz"; pqrs::file_path::normalize(file_path); EXPECT_EQ("/foo/baz", file_path); file_path = "foo/../bar"; pqrs::file_path::normalize(file_path); EXPECT_EQ("bar", file_path); file_path = "foo/.../bar"; pqrs::file_path::normalize(file_path); EXPECT_EQ("foo/.../bar", file_path); file_path = "a/../b/../c/d"; pqrs::file_path::normalize(file_path); EXPECT_EQ("c/d", file_path); file_path = "a/./b/./c/d"; pqrs::file_path::normalize(file_path); EXPECT_EQ("a/b/c/d", file_path); file_path = "foo/bar/.."; pqrs::file_path::normalize(file_path); EXPECT_EQ("foo", file_path); file_path = "foo/bar/../"; pqrs::file_path::normalize(file_path); EXPECT_EQ("foo/", file_path); file_path = "foo/bar/."; pqrs::file_path::normalize(file_path); EXPECT_EQ("foo/bar", file_path); file_path = "foo/bar/./"; pqrs::file_path::normalize(file_path); EXPECT_EQ("foo/bar/", file_path); file_path = "../foo/bar"; pqrs::file_path::normalize(file_path); EXPECT_EQ("../foo/bar", file_path); file_path = "../../../foo/bar"; pqrs::file_path::normalize(file_path); EXPECT_EQ("../../../foo/bar", file_path); file_path = "./foo/bar"; pqrs::file_path::normalize(file_path); EXPECT_EQ("foo/bar", file_path); file_path = "../foo/bar/.."; pqrs::file_path::normalize(file_path); EXPECT_EQ("../foo", file_path); file_path = "../foo/bar///..."; pqrs::file_path::normalize(file_path); EXPECT_EQ("../foo/bar/...", file_path); file_path = "../a/b/../c/../d///.."; pqrs::file_path::normalize(file_path); EXPECT_EQ("../a", file_path); }
#include <ostream> #include <gtest/gtest.h> #include "pqrs/file_path.hpp" TEST(pqrs_file_path, dirname) { EXPECT_EQ("/usr/bin", pqrs::file_path::dirname("/usr/bin/ls")); EXPECT_EQ("/usr/bin", pqrs::file_path::dirname("/usr/bin/ls/")); EXPECT_EQ("/usr/bin", pqrs::file_path::dirname("/usr/bin/l")); EXPECT_EQ("/usr/bin", pqrs::file_path::dirname("/usr/bin/l/")); EXPECT_EQ("/", pqrs::file_path::dirname("/usr")); EXPECT_EQ("/", pqrs::file_path::dirname("/")); EXPECT_EQ("usr/bin", pqrs::file_path::dirname("usr/bin/ls")); EXPECT_EQ("usr", pqrs::file_path::dirname("usr/bin/")); EXPECT_EQ(".", pqrs::file_path::dirname("usr")); EXPECT_EQ(".", pqrs::file_path::dirname("usr/")); EXPECT_EQ(".", pqrs::file_path::dirname("")); } TEST(pqrs_file_path, normalize) { std::string file_path; file_path = ""; pqrs::file_path::normalize(file_path); EXPECT_EQ(".", file_path); file_path = "."; pqrs::file_path::normalize(file_path); EXPECT_EQ(".", file_path); file_path = "./"; pqrs::file_path::normalize(file_path); EXPECT_EQ(".", file_path); file_path = ".."; pqrs::file_path::normalize(file_path); EXPECT_EQ("..", file_path); file_path = "../"; pqrs::file_path::normalize(file_path); EXPECT_EQ("../", file_path); file_path = "..//foo"; pqrs::file_path::normalize(file_path); EXPECT_EQ("../foo", file_path); file_path = "abcde"; pqrs::file_path::normalize(file_path); EXPECT_EQ("abcde", file_path); file_path = "abcde/"; pqrs::file_path::normalize(file_path); EXPECT_EQ("abcde/", file_path); file_path = "/foo//bar/../baz"; pqrs::file_path::normalize(file_path); EXPECT_EQ("/foo/baz", file_path); file_path = "/../foo//bar/../baz"; pqrs::file_path::normalize(file_path); EXPECT_EQ("/foo/baz", file_path); file_path = "foo/../bar"; pqrs::file_path::normalize(file_path); EXPECT_EQ("bar", file_path); file_path = "foo/.../bar"; pqrs::file_path::normalize(file_path); EXPECT_EQ("foo/.../bar", file_path); file_path = "a/../b/../c/d"; pqrs::file_path::normalize(file_path); EXPECT_EQ("c/d", file_path); file_path = "a/./b/./c/d"; pqrs::file_path::normalize(file_path); EXPECT_EQ("a/b/c/d", file_path); file_path = "foo/bar/.."; pqrs::file_path::normalize(file_path); EXPECT_EQ("foo", file_path); file_path = "foo/bar/../"; pqrs::file_path::normalize(file_path); EXPECT_EQ("foo/", file_path); file_path = "foo/bar/."; pqrs::file_path::normalize(file_path); EXPECT_EQ("foo/bar", file_path); file_path = "foo/bar/./"; pqrs::file_path::normalize(file_path); EXPECT_EQ("foo/bar/", file_path); file_path = "../foo/bar"; pqrs::file_path::normalize(file_path); EXPECT_EQ("../foo/bar", file_path); file_path = "../../../foo/bar"; pqrs::file_path::normalize(file_path); EXPECT_EQ("../../../foo/bar", file_path); file_path = "./foo/bar"; pqrs::file_path::normalize(file_path); EXPECT_EQ("foo/bar", file_path); file_path = "../foo/bar/.."; pqrs::file_path::normalize(file_path); EXPECT_EQ("../foo", file_path); file_path = "../foo/bar///..."; pqrs::file_path::normalize(file_path); EXPECT_EQ("../foo/bar/...", file_path); file_path = "../a/b/../c/../d///.."; pqrs::file_path::normalize(file_path); EXPECT_EQ("../a", file_path); file_path = "a/../..////../b/c"; pqrs::file_path::normalize(file_path); EXPECT_EQ("../../b/c", file_path); }
update test
update test
C++
unlicense
tekezo/Karabiner,chzyer-dev/Karabiner,runarbu/Karabiner,wataash/Karabiner,miaotaizi/Karabiner,tekezo/Karabiner,muramasa64/Karabiner,chzyer-dev/Karabiner,astachurski/Karabiner,muramasa64/Karabiner,miaotaizi/Karabiner,wataash/Karabiner,muramasa64/Karabiner,tekezo/Karabiner,runarbu/Karabiner,wataash/Karabiner,e-gaulue/Karabiner,runarbu/Karabiner,tekezo/Karabiner,miaotaizi/Karabiner,muramasa64/Karabiner,astachurski/Karabiner,chzyer-dev/Karabiner,astachurski/Karabiner,wataash/Karabiner,miaotaizi/Karabiner,e-gaulue/Karabiner,chzyer-dev/Karabiner,e-gaulue/Karabiner,astachurski/Karabiner,e-gaulue/Karabiner,runarbu/Karabiner
38ba7edf5326adab4b211c0b16d0aa11d3b06b31
cql3/restrictions/term_slice.hh
cql3/restrictions/term_slice.hh
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Copyright 2015 Cloudius Systems * * Modified by Cloudius Systems */ #pragma once #include "cql3/restrictions/abstract_restriction.hh" #include "cql3/term.hh" #include "core/shared_ptr.hh" #include "to_string.hh" #include "exceptions/exceptions.hh" namespace cql3 { namespace restrictions { class term_slice final { private: struct bound { bool inclusive; ::shared_ptr<term> t; }; bound _bounds[2]; private: term_slice(::shared_ptr<term> start, bool include_start, ::shared_ptr<term> end, bool include_end) : _bounds{{include_start, std::move(start)}, {include_end, std::move(end)}} { } public: static term_slice new_instance(statements::bound bound, bool include, ::shared_ptr<term> term) { if (is_start(bound)) { return term_slice(std::move(term), include, {}, false); } else { return term_slice({}, false, std::move(term), include); } } /** * Returns the boundary value. * * @param bound the boundary type * @return the boundary value */ ::shared_ptr<term> bound(statements::bound b) const { return _bounds[get_idx(b)].t; } /** * Checks if this slice has a boundary for the specified type. * * @param b the boundary type * @return <code>true</code> if this slice has a boundary for the specified type, <code>false</code> otherwise. */ bool has_bound(statements::bound b) const { return bool(_bounds[get_idx(b)].t); } /** * Checks if this slice boundary is inclusive for the specified type. * * @param b the boundary type * @return <code>true</code> if this slice boundary is inclusive for the specified type, * <code>false</code> otherwise. */ bool is_inclusive(statements::bound b) const { return !_bounds[get_idx(b)].t || _bounds[get_idx(b)].inclusive; } /** * Merges this slice with the specified one. * * @param other the slice to merge with */ void merge(const term_slice& other) { if (has_bound(statements::bound::START)) { assert(!other.has_bound(statements::bound::START)); _bounds[get_idx(statements::bound::END)] = other._bounds[get_idx(statements::bound::END)]; } else { assert(!other.has_bound(statements::bound::END)); _bounds[get_idx(statements::bound::START)] = other._bounds[get_idx(statements::bound::START)]; } } friend std::ostream& operator<<(std::ostream& out, const term_slice& slice) { static auto print_term = [] (::shared_ptr<term> t) -> sstring { return t ? t->to_string() : "null"; }; return out << sprint("(%s %s, %s %s)", slice._bounds[0].inclusive ? ">=" : ">", print_term(slice._bounds[0].t), slice._bounds[1].inclusive ? "<=" : "<", print_term(slice._bounds[1].t)); } #if 0 /** * Returns the index operator corresponding to the specified boundary. * * @param b the boundary type * @return the index operator corresponding to the specified boundary */ public Operator getIndexOperator(statements::bound b) { if (b.isStart()) return boundInclusive[get_idx(b)] ? Operator.GTE : Operator.GT; return boundInclusive[get_idx(b)] ? Operator.LTE : Operator.LT; } /** * Check if this <code>TermSlice</code> is supported by the specified index. * * @param index the Secondary index * @return <code>true</code> this type of <code>TermSlice</code> is supported by the specified index, * <code>false</code> otherwise. */ public bool isSupportedBy(SecondaryIndex index) { bool supported = false; if (has_bound(statements::bound::START)) supported |= isInclusive(statements::bound::START) ? index.supportsOperator(Operator.GTE) : index.supportsOperator(Operator.GT); if (has_bound(statements::bound::END)) supported |= isInclusive(statements::bound::END) ? index.supportsOperator(Operator.LTE) : index.supportsOperator(Operator.LT); return supported; } #endif }; } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Copyright 2015 Cloudius Systems * * Modified by Cloudius Systems */ #pragma once #include "cql3/restrictions/abstract_restriction.hh" #include "cql3/term.hh" #include "core/shared_ptr.hh" #include "to_string.hh" #include "exceptions/exceptions.hh" namespace cql3 { namespace restrictions { class term_slice final { private: struct bound { bool inclusive; ::shared_ptr<term> t; }; bound _bounds[2]; private: term_slice(::shared_ptr<term> start, bool include_start, ::shared_ptr<term> end, bool include_end) : _bounds{{include_start, std::move(start)}, {include_end, std::move(end)}} { } public: static term_slice new_instance(statements::bound bound, bool include, ::shared_ptr<term> term) { if (is_start(bound)) { return term_slice(std::move(term), include, {}, false); } else { return term_slice({}, false, std::move(term), include); } } /** * Returns the boundary value. * * @param bound the boundary type * @return the boundary value */ ::shared_ptr<term> bound(statements::bound b) const { return _bounds[get_idx(b)].t; } /** * Checks if this slice has a boundary for the specified type. * * @param b the boundary type * @return <code>true</code> if this slice has a boundary for the specified type, <code>false</code> otherwise. */ bool has_bound(statements::bound b) const { return bool(_bounds[get_idx(b)].t); } /** * Checks if this slice boundary is inclusive for the specified type. * * @param b the boundary type * @return <code>true</code> if this slice boundary is inclusive for the specified type, * <code>false</code> otherwise. */ bool is_inclusive(statements::bound b) const { return !_bounds[get_idx(b)].t || _bounds[get_idx(b)].inclusive; } /** * Merges this slice with the specified one. * * @param other the slice to merge with */ void merge(const term_slice& other) { if (has_bound(statements::bound::START)) { assert(!other.has_bound(statements::bound::START)); _bounds[get_idx(statements::bound::END)] = other._bounds[get_idx(statements::bound::END)]; } else { assert(!other.has_bound(statements::bound::END)); _bounds[get_idx(statements::bound::START)] = other._bounds[get_idx(statements::bound::START)]; } } sstring to_string() const { static auto print_term = [] (::shared_ptr<term> t) -> sstring { return t ? t->to_string() : "null"; }; return sprint("(%s %s, %s %s)", _bounds[0].inclusive ? ">=" : ">", print_term(_bounds[0].t), _bounds[1].inclusive ? "<=" : "<", print_term(_bounds[1].t)); } friend std::ostream& operator<<(std::ostream& out, const term_slice& slice) { return out << slice.to_string(); } #if 0 /** * Returns the index operator corresponding to the specified boundary. * * @param b the boundary type * @return the index operator corresponding to the specified boundary */ public Operator getIndexOperator(statements::bound b) { if (b.isStart()) return boundInclusive[get_idx(b)] ? Operator.GTE : Operator.GT; return boundInclusive[get_idx(b)] ? Operator.LTE : Operator.LT; } /** * Check if this <code>TermSlice</code> is supported by the specified index. * * @param index the Secondary index * @return <code>true</code> this type of <code>TermSlice</code> is supported by the specified index, * <code>false</code> otherwise. */ public bool isSupportedBy(SecondaryIndex index) { bool supported = false; if (has_bound(statements::bound::START)) supported |= isInclusive(statements::bound::START) ? index.supportsOperator(Operator.GTE) : index.supportsOperator(Operator.GT); if (has_bound(statements::bound::END)) supported |= isInclusive(statements::bound::END) ? index.supportsOperator(Operator.LTE) : index.supportsOperator(Operator.LT); return supported; } #endif }; } }
add method to_string() to term_slice
cql3: add method to_string() to term_slice Signed-off-by: Paweł Dziepak <[email protected]>
C++
agpl-3.0
justintung/scylla,wildinto/scylla,rentongzhang/scylla,glommer/scylla,avikivity/scylla,bowlofstew/scylla,bowlofstew/scylla,stamhe/scylla,phonkee/scylla,victorbriz/scylla,aruanruan/scylla,wildinto/scylla,guiquanz/scylla,bowlofstew/scylla,capturePointer/scylla,asias/scylla,wildinto/scylla,senseb/scylla,avikivity/scylla,linearregression/scylla,raphaelsc/scylla,shaunstanislaus/scylla,rluta/scylla,kjniemi/scylla,kangkot/scylla,guiquanz/scylla,scylladb/scylla,phonkee/scylla,duarten/scylla,victorbriz/scylla,shaunstanislaus/scylla,victorbriz/scylla,respu/scylla,aruanruan/scylla,dwdm/scylla,guiquanz/scylla,asias/scylla,stamhe/scylla,capturePointer/scylla,kangkot/scylla,acbellini/scylla,tempbottle/scylla,eklitzke/scylla,tempbottle/scylla,gwicke/scylla,rentongzhang/scylla,justintung/scylla,acbellini/scylla,duarten/scylla,gwicke/scylla,rentongzhang/scylla,aruanruan/scylla,raphaelsc/scylla,raphaelsc/scylla,linearregression/scylla,linearregression/scylla,dwdm/scylla,kangkot/scylla,glommer/scylla,dwdm/scylla,kjniemi/scylla,phonkee/scylla,justintung/scylla,acbellini/scylla,capturePointer/scylla,duarten/scylla,avikivity/scylla,asias/scylla,gwicke/scylla,kjniemi/scylla,tempbottle/scylla,senseb/scylla,stamhe/scylla,scylladb/scylla,shaunstanislaus/scylla,rluta/scylla,eklitzke/scylla,respu/scylla,senseb/scylla,scylladb/scylla,rluta/scylla,scylladb/scylla,glommer/scylla,eklitzke/scylla,respu/scylla
754d008390f13323ef5ea7542326f7ae24305ca0
W3CQtTestClient/src/main.cpp
W3CQtTestClient/src/main.cpp
#include <QtCore/QCoreApplication> #include "w3ctestclient.h" #include "w3ctestclienthandler.h" #include <QDebug> #include <QCommandLineParser> #include "logger.h" int main(int argc, char *argv[]) { qDebug() << "Client: main started"; QCoreApplication a(argc, argv); QCommandLineParser parser; parser.setApplicationDescription("Melco Gothenburg W3C VISS Reference Implementation - Test Client Application"); parser.addHelpOption(); //parser.addVersionOption(); parser.addPositionalArgument("tests", QCoreApplication::translate("main", "Test cases to run, [subscribe, subscribeall, authorize, getvss, getset, status]. Each test case can be entered several times.")); // TODO Add list to -help QCommandLineOption randomizeOption(QStringList() << "r" << "random", QCoreApplication::translate("main", "Shuffles the order the test cases are excecuted in. The order will be different on each client.")); parser.addOption(randomizeOption); QCommandLineOption secureOption(QStringList() << "s" << "secure", QCoreApplication::translate("main", "Use Secure Web Sockets. Does nothing at the moment since we are able to ignore all errors.")); parser.addOption(secureOption); QCommandLineOption clientOption(QStringList() << "c" << "clients", QCoreApplication::translate("main", "Number of clients to use."), QCoreApplication::translate("main", "nr of clients")); parser.addOption(clientOption); QCommandLineOption urlOption(QStringList() << "url", QCoreApplication::translate("main", "Full W3CServer target implementation url."), QCoreApplication::translate("main", "url")); parser.addOption(urlOption); QCommandLineOption softwareOption(QStringList() << "software", QCoreApplication::translate("main", "Software version the test is run upon. When run from Bamboo this is the git commit id."), QCoreApplication::translate("main", "version")); parser.addOption(softwareOption); QCommandLineOption timestampOption(QStringList() << "timestamp", QCoreApplication::translate("main", "Timestamp when the test were initialized. When run from bamboo this is the same timestamp found in the image created."), QCoreApplication::translate("main", "timestamp")); parser.addOption(timestampOption); QCommandLineOption reportDirOption(QStringList() << "report-dir", QCoreApplication::translate("main", "Path to the output directory for reports to be saved."), QCoreApplication::translate("main", "report-dir")); parser.addOption(reportDirOption); parser.process(a); qDebug() << parser.optionNames(); int nrOfClients = 2; // Default number of clients if(parser.isSet(clientOption)) { nrOfClients = parser.value(clientOption).toInt(); // Needs better validation } QQueue<TestCase> tests; for(auto test : parser.positionalArguments()) { if (test == "subscribe") { tests << TestCase::SUBSCRIBE_UNSUBSCRIBE; } else if (test == "subscribeall") { tests << TestCase::SUBSCRIBEALL_UNSUBSCRIBEALL; } else if (test == "authorize") { tests << TestCase::AUTHORIZE_SUCCESS; } else if (test == "getvss") { tests << TestCase::GET_VSS; } else if (test == "setget") { tests << TestCase::SET_GET; } else if (test == "set") { tests << TestCase::SET; } else if (test == "get") { tests << TestCase::GET; } else if (test == "status") { tests << TestCase::STATUS; } else { CRITICAL("Client Handler", "Unknown argument : " + test); return -1; } } if(tests.length() == 0) { //tests << TestCase::AUTHORIZE_SUCCESS; tests << TestCase::GET; //tests << TestCase::SUBSCRIBE_UNSUBSCRIBE; //tests << TestCase::GET_VSS; // tests << TestCase::STATUS; // tests << TestCase::SUBSCRIBE_UNSUBSCRIBE; // tests << TestCase::GET_VSS; // tests << TestCase::STATUS; } bool randomize = parser.isSet(randomizeOption); bool secure = parser.isSet(secureOption); <<<<<<< HEAD QString url = "ws://192.168.31.128:8080"; // default url ======= QString url = "wss://127.0.0.1:8080"; // default url >>>>>>> 2be540b533bceacded03eb83d9bef2a89a88d5d5 // Is url set, change url. If not, and secure is set, set to secure url, else use default url. if(parser.isSet(urlOption)) { url = parser.value(urlOption); } else if(secure) { url = "wss://127.0.0.1:8080"; // default secure url } QString reportDir = ""; if(parser.isSet(reportDirOption)) { reportDir = parser.value(reportDirOption); } INFO("Client Handler", QString("nrOfClients : %1, randomize : %2, secure : %3, url : %4").arg(QString::number(nrOfClients), QString(randomize), QString(secure), url)); QString swversion = parser.value(softwareOption); QString timestamp = parser.value(timestampOption); W3cTestClientHandler handler(nrOfClients, tests, url, swversion,timestamp,randomize, reportDir); Q_UNUSED(handler); return a.exec(); }
#include <QtCore/QCoreApplication> #include "w3ctestclient.h" #include "w3ctestclienthandler.h" #include <QDebug> #include <QCommandLineParser> #include "logger.h" int main(int argc, char *argv[]) { qDebug() << "Client: main started"; QCoreApplication a(argc, argv); QCommandLineParser parser; parser.setApplicationDescription("Melco Gothenburg W3C VISS Reference Implementation - Test Client Application"); parser.addHelpOption(); //parser.addVersionOption(); parser.addPositionalArgument("tests", QCoreApplication::translate("main", "Test cases to run, [subscribe, subscribeall, authorize, getvss, getset, status]. Each test case can be entered several times.")); // TODO Add list to -help QCommandLineOption randomizeOption(QStringList() << "r" << "random", QCoreApplication::translate("main", "Shuffles the order the test cases are excecuted in. The order will be different on each client.")); parser.addOption(randomizeOption); QCommandLineOption secureOption(QStringList() << "s" << "secure", QCoreApplication::translate("main", "Use Secure Web Sockets. Does nothing at the moment since we are able to ignore all errors.")); parser.addOption(secureOption); QCommandLineOption clientOption(QStringList() << "c" << "clients", QCoreApplication::translate("main", "Number of clients to use."), QCoreApplication::translate("main", "nr of clients")); parser.addOption(clientOption); QCommandLineOption urlOption(QStringList() << "url", QCoreApplication::translate("main", "Full W3CServer target implementation url."), QCoreApplication::translate("main", "url")); parser.addOption(urlOption); QCommandLineOption softwareOption(QStringList() << "software", QCoreApplication::translate("main", "Software version the test is run upon. When run from Bamboo this is the git commit id."), QCoreApplication::translate("main", "version")); parser.addOption(softwareOption); QCommandLineOption timestampOption(QStringList() << "timestamp", QCoreApplication::translate("main", "Timestamp when the test were initialized. When run from bamboo this is the same timestamp found in the image created."), QCoreApplication::translate("main", "timestamp")); parser.addOption(timestampOption); QCommandLineOption reportDirOption(QStringList() << "report-dir", QCoreApplication::translate("main", "Path to the output directory for reports to be saved."), QCoreApplication::translate("main", "report-dir")); parser.addOption(reportDirOption); parser.process(a); qDebug() << parser.optionNames(); int nrOfClients = 2; // Default number of clients if(parser.isSet(clientOption)) { nrOfClients = parser.value(clientOption).toInt(); // Needs better validation } QQueue<TestCase> tests; for(auto test : parser.positionalArguments()) { if (test == "subscribe") { tests << TestCase::SUBSCRIBE_UNSUBSCRIBE; } else if (test == "subscribeall") { tests << TestCase::SUBSCRIBEALL_UNSUBSCRIBEALL; } else if (test == "authorize") { tests << TestCase::AUTHORIZE_SUCCESS; } else if (test == "getvss") { tests << TestCase::GET_VSS; } else if (test == "setget") { tests << TestCase::SET_GET; } else if (test == "set") { tests << TestCase::SET; } else if (test == "get") { tests << TestCase::GET; } else if (test == "status") { tests << TestCase::STATUS; } else { CRITICAL("Client Handler", "Unknown argument : " + test); return -1; } } if(tests.length() == 0) { //tests << TestCase::AUTHORIZE_SUCCESS; tests << TestCase::GET; //tests << TestCase::SUBSCRIBE_UNSUBSCRIBE; //tests << TestCase::GET_VSS; // tests << TestCase::STATUS; // tests << TestCase::SUBSCRIBE_UNSUBSCRIBE; // tests << TestCase::GET_VSS; // tests << TestCase::STATUS; } bool randomize = parser.isSet(randomizeOption); bool secure = parser.isSet(secureOption); // QString url = "ws://192.168.31.128:8080"; // default url QString url = "wss://127.0.0.1:8080"; // default url // Is url set, change url. If not, and secure is set, set to secure url, else use default url. if(parser.isSet(urlOption)) { url = parser.value(urlOption); } else if(secure) { url = "wss://127.0.0.1:8080"; // default secure url } QString reportDir = ""; if(parser.isSet(reportDirOption)) { reportDir = parser.value(reportDirOption); } INFO("Client Handler", QString("nrOfClients : %1, randomize : %2, secure : %3, url : %4").arg(QString::number(nrOfClients), QString(randomize), QString(secure), url)); QString swversion = parser.value(softwareOption); QString timestamp = parser.value(timestampOption); W3cTestClientHandler handler(nrOfClients, tests, url, swversion,timestamp,randomize, reportDir); Q_UNUSED(handler); return a.exec(); }
Update main.cpp
Update main.cpp
C++
mit
PeterWinzell/GDP-melco,PeterWinzell/GDP-melco,PeterWinzell/GDP-melco,PeterWinzell/GDP-melco,PeterWinzell/GDP-melco
1f094d0ca6331153172f16ad55323b3ed85e6421
utilities/utility/forward/move_if_noexcept.pass.cpp
utilities/utility/forward/move_if_noexcept.pass.cpp
//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // <utility> // template <class T> // typename conditional // < // !has_nothrow_move_constructor<T>::value && has_copy_constructor<T>::value, // const T&, // T&& // >::type // move_if_noexcept(T& x); #include <utility> class A { A(const A&); A& operator=(const A&); public: A() {} #ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES A(A&&) {} #endif }; int main() { int i = 0; const int ci = 0; A a; const A ca; #ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES static_assert((std::is_same<decltype(std::move_if_noexcept(i)), int&&>::value), ""); static_assert((std::is_same<decltype(std::move_if_noexcept(ci)), const int&&>::value), ""); static_assert((std::is_same<decltype(std::move_if_noexcept(a)), const A&>::value), ""); static_assert((std::is_same<decltype(std::move_if_noexcept(ca)), const A&>::value), ""); #else // _LIBCPP_HAS_NO_RVALUE_REFERENCES static_assert((std::is_same<decltype(std::move_if_noexcept(i)), const int>::value), ""); static_assert((std::is_same<decltype(std::move_if_noexcept(ci)), const int>::value), ""); static_assert((std::is_same<decltype(std::move_if_noexcept(a)), const A>::value), ""); static_assert((std::is_same<decltype(std::move_if_noexcept(ca)), const A>::value), ""); #endif // _LIBCPP_HAS_NO_RVALUE_REFERENCES }
//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // <utility> // template <class T> // typename conditional // < // !is_nothrow_move_constructible<T>::value && is_copy_constructible<T>::value, // const T&, // T&& // >::type // move_if_noexcept(T& x); #include <utility> class A { A(const A&); A& operator=(const A&); public: A() {} #ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES A(A&&) {} #endif }; struct legacy { legacy() {} legacy(const legacy&); }; int main() { int i = 0; const int ci = 0; legacy l; A a; const A ca; #ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES static_assert((std::is_same<decltype(std::move_if_noexcept(i)), int&&>::value), ""); static_assert((std::is_same<decltype(std::move_if_noexcept(ci)), const int&&>::value), ""); static_assert((std::is_same<decltype(std::move_if_noexcept(a)), A&&>::value), ""); static_assert((std::is_same<decltype(std::move_if_noexcept(ca)), const A&&>::value), ""); #else // _LIBCPP_HAS_NO_RVALUE_REFERENCES static_assert((std::is_same<decltype(std::move_if_noexcept(i)), const int>::value), ""); static_assert((std::is_same<decltype(std::move_if_noexcept(ci)), const int>::value), ""); static_assert((std::is_same<decltype(std::move_if_noexcept(a)), const A>::value), ""); static_assert((std::is_same<decltype(std::move_if_noexcept(ca)), const A>::value), ""); #endif // _LIBCPP_HAS_NO_RVALUE_REFERENCES static_assert((std::is_same<decltype(std::move_if_noexcept(l)), const legacy&>::value), ""); }
Fix and beef up test bug for move_if_noexcept
Fix and beef up test bug for move_if_noexcept git-svn-id: 273b07cebdae5845b4a75aae04570b978db9eb50@131483 91177308-0d34-0410-b5e6-96231b3b80d8
C++
bsd-3-clause
lodyagin/bare_cxx,lodyagin/bare_cxx,lodyagin/bare_cxx,lodyagin/bare_cxx,lodyagin/bare_cxx
38b4fa6320366c8ea12fa7a95f0820ae3f0331d3
test/model.cpp
test/model.cpp
/* * bacteria-core, core for cellular automaton * Copyright (C) 2016 Pavel Dolgov * * See the LICENSE file for terms of use. */ #include <boost/foreach.hpp> #include <boost/test/unit_test.hpp> #include "Model.hpp" typedef int (Implementation::Model::*IntOneArgMethod) ( const Abstract::Point& coordinates ) const; typedef Abstract::CellState (Implementation::Model::*OneArgMethod2) ( const Abstract::Point& coordinates ) const; typedef void (Implementation::Model::*OneArgMethod) ( const Abstract::Point& coordinates ); typedef void (Implementation::Model::*TwoArgsMethod) ( const Abstract::Point& coordinates, int change ); typedef void (Implementation::Model::*IntThreeArgsMethod) ( int team, int bacterium_index, int spec ); typedef void (Implementation::Model::*ThreeArgsMethod) ( int team, int bacterium_index, const Abstract::Point& coordinates ); typedef void (Implementation::Model::*MultiArgsMethod) ( const Abstract::Point& coordinates, int mass, int direction, int team, int instruction ); template<typename Func> static void checkOneArgMethod( Implementation::Model* model, Func model_method, int arg1, int arg2 ) { Abstract::Point coordinates(arg1, arg2); BOOST_REQUIRE_THROW( ((*model).*model_method)(coordinates), Exception ); } template<typename Func> void checkModelMethodForThrow( Implementation::Model* model, Func model_method, int arg1, int arg2 ) { BOOST_REQUIRE_THROW( ((*model).*model_method)(arg1, arg2), Exception ); } template<> void checkModelMethodForThrow<IntOneArgMethod>( Implementation::Model* model, IntOneArgMethod model_method, int arg1, int arg2 ) { checkOneArgMethod(model, model_method, arg1, arg2); } template<> void checkModelMethodForThrow<OneArgMethod2>( Implementation::Model* model, OneArgMethod2 model_method, int arg1, int arg2 ) { checkOneArgMethod(model, model_method, arg1, arg2); } template<> void checkModelMethodForThrow<OneArgMethod>( Implementation::Model* model, OneArgMethod model_method, int arg1, int arg2 ) { checkOneArgMethod(model, model_method, arg1, arg2); } template<> void checkModelMethodForThrow<TwoArgsMethod>( Implementation::Model* model, TwoArgsMethod model_method, int arg1, int arg2 ) { Abstract::Point coordinates(arg1, arg2); BOOST_REQUIRE_THROW( ((*model).*model_method)(coordinates, 0), Exception ); } template<> void checkModelMethodForThrow<IntThreeArgsMethod>( Implementation::Model* model, IntThreeArgsMethod model_method, int arg1, int arg2 ) { int spec = 0; BOOST_REQUIRE_THROW( ((*model).*model_method)(arg1, arg2, spec), Exception ); } template<> void checkModelMethodForThrow<MultiArgsMethod>( Implementation::Model* model, MultiArgsMethod model_method, int arg1, int arg2 ) { Abstract::Point coordinates(arg1, arg2); BOOST_REQUIRE_THROW( ((*model).*model_method)( coordinates, DEFAULT_MASS, 0, 0, 0 ), Exception ); } // "dead" test: attempt to do something with dead bacterium template<typename Func> static void deadTest( Implementation::Model* model, Func model_method ) { model->kill(0, 0); checkModelMethodForThrow( model, model_method, 0, 0 ); } template<typename Func> static void checkErrorHandling( Implementation::Model* model, Func model_method, bool dead_test ) { // Range errors: test all combinations of // "wrong" (outside of correct range) arguments. // This solution works for coordinates and non-coordinates // methods of Model. (< 0, = 0, > MAX) int wrong_args[] = {-1, 0, MIN_WIDTH}; BOOST_FOREACH (int arg1, wrong_args) { BOOST_FOREACH (int arg2, wrong_args) { if ((arg1 != 0) || (arg2 != 0)) { // (0, 0) is correct checkModelMethodForThrow( model, model_method, arg1, arg2 ); } } } if (dead_test) { // "dead" error // (attempt to do something with dead bacterium) deadTest(model, model_method); } } static Abstract::Point createInBaseCoordinates( Implementation::Model* model ) { Abstract::Point coordinates(0, 0); model->createNewByCoordinates( coordinates, DEFAULT_MASS, 0, 0, 0 ); return coordinates; } static Implementation::Model* createBaseModel( int bacteria = 0, int teams = 1 ) { Implementation::Model* model = Abstract::makeModel<Implementation::Model>( MIN_WIDTH, MIN_HEIGHT, bacteria, teams ); return model; } BOOST_AUTO_TEST_CASE (get_team_coordinates_test) { Implementation::Model* model = createBaseModel(); Abstract::Point coordinates = createInBaseCoordinates(model); int team = model->getTeamByCoordinates(coordinates); BOOST_REQUIRE(team == 0); checkErrorHandling<IntOneArgMethod>( model, &Implementation::Model::getTeamByCoordinates, true ); delete model; } BOOST_AUTO_TEST_CASE (width_test) { Implementation::Model* model = createBaseModel(); BOOST_REQUIRE(model->getWidth() == MIN_WIDTH); delete model; } BOOST_AUTO_TEST_CASE (height_test) { Implementation::Model* model = createBaseModel(); BOOST_REQUIRE(model->getHeight() == MIN_HEIGHT); delete model; } BOOST_AUTO_TEST_CASE (bacteria_number_test) { Implementation::Model* model = createBaseModel(); int bacteria_number = model->getBacteriaNumber(0); BOOST_REQUIRE(bacteria_number == 0); createInBaseCoordinates(model); bacteria_number = model->getBacteriaNumber(0); BOOST_REQUIRE(bacteria_number == 1); // range errors BOOST_REQUIRE_THROW(model->getBacteriaNumber(-1), Exception); BOOST_REQUIRE_THROW(model->getBacteriaNumber(1), Exception); delete model; } BOOST_AUTO_TEST_CASE (is_alive_test) { Implementation::Model* model = createBaseModel(1, 1); checkErrorHandling( model, &Implementation::Model::isAlive, false ); BOOST_REQUIRE(model->isAlive(0, 0) == true); model->kill(0, 0); BOOST_REQUIRE(model->isAlive(0, 0) == false); delete model; } BOOST_AUTO_TEST_CASE (get_instruction_test) { Implementation::Model* model = createBaseModel(1, 1); int instruction = model->getInstruction(0, 0); BOOST_REQUIRE(instruction == 0); checkErrorHandling( model, &Implementation::Model::getInstruction, true ); delete model; } BOOST_AUTO_TEST_CASE (get_coordinates_test) { Implementation::Model* model = createBaseModel(); Abstract::Point coordinates = createInBaseCoordinates(model); Abstract::Point derived_coordinates = model->getCoordinates(0, 0); BOOST_REQUIRE(derived_coordinates == coordinates); checkErrorHandling( model, &Implementation::Model::getCoordinates, true ); delete model; } BOOST_AUTO_TEST_CASE (get_direction_test) { Implementation::Model* model = createBaseModel(); createInBaseCoordinates(model); int direction = model->getDirection(0, 0); BOOST_REQUIRE(direction == Abstract::LEFT); checkErrorHandling( model, &Implementation::Model::getDirection, true ); delete model; } BOOST_AUTO_TEST_CASE (get_mass_test) { Implementation::Model* model = createBaseModel(1, 1); int mass = model->getMass(0, 0); BOOST_REQUIRE(mass == DEFAULT_MASS); checkErrorHandling( model, &Implementation::Model::getMass, true ); delete model; } BOOST_AUTO_TEST_CASE (kill_test) { Implementation::Model* model = createBaseModel(); Abstract::Point coordinates = createInBaseCoordinates(model); model->kill(0, 0); Abstract::CellState state = model->cellState(coordinates); BOOST_REQUIRE(state == Abstract::EMPTY); BOOST_REQUIRE(model->isAlive(0, 0) == false); // error handling checks createInBaseCoordinates(model); model->clearBeforeMove(0); checkErrorHandling( model, &Implementation::Model::kill, true ); delete model; } BOOST_AUTO_TEST_CASE (kill_coordinates_test) { Implementation::Model* model = createBaseModel(); Abstract::Point coordinates = createInBaseCoordinates(model); model->killByCoordinates(coordinates); Abstract::CellState state = model->cellState(coordinates); BOOST_REQUIRE(state == Abstract::EMPTY); BOOST_REQUIRE(model->isAlive(0, 0) == false); // error handling checks createInBaseCoordinates(model); model->clearBeforeMove(0); checkErrorHandling<OneArgMethod>( model, &Implementation::Model::killByCoordinates, true ); delete model; } BOOST_AUTO_TEST_CASE (change_mass_coordinates_test) { Implementation::Model* model = createBaseModel(); Abstract::Point coordinates = createInBaseCoordinates(model); int test_val = 1; model->changeMassByCoordinates(coordinates, test_val); int new_mass = model->getMassByCoordinates(coordinates); BOOST_REQUIRE(new_mass == (DEFAULT_MASS + test_val)); model->changeMassByCoordinates(coordinates, -test_val); new_mass = model->getMassByCoordinates(coordinates); BOOST_REQUIRE(new_mass == DEFAULT_MASS); checkErrorHandling<TwoArgsMethod>( model, &Implementation::Model::changeMassByCoordinates, true ); delete model; } BOOST_AUTO_TEST_CASE (create_coordinates_test) { Implementation::Model* model = createBaseModel(); Abstract::Point coordinates = createInBaseCoordinates(model); Abstract::CellState state = model->cellState(coordinates); BOOST_REQUIRE(state == Abstract::BACTERIUM); checkErrorHandling<MultiArgsMethod>( model, &Implementation::Model::createNewByCoordinates, false ); delete model; }
/* * bacteria-core, core for cellular automaton * Copyright (C) 2016 Pavel Dolgov * * See the LICENSE file for terms of use. */ #include <boost/foreach.hpp> #include <boost/test/unit_test.hpp> #include "Model.hpp" typedef int (Implementation::Model::*IntOneArgMethod) ( const Abstract::Point& coordinates ) const; typedef Abstract::CellState (Implementation::Model::*OneArgMethod2) ( const Abstract::Point& coordinates ) const; typedef void (Implementation::Model::*OneArgMethod) ( const Abstract::Point& coordinates ); typedef void (Implementation::Model::*TwoArgsMethod) ( const Abstract::Point& coordinates, int change ); typedef void (Implementation::Model::*IntThreeArgsMethod) ( int team, int bacterium_index, int spec ); typedef void (Implementation::Model::*ThreeArgsMethod) ( int team, int bacterium_index, const Abstract::Point& coordinates ); typedef void (Implementation::Model::*MultiArgsMethod) ( const Abstract::Point& coordinates, int mass, int direction, int team, int instruction ); template<typename Func> static void checkOneArgMethod( Implementation::Model* model, Func model_method, int arg1, int arg2 ) { Abstract::Point coordinates(arg1, arg2); BOOST_REQUIRE_THROW( ((*model).*model_method)(coordinates), Exception ); } template<typename Func> void checkModelMethodForThrow( Implementation::Model* model, Func model_method, int arg1, int arg2 ) { BOOST_REQUIRE_THROW( ((*model).*model_method)(arg1, arg2), Exception ); } template<> void checkModelMethodForThrow<IntOneArgMethod>( Implementation::Model* model, IntOneArgMethod model_method, int arg1, int arg2 ) { checkOneArgMethod(model, model_method, arg1, arg2); } template<> void checkModelMethodForThrow<OneArgMethod2>( Implementation::Model* model, OneArgMethod2 model_method, int arg1, int arg2 ) { checkOneArgMethod(model, model_method, arg1, arg2); } template<> void checkModelMethodForThrow<OneArgMethod>( Implementation::Model* model, OneArgMethod model_method, int arg1, int arg2 ) { checkOneArgMethod(model, model_method, arg1, arg2); } template<> void checkModelMethodForThrow<TwoArgsMethod>( Implementation::Model* model, TwoArgsMethod model_method, int arg1, int arg2 ) { Abstract::Point coordinates(arg1, arg2); BOOST_REQUIRE_THROW( ((*model).*model_method)(coordinates, 0), Exception ); } template<> void checkModelMethodForThrow<IntThreeArgsMethod>( Implementation::Model* model, IntThreeArgsMethod model_method, int arg1, int arg2 ) { int spec = 0; BOOST_REQUIRE_THROW( ((*model).*model_method)(arg1, arg2, spec), Exception ); } template<> void checkModelMethodForThrow<ThreeArgsMethod>( Implementation::Model* model, ThreeArgsMethod model_method, int arg1, int arg2 ) { Abstract::Point coordinates(0, 0); BOOST_REQUIRE_THROW( ((*model).*model_method)(arg1, arg2, coordinates), Exception ); } template<> void checkModelMethodForThrow<MultiArgsMethod>( Implementation::Model* model, MultiArgsMethod model_method, int arg1, int arg2 ) { Abstract::Point coordinates(arg1, arg2); BOOST_REQUIRE_THROW( ((*model).*model_method)( coordinates, DEFAULT_MASS, 0, 0, 0 ), Exception ); } // "dead" test: attempt to do something with dead bacterium template<typename Func> static void deadTest( Implementation::Model* model, Func model_method ) { model->kill(0, 0); checkModelMethodForThrow( model, model_method, 0, 0 ); } template<typename Func> static void checkErrorHandling( Implementation::Model* model, Func model_method, bool dead_test ) { // Range errors: test all combinations of // "wrong" (outside of correct range) arguments. // This solution works for coordinates and non-coordinates // methods of Model. (< 0, = 0, > MAX) int wrong_args[] = {-1, 0, MIN_WIDTH}; BOOST_FOREACH (int arg1, wrong_args) { BOOST_FOREACH (int arg2, wrong_args) { if ((arg1 != 0) || (arg2 != 0)) { // (0, 0) is correct checkModelMethodForThrow( model, model_method, arg1, arg2 ); } } } if (dead_test) { // "dead" error // (attempt to do something with dead bacterium) deadTest(model, model_method); } } static Abstract::Point createInBaseCoordinates( Implementation::Model* model ) { Abstract::Point coordinates(0, 0); model->createNewByCoordinates( coordinates, DEFAULT_MASS, 0, 0, 0 ); return coordinates; } static Implementation::Model* createBaseModel( int bacteria = 0, int teams = 1 ) { Implementation::Model* model = Abstract::makeModel<Implementation::Model>( MIN_WIDTH, MIN_HEIGHT, bacteria, teams ); return model; } BOOST_AUTO_TEST_CASE (get_team_coordinates_test) { Implementation::Model* model = createBaseModel(); Abstract::Point coordinates = createInBaseCoordinates(model); int team = model->getTeamByCoordinates(coordinates); BOOST_REQUIRE(team == 0); checkErrorHandling<IntOneArgMethod>( model, &Implementation::Model::getTeamByCoordinates, true ); delete model; } BOOST_AUTO_TEST_CASE (width_test) { Implementation::Model* model = createBaseModel(); BOOST_REQUIRE(model->getWidth() == MIN_WIDTH); delete model; } BOOST_AUTO_TEST_CASE (height_test) { Implementation::Model* model = createBaseModel(); BOOST_REQUIRE(model->getHeight() == MIN_HEIGHT); delete model; } BOOST_AUTO_TEST_CASE (bacteria_number_test) { Implementation::Model* model = createBaseModel(); int bacteria_number = model->getBacteriaNumber(0); BOOST_REQUIRE(bacteria_number == 0); createInBaseCoordinates(model); bacteria_number = model->getBacteriaNumber(0); BOOST_REQUIRE(bacteria_number == 1); // range errors BOOST_REQUIRE_THROW(model->getBacteriaNumber(-1), Exception); BOOST_REQUIRE_THROW(model->getBacteriaNumber(1), Exception); delete model; } BOOST_AUTO_TEST_CASE (is_alive_test) { Implementation::Model* model = createBaseModel(1, 1); checkErrorHandling( model, &Implementation::Model::isAlive, false ); BOOST_REQUIRE(model->isAlive(0, 0) == true); model->kill(0, 0); BOOST_REQUIRE(model->isAlive(0, 0) == false); delete model; } BOOST_AUTO_TEST_CASE (get_instruction_test) { Implementation::Model* model = createBaseModel(1, 1); int instruction = model->getInstruction(0, 0); BOOST_REQUIRE(instruction == 0); checkErrorHandling( model, &Implementation::Model::getInstruction, true ); delete model; } BOOST_AUTO_TEST_CASE (get_coordinates_test) { Implementation::Model* model = createBaseModel(); Abstract::Point coordinates = createInBaseCoordinates(model); Abstract::Point derived_coordinates = model->getCoordinates(0, 0); BOOST_REQUIRE(derived_coordinates == coordinates); checkErrorHandling( model, &Implementation::Model::getCoordinates, true ); delete model; } BOOST_AUTO_TEST_CASE (get_direction_test) { Implementation::Model* model = createBaseModel(); createInBaseCoordinates(model); int direction = model->getDirection(0, 0); BOOST_REQUIRE(direction == Abstract::LEFT); checkErrorHandling( model, &Implementation::Model::getDirection, true ); delete model; } BOOST_AUTO_TEST_CASE (get_mass_test) { Implementation::Model* model = createBaseModel(1, 1); int mass = model->getMass(0, 0); BOOST_REQUIRE(mass == DEFAULT_MASS); checkErrorHandling( model, &Implementation::Model::getMass, true ); delete model; } BOOST_AUTO_TEST_CASE (kill_test) { Implementation::Model* model = createBaseModel(); Abstract::Point coordinates = createInBaseCoordinates(model); model->kill(0, 0); Abstract::CellState state = model->cellState(coordinates); BOOST_REQUIRE(state == Abstract::EMPTY); BOOST_REQUIRE(model->isAlive(0, 0) == false); // error handling checks createInBaseCoordinates(model); model->clearBeforeMove(0); checkErrorHandling( model, &Implementation::Model::kill, true ); delete model; } BOOST_AUTO_TEST_CASE (kill_coordinates_test) { Implementation::Model* model = createBaseModel(); Abstract::Point coordinates = createInBaseCoordinates(model); model->killByCoordinates(coordinates); Abstract::CellState state = model->cellState(coordinates); BOOST_REQUIRE(state == Abstract::EMPTY); BOOST_REQUIRE(model->isAlive(0, 0) == false); // error handling checks createInBaseCoordinates(model); model->clearBeforeMove(0); checkErrorHandling<OneArgMethod>( model, &Implementation::Model::killByCoordinates, true ); delete model; } BOOST_AUTO_TEST_CASE (change_mass_coordinates_test) { Implementation::Model* model = createBaseModel(); Abstract::Point coordinates = createInBaseCoordinates(model); int test_val = 1; model->changeMassByCoordinates(coordinates, test_val); int new_mass = model->getMassByCoordinates(coordinates); BOOST_REQUIRE(new_mass == (DEFAULT_MASS + test_val)); model->changeMassByCoordinates(coordinates, -test_val); new_mass = model->getMassByCoordinates(coordinates); BOOST_REQUIRE(new_mass == DEFAULT_MASS); checkErrorHandling<TwoArgsMethod>( model, &Implementation::Model::changeMassByCoordinates, true ); delete model; } BOOST_AUTO_TEST_CASE (create_coordinates_test) { Implementation::Model* model = createBaseModel(); Abstract::Point coordinates = createInBaseCoordinates(model); Abstract::CellState state = model->cellState(coordinates); BOOST_REQUIRE(state == Abstract::BACTERIUM); checkErrorHandling<MultiArgsMethod>( model, &Implementation::Model::createNewByCoordinates, false ); delete model; }
Implement checkModelMethodForThrow <ThreeArgsMethod>
Implement checkModelMethodForThrow <ThreeArgsMethod>
C++
mit
zer0main/bacteria-core,zer0main/bacteria-core,zer0main/bacteria-core
f5d7d012f72b98e524a5d0b940fc72eb4aece6fb
assert.hh
assert.hh
/** \file * * \brief Throwing implementation of assert(3) * * This file redefines the assert() macro known from C so that it throws * a std::logic_error exception containing the filename, line number and * description of the assertion that failed. */ #ifndef DSNUTIL_ASSERT_HPP #define DSNUTIL_ASSERT_HPP 1 #include <stdexcept> #include <string> #include <cassert> #ifndef NDEBUG # undef assert /** \brief Redefined assert(3) */ # define assert(test) assert2(test, __FILE__, __LINE__) /** \brief Helper macro to redefine assert(3) */ # define assert2(test, file, line) assert3(test, file, line) /** \brief Helper function for throwing assert(3) * * This is used to redefine the assert() macro from C with an implementation * that throws an exception. * * \param test Test condition for the assertion * \param msg Message text of the exception that shall be thrown * * \throw std::logic_error with the given message text if the test condition * is false */ inline void throwing_assert(bool test, const std::string& msg) { if (!test) throw std::logic_error(msg); } # if (__GNUC__ == 2 && __GNUC_MINOR__ >= 6) || __GNUC__ > 2 /** \brief Throwing assert(3) definition */ # define assert3(test, file, line) \ (::throwing_assert(test, \ std::string(file ":" #line ": ") \ .append(__PRETTY_FUNCTION__) \ .append(": assertion '" #test "' failed."))) # else /** \brief Throwing assert(3) definition */ # define assert3(test, file, line) \ (::throwing_assert(test, \ file ":" #line ": assertion '" #test "' failed.")) # endif #endif // !NDEBUG #endif // !DSNUTIL_ASSERT_HPP
/** \file * * \brief Throwing implementation of assert(3) * * This file redefines the assert() macro known from C so that it throws * a std::logic_error exception containing the filename, line number and * description of the assertion that failed. */ #ifndef DSNUTIL_ASSERT_HPP #define DSNUTIL_ASSERT_HPP 1 #include <stdexcept> #include <string> #include <cassert> #ifndef NDEBUG # undef assert /** \brief Redefined assert(3) */ # define assert(test) assert2(test, __FILE__, __LINE__) /** \brief Helper macro to redefine assert(3) */ # define assert2(test, file, line) assert3(test, file, line) /** \brief Helper function for throwing assert(3) * * This is used to redefine the assert() macro from C with an implementation * that throws an exception. * * \param test Test condition for the assertion * \param msg Message text of the exception that shall be thrown * * \throw std::logic_error with the given message text if the test condition * is false */ inline void throwing_assert(bool test, const std::string& msg) { if (!test) throw std::logic_error(msg); } # if (__GNUC__ == 2 && __GNUC_MINOR__ >= 6) || __GNUC__ > 2 || \ defined(__clang__) /** \brief Throwing assert(3) definition */ # define assert3(test, file, line) \ (::throwing_assert(test, \ std::string(file ":" #line ": ") \ .append(__PRETTY_FUNCTION__) \ .append(": assertion '" #test "' failed."))) # else /** \brief Throwing assert(3) definition */ # define assert3(test, file, line) \ (::throwing_assert(test, \ file ":" #line ": assertion '" #test "' failed.")) # endif #endif // !NDEBUG #endif // !DSNUTIL_ASSERT_HPP
support clang's function pretty printing
support clang's function pretty printing this commit enables support for __PRETTY_FUNCTION__ when the library is compiled using clang++ from the LLVM project.
C++
bsd-3-clause
png85/dsnutil,png85/dsnutil
d3d55cfec4bdfb1ee876028004bdec662e5074ba
test_SHAVS.cpp
test_SHAVS.cpp
#include <cassert> #include <cstdint> #include <cstdlib> #include <iostream> #include <sstream> #include <string> #include <vector> #include "snarkfront.hpp" using namespace snarkfront; using namespace std; void printUsage(const char* exeName) { cout << "usage: cat NIST_SHAVS_byte_test_vector_file | " << exeName << " -p BN128|Edwards -b 1|224|256|384|512 [-i Len|COUNT] [-z]" << endl << endl << "example: SHA1 short messages" << endl << "cat SHA1ShortMsg.rsp | " << exeName << " -p BN128 -b 1" << endl << endl << "example: SHA256 long messages with proof" << endl << "cat SHA256LongMsg.rsp | " << exeName << " -p Edwards -b 256 -z" << endl << endl << "example: SHA512 Monte Carlo mode" << endl << "cat SHA512Monte.txt | " << exeName << " -p BN128 -b 512" << endl << endl << "example: SHA224 short messages, only Len = 464 test case" << endl << "cat SHA224ShortMsg.rsp | " << exeName << " -p Edwards -b 224 -i 464" << endl << endl << "example: SHA384 Monte Carlo mode, only COUNT = 75 test case" << endl << "cat SHA384Monte.txt | " << exeName << " -p BN128 -b 384 -i 75" << endl; exit(EXIT_FAILURE); } // short and long message tests template <typename ZK_SHA, typename EVAL_SHA> bool runHash(const string& msg, const string& MD) { // convert hexadecimal message text to binary vector<uint8_t> v; if ("00" != msg && !asciiHexToVector(msg, v)) // 00 is null msg return false; // compute message digest const auto zk_digest = digest(ZK_SHA(), v); const auto eval_digest = digest(EVAL_SHA(), v); assert(zk_digest.size() == eval_digest.size()); // compare message zk and eval digest values bool valueOK = true; for (size_t i = 0; i < zk_digest.size(); ++i) { if (zk_digest[i]->value() != eval_digest[i]) valueOK = false; } // message digest proof constraint assert_true(zk_digest == eval_digest); // compare eval digest and SHAVS test case MD if (MD != asciiHex(eval_digest)) valueOK = false; return valueOK; } // Monte Carlo tests template <typename EVAL_SHA> bool runMC(const string& prevMD, const string& MD) { // prevMD is message digest input vector<typename EVAL_SHA::WordType> v0, v1, v2; if (!asciiHexToVector(prevMD, v2)) return false; v0 = v1 = v2; for (size_t i = 3; i < 1003; ++i) { // compute message digest // message is concatenation of last three digests const auto eval_digest = digest(EVAL_SHA(), v0, v1, v2); // rotate message digests v0 = v1; v1 = v2; assert(eval_digest.size() == v2.size()); for (size_t j = 0; j < v2.size(); ++j) v2[j] = eval_digest[j]; } // compare final message digest with test case MD return MD == asciiHex(v2); } bool readAssignment(const string& line, string& lhs, string& rhs) { stringstream ss(line); // left hand side if (!ss.eof()) ss >> lhs; // should be = string op; if (!!ss && !ss.eof() && !lhs.empty()) ss >> op; // right hand side if (!!ss && !ss.eof() && ("=" == op)) ss >> rhs; // true if lhs and rhs both defined and op is = return !!ss && !lhs.empty() && !rhs.empty(); } template <typename PAIRING> void readLoop(const size_t shaBits, const size_t testCase, const bool zkProof) { typedef typename PAIRING::Fr FR; stringstream ss; ss << testCase; const auto testCaseStr = ss.str(); // specific test case by Len/COUNT string line, count, seed, len, msg, MD; while (!cin.eof() && getline(cin, line)) { // skip empty lines and comments if (line.empty() || '#' == line[0]) continue; string lhs, rhs; if (! readAssignment(line, lhs, rhs)) continue; if ("Len" == lhs) { // length of message len = rhs; } else if ("Msg" == lhs) { // message msg = rhs; } else if ("MD" == lhs) { // message digest MD = rhs; } else if ("COUNT" == lhs) { // Monte-Carlo mode count = rhs; } else if ("Seed" == lhs) { // Monte-Carlo mode seed = rhs; // warning message if zero knowledge proof mode selected if (zkProof) { cout << "warning: proof generation disabled for Monte Carlo tests (too expensive)" << endl; } } if (seed.empty()) { // short and long message modes if (!len.empty() && !msg.empty() && !MD.empty()) { if (-1 == testCase || testCaseStr == len) { reset<PAIRING>(); bool result; if (1 == shaBits) { result = runHash<zk::SHA1<FR>, eval::SHA1>(msg, MD); } else if (224 == shaBits) { result = runHash<zk::SHA224<FR>, eval::SHA224>(msg, MD); } else if (256 == shaBits) { result = runHash<zk::SHA256<FR>, eval::SHA256>(msg, MD); } else if (384 == shaBits) { result = runHash<zk::SHA384<FR>, eval::SHA384>(msg, MD); } else if (512 == shaBits) { result = runHash<zk::SHA512<FR>, eval::SHA512>(msg, MD); } if (zkProof) { GenericProgressBar progress1(cerr), progress2(cerr, 50); cerr << "generate key pair"; const auto key = keypair<PAIRING>(progress2); cerr << endl; const auto in = input<PAIRING>(); cerr << "generate proof"; const auto p = proof(key, progress2); cerr << endl; cerr << "verify proof "; const bool proofOK = verify(key, in, p, progress1); cerr << endl; if (! proofOK) result = false; } cout << (result ? "OK" : "FAIL") << " " << len << " " << MD << endl; } len.clear(); msg.clear(); MD.clear(); } } else { // Monte-Carlo mode if (!MD.empty()) { if (-1 == testCase || testCaseStr == count) { bool result; if (1 == shaBits) { result = runMC<eval::SHA1>(seed, MD); } else if (224 == shaBits) { result = runMC<eval::SHA224>(seed, MD); } else if (256 == shaBits) { result = runMC<eval::SHA256>(seed, MD); } else if (384 == shaBits) { result = runMC<eval::SHA384>(seed, MD); } else if (512 == shaBits) { result = runMC<eval::SHA512>(seed, MD); } cout << (result ? "OK" : "FAIL") << " " << count << " " << seed << " " << MD << endl; } seed = MD; MD.clear(); } } } } int main(int argc, char *argv[]) { Getopt cmdLine(argc, argv, "p", "bi", "z"); if (!cmdLine || cmdLine.empty()) printUsage(argv[0]); const auto pairing = cmdLine.getString('p'); const auto shaBits = cmdLine.getNumber('b'); const auto testCase = cmdLine.getNumber('i'); const auto zkProof = cmdLine.getFlag('z'); if (!validPairingName(pairing) || !validSHA2Name(shaBits)) printUsage(argv[0]); if (pairingBN128(pairing)) { // Barreto-Naehrig 128 bits init_BN128(); readLoop<BN128_PAIRING>(shaBits, testCase, zkProof); } else if (pairingEdwards(pairing)) { // Edwards 80 bits init_Edwards(); readLoop<EDWARDS_PAIRING>(shaBits, testCase, zkProof); } exit(EXIT_SUCCESS); }
#include <cassert> #include <cstdint> #include <cstdlib> #include <iostream> #include <sstream> #include <string> #include <vector> #include "snarkfront.hpp" using namespace snarkfront; using namespace std; void printUsage(const char* exeName) { cout << "usage: cat NIST_SHAVS_byte_test_vector_file | " << exeName << " -p BN128|Edwards -b 1|224|256|384|512 [-i Len|COUNT] [-z]" << endl << endl << "example: SHA1 short messages" << endl << "cat SHA1ShortMsg.rsp | " << exeName << " -p BN128 -b 1" << endl << endl << "example: SHA256 long messages with proof" << endl << "cat SHA256LongMsg.rsp | " << exeName << " -p Edwards -b 256 -z" << endl << endl << "example: SHA512 Monte Carlo mode" << endl << "cat SHA512Monte.txt | " << exeName << " -p BN128 -b 512" << endl << endl << "example: SHA224 short messages, only Len = 464 test case" << endl << "cat SHA224ShortMsg.rsp | " << exeName << " -p Edwards -b 224 -i 464" << endl << endl << "example: SHA384 Monte Carlo mode, only COUNT = 75 test case" << endl << "cat SHA384Monte.txt | " << exeName << " -p BN128 -b 384 -i 75" << endl; exit(EXIT_FAILURE); } // short and long message tests template <typename ZK_SHA, typename EVAL_SHA> bool runHash(const string& msg, const string& MD) { // convert hexadecimal message text to binary vector<uint8_t> v; if ("00" != msg && !asciiHexToVector(msg, v)) // 00 is null msg return false; // compute message digest const auto zk_digest = digest(ZK_SHA(), v); const auto eval_digest = digest(EVAL_SHA(), v); assert(zk_digest.size() == eval_digest.size()); // compare message zk and eval digest values bool valueOK = true; for (size_t i = 0; i < zk_digest.size(); ++i) { if (zk_digest[i]->value() != eval_digest[i]) valueOK = false; } // message digest proof constraint assert_true(zk_digest == eval_digest); // compare eval digest and SHAVS test case MD if (MD != asciiHex(eval_digest)) valueOK = false; return valueOK; } // Monte Carlo tests template <typename EVAL_SHA> bool runMC(const string& prevMD, const string& MD) { // prevMD is message digest input vector<typename EVAL_SHA::WordType> v0, v1, v2; if (!asciiHexToVector(prevMD, v2)) return false; v0 = v1 = v2; for (size_t i = 3; i < 1003; ++i) { // compute message digest // message is concatenation of last three digests const auto eval_digest = digest(EVAL_SHA(), v0, v1, v2); // rotate message digests v0 = v1; v1 = v2; assert(eval_digest.size() == v2.size()); for (size_t j = 0; j < v2.size(); ++j) v2[j] = eval_digest[j]; } // compare final message digest with test case MD return MD == asciiHex(v2); } bool readAssignment(const string& line, string& lhs, string& rhs) { stringstream ss(line); // left hand side if (!ss.eof()) ss >> lhs; // should be = string op; if (!!ss && !ss.eof() && !lhs.empty()) ss >> op; // right hand side if (!!ss && !ss.eof() && ("=" == op)) ss >> rhs; // true if lhs and rhs both defined and op is = return !!ss && !lhs.empty() && !rhs.empty(); } template <typename PAIRING> void readLoop(const size_t shaBits, const size_t testCase, const bool zkProof) { typedef typename PAIRING::Fr FR; stringstream ss; ss << testCase; const auto testCaseStr = ss.str(); // specific test case by Len/COUNT string line, count, seed, len, msg, MD; while (!cin.eof() && getline(cin, line)) { // skip empty lines and comments if (line.empty() || '#' == line[0]) continue; string lhs, rhs; if (! readAssignment(line, lhs, rhs)) continue; if ("Len" == lhs) { // length of message len = rhs; } else if ("Msg" == lhs) { // message msg = rhs; } else if ("MD" == lhs) { // message digest MD = rhs; } else if ("COUNT" == lhs) { // Monte-Carlo mode count = rhs; } else if ("Seed" == lhs) { // Monte-Carlo mode seed = rhs; // warning message if zero knowledge proof mode selected if (zkProof) { cout << "warning: proof generation disabled for Monte Carlo tests (too expensive)" << endl; } } if (seed.empty()) { // short and long message modes if (!len.empty() && !msg.empty() && !MD.empty()) { if (-1 == testCase || testCaseStr == len) { reset<PAIRING>(); bool result; if (1 == shaBits) { result = runHash<zk::SHA1<FR>, eval::SHA1>(msg, MD); } else if (224 == shaBits) { result = runHash<zk::SHA224<FR>, eval::SHA224>(msg, MD); } else if (256 == shaBits) { result = runHash<zk::SHA256<FR>, eval::SHA256>(msg, MD); } else if (384 == shaBits) { result = runHash<zk::SHA384<FR>, eval::SHA384>(msg, MD); } else if (512 == shaBits) { result = runHash<zk::SHA512<FR>, eval::SHA512>(msg, MD); } if (zkProof) { GenericProgressBar progress1(cerr), progress2(cerr, 50); cerr << "generate key pair"; const auto key = keypair<PAIRING>(progress2); cerr << endl; const auto in = input<PAIRING>(); cerr << "generate proof"; const auto p = proof(key, progress2); cerr << endl; cerr << "verify proof "; const bool proofOK = verify(key, in, p, progress1); cerr << endl; if (! proofOK) result = false; } cout << (result ? "OK" : "FAIL") << " " << len << " " << MD << endl; } len.clear(); msg.clear(); MD.clear(); } } else { // Monte-Carlo mode if (!MD.empty()) { if (-1 == testCase || testCaseStr == count) { bool result; if (1 == shaBits) { result = runMC<eval::SHA1>(seed, MD); } else if (224 == shaBits) { result = runMC<eval::SHA224>(seed, MD); } else if (256 == shaBits) { result = runMC<eval::SHA256>(seed, MD); } else if (384 == shaBits) { result = runMC<eval::SHA384>(seed, MD); } else if (512 == shaBits) { result = runMC<eval::SHA512>(seed, MD); } cout << (result ? "OK" : "FAIL") << " " << count << " " << seed << " " << MD << endl; } seed = MD; MD.clear(); } } } } int main(int argc, char *argv[]) { Getopt cmdLine(argc, argv, "p", "bi", "z"); if (!cmdLine || cmdLine.empty()) printUsage(argv[0]); const auto pairing = cmdLine.getString('p'); const auto shaBits = cmdLine.getNumber('b'); const auto testCase = cmdLine.getNumber('i'); const auto zkProof = cmdLine.getFlag('z'); if (!validPairingName(pairing) || !validSHA2Name(shaBits)) printUsage(argv[0]); if (pairingBN128(pairing)) { // Barreto-Naehrig 128 bits init_BN128(); readLoop<BN128_PAIRING>(shaBits, testCase, zkProof); } else if (pairingEdwards(pairing)) { // Edwards 80 bits init_Edwards(); readLoop<EDWARDS_PAIRING>(shaBits, testCase, zkProof); } return EXIT_SUCCESS; }
return EXIT_SUCCESS in main()
return EXIT_SUCCESS in main()
C++
mit
jancarlsson/snarkfront,jancarlsson/snarkfront
edf685c488a44e1132472632832d4dc96a079b79
value.cpp
value.cpp
#include "api.h" static Value * newValue(uint32_t homeId, OpenZWave::ValueID const &valueId) { Value * tmp = (Value *)malloc(sizeof(Value)); *tmp = (struct Value){0}; tmp->homeId = homeId; tmp->valueId.id = valueId.GetId(); tmp->valueId.valueType = valueId.GetType(); tmp->valueId.commandClassId = valueId.GetCommandClassId(); tmp->valueId.instance = valueId.GetInstance(); tmp->valueId.index = valueId.GetIndex(); return tmp; } void freeValue(Value * valueObj) { if (valueObj->value) { free(valueObj->value); } if (valueObj->label) { free(valueObj->label); } if (valueObj->units) { free(valueObj->units); } if (valueObj->help) { free(valueObj->help); } free(valueObj); } Value * exportValue(API * api, uint32_t homeId, OpenZWave::ValueID const &valueId) { Value * const tmp = newValue(homeId, valueId); std::string value; OpenZWave::Manager * const zwManager = OpenZWave::Manager::Get(); if (zwManager->GetValueAsString(valueId, &value)) { tmp->value = strdup(value.c_str()); } else { tmp->value = strdup(""); } tmp->label = strdup(zwManager->GetValueLabel(valueId).c_str()); tmp->help = strdup(zwManager->GetValueHelp(valueId).c_str()); tmp->units = strdup(zwManager->GetValueUnits(valueId).c_str()); tmp->min = zwManager->GetValueMin(valueId); tmp->max = zwManager->GetValueMax(valueId); tmp->isSet = zwManager->IsValueSet(valueId); return tmp; } bool setUint8Value(uint32_t homeId, uint64_t id, uint8_t value) { return OpenZWave::Manager::Get()->SetValue(OpenZWave::ValueID(homeId, id), value); } bool getUint8Value(uint32_t homeId, uint64_t id, uint8_t *value) { return OpenZWave::Manager::Get()->GetValueAsByte(OpenZWave::ValueID(homeId, id), value); } bool setBoolValue(uint32_t homeId, uint64_t id, bool value) { return OpenZWave::Manager::Get()->SetValue(OpenZWave::ValueID(homeId, id), value); } bool getBoolValue(uint32_t homeId, uint64_t id, bool *value) { return OpenZWave::Manager::Get()->GetValueAsBool(OpenZWave::ValueID(homeId, id), value); } bool setFloatValue(uint32_t homeId, uint64_t id, float value) { return OpenZWave::Manager::Get()->SetValue(OpenZWave::ValueID(homeId, id), value); } bool getFloatValue(uint32_t homeId, uint64_t id, float *value) { return OpenZWave::Manager::Get()->GetValueAsFloat(OpenZWave::ValueID(homeId, id), value); } bool setIntValue(uint32_t homeId, uint64_t id, int value) { return OpenZWave::Manager::Get()->SetValue(OpenZWave::ValueID(homeId, id), value); } bool getIntValue(uint32_t homeId, uint64_t id, int *value) { return OpenZWave::Manager::Get()->GetValueAsInt(OpenZWave::ValueID(homeId, id), value); } bool setStringValue(uint32_t homeId, uint64_t id, char * value) { bool result = OpenZWave::Manager::Get()->SetValue(OpenZWave::ValueID(homeId, id), std::string(value)); free(value); return result; } bool getStringValue(uint32_t homeId, uint64_t id, char ** value) { std::string tmp; if (OpenZWave::Manager::Get()->GetValueAsString(OpenZWave::ValueID(homeId, id), &tmp)) { *value = strdup(tmp.c_str()); return true; } else { *value = NULL; return false; } } bool refreshValue(uint32_t homeId, uint64_t id) { return OpenZWave::Manager::Get()->RefreshValue(OpenZWave::ValueID(homeId, id)); } bool setPollingState(uint32_t homeId, uint64_t id, bool state) { if (state) { return OpenZWave::Manager::Get()->EnablePoll(OpenZWave::ValueID(homeId, id)); } else { return OpenZWave::Manager::Get()->DisablePoll(OpenZWave::ValueID(homeId, id)); } }
#include "api.h" static Value * newValue(uint32_t homeId, OpenZWave::ValueID const &valueId) { Value * tmp = (Value *)malloc(sizeof(Value)); *tmp = (struct Value){0}; tmp->homeId = homeId; tmp->valueId.id = valueId.GetId(); tmp->valueId.valueType = valueId.GetType(); tmp->valueId.commandClassId = valueId.GetCommandClassId(); tmp->valueId.instance = valueId.GetInstance(); tmp->valueId.index = valueId.GetIndex(); return tmp; } void freeValue(Value * valueObj) { if (valueObj->value) { free(valueObj->value); } if (valueObj->label) { free(valueObj->label); } if (valueObj->units) { free(valueObj->units); } if (valueObj->help) { free(valueObj->help); } free(valueObj); } Value * exportValue(API * api, uint32_t homeId, OpenZWave::ValueID const &valueId) { Value * const tmp = newValue(homeId, valueId); std::string value; OpenZWave::Manager * const zwManager = OpenZWave::Manager::Get(); if (zwManager->GetValueAsString(valueId, &value)) { tmp->value = strdup(value.c_str()); } else { tmp->value = strdup(""); } tmp->label = strdup(zwManager->GetValueLabel(valueId).c_str()); tmp->help = strdup(zwManager->GetValueHelp(valueId).c_str()); tmp->units = strdup(zwManager->GetValueUnits(valueId).c_str()); tmp->min = zwManager->GetValueMin(valueId); tmp->max = zwManager->GetValueMax(valueId); tmp->isSet = zwManager->IsValueSet(valueId); return tmp; } bool setUint8Value(uint32_t homeId, uint64_t id, uint8_t value) { OpenZWave::ValueID valueId = OpenZWave::ValueID(homeId, id); OpenZWave::Manager::Get()->SetChangeVerified(valueId, true); return OpenZWave::Manager::Get()->SetValue(valueId, value); } bool getUint8Value(uint32_t homeId, uint64_t id, uint8_t *value) { return OpenZWave::Manager::Get()->GetValueAsByte(OpenZWave::ValueID(homeId, id), value); } bool setBoolValue(uint32_t homeId, uint64_t id, bool value) { return OpenZWave::Manager::Get()->SetValue(OpenZWave::ValueID(homeId, id), value); } bool getBoolValue(uint32_t homeId, uint64_t id, bool *value) { return OpenZWave::Manager::Get()->GetValueAsBool(OpenZWave::ValueID(homeId, id), value); } bool setFloatValue(uint32_t homeId, uint64_t id, float value) { return OpenZWave::Manager::Get()->SetValue(OpenZWave::ValueID(homeId, id), value); } bool getFloatValue(uint32_t homeId, uint64_t id, float *value) { return OpenZWave::Manager::Get()->GetValueAsFloat(OpenZWave::ValueID(homeId, id), value); } bool setIntValue(uint32_t homeId, uint64_t id, int value) { return OpenZWave::Manager::Get()->SetValue(OpenZWave::ValueID(homeId, id), value); } bool getIntValue(uint32_t homeId, uint64_t id, int *value) { return OpenZWave::Manager::Get()->GetValueAsInt(OpenZWave::ValueID(homeId, id), value); } bool setStringValue(uint32_t homeId, uint64_t id, char * value) { bool result = OpenZWave::Manager::Get()->SetValue(OpenZWave::ValueID(homeId, id), std::string(value)); free(value); return result; } bool getStringValue(uint32_t homeId, uint64_t id, char ** value) { std::string tmp; if (OpenZWave::Manager::Get()->GetValueAsString(OpenZWave::ValueID(homeId, id), &tmp)) { *value = strdup(tmp.c_str()); return true; } else { *value = NULL; return false; } } bool refreshValue(uint32_t homeId, uint64_t id) { return OpenZWave::Manager::Get()->RefreshValue(OpenZWave::ValueID(homeId, id)); } bool setPollingState(uint32_t homeId, uint64_t id, bool state) { if (state) { return OpenZWave::Manager::Get()->EnablePoll(OpenZWave::ValueID(homeId, id)); } else { return OpenZWave::Manager::Get()->DisablePoll(OpenZWave::ValueID(homeId, id)); } }
Use verified changes.
Use verified changes. Signed-off-by: Jon Seymour <[email protected]>
C++
mit
ninjasphere/go-openzwave,ninjasphere/go-openzwave,ninjasphere/go-openzwave,ninjasphere/go-openzwave,ninjasphere/go-openzwave,ninjasphere/go-openzwave
5a0eade6d8d8599b0847e08889ce42c4031c0d4c
include/hnc/mpi.hpp
include/hnc/mpi.hpp
// Copyright © 2013 Lénaïc Bagnères, [email protected] // This file is part of hnc. // hnc 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. // hnc 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 hnc. If not, see <http://www.gnu.org/licenses/> #ifndef HNC_MPI_HPP #define HNC_MPI_HPP #include "mpi/future.hpp" namespace hnc { /** * @brief MPI (Message Passing Interface) functions * * @code * #include <hnc/mpi.hpp> * @endcode * * @b From @b Wikipedia http://en.wikipedia.org/wiki/Message_Passing_Interface @n * Message Passing Interface (MPI) is a standardized and portable message-passing system designed by a group of researchers from academia and industry to function on a wide variety of parallel computers. The standard defines the syntax and semantics of a core of library routines useful to a wide range of users writing portable message-passing programs in Fortran 77 or the C programming language. Several well-tested and efficient implementations of MPI include some that are free and in the public domain. These fostered the development of a parallel software industry, and there encouraged development of portable and scalable large-scale parallel applications. * * With MPI you can write distributed program to: * - increase performances * - solve a bigger problem who can do with only one computer */ namespace mpi { // For Doxygen only } } #endif
// Copyright © 2013 Lénaïc Bagnères, [email protected] // This file is part of hnc. // hnc 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. // hnc 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 hnc. If not, see <http://www.gnu.org/licenses/> #ifndef HNC_MPI_HPP #define HNC_MPI_HPP #include "mpi/future.hpp" namespace hnc { /** * @brief MPI (Message Passing Interface) functions * * @code * #include <hnc/mpi.hpp> * @endcode * * With MPI you can write distributed program to: * - increase performances * - solve a bigger problem who can do with only one computer * * @b From @b Wikipedia http://en.wikipedia.org/wiki/Message_Passing_Interface @n * Message Passing Interface (MPI) is a standardized and portable message-passing system designed by a group of researchers from academia and industry to function on a wide variety of parallel computers. The standard defines the syntax and semantics of a core of library routines useful to a wide range of users writing portable message-passing programs in Fortran 77 or the C programming language. Several well-tested and efficient implementations of MPI include some that are free and in the public domain. These fostered the development of a parallel software industry, and there encouraged development of portable and scalable large-scale parallel applications. * * To use MPI code, you need Boost.MPI and Boost.Serialization @n * You can add this in your CMakeLists.txt * @code * find_package(Boost COMPONENTS mpi serialization) * if (Boost_FOUND) * # Boost.MPI and Boost.Serialization * set(boost_mpi_serialization "${Boost_LIBRARIES}") * message(STATUS "Boost.MPI and Boost.Serialization found :) ${boost_mpi_serialization}") * # MPI compiler * find_program(MPICXX_COMPILER NAMES mpic++ mpicxx mpiCC mpicc) * if (MPICXX_COMPILER) * # Change the compiler * message(STATUS "MPI C++ compiler found = ${MPICXX_COMPILER}") * set(CMAKE_CXX_COMPILER ${MPICXX_COMPILER}) * else() * message(STATUS "MPI C++ compiler not found :(") * endif() * # MPI run * find_program(MPIRUN_EXE NAMES mpirun) * if (MPIRUN_EXE) * message(STATUS "mpirun executable found = ${MPIRUN_EXE}") * else() * message(STATUS "mpirun executable not found :(") * endif() * else() * message(STATUS "Boost.MPI and Boost.Serialization not found :(") * endif() * * # ... * * # Create the executable * add_executable(your_exe your_exe.cpp) * target_link_libraries(your_exe ${boost_mpi_serialization}) * @endcode * * For quick test, if you use GCC from the command line and Boost is installed, you can link directly with: * @code * -lboost_mpi -lboost_serialization * @endcode * * On Debian GNU/Linux distribution you can install the packages: * @code * openmpi-bin openmpi-dev libboost-serialization-dev libboost-mpi-dev * @endcode * * To run a program with MPI, run your program with: * @code * mpirun -np number_of_processors your_exe * @endcode * * If you want compile without Boost.MPI, you can define the macro * @code * #define NO_HNC_Boost_MPI * @endcode */ namespace mpi { // For Doxygen only } } #endif
Upgrade hnc::mpi namespace doxygen
Upgrade hnc::mpi namespace doxygen
C++
apache-2.0
seken/hnc
af16ba462091831d212e07b2b1a7423c6a485ed7
include/lockwrap.hh
include/lockwrap.hh
#pragma once #include "seqlock.hh" template<typename T> class ptr_wrap { public: ptr_wrap(T* ptr) : ptr_(ptr) {} T* operator->() const { return ptr_; } T& operator*() const { return *ptr_; } private: T* ptr_; }; template<typename T> class seq_reader { public: seq_reader(T* v, seqcount<u32>* seq) { for (;;) { auto r = seq->read_begin(); state_ = *v; if (!r.need_retry()) return; } } const T* operator->() const { return &state_; } const T& operator*() const { return state_; } private: T state_; }; class seq_writer { public: seq_writer(seqcount<u32>* seq) : w_(seq->write_begin()) {} private: seqcount<u32>::writer w_; };
#pragma once #include "seqlock.hh" template<typename T> class ptr_wrap { public: ptr_wrap(T* ptr) : ptr_(ptr) {} T* operator->() const { return ptr_; } T& operator*() const { return *ptr_; } private: T* ptr_; }; template<typename T> class seq_reader { public: seq_reader(const T* v, const seqcount<u32>* seq) { for (;;) { auto r = seq->read_begin(); state_ = *v; if (!r.need_retry()) return; } } const T* operator->() const { return &state_; } const T& operator*() const { return state_; } private: T state_; }; class seq_writer { public: seq_writer(seqcount<u32>* seq) : w_(seq->write_begin()) {} private: seqcount<u32>::writer w_; };
fix constness
seq_reader: fix constness
C++
mit
aclements/sv6,bowlofstew/sv6,aclements/sv6,aclements/sv6,bowlofstew/sv6,bowlofstew/sv6,bowlofstew/sv6,bowlofstew/sv6,aclements/sv6,aclements/sv6
fd06fbf3c31b3a5d81d4b7d2261cf41766ea506f
tests/init.cpp
tests/init.cpp
#include <matrix.hpp> #include <catch.hpp> SCENARIO("def constructor") { Matrix matrix; REQUIRE(matrix.Strings_() == 0); REQUIRE(matrix.Columns_() == 0); } SCENARIO("param constructor") { Matrix matrix(2, 2); REQUIRE(matrix.Strings_() == 2); REQUIRE(matrix.Columns_() == 2); } SCENARIO("copy constructor") { Matrix matrix (2, 2); Matrix copy(matrix); REQUIRE(copy.Strings_() == 2); REQUIRE(copy.Columns_() == 2); } SCENARIO("operator +") { Matrix matrix1 (2, 2); Matrix matrix2 (2, 2); Matrix matrix3 (2, 2); std::ifstream("test.txt") >> matrix1; std::ifstream("matrix2.txt") >> matrix2; std::ifstream("sum.txt") >> matrix3; REQUIRE(matrix1 + matrix2 == matrix3); } SCENARIO("operator *") { Matrix matrix1 (2, 2); Matrix matrix2 (2, 2); Matrix matrix3 (2, 2); std::ifstream("test.txt") >> matrix1; std::ifstream("matrix2.txt") >> matrix2; std::ifstream("multi.txt") >> matrix3; REQUIRE(matrix1 * matrix2 == matrix3); } SCENARIO("operator =") { Matrix matrix(2, 2); Matrix matrix = matrix1; REQUIRE(matrix == matrix1); } SCENARIO("operator ==") { Matrix matrix(2, 2); Matrix matrix1(2, 2); REQUIRE(matrix == matrix1); }
#include <matrix.hpp> #include <catch.hpp> SCENARIO("def constructor") { Matrix matrix; REQUIRE(matrix.Strings_() == 0); REQUIRE(matrix.Columns_() == 0); } SCENARIO("param constructor") { Matrix matrix(2, 2); REQUIRE(matrix.Strings_() == 2); REQUIRE(matrix.Columns_() == 2); } SCENARIO("copy constructor") { Matrix matrix (2, 2); Matrix copy(matrix); REQUIRE(copy.Strings_() == 2); REQUIRE(copy.Columns_() == 2); } SCENARIO("operator +") { Matrix matrix1 (2, 2); Matrix matrix2 (2, 2); Matrix matrix3 (2, 2); std::ifstream("test.txt") >> matrix1; std::ifstream("matrix2.txt") >> matrix2; std::ifstream("sum.txt") >> matrix3; REQUIRE(matrix1 + matrix2 == matrix3); } SCENARIO("operator *") { Matrix matrix1 (2, 2); Matrix matrix2 (2, 2); Matrix matrix3 (2, 2); std::ifstream("test.txt") >> matrix1; std::ifstream("matrix2.txt") >> matrix2; std::ifstream("multi.txt") >> matrix3; REQUIRE(matrix1 * matrix2 == matrix3); } SCENARIO("operator =") { Matrix matrix(2, 2); Matrix matrix1 = matrix; REQUIRE(matrix == matrix1); } SCENARIO("operator ==") { Matrix matrix(2, 2); Matrix matrix1(2, 2); REQUIRE(matrix == matrix1); }
Update init.cpp
Update init.cpp
C++
mit
elinagabitova/matrix
56ecd3dfa6f62b6685e5f5cf054a4c7790066d42
tests/init.cpp
tests/init.cpp
#include <matrix.hpp> #include <catch.hpp> #include <iostream> SCENARIO ("init", "[init]") { BinaryTree<int> tree; REQUIRE(tree.root_() == nullptr); } SCENARIO ("output", "[output]") { BinaryTree<int> tree; tree.insertNode(1); REQUIRE( std::cout << tree ); } SCENARIO("findNode", "[findNode]") { BinaryTree<int> tree; tree.insert_node(4); tree.insert_node(2); REQUIRE(tree.find_node(2, tree.root_()) != nullptr); REQUIRE(tree.find_node(2, tree.root_())->data == 2); } SCENARIO("insert", "[insert]") { BinaryTree<int> tree; tree.insert_node(3); REQUIRE(tree.find_node(3, tree.root_())->data == 3); } SCENARIO("removeElement", "[remEl]") { BinaryTree<int> obj; tree.insert_node(1); tree.insert_node(2); tree.insert_node(3); tree.deleteVal(1); REQUIRE(tree.find_node(1, tree.root_())== nullptr); REQUIRE(tree.find_node(2, tree.root_())== tree.root_()); REQUIRE(tree.root_() != nullptr); } SCENARIO("DEL", "[Del]") { BinaryTree<int> tree; tree.insert_node(1); tree.insert_node(2); tree.deleteVal(2); REQUIRE(obj.getCount() == 1); }
#include <matrix.hpp> #include <catch.hpp> #include <iostream> SCENARIO ("init", "[init]") { BinaryTree<int> tree; REQUIRE(tree.root_() == nullptr); } SCENARIO ("output", "[output]") { BinaryTree<int> tree; tree.insertNode(1); REQUIRE( std::cout << tree ); } SCENARIO("find", "[find]") { BinaryTree<int> tree; tree.insertNode(4); tree.insertNode(2); REQUIRE(tree.findNode(2, tree.root_()) != nullptr); REQUIRE(tree.findNode(2, tree.root_())->data == 2); } SCENARIO("insert", "[insert]") { BinaryTree<int> tree; tree.insertNode(3); REQUIRE(tree.findNode(3, tree.root_())->data == 3); } SCENARIO("remove", "[remove]") { BinaryTree<int> obj; tree.insertNode(1); tree.insertNode(2); tree.insertNode(3); tree.deleteVal(1); REQUIRE(tree.findNode(1, tree.root_())== nullptr); REQUIRE(tree.findNode(2, tree.root_())== tree.root_()); REQUIRE(tree.root_() != nullptr); } SCENARIO("delete", "[delete]") { BinaryTree<int> tree; tree.insertNode(1); tree.insertNode(2); tree.deleteValue(2); REQUIRE(obj.getCount() == 1); }
Create init.cpp
Create init.cpp
C++
mit
BURNINGTIGER/Tree
9ea43e50c42474c6d6cc338dc26bb9a74cc74641
tests/memcp.cc
tests/memcp.cc
/* vim:expandtab:shiftwidth=2:tabstop=2:smarttab: * * Test memcp * * Copyright (C) 2011 Data Differential, http://datadifferential.com/ * * 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. * * * The names of its contributors may not 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. * */ /* Test that we are cycling the servers we are creating during testing. */ #include <mem_config.h> #include <libtest/test.hpp> #include <libmemcached-1.0/memcached.h> #include <sys/stat.h> using namespace libtest; #ifndef __INTEL_COMPILER #pragma GCC diagnostic ignored "-Wstrict-aliasing" #endif static std::string executable("./clients/memcp"); static test_return_t help_test(void *) { const char *args[]= { "--help", 0 }; test_compare(EXIT_SUCCESS, exec_cmdline(executable, args, true)); return TEST_SUCCESS; } static test_return_t server_test(void *) { int fd; std::string tmp_file= create_tmpfile("memcp", fd); ASSERT_TRUE(tmp_file.c_str()); struct stat buf; ASSERT_EQ(fstat(fd, &buf), 0); ASSERT_EQ(buf.st_size, 0); char buffer[1024]; snprintf(buffer, sizeof(buffer), "--servers=localhost:%d", int(default_port())); const char *args[]= { buffer, tmp_file.c_str(), 0 }; test_compare(EXIT_SUCCESS, exec_cmdline(executable, args, true)); close(fd); unlink(tmp_file.c_str()); return TEST_SUCCESS; } test_st memcp_tests[] ={ {"--help", true, help_test }, {"--server_test", true, server_test }, {0, 0, 0} }; collection_st collection[] ={ {"memcp", 0, 0, memcp_tests }, {0, 0, 0, 0} }; static void *world_create(server_startup_st& servers, test_return_t& error) { if (libtest::has_memcached() == false) { error= TEST_SKIPPED; return NULL; } if (server_startup(servers, "memcached", libtest::default_port(), NULL) == false) { error= TEST_FAILURE; } return &servers; } void get_world(libtest::Framework* world) { world->collections(collection); world->create(world_create); }
/* vim:expandtab:shiftwidth=2:tabstop=2:smarttab: * * Test memcp * * Copyright (C) 2011 Data Differential, http://datadifferential.com/ * * 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. * * * The names of its contributors may not 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. * */ /* Test that we are cycling the servers we are creating during testing. */ #include <mem_config.h> #include <libtest/test.hpp> #include <libmemcached-1.0/memcached.h> #include <sys/stat.h> using namespace libtest; #ifndef __INTEL_COMPILER #pragma GCC diagnostic ignored "-Wstrict-aliasing" #endif static std::string executable("./clients/memcp"); static test_return_t help_test(void *) { const char *args[]= { "--help", 0 }; test_compare(EXIT_SUCCESS, exec_cmdline(executable, args, true)); return TEST_SUCCESS; } #if 0 static test_return_t server_test(void *) { int fd; std::string tmp_file= create_tmpfile("memcp", fd); ASSERT_TRUE(tmp_file.c_str()); struct stat buf; ASSERT_EQ(fstat(fd, &buf), 0); ASSERT_EQ(buf.st_size, 0); char buffer[1024]; snprintf(buffer, sizeof(buffer), "--servers=localhost:%d", int(default_port())); const char *args[]= { buffer, tmp_file.c_str(), 0 }; test_compare(EXIT_SUCCESS, exec_cmdline(executable, args, true)); close(fd); unlink(tmp_file.c_str()); return TEST_SUCCESS; } #endif test_st memcp_tests[] ={ {"--help", true, help_test }, #if 0 {"--server_test", true, server_test }, #endif {0, 0, 0} }; collection_st collection[] ={ {"memcp", 0, 0, memcp_tests }, {0, 0, 0, 0} }; static void *world_create(server_startup_st& servers, test_return_t& error) { if (libtest::has_memcached() == false) { error= TEST_SKIPPED; return NULL; } if (server_startup(servers, "memcached", libtest::default_port(), NULL) == false) { error= TEST_FAILURE; } return &servers; } void get_world(libtest::Framework* world) { world->collections(collection); world->create(world_create); }
Disable broken test for the moment.
Disable broken test for the moment.
C++
bsd-3-clause
mckelvin/libmemcached,mckelvin/libmemcached,mckelvin/libmemcached
a0fc01b51d58def52495009ffaa9a6e21fb85ef8
examples/gp/scalar/gpscalar.C
examples/gp/scalar/gpscalar.C
#include <queso/GslVector.h> #include <queso/GslMatrix.h> #include <queso/UniformVectorRV.h> #include <queso/StatisticalInverseProblem.h> #include <queso/VectorSet.h> #include <queso/GaussianProcessEmulator.h> int main(int argc, char ** argv) { // Step 0: Set up some variables unsigned int numExperiments = 6; // Number of experiments unsigned int numUncertainVars = 1; // Number of things to calibrate unsigned int numSimulations = 25; // Number of simulations unsigned int numConfigVars = 1; // Dimension of configuration space unsigned int numEta = 1; // Number of responses the model is returning unsigned int experimentSize = 1; // Size of each experiment MPI_Init(&argc, &argv); // Step 1: Set up QUESO environment QUESO::FullEnvironment env(MPI_COMM_WORLD, argv[1], "", NULL); // Step 2: Set up prior for calibration parameters QUESO::VectorSpace<QUESO::GslVector, QUESO::GslMatrix> paramSpace(env, "param_", numUncertainVars, NULL); QUESO::GslVector paramMins(paramSpace.zeroVector()); paramMins.cwSet(0.0); QUESO::GslVector paramMaxs(paramSpace.zeroVector()); paramMaxs.cwSet(1.0); QUESO::BoxSubset<QUESO::GslVector, QUESO::GslMatrix> paramDomain("param_", paramSpace, paramMins, paramMaxs); QUESO::UniformVectorRV<QUESO::GslVector, QUESO::GslMatrix> priorRv("prior_", paramDomain); // Step 3: Instantiate the 'scenario' and 'output' spaces for simulation QUESO::VectorSpace<QUESO::GslVector, QUESO::GslMatrix> configSpace(env, "scenario_", numConfigVars, NULL); QUESO::VectorSpace<QUESO::GslVector, QUESO::GslMatrix> nEtaSpace(env, "output_", numEta, NULL); // Step 4: Instantiate the 'output' space for the experiments QUESO::VectorSpace<QUESO::GslVector, QUESO::GslMatrix> experimentSpace(env, "experimentspace_", experimentSize, NULL); QUESO::VectorSpace<QUESO::GslVector, QUESO::GslMatrix> totalExperimentSpace(env, "experimentspace_", experimentSize * numExperiments, NULL); // Step 5: Instantiate the Gaussian process emulator object // // Regarding simulation scenario input values, QUESO should standardise them // so that they exist inside a hypercube. // // Regarding simulation output data, QUESO should transform it so that the // mean is zero and the variance is one. // // Regarding experimental scenario input values, QUESO should standardize // them so that they exist inside a hypercube. // // Regarding experimental data, QUESO should transformed it so that it has // zero mean and variance one. // GaussianProcessEmulator stores all the information about our simulation // data and experimental data. It also stores default information about the // hyperparameter distributions. QUESO::GaussianProcessFactory<QUESO::GslVector, QUESO::GslMatrix> gpFactory("gp_", priorRv, configSpace, paramSpace, nEtaSpace, experimentSpace, numSimulations, numExperiments); // std::vector containing all the points in scenario space where we have // simulations std::vector<QUESO::GslVector *> simulationScenarios(numSimulations, (QUESO::GslVector *) NULL); // std::vector containing all the points in parameter space where we have // simulations std::vector<QUESO::GslVector *> paramVecs(numSimulations, (QUESO::GslVector *) NULL); // std::vector containing all the simulation output data std::vector<QUESO::GslVector *> outputVecs(numSimulations, (QUESO::GslVector *) NULL); // std::vector containing all the points in scenario space where we have // experiments std::vector<QUESO::GslVector *> experimentScenarios(numExperiments, (QUESO::GslVector *) NULL); // std::vector containing all the experimental output data std::vector<QUESO::GslVector *> experimentVecs(numExperiments, (QUESO::GslVector *) NULL); // The experimental output data observation error covariance matrix QUESO::GslMatrix experimentMat(totalExperimentSpace.zeroVector()); // Instantiate each of the simulation points/outputs for (unsigned int i = 0; i < numSimulations; i++) { simulationScenarios[i] = new QUESO::GslVector(configSpace.zeroVector()); // 'x_{i+1}^*' in paper paramVecs [i] = new QUESO::GslVector(paramSpace.zeroVector()); // 't_{i+1}^*' in paper outputVecs [i] = new QUESO::GslVector(nEtaSpace.zeroVector()); // 'eta_{i+1}' in paper } // All the positions in scenario space where simulations were run // This should probably be read from a file (*(simulationScenarios[0]))[0] = 0.0416667; (*(simulationScenarios[1]))[0] = 0.125; (*(simulationScenarios[2]))[0] = 0; (*(simulationScenarios[3]))[0] = 0.166667; (*(simulationScenarios[4]))[0] = 0.0833333; (*(simulationScenarios[5]))[0] = 0.333333; (*(simulationScenarios[6]))[0] = 0.208333; (*(simulationScenarios[7]))[0] = 0.291667; (*(simulationScenarios[8]))[0] = 0.375; (*(simulationScenarios[9]))[0] = 0.25; (*(simulationScenarios[10]))[0] = 0.583333; (*(simulationScenarios[11]))[0] = 0.416667; (*(simulationScenarios[12]))[0] = 0.541667; (*(simulationScenarios[13]))[0] = 0.5; (*(simulationScenarios[14]))[0] = 0.458333; (*(simulationScenarios[15]))[0] = 0.708333; (*(simulationScenarios[16]))[0] = 0.75; (*(simulationScenarios[17]))[0] = 0.666667; (*(simulationScenarios[18]))[0] = 0.625; (*(simulationScenarios[19]))[0] = 0.791667; (*(simulationScenarios[20]))[0] = 0.875; (*(simulationScenarios[21]))[0] = 1; (*(simulationScenarios[22]))[0] = 0.833333; (*(simulationScenarios[23]))[0] = 0.958333; (*(simulationScenarios[24]))[0] = 0.916667; // All the positions in parameter space where simulations were run // This should probably be read from a file (*(paramVecs[0]))[0] = 0.125; (*(paramVecs[1]))[0] = 0.375; (*(paramVecs[2]))[0] = 0.583333; (*(paramVecs[3]))[0] = 0.708333; (*(paramVecs[4]))[0] = 0.875; (*(paramVecs[5]))[0] = 0.0; (*(paramVecs[6]))[0] = 0.208333; (*(paramVecs[7]))[0] = 0.5; (*(paramVecs[8]))[0] = 0.791667; (*(paramVecs[9]))[0] = 0.916667; (*(paramVecs[10]))[0] = 0.0416667; (*(paramVecs[11]))[0] = 0.291667; (*(paramVecs[12]))[0] = 0.416667; (*(paramVecs[13]))[0] = 0.625; (*(paramVecs[14]))[0] = 1.0; (*(paramVecs[15]))[0] = 0.166667; (*(paramVecs[16]))[0] = 0.333333; (*(paramVecs[17]))[0] = 0.541667; (*(paramVecs[18]))[0] = 0.75; (*(paramVecs[19]))[0] = 0.833333; (*(paramVecs[20]))[0] = 0.0833333; (*(paramVecs[21]))[0] = 0.25; (*(paramVecs[22]))[0] = 0.458333; (*(paramVecs[23]))[0] = 0.666667; (*(paramVecs[24]))[0] = 0.958333; // Simulation output from sim_outputs file from matlab gpmsa implementation // This should probably be read from a file (*(outputVecs[0]))[0] = 1.60656419103786; (*(outputVecs[1]))[0] = 2.03091732612410; (*(outputVecs[2]))[0] = 1.63843806135107; (*(outputVecs[3]))[0] = 2.4638773088846; (*(outputVecs[4]))[0] = 2.21838509163166; (*(outputVecs[5]))[0] = 2.30939315250214; (*(outputVecs[6]))[0] = 2.17300595474166; (*(outputVecs[7]))[0] = 2.71440886744846; (*(outputVecs[8]))[0] = 3.45738385598637; (*(outputVecs[9]))[0] = 3.08913132945656; (*(outputVecs[10]))[0] = 2.8542802908597; (*(outputVecs[11]))[0] = 2.82284112252142; (*(outputVecs[12]))[0] = 3.35111130604648; (*(outputVecs[13]))[0] = 3.62106706299426; (*(outputVecs[14]))[0] = 4.27778530159255; (*(outputVecs[15]))[0] = 3.28874614306084; (*(outputVecs[16]))[0] = 3.71321395867495; (*(outputVecs[17]))[0] = 3.97952570579624; (*(outputVecs[18]))[0] = 4.37705002709939; (*(outputVecs[19]))[0] = 5.31766210668879; (*(outputVecs[20]))[0] = 3.43505963946617; (*(outputVecs[21]))[0] = 4.04494232394982; (*(outputVecs[22]))[0] = 4.23694028613074; (*(outputVecs[23]))[0] = 5.31781675076092; (*(outputVecs[24]))[0] = 6.39189142027432; for (unsigned int i = 0; i < numExperiments; i++) { experimentScenarios[i] = new QUESO::GslVector(configSpace.zeroVector()); // 'x_{i+1}' in paper experimentVecs[i] = new QUESO::GslVector(experimentSpace.zeroVector()); } // All the positions in scenario space where we have experimental data // This should probably be read from a file (*(experimentScenarios[0]))[0] = 0.0; (*(experimentScenarios[1]))[0] = 0.2; (*(experimentScenarios[2]))[0] = 0.4; (*(experimentScenarios[3]))[0] = 0.6; (*(experimentScenarios[4]))[0] = 0.8; (*(experimentScenarios[5]))[0] = 1.0; // These are the experimental data // This should probably be read from a file (*(experimentVecs[0]))[0] = 1.59294826065229; (*(experimentVecs[1]))[0] = 2.17696977275016; (*(experimentVecs[2]))[0] = 2.87061286591332; (*(experimentVecs[3]))[0] = 3.8330395105599; (*(experimentVecs[4]))[0] = 4.59654198432239; (*(experimentVecs[5]))[0] = 4.75087857533489; // Add simulation and experimental data gpFactory.addSimulations(simulationScenarios, paramVecs, outputVecs); gpFactory.addExperiments(experimentScenarios, experimentVecs, &experimentMat); QUESO::GenericVectorRV<QUESO::GslVector, QUESO::GslMatrix> postRv( "post_", gpFactory.prior().imageSet().vectorSpace()); QUESO::StatisticalInverseProblem<QUESO::GslVector, QUESO::GslMatrix> ip("", NULL, gpFactory, postRv); QUESO::GslVector paramInitials( gpFactory.prior().imageSet().vectorSpace().zeroVector()); // Initial condition of the chain for (unsigned int i = 0; i < paramInitials.sizeLocal(); i++) { paramInitials[i] = 0.5; } QUESO::GslMatrix proposalCovMatrix( gpFactory.prior().imageSet().vectorSpace().zeroVector()); for (unsigned int i = 0; i < proposalCovMatrix.numRowsLocal(); i++) { proposalCovMatrix(i, i) = 0.01; } std::cout << "got here 25" << std::endl; ip.solveWithBayesMetropolisHastings(NULL, paramInitials, &proposalCovMatrix); std::cout << "got here 26" << std::endl; MPI_Finalize(); std::cout << "got here 27" << std::endl; return 0; }
#include <queso/GslVector.h> #include <queso/GslMatrix.h> #include <queso/UniformVectorRV.h> #include <queso/StatisticalInverseProblem.h> #include <queso/VectorSet.h> #include <queso/GaussianProcessEmulator.h> int main(int argc, char ** argv) { // Step 0: Set up some variables unsigned int numExperiments = 6; // Number of experiments unsigned int numUncertainVars = 1; // Number of things to calibrate unsigned int numSimulations = 25; // Number of simulations unsigned int numConfigVars = 1; // Dimension of configuration space unsigned int numEta = 1; // Number of responses the model is returning unsigned int experimentSize = 1; // Size of each experiment MPI_Init(&argc, &argv); // Step 1: Set up QUESO environment QUESO::FullEnvironment env(MPI_COMM_WORLD, argv[1], "", NULL); // Step 2: Set up prior for calibration parameters QUESO::VectorSpace<QUESO::GslVector, QUESO::GslMatrix> paramSpace(env, "param_", numUncertainVars, NULL); QUESO::GslVector paramMins(paramSpace.zeroVector()); paramMins.cwSet(0.0); QUESO::GslVector paramMaxs(paramSpace.zeroVector()); paramMaxs.cwSet(1.0); QUESO::BoxSubset<QUESO::GslVector, QUESO::GslMatrix> paramDomain("param_", paramSpace, paramMins, paramMaxs); QUESO::UniformVectorRV<QUESO::GslVector, QUESO::GslMatrix> priorRv("prior_", paramDomain); // Step 3: Instantiate the 'scenario' and 'output' spaces for simulation QUESO::VectorSpace<QUESO::GslVector, QUESO::GslMatrix> configSpace(env, "scenario_", numConfigVars, NULL); QUESO::VectorSpace<QUESO::GslVector, QUESO::GslMatrix> nEtaSpace(env, "output_", numEta, NULL); // Step 4: Instantiate the 'output' space for the experiments QUESO::VectorSpace<QUESO::GslVector, QUESO::GslMatrix> experimentSpace(env, "experimentspace_", experimentSize, NULL); QUESO::VectorSpace<QUESO::GslVector, QUESO::GslMatrix> totalExperimentSpace(env, "experimentspace_", experimentSize * numExperiments, NULL); // Step 5: Instantiate the Gaussian process emulator object // // Regarding simulation scenario input values, QUESO should standardise them // so that they exist inside a hypercube. // // Regarding simulation output data, QUESO should transform it so that the // mean is zero and the variance is one. // // Regarding experimental scenario input values, QUESO should standardize // them so that they exist inside a hypercube. // // Regarding experimental data, QUESO should transformed it so that it has // zero mean and variance one. // GaussianProcessEmulator stores all the information about our simulation // data and experimental data. It also stores default information about the // hyperparameter distributions. QUESO::GaussianProcessFactory<QUESO::GslVector, QUESO::GslMatrix> gpFactory("gp_", priorRv, configSpace, paramSpace, nEtaSpace, experimentSpace, numSimulations, numExperiments); // std::vector containing all the points in scenario space where we have // simulations std::vector<QUESO::GslVector *> simulationScenarios(numSimulations, (QUESO::GslVector *) NULL); // std::vector containing all the points in parameter space where we have // simulations std::vector<QUESO::GslVector *> paramVecs(numSimulations, (QUESO::GslVector *) NULL); // std::vector containing all the simulation output data std::vector<QUESO::GslVector *> outputVecs(numSimulations, (QUESO::GslVector *) NULL); // std::vector containing all the points in scenario space where we have // experiments std::vector<QUESO::GslVector *> experimentScenarios(numExperiments, (QUESO::GslVector *) NULL); // std::vector containing all the experimental output data std::vector<QUESO::GslVector *> experimentVecs(numExperiments, (QUESO::GslVector *) NULL); // The experimental output data observation error covariance matrix QUESO::GslMatrix experimentMat(totalExperimentSpace.zeroVector()); // Instantiate each of the simulation points/outputs for (unsigned int i = 0; i < numSimulations; i++) { simulationScenarios[i] = new QUESO::GslVector(configSpace.zeroVector()); // 'x_{i+1}^*' in paper paramVecs [i] = new QUESO::GslVector(paramSpace.zeroVector()); // 't_{i+1}^*' in paper outputVecs [i] = new QUESO::GslVector(nEtaSpace.zeroVector()); // 'eta_{i+1}' in paper } // All the positions in scenario space where simulations were run // This should probably be read from a file (*(simulationScenarios[0]))[0] = 0.0416667; (*(simulationScenarios[1]))[0] = 0.125; (*(simulationScenarios[2]))[0] = 0; (*(simulationScenarios[3]))[0] = 0.166667; (*(simulationScenarios[4]))[0] = 0.0833333; (*(simulationScenarios[5]))[0] = 0.333333; (*(simulationScenarios[6]))[0] = 0.208333; (*(simulationScenarios[7]))[0] = 0.291667; (*(simulationScenarios[8]))[0] = 0.375; (*(simulationScenarios[9]))[0] = 0.25; (*(simulationScenarios[10]))[0] = 0.583333; (*(simulationScenarios[11]))[0] = 0.416667; (*(simulationScenarios[12]))[0] = 0.541667; (*(simulationScenarios[13]))[0] = 0.5; (*(simulationScenarios[14]))[0] = 0.458333; (*(simulationScenarios[15]))[0] = 0.708333; (*(simulationScenarios[16]))[0] = 0.75; (*(simulationScenarios[17]))[0] = 0.666667; (*(simulationScenarios[18]))[0] = 0.625; (*(simulationScenarios[19]))[0] = 0.791667; (*(simulationScenarios[20]))[0] = 0.875; (*(simulationScenarios[21]))[0] = 1; (*(simulationScenarios[22]))[0] = 0.833333; (*(simulationScenarios[23]))[0] = 0.958333; (*(simulationScenarios[24]))[0] = 0.916667; // All the positions in parameter space where simulations were run // This should probably be read from a file (*(paramVecs[0]))[0] = 0.125; (*(paramVecs[1]))[0] = 0.375; (*(paramVecs[2]))[0] = 0.583333; (*(paramVecs[3]))[0] = 0.708333; (*(paramVecs[4]))[0] = 0.875; (*(paramVecs[5]))[0] = 0.0; (*(paramVecs[6]))[0] = 0.208333; (*(paramVecs[7]))[0] = 0.5; (*(paramVecs[8]))[0] = 0.791667; (*(paramVecs[9]))[0] = 0.916667; (*(paramVecs[10]))[0] = 0.0416667; (*(paramVecs[11]))[0] = 0.291667; (*(paramVecs[12]))[0] = 0.416667; (*(paramVecs[13]))[0] = 0.625; (*(paramVecs[14]))[0] = 1.0; (*(paramVecs[15]))[0] = 0.166667; (*(paramVecs[16]))[0] = 0.333333; (*(paramVecs[17]))[0] = 0.541667; (*(paramVecs[18]))[0] = 0.75; (*(paramVecs[19]))[0] = 0.833333; (*(paramVecs[20]))[0] = 0.0833333; (*(paramVecs[21]))[0] = 0.25; (*(paramVecs[22]))[0] = 0.458333; (*(paramVecs[23]))[0] = 0.666667; (*(paramVecs[24]))[0] = 0.958333; // Simulation output from sim_outputs file from matlab gpmsa implementation // This should probably be read from a file (*(outputVecs[0]))[0] = 1.60656419103786; (*(outputVecs[1]))[0] = 2.03091732612410; (*(outputVecs[2]))[0] = 1.63843806135107; (*(outputVecs[3]))[0] = 2.4638773088846; (*(outputVecs[4]))[0] = 2.21838509163166; (*(outputVecs[5]))[0] = 2.30939315250214; (*(outputVecs[6]))[0] = 2.17300595474166; (*(outputVecs[7]))[0] = 2.71440886744846; (*(outputVecs[8]))[0] = 3.45738385598637; (*(outputVecs[9]))[0] = 3.08913132945656; (*(outputVecs[10]))[0] = 2.8542802908597; (*(outputVecs[11]))[0] = 2.82284112252142; (*(outputVecs[12]))[0] = 3.35111130604648; (*(outputVecs[13]))[0] = 3.62106706299426; (*(outputVecs[14]))[0] = 4.27778530159255; (*(outputVecs[15]))[0] = 3.28874614306084; (*(outputVecs[16]))[0] = 3.71321395867495; (*(outputVecs[17]))[0] = 3.97952570579624; (*(outputVecs[18]))[0] = 4.37705002709939; (*(outputVecs[19]))[0] = 5.31766210668879; (*(outputVecs[20]))[0] = 3.43505963946617; (*(outputVecs[21]))[0] = 4.04494232394982; (*(outputVecs[22]))[0] = 4.23694028613074; (*(outputVecs[23]))[0] = 5.31781675076092; (*(outputVecs[24]))[0] = 6.39189142027432; for (unsigned int i = 0; i < numExperiments; i++) { experimentScenarios[i] = new QUESO::GslVector(configSpace.zeroVector()); // 'x_{i+1}' in paper experimentVecs[i] = new QUESO::GslVector(experimentSpace.zeroVector()); } // All the positions in scenario space where we have experimental data // This should probably be read from a file (*(experimentScenarios[0]))[0] = 0.0; (*(experimentScenarios[1]))[0] = 0.2; (*(experimentScenarios[2]))[0] = 0.4; (*(experimentScenarios[3]))[0] = 0.6; (*(experimentScenarios[4]))[0] = 0.8; (*(experimentScenarios[5]))[0] = 1.0; // These are the experimental data // This should probably be read from a file (*(experimentVecs[0]))[0] = 1.59294826065229; (*(experimentVecs[1]))[0] = 2.17696977275016; (*(experimentVecs[2]))[0] = 2.87061286591332; (*(experimentVecs[3]))[0] = 3.8330395105599; (*(experimentVecs[4]))[0] = 4.59654198432239; (*(experimentVecs[5]))[0] = 4.75087857533489; for (unsigned int i = 0; i < 5; i++) { experimentMat(i, i) = 0.075 * 0.075; } // Add simulation and experimental data gpFactory.addSimulations(simulationScenarios, paramVecs, outputVecs); gpFactory.addExperiments(experimentScenarios, experimentVecs, &experimentMat); QUESO::GenericVectorRV<QUESO::GslVector, QUESO::GslMatrix> postRv( "post_", gpFactory.prior().imageSet().vectorSpace()); QUESO::StatisticalInverseProblem<QUESO::GslVector, QUESO::GslMatrix> ip("", NULL, gpFactory, postRv); QUESO::GslVector paramInitials( gpFactory.prior().imageSet().vectorSpace().zeroVector()); // Initial condition of the chain for (unsigned int i = 0; i < paramInitials.sizeLocal(); i++) { paramInitials[i] = 0.5; } QUESO::GslMatrix proposalCovMatrix( gpFactory.prior().imageSet().vectorSpace().zeroVector()); for (unsigned int i = 0; i < proposalCovMatrix.numRowsLocal(); i++) { proposalCovMatrix(i, i) = 0.01; } std::cout << "got here 25" << std::endl; ip.solveWithBayesMetropolisHastings(NULL, paramInitials, &proposalCovMatrix); std::cout << "got here 26" << std::endl; MPI_Finalize(); std::cout << "got here 27" << std::endl; return 0; }
Set experimental obs var properly
Set experimental obs var properly
C++
lgpl-2.1
roystgnr/queso,briadam/queso,briadam/queso,briadam/queso,briadam/queso,roystgnr/queso,briadam/queso,roystgnr/queso,roystgnr/queso,roystgnr/queso,roystgnr/queso
a661ca9199f773b9b828cb1d38ee439e9b3c6351
sources/vvvstlhelper.hpp
sources/vvvstlhelper.hpp
#ifndef VVVSTLHELPER_H #define VVVSTLHELPER_H #include <algorithm> #include <string> #include <vector> template<typename C, class P, typename = typename std::enable_if_t<std::is_rvalue_reference<C&&>::value> > inline decltype(auto) filter(C&& v, P p ) { const auto n = std::copy_if( v.begin(), v.end(), v.begin(), p ); v.resize( std::distance(v.begin(), n) ); return std::move(v); } template<class C, class P> inline C filter( const C& v, P p) { C ret; std::copy_if( v.begin(), v.end(), std::back_inserter( ret ), p ); return ret; } template<class C, class P> inline bool any_of(const C& c, const P& p) { return std::any_of(c.cbegin(), c.cend(), p); } template<class C, class V> inline bool contain(const C& c, const V& v) { return any_of(c, [&v](const auto& e){return e == v;}); } inline std::string joinStringsWith( const std::vector<std::string>& v, const std::string& delimiter) { std::string ret; const auto numStrings = v.size(); const auto lastIndex = numStrings-1; for(size_t i = 0; i < numStrings; ++i) { ret += v[i]; if( i!= lastIndex) ret += delimiter; } return ret; } inline void split(const std::string& input, char delimiter, std::vector<std::string>& ret) { using namespace std; size_t last_pos = 0; while(true) { const size_t current_pos = input.find(delimiter,last_pos); if(current_pos == string::npos) { const string substr = input.substr(last_pos, input.size() - last_pos ); ret.push_back(substr); break; } else { const string substr = input.substr(last_pos, current_pos-last_pos); ret.push_back(substr); last_pos = current_pos+1; }} } inline std::vector<std::string> split(const std::string& str, char delimiter=' ') { std::vector<std::string> ret; split(str, delimiter, ret); return ret; } #endif
#ifndef VVVSTLHELPER_H #define VVVSTLHELPER_H #include <algorithm> #include <string> #include <vector> template<typename C, class P, typename = typename std::enable_if_t<std::is_rvalue_reference<C&&>::value> > inline decltype(auto) filter(C&& v, P p ) { const auto n = std::copy_if( v.begin(), v.end(), v.begin(), p ); v.resize( std::distance(v.begin(), n) ); return std::move(v); } template<class C, class P> inline C filter( const C& v, P p) { C ret; std::copy_if( v.begin(), v.end(), std::back_inserter( ret ), p ); return ret; } template<class C, class P> inline bool any_of(const C& c, const P& p) { return std::any_of(c.begin(), c.end(), p); } template<class C, class V> inline bool contain(const C& c, const V& v) { return any_of(c, [&v](const auto& e){return e == v;}); } inline std::string joinStringsWith( const std::vector<std::string>& v, const std::string& delimiter) { std::string ret; const auto numStrings = v.size(); const auto lastIndex = numStrings-1; for(size_t i = 0; i < numStrings; ++i) { ret += v[i]; if( i!= lastIndex) ret += delimiter; } return ret; } inline void split(const std::string& input, char delimiter, std::vector<std::string>& ret) { using namespace std; size_t last_pos = 0; while(true) { const size_t current_pos = input.find(delimiter,last_pos); if(current_pos == string::npos) { const string substr = input.substr(last_pos, input.size() - last_pos ); ret.push_back(substr); break; } else { const string substr = input.substr(last_pos, current_pos-last_pos); ret.push_back(substr); last_pos = current_pos+1; }} } inline std::vector<std::string> split(const std::string& str, char delimiter=' ') { std::vector<std::string> ret; split(str, delimiter, ret); return ret; } #endif
fix contain() function compatibility with initializer_list
fix contain() function compatibility with initializer_list
C++
mit
VyacheslavVanin/cstructinfo,VyacheslavVanin/cstructinfo
c749e2b824c4e89d40bed41eb4002818e5d83217
stt_runner.cpp
stt_runner.cpp
#include "stt_runner.h" #include "stt_error.h" #include "core/os/memory.h" // memnew(), memdelete() STTError::Error STTRunner::start() { if (config.is_null()) { STT_ERR_PRINTS(STTError::UNDEF_CONFIG_ERR); return STTError::UNDEF_CONFIG_ERR; } if (queue.is_null()) { STT_ERR_PRINTS(STTError::UNDEF_QUEUE_ERR); return STTError::UNDEF_QUEUE_ERR; } if (is_running) stop(); is_running = true; recognition = Thread::create(STTRunner::_thread_recognize, this); return STTError::OK; } bool STTRunner::running() { return is_running; } void STTRunner::stop() { if (recognition != NULL) { is_running = false; Thread::wait_to_finish(recognition); memdelete(recognition); recognition = NULL; } } void STTRunner::_thread_recognize(void *runner) { STTRunner *self = (STTRunner *) runner; self->_recognize(); } void STTRunner::_recognize() { int16 buffer[rec_buffer_size]; int32 n; const char *hyp; // Start recording if (ad_start_rec(config->recorder) < 0) { _error_stop(STTError::REC_START_ERR); return; } // Start utterance if (ps_start_utt(config->decoder) < 0) { _error_stop(STTError::UTT_START_ERR); return; } while (is_running) { // Read data from microphone if ((n = ad_read(config->recorder, buffer, rec_buffer_size)) < 0) { _error_stop(STTError::AUDIO_READ_ERR); return; } // Process captured sound ps_process_raw(config->decoder, buffer, n, FALSE, FALSE); // Check for keyword in captured sound hyp = ps_get_hyp(config->decoder, NULL); if (hyp != NULL) { // Add new keyword to queue, if possible if (queue->add(String(hyp))) { #ifdef DEBUG_ENABLED print_line("[STTRunner] " + String(hyp)); #endif } else WARN_PRINT("Cannot store more keywords in the STTQueue!"); // Restart decoder ps_end_utt(config->decoder); if (ps_start_utt(config->decoder) < 0) { _error_stop(STTError::UTT_RESTART_ERR); return; } } } // Stop recording if (ad_stop_rec(config->recorder) < 0) _error_stop(STTError::REC_STOP_ERR); } void STTRunner::_error_stop(STTError::Error err) { STT_ERR_PRINTS(err); ad_stop_rec(config->recorder); ps_end_utt(config->decoder); emit_signal(STT_RUNNER_END_SIGNAL, err); is_running = false; } void STTRunner::set_config(const Ref<STTConfig> &p_config) { stop(); config = p_config; } Ref<STTConfig> STTRunner::get_config() const { return config; } void STTRunner::set_queue(const Ref<STTQueue> &p_queue) { stop(); queue = p_queue; } Ref<STTQueue> STTRunner::get_queue() const { return queue; } void STTRunner::set_rec_buffer_size(int rec_buffer_size) { if (rec_buffer_size <= 0) { ERR_PRINT("Microphone recorder buffer size must be greater than 0"); return; } stop(); this->rec_buffer_size = rec_buffer_size; } int STTRunner::get_rec_buffer_size() { return rec_buffer_size; } void STTRunner::_bind_methods() { ObjectTypeDB::bind_method("start", &STTRunner::start); ObjectTypeDB::bind_method("running", &STTRunner::running); ObjectTypeDB::bind_method("stop", &STTRunner::stop); ObjectTypeDB::bind_method(_MD("set_config", "stt_config"), &STTRunner::set_config); ObjectTypeDB::bind_method("get_config", &STTRunner::get_config); ObjectTypeDB::bind_method(_MD("set_queue", "stt_queue"), &STTRunner::set_queue); ObjectTypeDB::bind_method("get_queue", &STTRunner::get_queue); ObjectTypeDB::bind_method(_MD("set_rec_buffer_size", "size"), &STTRunner::set_rec_buffer_size); ObjectTypeDB::bind_method("get_rec_buffer_size", &STTRunner::get_rec_buffer_size); BIND_CONSTANT(DEFAULT_REC_BUFFER_SIZE); ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "config", PROPERTY_HINT_RESOURCE_TYPE, "STTConfig"), _SCS("set_config"), _SCS("get_config")); ADD_PROPERTY(PropertyInfo(Variant::INT, "recorder buffer size (bytes)", PROPERTY_HINT_RANGE, "256,4096,32"), _SCS("set_rec_buffer_size"), _SCS("get_rec_buffer_size")); ADD_SIGNAL(MethodInfo(STT_RUNNER_END_SIGNAL, PropertyInfo(Variant::INT, "error number"))); } STTRunner::STTRunner() { recognition = NULL; is_running = false; rec_buffer_size = DEFAULT_REC_BUFFER_SIZE; } STTRunner::~STTRunner() { if (recognition != NULL) { is_running = false; Thread::wait_to_finish(recognition); memdelete(recognition); } }
#include "stt_runner.h" #include "stt_error.h" #include "core/os/memory.h" // memnew(), memdelete() STTError::Error STTRunner::start() { if (config.is_null()) { STT_ERR_PRINTS(STTError::UNDEF_CONFIG_ERR); return STTError::UNDEF_CONFIG_ERR; } if (queue.is_null()) { STT_ERR_PRINTS(STTError::UNDEF_QUEUE_ERR); return STTError::UNDEF_QUEUE_ERR; } if (is_running) stop(); is_running = true; recognition = Thread::create(STTRunner::_thread_recognize, this); return STTError::OK; } bool STTRunner::running() { return is_running; } void STTRunner::stop() { if (recognition != NULL) { is_running = false; Thread::wait_to_finish(recognition); memdelete(recognition); recognition = NULL; } } void STTRunner::_thread_recognize(void *runner) { STTRunner *self = (STTRunner *) runner; self->_recognize(); } void STTRunner::_recognize() { int16 buffer[rec_buffer_size]; int32 n; const char *hyp; // Start recording if (ad_start_rec(config->recorder) < 0) { _error_stop(STTError::REC_START_ERR); return; } // Start utterance if (ps_start_utt(config->decoder) < 0) { _error_stop(STTError::UTT_START_ERR); return; } while (is_running) { // Read data from microphone if ((n = ad_read(config->recorder, buffer, rec_buffer_size)) < 0) { _error_stop(STTError::AUDIO_READ_ERR); return; } // Process captured sound ps_process_raw(config->decoder, buffer, n, FALSE, FALSE); // Check for keyword in captured sound hyp = ps_get_hyp(config->decoder, NULL); if (hyp != NULL) { // Add new keyword to queue, if possible if (queue->add(String(hyp))) { #ifdef DEBUG_ENABLED print_line("[STTRunner] " + String(hyp)); #endif } else WARN_PRINT("Cannot store more keywords in the STTQueue!"); // Restart decoder ps_end_utt(config->decoder); if (ps_start_utt(config->decoder) < 0) { _error_stop(STTError::UTT_RESTART_ERR); return; } } } ps_end_utt(config->decoder); // Stop recording if (ad_stop_rec(config->recorder) < 0) _error_stop(STTError::REC_STOP_ERR); } void STTRunner::_error_stop(STTError::Error err) { STT_ERR_PRINTS(err); ad_stop_rec(config->recorder); ps_end_utt(config->decoder); emit_signal(STT_RUNNER_END_SIGNAL, err); is_running = false; } void STTRunner::set_config(const Ref<STTConfig> &p_config) { stop(); config = p_config; } Ref<STTConfig> STTRunner::get_config() const { return config; } void STTRunner::set_queue(const Ref<STTQueue> &p_queue) { stop(); queue = p_queue; } Ref<STTQueue> STTRunner::get_queue() const { return queue; } void STTRunner::set_rec_buffer_size(int rec_buffer_size) { if (rec_buffer_size <= 0) { ERR_PRINT("Microphone recorder buffer size must be greater than 0"); return; } stop(); this->rec_buffer_size = rec_buffer_size; } int STTRunner::get_rec_buffer_size() { return rec_buffer_size; } void STTRunner::_bind_methods() { ObjectTypeDB::bind_method("start", &STTRunner::start); ObjectTypeDB::bind_method("running", &STTRunner::running); ObjectTypeDB::bind_method("stop", &STTRunner::stop); ObjectTypeDB::bind_method(_MD("set_config", "stt_config"), &STTRunner::set_config); ObjectTypeDB::bind_method("get_config", &STTRunner::get_config); ObjectTypeDB::bind_method(_MD("set_queue", "stt_queue"), &STTRunner::set_queue); ObjectTypeDB::bind_method("get_queue", &STTRunner::get_queue); ObjectTypeDB::bind_method(_MD("set_rec_buffer_size", "size"), &STTRunner::set_rec_buffer_size); ObjectTypeDB::bind_method("get_rec_buffer_size", &STTRunner::get_rec_buffer_size); BIND_CONSTANT(DEFAULT_REC_BUFFER_SIZE); ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "config", PROPERTY_HINT_RESOURCE_TYPE, "STTConfig"), _SCS("set_config"), _SCS("get_config")); ADD_PROPERTY(PropertyInfo(Variant::INT, "recorder buffer size (bytes)", PROPERTY_HINT_RANGE, "256,4096,32"), _SCS("set_rec_buffer_size"), _SCS("get_rec_buffer_size")); ADD_SIGNAL(MethodInfo(STT_RUNNER_END_SIGNAL, PropertyInfo(Variant::INT, "error number"))); } STTRunner::STTRunner() { recognition = NULL; is_running = false; rec_buffer_size = DEFAULT_REC_BUFFER_SIZE; } STTRunner::~STTRunner() { if (recognition != NULL) { is_running = false; Thread::wait_to_finish(recognition); memdelete(recognition); } }
Fix bug when calling start() after STTRunner stop()
Fix bug when calling start() after STTRunner stop() - Fix: Stop utterance when ending STTRunner thread
C++
mit
SamuraiSigma/speech-to-text,SamuraiSigma/speech-to-text,SamuraiSigma/speech-to-text
af8d16b9b9b85a71b75906a03ab6d5be06e0f3b7
source/chip/STM32/STM32F7/STM32F7-lowLevelInitialization.cpp
source/chip/STM32/STM32F7/STM32F7-lowLevelInitialization.cpp
/** * \file * \brief chip::lowLevelInitialization() implementation for STM32F7 * * \author Copyright (C) 2017 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "distortos/chip/lowLevelInitialization.hpp" #include "distortos/chip/CMSIS-proxy.h" #include "distortos/chip/STM32F7-FLASH.hpp" namespace distortos { namespace chip { /*---------------------------------------------------------------------------------------------------------------------+ | global functions +---------------------------------------------------------------------------------------------------------------------*/ void lowLevelInitialization() { #ifdef CONFIG_CHIP_STM32F7_FLASH_PREFETCH_ENABLE configureInstructionPrefetch(true); #else // !def CONFIG_CHIP_STM32F7_FLASH_PREFETCH_ENABLE configureInstructionPrefetch(false); #endif // !def CONFIG_CHIP_STM32F7_FLASH_PREFETCH_ENABLE #ifdef CONFIG_CHIP_STM32F7_FLASH_ART_ACCELERATOR_ENABLE enableArtAccelerator(); #else // !def CONFIG_CHIP_STM32F7_FLASH_ART_ACCELERATOR_ENABLE disableArtAccelerator(); #endif // !def CONFIG_CHIP_STM32F7_FLASH_ART_ACCELERATOR_ENABLE RCC->AHB1ENR |= #ifdef CONFIG_CHIP_STM32_GPIOV2_GPIOA_ENABLE RCC_AHB1ENR_GPIOAEN | #endif // def CONFIG_CHIP_STM32_GPIOV2_GPIOA_ENABLE #ifdef CONFIG_CHIP_STM32_GPIOV2_GPIOB_ENABLE RCC_AHB1ENR_GPIOBEN | #endif // def CONFIG_CHIP_STM32_GPIOV2_GPIOB_ENABLE #ifdef CONFIG_CHIP_STM32_GPIOV2_GPIOC_ENABLE RCC_AHB1ENR_GPIOCEN | #endif // def CONFIG_CHIP_STM32_GPIOV2_GPIOC_ENABLE #ifdef CONFIG_CHIP_STM32_GPIOV2_GPIOD_ENABLE RCC_AHB1ENR_GPIODEN | #endif // def CONFIG_CHIP_STM32_GPIOV2_GPIOD_ENABLE #ifdef CONFIG_CHIP_STM32_GPIOV2_GPIOE_ENABLE RCC_AHB1ENR_GPIOEEN | #endif // def CONFIG_CHIP_STM32_GPIOV2_GPIOE_ENABLE #ifdef CONFIG_CHIP_STM32_GPIOV2_GPIOF_ENABLE RCC_AHB1ENR_GPIOFEN | #endif // def CONFIG_CHIP_STM32_GPIOV2_GPIOF_ENABLE #ifdef CONFIG_CHIP_STM32_GPIOV2_GPIOG_ENABLE RCC_AHB1ENR_GPIOGEN | #endif // def CONFIG_CHIP_STM32_GPIOV2_GPIOG_ENABLE #ifdef CONFIG_CHIP_STM32_GPIOV2_GPIOH_ENABLE RCC_AHB1ENR_GPIOHEN | #endif // def CONFIG_CHIP_STM32_GPIOV2_GPIOH_ENABLE #ifdef CONFIG_CHIP_STM32_GPIOV2_GPIOI_ENABLE RCC_AHB1ENR_GPIOIEN | #endif // def CONFIG_CHIP_STM32_GPIOV2_GPIOI_ENABLE #ifdef CONFIG_CHIP_STM32_GPIOV2_GPIOJ_ENABLE RCC_AHB1ENR_GPIOJEN | #endif // def CONFIG_CHIP_STM32_GPIOV2_GPIOJ_ENABLE #ifdef CONFIG_CHIP_STM32_GPIOV2_GPIOK_ENABLE RCC_AHB1ENR_GPIOKEN | #endif // def CONFIG_CHIP_STM32_GPIOV2_GPIOK_ENABLE 0; } } // namespace chip } // namespace distortos
/** * \file * \brief chip::lowLevelInitialization() implementation for STM32F7 * * \author Copyright (C) 2017 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "distortos/chip/lowLevelInitialization.hpp" #include "distortos/chip/clocks.hpp" #include "distortos/chip/CMSIS-proxy.h" #include "distortos/chip/STM32F7-FLASH.hpp" #include "distortos/chip/STM32F7-PWR.hpp" #include "distortos/chip/STM32F7-RCC.hpp" namespace distortos { namespace chip { /*---------------------------------------------------------------------------------------------------------------------+ | global functions +---------------------------------------------------------------------------------------------------------------------*/ void lowLevelInitialization() { #ifdef CONFIG_CHIP_STM32F7_FLASH_PREFETCH_ENABLE configureInstructionPrefetch(true); #else // !def CONFIG_CHIP_STM32F7_FLASH_PREFETCH_ENABLE configureInstructionPrefetch(false); #endif // !def CONFIG_CHIP_STM32F7_FLASH_PREFETCH_ENABLE #ifdef CONFIG_CHIP_STM32F7_FLASH_ART_ACCELERATOR_ENABLE enableArtAccelerator(); #else // !def CONFIG_CHIP_STM32F7_FLASH_ART_ACCELERATOR_ENABLE disableArtAccelerator(); #endif // !def CONFIG_CHIP_STM32F7_FLASH_ART_ACCELERATOR_ENABLE #ifdef CONFIG_CHIP_STM32F7_STANDARD_CLOCK_CONFIGURATION_ENABLE RCC->APB1ENR |= RCC_APB1ENR_PWREN; configureVoltageScaling(CONFIG_CHIP_STM32F7_PWR_VOLTAGE_SCALE_MODE); #if defined(CONFIG_CHIP_STM32F7_PWR_OVER_DRIVE_ENABLE) enableOverDriveMode(); #endif // defined(CONFIG_CHIP_STM32F7_PWR_OVER_DRIVE_ENABLE) #ifdef CONFIG_CHIP_STM32F7_RCC_HSE_ENABLE #ifdef CONFIG_CHIP_STM32F7_RCC_HSE_CLOCK_BYPASS enableHse(true); #else // !def CONFIG_CHIP_STM32F7_RCC_HSE_CLOCK_BYPASS enableHse(false); #endif // !def CONFIG_CHIP_STM32F7_RCC_HSE_CLOCK_BYPASS #endif // def CONFIG_CHIP_STM32F7_RCC_HSE_ENABLE #ifdef CONFIG_CHIP_STM32F7_RCC_PLL_ENABLE #if defined(CONFIG_CHIP_STM32F7_RCC_PLLSRC_HSI) configurePllClockSource(false); #elif defined(CONFIG_CHIP_STM32F7_RCC_PLLSRC_HSE) configurePllClockSource(true); #endif configurePllInputClockDivider(CONFIG_CHIP_STM32F7_RCC_PLLM); #if defined(CONFIG_CHIP_STM32F76) || defined(CONFIG_CHIP_STM32F77) enablePll(CONFIG_CHIP_STM32F7_RCC_PLLN, CONFIG_CHIP_STM32F7_RCC_PLLP, CONFIG_CHIP_STM32F7_RCC_PLLQ, CONFIG_CHIP_STM32F7_RCC_PLLR); #else // !defined(CONFIG_CHIP_STM32F76) && !defined(CONFIG_CHIP_STM32F77) enablePll(CONFIG_CHIP_STM32F7_RCC_PLLN, CONFIG_CHIP_STM32F7_RCC_PLLP, CONFIG_CHIP_STM32F7_RCC_PLLQ); #endif // !defined(CONFIG_CHIP_STM32F76) && !defined(CONFIG_CHIP_STM32F77) #endif // def CONFIG_CHIP_STM32F7_RCC_PLL_ENABLE configureAhbClockDivider(CONFIG_CHIP_STM32F7_RCC_HPRE); configureApbClockDivider(false, CONFIG_CHIP_STM32F7_RCC_PPRE1); configureApbClockDivider(true, CONFIG_CHIP_STM32F7_RCC_PPRE2); #if CONFIG_CHIP_STM32F7_VDD_MV < 2100 constexpr uint32_t frequencyThreshold {20000000}; #elif CONFIG_CHIP_STM32F7_VDD_MV < 2400 constexpr uint32_t frequencyThreshold {22000000}; #elif CONFIG_CHIP_STM32F7_VDD_MV < 2700 constexpr uint32_t frequencyThreshold {24000000}; #else constexpr uint32_t frequencyThreshold {30000000}; #endif constexpr uint8_t flashLatency {(ahbFrequency - 1) / frequencyThreshold}; static_assert(flashLatency <= maxFlashLatency, "Invalid flash latency!"); configureFlashLatency(flashLatency); #if defined(CONFIG_CHIP_STM32F7_RCC_SYSCLK_HSI) switchSystemClock(SystemClockSource::hsi); #elif defined(CONFIG_CHIP_STM32F7_RCC_SYSCLK_HSE) switchSystemClock(SystemClockSource::hse); #elif defined(CONFIG_CHIP_STM32F7_RCC_SYSCLK_PLL) switchSystemClock(SystemClockSource::pll); #endif // defined(CONFIG_CHIP_STM32F7_RCC_SYSCLK_PLL) #endif // def CONFIG_CHIP_STM32F7_STANDARD_CLOCK_CONFIGURATION_ENABLE RCC->AHB1ENR |= #ifdef CONFIG_CHIP_STM32_GPIOV2_GPIOA_ENABLE RCC_AHB1ENR_GPIOAEN | #endif // def CONFIG_CHIP_STM32_GPIOV2_GPIOA_ENABLE #ifdef CONFIG_CHIP_STM32_GPIOV2_GPIOB_ENABLE RCC_AHB1ENR_GPIOBEN | #endif // def CONFIG_CHIP_STM32_GPIOV2_GPIOB_ENABLE #ifdef CONFIG_CHIP_STM32_GPIOV2_GPIOC_ENABLE RCC_AHB1ENR_GPIOCEN | #endif // def CONFIG_CHIP_STM32_GPIOV2_GPIOC_ENABLE #ifdef CONFIG_CHIP_STM32_GPIOV2_GPIOD_ENABLE RCC_AHB1ENR_GPIODEN | #endif // def CONFIG_CHIP_STM32_GPIOV2_GPIOD_ENABLE #ifdef CONFIG_CHIP_STM32_GPIOV2_GPIOE_ENABLE RCC_AHB1ENR_GPIOEEN | #endif // def CONFIG_CHIP_STM32_GPIOV2_GPIOE_ENABLE #ifdef CONFIG_CHIP_STM32_GPIOV2_GPIOF_ENABLE RCC_AHB1ENR_GPIOFEN | #endif // def CONFIG_CHIP_STM32_GPIOV2_GPIOF_ENABLE #ifdef CONFIG_CHIP_STM32_GPIOV2_GPIOG_ENABLE RCC_AHB1ENR_GPIOGEN | #endif // def CONFIG_CHIP_STM32_GPIOV2_GPIOG_ENABLE #ifdef CONFIG_CHIP_STM32_GPIOV2_GPIOH_ENABLE RCC_AHB1ENR_GPIOHEN | #endif // def CONFIG_CHIP_STM32_GPIOV2_GPIOH_ENABLE #ifdef CONFIG_CHIP_STM32_GPIOV2_GPIOI_ENABLE RCC_AHB1ENR_GPIOIEN | #endif // def CONFIG_CHIP_STM32_GPIOV2_GPIOI_ENABLE #ifdef CONFIG_CHIP_STM32_GPIOV2_GPIOJ_ENABLE RCC_AHB1ENR_GPIOJEN | #endif // def CONFIG_CHIP_STM32_GPIOV2_GPIOJ_ENABLE #ifdef CONFIG_CHIP_STM32_GPIOV2_GPIOK_ENABLE RCC_AHB1ENR_GPIOKEN | #endif // def CONFIG_CHIP_STM32_GPIOV2_GPIOK_ENABLE 0; } } // namespace chip } // namespace distortos
Update STM32F7's low-level init in preparation for standard clock config
Update STM32F7's low-level init in preparation for standard clock config
C++
mpl-2.0
jasmin-j/distortos,CezaryGapinski/distortos,jasmin-j/distortos,CezaryGapinski/distortos,DISTORTEC/distortos,CezaryGapinski/distortos,jasmin-j/distortos,jasmin-j/distortos,CezaryGapinski/distortos,CezaryGapinski/distortos,DISTORTEC/distortos,DISTORTEC/distortos,DISTORTEC/distortos,jasmin-j/distortos
0a696eaaf1ef301fec0f16b2c2d7f1ca3b0a997e
bench.cpp
bench.cpp
#include "include/kdbush.hpp" #include <chrono> #include <iostream> #include <random> #include <vector> int main() { std::random_device rd; std::mt19937 gen(rd()); std::uniform_int_distribution<> dis(-10000, 10000); using Point = std::pair<int, int>; const std::size_t num_points = 1000000; std::vector<Point> points; points.reserve(num_points); for (std::size_t i = 0; i < num_points; i++) { points.emplace_back(dis(gen), dis(gen)); } const auto started = std::chrono::high_resolution_clock::now(); kdbush::KDBush<Point> index(points); const auto finished = std::chrono::high_resolution_clock::now(); const auto duration = std::chrono::duration_cast<std::chrono::nanoseconds>(finished - started).count(); std::cerr << "indexed 1M points in " << (duration / 1e6) << "ms\n"; return 0; }
#include "include/kdbush.hpp" #include <chrono> #include <iostream> #include <random> #include <vector> int main() { std::mt19937 gen(0); std::uniform_int_distribution<> dis(-10000, 10000); using Point = std::pair<int, int>; const std::size_t num_points = 1000000; std::vector<Point> points; points.reserve(num_points); for (std::size_t i = 0; i < num_points; i++) { points.emplace_back(dis(gen), dis(gen)); } const auto started = std::chrono::high_resolution_clock::now(); kdbush::KDBush<Point> index(points); const auto finished = std::chrono::high_resolution_clock::now(); const auto duration = std::chrono::duration_cast<std::chrono::nanoseconds>(finished - started).count(); std::cerr << "indexed 1M points in " << (duration / 1e6) << "ms\n"; return 0; }
use fixed seed for bench random data
use fixed seed for bench random data
C++
isc
mourner/kdbush.hpp
4919857fb5ab7556bdad0b3c98cac8dcb641c730
tools/pbprint.cc
tools/pbprint.cc
#include <cstring> #include <fstream> #include <iomanip> #include <iostream> #include <vector> #include <asio.hpp> #include <asio/serial_port.hpp> #include <asio/signal_set.hpp> #include <google/protobuf/io/coded_stream.h> #include "cobs.h" #include "pose.pb.h" #include "simulation.pb.h" namespace { using std::size_t; asio::io_service io_service; asio::serial_port port(io_service); std::ifstream* input_file = nullptr; // serial port // --[read]--> serial_buffer // --[cobs decode]--> packet_buffer // --[protobuf deserialize]--> message_object constexpr size_t SERIAL_BUFFER_CAPACITY = 2000; uint8_t serial_buffer_start[SERIAL_BUFFER_CAPACITY]; uint8_t * serial_buffer_write = serial_buffer_start; uint8_t * const serial_buffer_end = serial_buffer_start + SERIAL_BUFFER_CAPACITY; void handle_read(const asio::error_code&, size_t); void start_read() { const size_t serial_buffer_remaining = serial_buffer_end - serial_buffer_write; port.async_read_some( asio::buffer(serial_buffer_write, serial_buffer_remaining), &handle_read ); } void start_read(std::ifstream* ifs) { const size_t serial_buffer_remaining = serial_buffer_end - serial_buffer_write; const size_t bytes_read = ifs->readsome(reinterpret_cast<char*>(serial_buffer_write), serial_buffer_remaining); if (bytes_read > 0) { asio::error_code error; handle_read(error, bytes_read); } } void deserialize_packet(const uint8_t * const packet_buffer_start, const size_t packet_buffer_length) { google::protobuf::io::CodedInputStream input( packet_buffer_start, packet_buffer_length ); uint32_t size; if (!input.ReadVarint32(&size)) { std::cerr << "Unable to decode packet size from serialized data." << std::endl; exit(EXIT_FAILURE); } SimulationMessage msg; if (!msg.ParsePartialFromCodedStream(&input)) { std::cerr << "Unable to parse protobuf message." << std::endl; exit(EXIT_FAILURE); } if (!input.ConsumedEntireMessage()) { std::cerr << "Entire message not consumed. Number of extra bytes: " << input.BytesUntilLimit() << std::endl; exit(EXIT_FAILURE); } msg.PrintDebugString(); } void handle_read(const asio::error_code& error, size_t serial_buffer_write_count) { if (error) { std::cerr << error.message() << std::endl; exit(EXIT_FAILURE); } // Update the location we will write to next time. This is // simultaneously the end of the readable part of serial_buffer. serial_buffer_write += serial_buffer_write_count; // Decode as many packets as possible starting from serial_buffer_start. const uint8_t * serial_buffer = serial_buffer_start; while (serial_buffer < serial_buffer_write) { // Compute the remaining length. const size_t serial_buffer_len = serial_buffer_write - serial_buffer; // Create an output buffer and decode into it. std::array<uint8_t, 2000> packet_buffer; cobs::DecodeResult result = cobs::decode( serial_buffer, serial_buffer_len, packet_buffer.data(), packet_buffer.size() ); switch (result.status) { case cobs::DecodeResult::Status::OK: { serial_buffer += result.consumed; // Decoded result.consumed bytes into result.produced bytes. deserialize_packet(packet_buffer.data(), result.produced); continue; } case cobs::DecodeResult::Status::WRITE_OVERFLOW: { std::cerr << "Package too large to decode." << std::endl; exit(EXIT_FAILURE); } case cobs::DecodeResult::Status::READ_OVERFLOW: { // Hitting a read overflow is usually not a problem. It just // means that the encoded data is not fully available yet. If // however we were decoding using the entire buffer and still // hit a read overflow... if (serial_buffer == serial_buffer_start && serial_buffer_write == serial_buffer_end) { // ...we need a bigger serial_buffer. std::cerr << "Encoded package does not fit in read buffer." << std::endl; exit(EXIT_FAILURE); } break; } case cobs::DecodeResult::Status::UNEXPECTED_ZERO: { serial_buffer += result.consumed; std::cout << "Unexpected zero, resuming decoding at next byte." << std::endl; continue; } default: { std::cerr << "Unknown DecodeResult::Status." << std::endl; exit(EXIT_FAILURE); } } // Break the loop by default. break; } // Shove remaining bytes in buffer back to the beginning, making sure // new data is written after these left-over bytes. const size_t serial_buffer_remaining = serial_buffer_write - serial_buffer; std::memmove(serial_buffer_start, serial_buffer, serial_buffer_remaining); serial_buffer_write = serial_buffer_start + serial_buffer_remaining; // Start another read operation. if (input_file == nullptr) { start_read(); } else { start_read(input_file); } } void handle_stop(const asio::error_code&, int signal_number) { if ((signal_number == SIGINT) || (signal_number == SIGTERM)) { io_service.stop(); } } } // namespace int main(int argc, char* argv[]) { GOOGLE_PROTOBUF_VERIFY_VERSION; if (argc < 2) { std::cerr << "Usage: " << argv[0] << " <serial_device> [<baud_rate>]\n\n" << "Decode streaming serialized simulation protobuf messages.\n" << " <serial_device> device or file from which to read serial data\n" << " <baud_rate=115200> serial baud rate\n" << "A virtual serial port can be created using socat with:\n" << " $ socat -d -d pty,raw,echo=0 pty,raw,echo=0\n\n" << "This can be used to decode a log file of the serialized protobuf stream data.\n" << "Here is an example:\n" << " $ socat -d -d pty,raw,echo=0 pty,raw,echo=0\n" << " 2017/02/17 18:00:30 socat[71176] N PTY is /dev/ttys009\n" << " 2017/02/17 18:00:30 socat[71176] N PTY is /dev/ttys010\n" << " 2017/02/17 18:00:30 socat[71176] N starting data transfer loop with FDs [5,5] and [7,7]\n\n" << " $ ./pbprint /dev/ttys010\n\n" << " $ cat log.pb.cobs > /dev/ttys009\n"; return EXIT_FAILURE; } const std::string devname(argv[1]); uint32_t baud_rate = 115200; if (argc > 2) { baud_rate = std::atoi(argv[2]); } try { port.open(devname); } catch (const std::system_error& e) { // assume we have a file std::ifstream ifs(devname, std::ios::binary); input_file = &ifs; start_read(input_file); return EXIT_SUCCESS; } port.set_option(asio::serial_port_base::baud_rate(baud_rate)); port.set_option(asio::serial_port_base::parity(asio::serial_port_base::parity::none)); port.set_option(asio::serial_port_base::character_size(8)); port.set_option(asio::serial_port_base::flow_control(asio::serial_port_base::flow_control::none)); port.set_option(asio::serial_port_base::stop_bits(asio::serial_port_base::stop_bits::one)); asio::signal_set signals(io_service, SIGINT, SIGTERM); signals.async_wait(handle_stop); start_read(); io_service.run(); return EXIT_SUCCESS; }
#include <cstring> #include <fstream> #include <iomanip> #include <iostream> #include <vector> #include <asio.hpp> #include <asio/serial_port.hpp> #include <asio/signal_set.hpp> #include <google/protobuf/io/coded_stream.h> #include "cobs.h" #include "pose.pb.h" #include "simulation.pb.h" namespace { using std::size_t; asio::io_service io_service; asio::serial_port port(io_service); std::ifstream* input_file = nullptr; // serial port // --[read]--> serial_buffer // --[cobs decode]--> packet_buffer // --[protobuf deserialize]--> message_object constexpr size_t SERIAL_BUFFER_CAPACITY = 2000; uint8_t serial_buffer_start[SERIAL_BUFFER_CAPACITY]; uint8_t * serial_buffer_write = serial_buffer_start; uint8_t * const serial_buffer_end = serial_buffer_start + SERIAL_BUFFER_CAPACITY; void handle_read(const asio::error_code&, size_t); void start_read() { const size_t serial_buffer_remaining = serial_buffer_end - serial_buffer_write; port.async_read_some( asio::buffer(serial_buffer_write, serial_buffer_remaining), &handle_read ); } void start_read(std::ifstream* ifs) { const size_t serial_buffer_remaining = serial_buffer_end - serial_buffer_write; ifs->read(reinterpret_cast<char*>(serial_buffer_write), serial_buffer_remaining); const size_t bytes_read = ifs->gcount(); if (bytes_read > 0) { asio::error_code error; handle_read(error, bytes_read); } } void deserialize_packet(const uint8_t * const packet_buffer_start, const size_t packet_buffer_length) { google::protobuf::io::CodedInputStream input( packet_buffer_start, packet_buffer_length ); uint32_t size; if (!input.ReadVarint32(&size)) { std::cerr << "Unable to decode packet size from serialized data." << std::endl; exit(EXIT_FAILURE); } SimulationMessage msg; if (!msg.ParsePartialFromCodedStream(&input)) { std::cerr << "Unable to parse protobuf message." << std::endl; exit(EXIT_FAILURE); } if (!input.ConsumedEntireMessage()) { std::cerr << "Entire message not consumed. Number of extra bytes: " << input.BytesUntilLimit() << std::endl; exit(EXIT_FAILURE); } msg.PrintDebugString(); } void handle_read(const asio::error_code& error, size_t serial_buffer_write_count) { if (error) { std::cerr << error.message() << std::endl; exit(EXIT_FAILURE); } // Update the location we will write to next time. This is // simultaneously the end of the readable part of serial_buffer. serial_buffer_write += serial_buffer_write_count; // Decode as many packets as possible starting from serial_buffer_start. const uint8_t * serial_buffer = serial_buffer_start; while (serial_buffer < serial_buffer_write) { // Compute the remaining length. const size_t serial_buffer_len = serial_buffer_write - serial_buffer; // Create an output buffer and decode into it. std::array<uint8_t, 2000> packet_buffer; cobs::DecodeResult result = cobs::decode( serial_buffer, serial_buffer_len, packet_buffer.data(), packet_buffer.size() ); switch (result.status) { case cobs::DecodeResult::Status::OK: { serial_buffer += result.consumed; // Decoded result.consumed bytes into result.produced bytes. deserialize_packet(packet_buffer.data(), result.produced); continue; } case cobs::DecodeResult::Status::WRITE_OVERFLOW: { std::cerr << "Package too large to decode." << std::endl; exit(EXIT_FAILURE); } case cobs::DecodeResult::Status::READ_OVERFLOW: { // Hitting a read overflow is usually not a problem. It just // means that the encoded data is not fully available yet. If // however we were decoding using the entire buffer and still // hit a read overflow... if (serial_buffer == serial_buffer_start && serial_buffer_write == serial_buffer_end) { // ...we need a bigger serial_buffer. std::cerr << "Encoded package does not fit in read buffer." << std::endl; exit(EXIT_FAILURE); } break; } case cobs::DecodeResult::Status::UNEXPECTED_ZERO: { serial_buffer += result.consumed; std::cout << "Unexpected zero, resuming decoding at next byte." << std::endl; continue; } default: { std::cerr << "Unknown DecodeResult::Status." << std::endl; exit(EXIT_FAILURE); } } // Break the loop by default. break; } // Shove remaining bytes in buffer back to the beginning, making sure // new data is written after these left-over bytes. const size_t serial_buffer_remaining = serial_buffer_write - serial_buffer; std::memmove(serial_buffer_start, serial_buffer, serial_buffer_remaining); serial_buffer_write = serial_buffer_start + serial_buffer_remaining; // Start another read operation. if (input_file == nullptr) { start_read(); } else { start_read(input_file); } } void handle_stop(const asio::error_code&, int signal_number) { if ((signal_number == SIGINT) || (signal_number == SIGTERM)) { io_service.stop(); } } } // namespace int main(int argc, char* argv[]) { GOOGLE_PROTOBUF_VERIFY_VERSION; if (argc < 2) { std::cerr << "Usage: " << argv[0] << " <serial_device> [<baud_rate>]\n\n" << "Decode streaming serialized simulation protobuf messages.\n" << " <serial_device> device or file from which to read serial data\n" << " <baud_rate=115200> serial baud rate\n" << "A virtual serial port can be created using socat with:\n" << " $ socat -d -d pty,raw,echo=0 pty,raw,echo=0\n\n" << "This can be used to decode a log file of the serialized protobuf stream data.\n" << "Here is an example:\n" << " $ socat -d -d pty,raw,echo=0 pty,raw,echo=0\n" << " 2017/02/17 18:00:30 socat[71176] N PTY is /dev/ttys009\n" << " 2017/02/17 18:00:30 socat[71176] N PTY is /dev/ttys010\n" << " 2017/02/17 18:00:30 socat[71176] N starting data transfer loop with FDs [5,5] and [7,7]\n\n" << " $ ./pbprint /dev/ttys010\n\n" << " $ cat log.pb.cobs > /dev/ttys009\n"; return EXIT_FAILURE; } const std::string devname(argv[1]); uint32_t baud_rate = 115200; if (argc > 2) { baud_rate = std::atoi(argv[2]); } try { port.open(devname); } catch (const std::system_error& e) { // assume we have a file std::ifstream ifs(devname, std::ios::binary); input_file = &ifs; start_read(input_file); return EXIT_SUCCESS; } port.set_option(asio::serial_port_base::baud_rate(baud_rate)); port.set_option(asio::serial_port_base::parity(asio::serial_port_base::parity::none)); port.set_option(asio::serial_port_base::character_size(8)); port.set_option(asio::serial_port_base::flow_control(asio::serial_port_base::flow_control::none)); port.set_option(asio::serial_port_base::stop_bits(asio::serial_port_base::stop_bits::one)); asio::signal_set signals(io_service, SIGINT, SIGTERM); signals.async_wait(handle_stop); start_read(); io_service.run(); return EXIT_SUCCESS; }
Fix pbprint file read
Fix pbprint file read Replace use of std::basic_istream::readsome with std::basic_istream::read due to standard library implementation-specific file read failures.
C++
bsd-2-clause
oliverlee/phobos,oliverlee/phobos,oliverlee/phobos,oliverlee/phobos
8e01e567cfa0b0e76e0a5f301b6edeb2f122489c
core/src/style/style.cpp
core/src/style/style.cpp
#include "style.h" #include "scene/scene.h" #include "scene/sceneLayer.h" #include "scene/light.h" #include "tile/tile.h" #include "gl/vboMesh.h" #include "view/view.h" #include "glm/gtc/type_ptr.hpp" namespace Tangram { Style::Style(std::string _name, Blending _blendMode, GLenum _drawMode) : m_name(_name), m_blend(_blendMode), m_drawMode(_drawMode), m_contextLost(true) { } Style::~Style() {} void Style::build(const std::vector<std::unique_ptr<Light>>& _lights) { constructVertexLayout(); constructShaderProgram(); switch (m_lightingType) { case LightingType::vertex: m_shaderProgram->addSourceBlock("defines", "#define TANGRAM_LIGHTING_VERTEX\n", false); break; case LightingType::fragment: m_shaderProgram->addSourceBlock("defines", "#define TANGRAM_LIGHTING_FRAGMENT\n", false); break; default: break; } m_material->injectOnProgram(*m_shaderProgram); for (auto& light : _lights) { light->injectOnProgram(*m_shaderProgram); } } void Style::setMaterial(const std::shared_ptr<Material>& _material) { m_material = _material; } void Style::setLightingType(LightingType _type){ m_lightingType = _type; } void Style::buildFeature(Tile& _tile, const Feature& _feat, const DrawRule& _rule) const { auto& mesh = _tile.getMesh(*this); if (!mesh) { mesh.reset(newMesh()); } switch (_feat.geometryType) { case GeometryType::points: for (auto& point : _feat.points) { buildPoint(point, _rule, _feat.props, *mesh, _tile); } break; case GeometryType::lines: for (auto& line : _feat.lines) { buildLine(line, _rule, _feat.props, *mesh, _tile); } break; case GeometryType::polygons: for (auto& polygon : _feat.polygons) { buildPolygon(polygon, _rule, _feat.props, *mesh, _tile); } break; default: break; } } void Style::setupShaderUniforms(int _textureUnit, bool _update, Scene& _scene) { for (const auto& uniformPair : m_styleUniforms) { const auto& name = uniformPair.first; const auto& value = uniformPair.second; auto& textures = _scene.textures(); if (value.is<std::string>()) { auto& tex = textures[value.get<std::string>()]; tex->update(_textureUnit); tex->bind(_textureUnit); if (_update) { m_shaderProgram->setUniformi(name, _textureUnit); } _textureUnit++; } else { if (!_update) { continue; } if (value.is<bool>()) { m_shaderProgram->setUniformi(name, value.get<bool>()); } else if(value.is<float>()) { m_shaderProgram->setUniformf(name, value.get<float>()); } else if(value.is<glm::vec2>()) { m_shaderProgram->setUniformf(name, value.get<glm::vec2>()); } else if(value.is<glm::vec3>()) { m_shaderProgram->setUniformf(name, value.get<glm::vec3>()); } else if(value.is<glm::vec4>()) { m_shaderProgram->setUniformf(name, value.get<glm::vec4>()); } else { // TODO: Throw away uniform on loading! // none_type } } } } void Style::onBeginDrawFrame(const View& _view, Scene& _scene) { bool contextLost = glContextLost(); m_material->setupProgram(*m_shaderProgram); // Set up lights for (const auto& light : _scene.lights()) { light->setupProgram(_view, *m_shaderProgram); } // Set Map Position if (m_dirtyViewport) { m_shaderProgram->setUniformf("u_resolution", _view.getWidth(), _view.getHeight()); } const auto& mapPos = _view.getPosition(); m_shaderProgram->setUniformf("u_map_position", mapPos.x, mapPos.y, _view.getZoom()); m_shaderProgram->setUniformMatrix3f("u_normalMatrix", glm::value_ptr(_view.getNormalMatrix())); m_shaderProgram->setUniformf("u_meters_per_pixel", _view.pixelsPerMeter()); m_shaderProgram->setUniformMatrix4f("u_view", glm::value_ptr(_view.getViewMatrix())); m_shaderProgram->setUniformMatrix4f("u_proj", glm::value_ptr(_view.getProjectionMatrix())); setupShaderUniforms(0, contextLost, _scene); // Configure render state switch (m_blend) { case Blending::none: RenderState::blending(GL_FALSE); RenderState::blendingFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); RenderState::depthTest(GL_TRUE); RenderState::depthWrite(GL_TRUE); break; case Blending::add: RenderState::blending(GL_TRUE); RenderState::blendingFunc(GL_ONE, GL_ONE); RenderState::depthTest(GL_FALSE); RenderState::depthWrite(GL_TRUE); break; case Blending::multiply: RenderState::blending(GL_TRUE); RenderState::blendingFunc(GL_ZERO, GL_SRC_COLOR); RenderState::depthTest(GL_FALSE); RenderState::depthWrite(GL_TRUE); break; case Blending::overlay: RenderState::blending(GL_TRUE); RenderState::blendingFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); RenderState::depthTest(GL_FALSE); RenderState::depthWrite(GL_FALSE); break; case Blending::inlay: // TODO: inlay does not behave correctly for labels because they don't have a z position RenderState::blending(GL_TRUE); RenderState::blendingFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); RenderState::depthTest(GL_TRUE); RenderState::depthWrite(GL_FALSE); break; default: break; } } void Style::onBeginBuildTile(Tile& _tile) const { // No-op by default } void Style::onEndBuildTile(Tile& _tile) const { // No-op by default } void Style::buildPoint(const Point& _point, const DrawRule& _rule, const Properties& _props, VboMesh& _mesh, Tile& _tile) const { // No-op by default } void Style::buildLine(const Line& _line, const DrawRule& _rule, const Properties& _props, VboMesh& _mesh, Tile& _tile) const { // No-op by default } void Style::buildPolygon(const Polygon& _polygon, const DrawRule& _rule, const Properties& _props, VboMesh& _mesh, Tile& _tile) const { // No-op by default } bool Style::glContextLost() { bool contextLost = m_contextLost; if (m_contextLost) { m_contextLost = false; } return contextLost; } }
#include "style.h" #include "scene/scene.h" #include "scene/sceneLayer.h" #include "scene/light.h" #include "tile/tile.h" #include "gl/vboMesh.h" #include "view/view.h" #include "glm/gtc/type_ptr.hpp" namespace Tangram { Style::Style(std::string _name, Blending _blendMode, GLenum _drawMode) : m_name(_name), m_blend(_blendMode), m_drawMode(_drawMode), m_contextLost(true) { } Style::~Style() {} void Style::build(const std::vector<std::unique_ptr<Light>>& _lights) { constructVertexLayout(); constructShaderProgram(); switch (m_lightingType) { case LightingType::vertex: m_shaderProgram->addSourceBlock("defines", "#define TANGRAM_LIGHTING_VERTEX\n", false); break; case LightingType::fragment: m_shaderProgram->addSourceBlock("defines", "#define TANGRAM_LIGHTING_FRAGMENT\n", false); break; default: break; } m_material->injectOnProgram(*m_shaderProgram); for (auto& light : _lights) { light->injectOnProgram(*m_shaderProgram); } } void Style::setMaterial(const std::shared_ptr<Material>& _material) { m_material = _material; } void Style::setLightingType(LightingType _type){ m_lightingType = _type; } void Style::buildFeature(Tile& _tile, const Feature& _feat, const DrawRule& _rule) const { auto& mesh = _tile.getMesh(*this); if (!mesh) { mesh.reset(newMesh()); } switch (_feat.geometryType) { case GeometryType::points: for (auto& point : _feat.points) { buildPoint(point, _rule, _feat.props, *mesh, _tile); } break; case GeometryType::lines: for (auto& line : _feat.lines) { buildLine(line, _rule, _feat.props, *mesh, _tile); } break; case GeometryType::polygons: for (auto& polygon : _feat.polygons) { buildPolygon(polygon, _rule, _feat.props, *mesh, _tile); } break; default: break; } } void Style::setupShaderUniforms(int _textureUnit, bool _update, Scene& _scene) { for (const auto& uniformPair : m_styleUniforms) { const auto& name = uniformPair.first; const auto& value = uniformPair.second; auto& textures = _scene.textures(); if (value.is<std::string>()) { auto& tex = textures[value.get<std::string>()]; tex->update(_textureUnit); tex->bind(_textureUnit); if (_update) { m_shaderProgram->setUniformi(name, _textureUnit); } _textureUnit++; } else { if (!_update) { continue; } if (value.is<bool>()) { m_shaderProgram->setUniformi(name, value.get<bool>()); } else if(value.is<float>()) { m_shaderProgram->setUniformf(name, value.get<float>()); } else if(value.is<glm::vec2>()) { m_shaderProgram->setUniformf(name, value.get<glm::vec2>()); } else if(value.is<glm::vec3>()) { m_shaderProgram->setUniformf(name, value.get<glm::vec3>()); } else if(value.is<glm::vec4>()) { m_shaderProgram->setUniformf(name, value.get<glm::vec4>()); } else { // TODO: Throw away uniform on loading! // none_type } } } } void Style::onBeginDrawFrame(const View& _view, Scene& _scene) { bool contextLost = glContextLost(); m_material->setupProgram(*m_shaderProgram); // Set up lights for (const auto& light : _scene.lights()) { light->setupProgram(_view, *m_shaderProgram); } // Set Map Position if (m_dirtyViewport) { m_shaderProgram->setUniformf("u_resolution", _view.getWidth(), _view.getHeight()); } const auto& mapPos = _view.getPosition(); m_shaderProgram->setUniformf("u_map_position", mapPos.x, mapPos.y, _view.getZoom()); m_shaderProgram->setUniformMatrix3f("u_normalMatrix", glm::value_ptr(_view.getNormalMatrix())); m_shaderProgram->setUniformf("u_meters_per_pixel", 1.0 / _view.pixelsPerMeter()); m_shaderProgram->setUniformMatrix4f("u_view", glm::value_ptr(_view.getViewMatrix())); m_shaderProgram->setUniformMatrix4f("u_proj", glm::value_ptr(_view.getProjectionMatrix())); setupShaderUniforms(0, contextLost, _scene); // Configure render state switch (m_blend) { case Blending::none: RenderState::blending(GL_FALSE); RenderState::blendingFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); RenderState::depthTest(GL_TRUE); RenderState::depthWrite(GL_TRUE); break; case Blending::add: RenderState::blending(GL_TRUE); RenderState::blendingFunc(GL_ONE, GL_ONE); RenderState::depthTest(GL_FALSE); RenderState::depthWrite(GL_TRUE); break; case Blending::multiply: RenderState::blending(GL_TRUE); RenderState::blendingFunc(GL_ZERO, GL_SRC_COLOR); RenderState::depthTest(GL_FALSE); RenderState::depthWrite(GL_TRUE); break; case Blending::overlay: RenderState::blending(GL_TRUE); RenderState::blendingFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); RenderState::depthTest(GL_FALSE); RenderState::depthWrite(GL_FALSE); break; case Blending::inlay: // TODO: inlay does not behave correctly for labels because they don't have a z position RenderState::blending(GL_TRUE); RenderState::blendingFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); RenderState::depthTest(GL_TRUE); RenderState::depthWrite(GL_FALSE); break; default: break; } } void Style::onBeginBuildTile(Tile& _tile) const { // No-op by default } void Style::onEndBuildTile(Tile& _tile) const { // No-op by default } void Style::buildPoint(const Point& _point, const DrawRule& _rule, const Properties& _props, VboMesh& _mesh, Tile& _tile) const { // No-op by default } void Style::buildLine(const Line& _line, const DrawRule& _rule, const Properties& _props, VboMesh& _mesh, Tile& _tile) const { // No-op by default } void Style::buildPolygon(const Polygon& _polygon, const DrawRule& _rule, const Properties& _props, VboMesh& _mesh, Tile& _tile) const { // No-op by default } bool Style::glContextLost() { bool contextLost = m_contextLost; if (m_contextLost) { m_contextLost = false; } return contextLost; } }
Fix 'u_meters_per_pixel' assignment
Fix 'u_meters_per_pixel' assignment
C++
mit
cleeus/tangram-es,cleeus/tangram-es,tangrams/tangram-es,tangrams/tangram-es,tangrams/tangram-es,cleeus/tangram-es,quitejonny/tangram-es,quitejonny/tangram-es,quitejonny/tangram-es,cleeus/tangram-es,cleeus/tangram-es,tangrams/tangram-es,tangrams/tangram-es,quitejonny/tangram-es,quitejonny/tangram-es,tangrams/tangram-es,tangrams/tangram-es,cleeus/tangram-es,quitejonny/tangram-es
b4a00833fdfa84aec50497a090040842e8d793d0
src/DebugVisitor.cpp
src/DebugVisitor.cpp
//======================================================================= // Copyright Baptiste Wicht 2011. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= #include <iostream> #include "DebugVisitor.hpp" #include "VisitorUtils.hpp" #include "ast/Program.hpp" using namespace eddic; DebugVisitor::DebugVisitor() : level(0) {} std::string DebugVisitor::indent() const { std::string acc = ""; for(int i = 0; i < level; ++i){ acc += "\t"; } return acc; } void DebugVisitor::operator()(ast::Program& program) const { std::cout << indent() << "Program" << std::endl; ++level; visit_each(*this, program.Content->blocks); } void DebugVisitor::operator()(ast::FunctionDeclaration& declaration) const { std::cout << indent() << "Function " << declaration.Content->functionName << std::endl; ++level; visit_each(*this, declaration.Content->instructions); --level; } void DebugVisitor::operator()(ast::GlobalVariableDeclaration&) const { std::cout << indent() << "Global Variable" << std::endl; } void DebugVisitor::operator()(ast::GlobalArrayDeclaration&) const { std::cout << indent() << "Global Array" << std::endl; } void DebugVisitor::operator()(ast::For& for_) const { std::cout << indent() << "For" << std::endl; ++level; visit_each(*this, for_.Content->instructions); --level; } void DebugVisitor::operator()(ast::Foreach& for_) const { std::cout << indent() << "Foreach" << std::endl; ++level; visit_each(*this, for_.Content->instructions); --level; } void DebugVisitor::operator()(ast::ForeachIn& for_) const { std::cout << indent() << "Foreach in " << std::endl; ++level; visit_each(*this, for_.Content->instructions); --level; } void DebugVisitor::operator()(ast::While& while_) const { std::cout << indent() << "While" << std::endl; ++level; visit_each(*this, while_.Content->instructions); --level; } void DebugVisitor::operator()(ast::Swap&) const { std::cout << indent() << "Swap" << std::endl; } void DebugVisitor::operator()(ast::If& if_) const { std::cout << indent() << "If" << std::endl; ++level; visit_each(*this, if_.Content->instructions); --level; } void DebugVisitor::operator()(ast::FunctionCall& call) const { std::cout << indent() << "FunctionCall " << call.Content->functionName << std::endl; ++level; visit_each(*this, call.Content->values); --level; } void DebugVisitor::operator()(ast::VariableDeclaration& declaration) const { std::cout << indent() << "Variable declaration" << std::endl; if(declaration.Content->value){ ++level; visit(*this, *declaration.Content->value); --level; } } void DebugVisitor::operator()(ast::ArrayDeclaration&) const { std::cout << indent() << "Array declaration" << std::endl; } void DebugVisitor::operator()(ast::Assignment& assign) const { std::cout << indent() << "Variable assignment" << std::endl; ++level; visit(*this, assign.Content->value); --level; } void DebugVisitor::operator()(ast::Return& return_) const { std::cout << indent() << "Function return" << std::endl; ++level; visit(*this, return_.Content->value); --level; } void DebugVisitor::operator()(ast::ArrayAssignment& assign) const { std::cout << indent() << "Array assignment" << std::endl; ++level; visit(*this, assign.Content->value); --level; } void DebugVisitor::operator()(ast::Litteral&) const { std::cout << indent() << "Litteral" << std::endl; } void DebugVisitor::operator()(ast::Integer& integer) const { std::cout << indent() << "Integer [" << integer.value << "]" << std::endl; } void DebugVisitor::operator()(ast::VariableValue&) const { std::cout << indent() << "Variable" << std::endl; } void DebugVisitor::operator()(ast::ArrayValue&) const { std::cout << indent() << "Array value" << std::endl; } void DebugVisitor::operator()(ast::ComposedValue& value) const { std::cout << indent() << "Composed value [" << value.Content->operations.size() << "]" << std::endl; ++level; visit(*this, value.Content->first); for(auto& operation : value.Content->operations){ std::cout << indent() << operation.get<0>() << std::endl; visit(*this, operation.get<1>()); } --level; }
//======================================================================= // Copyright Baptiste Wicht 2011. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= #include <iostream> #include "DebugVisitor.hpp" #include "VisitorUtils.hpp" #include "ast/Program.hpp" using namespace eddic; DebugVisitor::DebugVisitor() : level(0) {} std::string DebugVisitor::indent() const { std::string acc = ""; for(int i = 0; i < level; ++i){ acc += "\t"; } return acc; } void DebugVisitor::operator()(ast::Program& program) const { std::cout << indent() << "Program" << std::endl; ++level; visit_each(*this, program.Content->blocks); } void DebugVisitor::operator()(ast::FunctionDeclaration& declaration) const { std::cout << indent() << "Function " << declaration.Content->functionName << std::endl; ++level; visit_each(*this, declaration.Content->instructions); --level; } void DebugVisitor::operator()(ast::GlobalVariableDeclaration&) const { std::cout << indent() << "Global Variable" << std::endl; } void DebugVisitor::operator()(ast::GlobalArrayDeclaration&) const { std::cout << indent() << "Global Array" << std::endl; } void DebugVisitor::operator()(ast::For& for_) const { std::cout << indent() << "For" << std::endl; ++level; visit_each(*this, for_.Content->instructions); --level; } void DebugVisitor::operator()(ast::Foreach& for_) const { std::cout << indent() << "Foreach" << std::endl; ++level; visit_each(*this, for_.Content->instructions); --level; } void DebugVisitor::operator()(ast::ForeachIn& for_) const { std::cout << indent() << "Foreach in " << std::endl; ++level; visit_each(*this, for_.Content->instructions); --level; } void DebugVisitor::operator()(ast::While& while_) const { std::cout << indent() << "While" << std::endl; ++level; visit_each(*this, while_.Content->instructions); --level; } void DebugVisitor::operator()(ast::Swap&) const { std::cout << indent() << "Swap" << std::endl; } void DebugVisitor::operator()(ast::If& if_) const { std::cout << indent() << "If" << std::endl; ++level; visit_each(*this, if_.Content->instructions); --level; } void DebugVisitor::operator()(ast::FunctionCall& call) const { std::cout << indent() << "FunctionCall " << call.Content->functionName << std::endl; ++level; visit_each(*this, call.Content->values); --level; } void DebugVisitor::operator()(ast::VariableDeclaration& declaration) const { std::cout << indent() << "Variable declaration" << std::endl; if(declaration.Content->value){ ++level; visit(*this, *declaration.Content->value); --level; } } void DebugVisitor::operator()(ast::ArrayDeclaration&) const { std::cout << indent() << "Array declaration" << std::endl; } void DebugVisitor::operator()(ast::Assignment& assign) const { std::cout << indent() << "Variable assignment" << std::endl; ++level; visit(*this, assign.Content->value); --level; } void DebugVisitor::operator()(ast::Return& return_) const { std::cout << indent() << "Function return" << std::endl; ++level; visit(*this, return_.Content->value); --level; } void DebugVisitor::operator()(ast::ArrayAssignment& assign) const { std::cout << indent() << "Array assignment" << std::endl; ++level; visit(*this, assign.Content->value); --level; } void DebugVisitor::operator()(ast::Litteral& litteral) const { std::cout << indent() << "Litteral [" << litteral.value << "]" << std::endl; } void DebugVisitor::operator()(ast::Integer& integer) const { std::cout << indent() << "Integer [" << integer.value << "]" << std::endl; } void DebugVisitor::operator()(ast::VariableValue&) const { std::cout << indent() << "Variable" << std::endl; } void DebugVisitor::operator()(ast::ArrayValue&) const { std::cout << indent() << "Array value" << std::endl; } void DebugVisitor::operator()(ast::ComposedValue& value) const { std::cout << indent() << "Composed value [" << value.Content->operations.size() << "]" << std::endl; ++level; visit(*this, value.Content->first); for(auto& operation : value.Content->operations){ std::cout << indent() << operation.get<0>() << std::endl; visit(*this, operation.get<1>()); } --level; }
Improve visitor
Improve visitor
C++
mit
vogelsgesang/eddic,wichtounet/eddic,vogelsgesang/eddic,wichtounet/eddic,vogelsgesang/eddic,wichtounet/eddic
8e01141f9c3596e31865401702b87fc942d52d01
src/cxxconfig.hpp
src/cxxconfig.hpp
#ifndef TOML_CXX_CONFIG #define TOML_CXX_CONFIG #ifndef __cplusplus #error "__cplusplus macro is not defined." #endif #if __cplusplus >= 201103L # define TOML_ENABLE_CXX11 1 # define TOML_CONSTEXPR constexpr # define TOML_NOEXCEPT noexcept # define TOML_OVERRIDE override # define TOML_NULLPTR nullptr #else # define TOML_CONSTEXPR # define TOML_NOEXCEPT throw() # define TOML_OVERRIDE # define TOML_NULLPTR NULL #endif #ifdef TOML_ENABLE_CXX11 # include <memory> # include <chrono> # include <cstdint> namespace toml { using std::shared_ptr; using std::make_shared; using std::chrono; using std::int_least64_t; } #else // c++98 only # include <boost/shared_ptr.hpp> # include <boost/make_shared.hpp> # include <boost/chrono.hpp> namespace toml { using boost::shared_ptr; using boost::make_shared; using boost::chrono; } #ifdef TOML_HAVE_STDINT_H # include <stdint.h> namespace toml { using ::int_least64_t; } #else # include <boost/cstdint.hpp> namespace toml { using boost::int_least64_t; } #endif #endif // c++11 #endif /* TOML_CXX_CONFIG */
#ifndef TOML_CXX_CONFIG #define TOML_CXX_CONFIG #ifndef __cplusplus #error "__cplusplus macro is not defined." #endif #if __cplusplus >= 201103L # define TOML_ENABLE_CXX11 1 # define TOML_CONSTEXPR constexpr # define TOML_NOEXCEPT noexcept # define TOML_OVERRIDE override # define TOML_NULLPTR nullptr #else # define TOML_CONSTEXPR # define TOML_NOEXCEPT throw() # define TOML_OVERRIDE # define TOML_NULLPTR NULL #endif #ifdef TOML_ENABLE_CXX11 # include <memory> # include <chrono> # include <cstdint> namespace toml { using std::shared_ptr; using std::make_shared; using std::dynamic_pointer_cast; using std::chrono; using std::int_least64_t; } #else // c++98 only # include <boost/shared_ptr.hpp> # include <boost/make_shared.hpp> # include <boost/chrono.hpp> namespace toml { using boost::shared_ptr; using boost::make_shared; using boost::dynamic_pointer_cast; using boost::chrono; } #ifdef TOML_HAVE_STDINT_H # include <stdint.h> namespace toml { using ::int_least64_t; } #else # include <boost/cstdint.hpp> namespace toml { using boost::int_least64_t; } #endif #endif // c++11 #endif /* TOML_CXX_CONFIG */
add using dynamic_pointer_cast
add using dynamic_pointer_cast
C++
mit
ToruNiina/TOMLParser
c316c3bb94a3b20a132156bd0a215963176eebeb
cores/cosa/Cosa/Shell.hh
cores/cosa/Cosa/Shell.hh
/** * @file Cosa/Shell.hh * @version 1.0 * * @section License * Copyright (C) 2014, Mikael Patel * * 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. * * This file is part of the Arduino Che Cosa project. */ #ifndef COSA_SHELL_HH #define COSA_SHELL_HH #include "Cosa/Types.h" #include "Cosa/IOStream.hh" class Shell { public: /** * Shell command action function. Called with number arguments * and NULL terminated argument vector. Should return zero(0) if * successful otherwise a negative error code. * @param[in] argc argument count. * @param[in] argv argument vector. * @return zero or negative error code. */ typedef int (*action_fn)(int argc, char* argv[]); /** * Shell command descriptor with name, help string and action function. */ struct command_t { const char* name; //!< Shell command name string (PROGMEM). const char* help; //!< Short description of command. action_fn action; //!< Shell command action function. }; /** * Construct command shell with given command list and prompt. * @param[in] cmdc number of commands in vector (max 255). * @param[in] cmdtab command table (in program memory). * @param[in] prompt to be written to cout. */ Shell(uint8_t cmdc, const command_t* cmdtab, const char* prompt = NULL) : m_cmdc(cmdc), m_cmdtab(cmdtab), m_prompt(prompt == NULL ? DEFAULT_PROMPT : prompt), m_echo(true) {} /** * Set command line echo mode. Useful for Arduino Serial Monitor to * echo commands received. * @param[in] flag on or off. */ void set_echo(bool flag) { m_echo = flag; } /** * Parse command parameter list for options. The command has the * format: NAME -X -XVALUE OPTION=VALUE ARGUMENT.., where X is an * option character with or without VALUE string, OPTION is an * option name (string), and ARGUMENT is the first * non-option. Returns zero and option string and value if * successful otherwise the index of the first argument in the * argument vector. * @param[out] option string. * @param[out] value string. * @return zero or index of first argument. */ int get(char* &option, char* &value); /** * Parse buffer and create command, option and parameter * list. Lookup command in given command vector. If found call * action function with arguments and count. Return value from * action function or negative error code if not found. * @param[in] buf command line (zero terminated string). * @return value from action function or negative error code. */ int execute(char* buf); /** * Prompt to given output stream (if not NULL), read line from given * input stream and execute command. Return zero or negative error * code. * @param[in] ins input stream. * @param[in] outs output stream (default NULL). * @return zero or negative error code. */ int run(IOStream* ins, IOStream* outs = NULL); /** * Print short description of commands to the given output * stream. Return zero or negative error code. * @param[in] outs output stream. * @return zero or negative error code. */ int help(IOStream& outs); protected: /** Default prompt */ static const char DEFAULT_PROMPT[] PROGMEM; /** Max command line buffer size */ static const size_t BUF_MAX = 64; /** Max number of arguments */ const size_t ARGV_MAX = 16; uint8_t m_cmdc; //!< Number of shell commands. const command_t* m_cmdtab; //!< Vector with shell command decriptors. const char* m_prompt; //!< Shell prompt. bool m_echo; //!< Echo command line. uint8_t m_argc; //!< Number of arguments. char** m_argv; //!< Argument vector. uint8_t m_optind; //!< Next option index. bool m_optend; //!< End of options. /** * Lookup given command name in command set. Return command entry * in program memory or NULL. * @param[in] name of shell command. * @return command entry or NULL. */ const command_t* lookup(char* name); /** * Execute script in program memory. Return zero or the script * command line number of the failed. * @param[in] script pointer to script in program memory. * @param[in] argc argument count. * @param[in] argv argument vector. * @return zero or script line number. */ int execute(const char* script, int argc, char* argv[]); }; /** * Shell script magic marker. */ #define SHELL_SCRIPT_MAGIC "#!Cosa/Shell\n" #endif
/** * @file Cosa/Shell.hh * @version 1.0 * * @section License * Copyright (C) 2014, Mikael Patel * * 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. * * This file is part of the Arduino Che Cosa project. */ #ifndef COSA_SHELL_HH #define COSA_SHELL_HH #include "Cosa/Types.h" #include "Cosa/IOStream.hh" class Shell { public: /** * Shell command action function. Called with number arguments * and NULL terminated argument vector. Should return zero(0) if * successful otherwise a negative error code. * @param[in] argc argument count. * @param[in] argv argument vector. * @return zero or negative error code. */ typedef int (*action_fn)(int argc, char* argv[]); /** * Shell command descriptor with name, help string and action function. */ struct command_t { const char* name; //!< Shell command name string (PROGMEM). const char* help; //!< Short description of command. action_fn action; //!< Shell command action function. }; /** * Construct command shell with given command list and prompt. * @param[in] cmdc number of commands in vector (max 255). * @param[in] cmdtab command table (in program memory). * @param[in] prompt to be written to cout. */ Shell(uint8_t cmdc, const command_t* cmdtab, const char* prompt = NULL) : m_cmdc(cmdc), m_cmdtab(cmdtab), m_prompt(prompt == NULL ? DEFAULT_PROMPT : prompt), m_echo(true) {} /** * Set command line echo mode. Useful for Arduino Serial Monitor to * echo commands received. * @param[in] flag on or off. */ void set_echo(bool flag) { m_echo = flag; } /** * Parse command parameter list for options. The command has the * format: NAME -X -XVALUE OPTION=VALUE ARGUMENT.., where X is an * option character with or without VALUE string, OPTION is an * option name (string), and ARGUMENT is the first * non-option. Returns zero and option string and value if * successful otherwise the index of the first argument in the * argument vector. * @param[out] option string. * @param[out] value string. * @return zero or index of first argument. */ int get(char* &option, char* &value); /** * Parse buffer and create command, option and parameter * list. Lookup command in given command vector. If found call * action function with arguments and count. Return value from * action function or negative error code if not found. * @param[in] buf command line (zero terminated string). * @return value from action function or negative error code. */ int execute(char* buf); /** * Prompt to given output stream (if not NULL), read line from given * input stream and execute command. Return zero or negative error * code. * @param[in] ins input stream. * @param[in] outs output stream (default NULL). * @return zero or negative error code. */ int run(IOStream* ins, IOStream* outs = NULL); /** * Print short description of commands to the given output * stream. Return zero or negative error code. * @param[in] outs output stream. * @return zero or negative error code. */ int help(IOStream& outs); protected: /** Default prompt */ static const char DEFAULT_PROMPT[] PROGMEM; /** Max command line buffer size */ static const size_t BUF_MAX = 64; /** Max number of arguments */ static const size_t ARGV_MAX = 16; uint8_t m_cmdc; //!< Number of shell commands. const command_t* m_cmdtab; //!< Vector with shell command decriptors. const char* m_prompt; //!< Shell prompt. bool m_echo; //!< Echo command line. uint8_t m_argc; //!< Number of arguments. char** m_argv; //!< Argument vector. uint8_t m_optind; //!< Next option index. bool m_optend; //!< End of options. /** * Lookup given command name in command set. Return command entry * in program memory or NULL. * @param[in] name of shell command. * @return command entry or NULL. */ const command_t* lookup(char* name); /** * Execute script in program memory. Return zero or the script * command line number of the failed. * @param[in] script pointer to script in program memory. * @param[in] argc argument count. * @param[in] argv argument vector. * @return zero or script line number. */ int execute(const char* script, int argc, char* argv[]); }; /** * Shell script magic marker. */ #define SHELL_SCRIPT_MAGIC "#!Cosa/Shell\n" #endif
Fix compile for Arduino 1.0.X.
Fix compile for Arduino 1.0.X.
C++
lgpl-2.1
jeditekunum/Cosa,rrobinet/Cosa,rrobinet/Cosa,dansut/Cosa,kc9jud/Cosa,mikaelpatel/Cosa,dansut/Cosa,kc9jud/Cosa,jeditekunum/Cosa,dansut/Cosa,rrobinet/Cosa,kc9jud/Cosa,mikaelpatel/Cosa,mikaelpatel/Cosa,jeditekunum/Cosa,kc9jud/Cosa,dansut/Cosa,mikaelpatel/Cosa,jeditekunum/Cosa,rrobinet/Cosa
0f65c30d3a30b556c17b9d6276147edc220a90ba
monitor/gtk/src/main.cpp
monitor/gtk/src/main.cpp
#include <gtkmm.h> #include <iostream> #include <string> #include "dharc/monitor.hpp" #include <type_traits> #include <sigc++/sigc++.h> namespace sigc { template <typename Functor> struct functor_trait<Functor, false> { typedef decltype (::sigc::mem_fun (std::declval<Functor&> (), &Functor::operator())) _intermediate; typedef typename _intermediate::result_type result_type; typedef Functor functor_type; }; }; using std::string; using dharc::Monitor; class StatsColumns : public Gtk::TreeModel::ColumnRecord { public: StatsColumns() { add(name); add(value); } Gtk::TreeModelColumn<Glib::ustring> name; Gtk::TreeModelColumn<Glib::ustring> value; }; StatsColumns statscols; int main(int argc, char *argv[]) { Monitor monitor("localhost", 7878); Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv, "uk.co.dharc.monitor"); Gtk::Window *window; auto statstore = Gtk::TreeStore::create(statscols); Gtk::TreeView *statsview; //window.set_default_size(200, 200); Glib::RefPtr<Gtk::Builder> builder = Gtk::Builder::create(); builder->add_from_file("ui.glade"); builder->get_widget("dmonmain", window); builder->get_widget("statsview", statsview); auto title = statstore->append(); (*title)[statscols.name] = "Scale Statistics"; auto stat_numharcs = *statstore->append(title->children()); auto stat_numbranch = *statstore->append(title->children()); auto stat_bfactor = *statstore->append(title->children()); title = statstore->append(); (*title)[statscols.name] = "Performance Statistics"; auto stat_active = *statstore->append(title->children()); auto stat_processed = *statstore->append(title->children()); stat_numharcs[statscols.name] = "Number of Harcs"; stat_numbranch[statscols.name] = "Number of Branches"; stat_bfactor[statscols.name] = "Branch Factor"; stat_active[statscols.name] = "Activations (Kps)"; stat_processed[statscols.name] = "Processed (Mps)"; statsview->set_model(statstore); sigc::connection stat_conn = Glib::signal_timeout().connect([&]() { int harccount = monitor.harcCount(); int branchcount = monitor.branchCount(); float bfactor = static_cast<float>(branchcount) / static_cast<float>(harccount); float actives = monitor.activationsPerSecond() / 1000.0f; float processed = monitor.processedPerSecond() / 1000.0f; char buffer[100]; sprintf(buffer, "%dK", harccount / 1000); stat_numharcs[statscols.value] = buffer; sprintf(buffer, "%dK", branchcount / 1000); stat_numbranch[statscols.value] = buffer; sprintf(buffer, "%.2f", bfactor); stat_bfactor[statscols.value] = buffer; sprintf(buffer, "%.2f", actives); stat_active[statscols.value] = buffer; sprintf(buffer, "%.2f", processed); stat_processed[statscols.value] = buffer; return true; }, 100); return app->run(*window); }
#include <gtkmm.h> #include <iostream> #include <string> #include "dharc/monitor.hpp" #include <type_traits> #include <sigc++/sigc++.h> namespace sigc { template <typename Functor> struct functor_trait<Functor, false> { typedef decltype (::sigc::mem_fun (std::declval<Functor&> (), &Functor::operator())) _intermediate; typedef typename _intermediate::result_type result_type; typedef Functor functor_type; }; }; using std::string; using dharc::Monitor; class StatsColumns : public Gtk::TreeModel::ColumnRecord { public: StatsColumns() { add(name); add(value); } Gtk::TreeModelColumn<Glib::ustring> name; Gtk::TreeModelColumn<Glib::ustring> value; }; StatsColumns statscols; int main(int argc, char *argv[]) { Monitor monitor("localhost", 7878); Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv, "uk.co.dharc.monitor"); Gtk::Window *window; auto statstore = Gtk::TreeStore::create(statscols); Gtk::TreeView *statsview; //window.set_default_size(200, 200); Glib::RefPtr<Gtk::Builder> builder = Gtk::Builder::create(); builder->add_from_file("ui.glade"); builder->get_widget("dmonmain", window); builder->get_widget("statsview", statsview); auto title = statstore->append(); (*title)[statscols.name] = "Scale Statistics"; auto stat_numharcs = *statstore->append(title->children()); auto stat_numbranch = *statstore->append(title->children()); auto stat_bfactor = *statstore->append(title->children()); title = statstore->append(); (*title)[statscols.name] = "Performance Statistics"; auto stat_active = *statstore->append(title->children()); auto stat_processed = *statstore->append(title->children()); auto stat_follows = *statstore->append(title->children()); stat_numharcs[statscols.name] = "Number of Harcs"; stat_numbranch[statscols.name] = "Number of Branches"; stat_bfactor[statscols.name] = "Branch Factor"; stat_active[statscols.name] = "Activations (Kps)"; stat_processed[statscols.name] = "Processed (Kps)"; stat_follows[statscols.name] = "Harc Follows (Kps)"; statsview->set_model(statstore); sigc::connection stat_conn = Glib::signal_timeout().connect([&]() { int harccount = monitor.harcCount(); int branchcount = monitor.branchCount(); float bfactor = static_cast<float>(branchcount) / static_cast<float>(harccount); float actives = monitor.activationsPerSecond() / 1000.0f; float processed = monitor.processedPerSecond() / 1000.0f; float follows = monitor.followsPerSecond() / 1000.0f; char buffer[100]; sprintf(buffer, "%dK", harccount / 1000); stat_numharcs[statscols.value] = buffer; sprintf(buffer, "%dK", branchcount / 1000); stat_numbranch[statscols.value] = buffer; sprintf(buffer, "%.2f", bfactor); stat_bfactor[statscols.value] = buffer; sprintf(buffer, "%.2f", actives); stat_active[statscols.value] = buffer; sprintf(buffer, "%.2f", processed); stat_processed[statscols.value] = buffer; sprintf(buffer, "%.2f", follows); stat_follows[statscols.value] = buffer; return true; }, 100); return app->run(*window); }
Monitor shows harc follows
Monitor shows harc follows
C++
bsd-2-clause
dharc/dharc
21950d62df41263b06be50f8e4ec215fca585855
src/MemoryDumper.cpp
src/MemoryDumper.cpp
#include "MemoryDumper.h" using namespace std; MemoryDumper::MemoryDumper(){ this->chunks = new std::vector<Bits *>; this->plugins = new std::vector<plugin_t *>; } MemoryDumper::~MemoryDumper(){ for(std::vector<struct plugin_t *>::iterator plugins_iter = this->plugins->begin(); plugins_iter != this->plugins->end(); ++plugins_iter){ dlclose((*plugins_iter)->hndl); free((*plugins_iter)); } if(this->chunks != NULL){ delete this->chunks; } if(this->plugins != NULL){ delete this->plugins; } if(this->from_file && this->file != NULL){ free(this->file); } } bool MemoryDumper::init(const string& file){ this->file = (char *) calloc(1, PATH_MAX+1); this->from_file = true; /*Get full path of file*/ char *p = realpath(file.c_str(), this->file); if(p == NULL){ return false; } return true; } bool MemoryDumper::init(int pid){ this->pid = pid; this->from_process = true; /*Try to attach to the process*/ if(ptrace(PTRACE_ATTACH, this->pid, NULL, NULL) == -1){ printf("Error attaching to process.\n"); return false; } waitpid(this->pid, NULL, 0); /*Dettach from the process*/ ptrace(PTRACE_DETACH, this->pid, NULL, NULL); return true; } bool MemoryDumper::initPlugins(char *plugins_list){ DIR *dir; char *error; struct dirent *ent; /*Open the plugins folder...*/ if((dir = opendir(PLUGINS_DIR)) == NULL){ printf("Can't open plugins dir\n"); return EXIT_FAILURE; } /*... and read it's content*/ while((ent = readdir(dir)) != NULL){ /*Make vars shorter*/ char *fname = ent->d_name; int fnlen = strlen(fname); /*If the file name is shorter than 3 chars or it doesn't end with '.so'*/ /*then it's not a possible plugin, so just skip it*/ if(fnlen <= 3 || strcmp(fname + fnlen - 3, ".so") != 0){ continue; } printf("Loading %s... ", fname); /*Allocate some space for the path to the plugin, NULL-terminated*/ char *lib_path = (char *) calloc(1, strlen(PLUGINS_DIR) + fnlen + 1); sprintf(lib_path, "%s%s", PLUGINS_DIR, fname); /*Load the plugin*/ void *plugin_handle = dlopen(lib_path, RTLD_NOW); free(lib_path); /*Error trying to load the .so file we found. Maybe not a plugin?*/ /*Keep going anyways...*/ if(!plugin_handle){ printf("Error loading plugin!\n%s\n", dlerror()); continue; } /*Init the plugin by calling it's 'init' function*/ plugin_t *(*initf)(void); initf = (plugin_t *(*)()) dlsym(plugin_handle, "init"); if((error = dlerror()) != NULL){ /*Oops... something wen't wrong calling the plugin's init function*/ printf("Error loading init function!\n%s\n", error); continue; } printf("Ok\n"); /*Everything went fine, lets create/update the linked list containing all the loaded plugins*/ plugin_t *plugin = initf(); plugin->hndl = plugin_handle; this->plugins->push_back(plugin); printf("\t%s - %s\n", plugin->name.c_str(), plugin->description.c_str()); /*Check if we should actually load the plugin*/ if(plugins_list != NULL){ printf("\tPlugin does not match with load list, unloading %s...\n", plugin->name.c_str()); /*Close handle and free memory*/ dlclose(plugin->hndl); free(plugin); } } /*We are done, close the plugins folder*/ closedir(dir); return true; } bool MemoryDumper::getChunksFromFile(){ Bits *f = new Bits(this->file); this->chunks->push_back(f); return true; } bool MemoryDumper::getChunksFromProcess(){ off64_t start, end; unsigned long int inode, foo; char path[BUFSIZ], line_buf[BUFSIZ + 1], mapname[PATH_MAX], perm[5], dev[6]; /*Attach to the process*/ if(ptrace(PTRACE_ATTACH, this->pid, NULL, NULL) == -1){ printf("Error attaching to process.\n"); return EXIT_FAILURE; } waitpid(this->pid, NULL, 0); /*Open the fds from where we're going to read*/ snprintf(path, sizeof(path), "/proc/%d/maps", this->pid); FILE *maps_fd = fopen(path, "r"); snprintf(path, sizeof(path), "/proc/%d/mem", this->pid); int mem_fd = open(path, O_RDONLY); if(!maps_fd || mem_fd == -1){ printf("Error opening /proc/%d/maps or /proc/%d/mem\n", this->pid, this->pid); return false; } /*We're ready to read*/ while(fgets(line_buf, BUFSIZ, maps_fd) != NULL){ /*Quit faster if we receive Ctrl-c*/ //if(!this->keep_running){ // break; //} mapname[0] = '\0'; sscanf(line_buf, "%lx-%lx %4s %lx %5s %ld %s", &start, &end, perm, &foo, dev, &inode, mapname); /*We don't want to read the memory of shared libraries, devices, etc...*/ if(foo != 0 || inode != 0 || access(mapname, R_OK) == 0){ continue; } /*Avoid non-sense*/ if(start > end){ continue; } size_t mem_size = end - start; unsigned char *mem_buf = (unsigned char *) malloc(mem_size); if(!mem_buf){ printf("Error allocating space!\n"); continue; } lseek64(mem_fd, start, SEEK_SET); if(read(mem_fd, mem_buf, mem_size) == -1){ printf("Error copying raw memory! (%s)\n", strerror(errno)); free(mem_buf); continue; } /*Push a Bits object to the chunks vector so we can then use it from the plugins*/ Bits *b = new Bits(mem_buf, mem_size, true); this->chunks->push_back(b); } /*Dettach from the process*/ ptrace(PTRACE_DETACH, this->pid, NULL, NULL); /*Close file descriptors*/ mem_fd != -1 && close(mem_fd); maps_fd && fclose(maps_fd); return true; } int main(int argc, char **argv){ char *plugins_list = NULL; int ch; bool only_show_plugins = false; MemoryDumper *md = new MemoryDumper(); /*Get all those args!*/ while((ch = getopt(argc, argv, "f:p:l:sh")) != -1){ switch(ch){ case 'f': if(md->init(optarg) == false){ delete md; return EXIT_FAILURE; } break; case 'p': if(md->init(atoi(optarg)) == false){ delete md; return EXIT_FAILURE; } break; case 'l': plugins_list = optarg; break; case 's': only_show_plugins = true; break; case 'h': printf("Available options:\n"); printf("\tf <file path> - File path of the file you want to scan\n"); printf("\tp <pid> - PID of the process you want to dump\n"); printf("\tl <list,of,plugins | all> - Load only certain plugins, comma separated\n"); printf("\ts - Show available plugins\n"); printf("\th - Show this help\n"); } } if(only_show_plugins){ printf("Available plugins:\n"); } md->initPlugins(plugins_list); if(only_show_plugins){ delete md; return EXIT_SUCCESS; } if(md->from_file){ md->getChunksFromFile(); }else if(md->from_process){ md->getChunksFromProcess(); } for(std::vector<struct plugin_t *>::iterator plugins_iter = md->plugins->begin(); plugins_iter != md->plugins->end(); ++plugins_iter){ for(std::vector<Bits *>::iterator chunks_iter = md->chunks->begin(); chunks_iter != md->chunks->end(); ++chunks_iter){ void *(*f)(Bits *); f = (void *(*)(Bits *)) dlsym((*plugins_iter)->hndl, "process"); f(*chunks_iter); } } delete md; return EXIT_SUCCESS; }
#include "MemoryDumper.h" using namespace std; MemoryDumper::MemoryDumper(){ this->chunks = new std::vector<Bits *>; this->plugins = new std::vector<plugin_t *>; } MemoryDumper::~MemoryDumper(){ for(std::vector<struct plugin_t *>::iterator plugins_iter = this->plugins->begin(); plugins_iter != this->plugins->end(); ++plugins_iter){ dlclose((*plugins_iter)->hndl); free((*plugins_iter)); } if(this->chunks != NULL){ delete this->chunks; } if(this->plugins != NULL){ delete this->plugins; } if(this->from_file && this->file != NULL){ free(this->file); } } bool MemoryDumper::init(const string& file){ this->file = (char *) calloc(1, PATH_MAX+1); this->from_file = true; /*Get full path of file*/ char *p = realpath(file.c_str(), this->file); if(p == NULL){ return false; } return true; } bool MemoryDumper::init(int pid){ this->pid = pid; this->from_process = true; /*Try to attach to the process*/ if(ptrace(PTRACE_ATTACH, this->pid, NULL, NULL) == -1){ printf("Error attaching to process.\n"); return false; } waitpid(this->pid, NULL, 0); /*Dettach from the process*/ ptrace(PTRACE_DETACH, this->pid, NULL, NULL); return true; } bool MemoryDumper::initPlugins(char *plugins_list){ DIR *dir; char *error; struct dirent *ent; /*Open the plugins folder...*/ if((dir = opendir(PLUGINS_DIR)) == NULL){ printf("Can't open plugins dir\n"); return EXIT_FAILURE; } /*... and read it's content*/ while((ent = readdir(dir)) != NULL){ /*Make vars shorter*/ char *fname = ent->d_name; int fnlen = strlen(fname); /*If the file name is shorter than 3 chars or it doesn't end with '.so'*/ /*then it's not a possible plugin, so just skip it*/ if(fnlen <= 3 || strcmp(fname + fnlen - 3, ".so") != 0){ continue; } printf("Loading %s... ", fname); /*Allocate some space for the path to the plugin, NULL-terminated*/ char *lib_path = (char *) calloc(1, strlen(PLUGINS_DIR) + fnlen + 1); sprintf(lib_path, "%s%s", PLUGINS_DIR, fname); /*Load the plugin*/ void *plugin_handle = dlopen(lib_path, RTLD_NOW); free(lib_path); /*Error trying to load the .so file we found. Maybe not a plugin?*/ /*Keep going anyways...*/ if(!plugin_handle){ printf("Error loading plugin!\n%s\n", dlerror()); continue; } /*Init the plugin by calling it's 'init' function*/ plugin_t *(*initf)(void); initf = (plugin_t *(*)()) dlsym(plugin_handle, "init"); if((error = dlerror()) != NULL){ /*Oops... something wen't wrong calling the plugin's init function*/ printf("Error loading init function!\n%s\n", error); continue; } printf("Ok\n"); /*Everything went fine, lets create/update the linked list containing all the loaded plugins*/ plugin_t *plugin = initf(); plugin->hndl = plugin_handle; this->plugins->push_back(plugin); printf("\t%s - %s\n", plugin->name.c_str(), plugin->description.c_str()); /*Check if we should actually load the plugin*/ if(plugins_list != NULL){ printf("\tPlugin does not match with load list, unloading %s...\n", plugin->name.c_str()); /*Close handle and free memory*/ dlclose(plugin->hndl); free(plugin); } } /*We are done, close the plugins folder*/ closedir(dir); return true; } bool MemoryDumper::getChunksFromFile(){ Bits *f = new Bits(this->file); this->chunks->push_back(f); return true; } bool MemoryDumper::getChunksFromProcess(){ off64_t start, end; unsigned long int inode, foo; char path[BUFSIZ], line_buf[BUFSIZ + 1], mapname[PATH_MAX], perm[5], dev[6]; /*Attach to the process*/ if(ptrace(PTRACE_ATTACH, this->pid, NULL, NULL) == -1){ printf("Error attaching to process.\n"); return EXIT_FAILURE; } waitpid(this->pid, NULL, 0); /*Open the fds from where we're going to read*/ snprintf(path, sizeof(path), "/proc/%d/maps", this->pid); FILE *maps_fd = fopen(path, "r"); snprintf(path, sizeof(path), "/proc/%d/mem", this->pid); int mem_fd = open(path, O_RDONLY); if(!maps_fd || mem_fd == -1){ printf("Error opening /proc/%d/maps or /proc/%d/mem\n", this->pid, this->pid); return false; } /*We're ready to read*/ while(fgets(line_buf, BUFSIZ, maps_fd) != NULL){ /*Quit faster if we receive Ctrl-c*/ //if(!this->keep_running){ // break; //} mapname[0] = '\0'; sscanf(line_buf, "%lx-%lx %4s %lx %5s %ld %s", &start, &end, perm, &foo, dev, &inode, mapname); /*We don't want to read the memory of shared libraries, devices, etc...*/ if(foo != 0 || inode != 0 || access(mapname, R_OK) == 0){ continue; } /*Avoid non-sense*/ if(start > end){ continue; } size_t mem_size = end - start; unsigned char *mem_buf = (unsigned char *) malloc(mem_size); if(!mem_buf){ printf("Error allocating space!\n"); continue; } lseek64(mem_fd, start, SEEK_SET); if(read(mem_fd, mem_buf, mem_size) == -1){ printf("Error copying raw memory! (%s)\n", strerror(errno)); free(mem_buf); continue; } /*Push a Bits object to the chunks vector so we can then use it from the plugins*/ Bits *b = new Bits(mem_buf, mem_size, true); this->chunks->push_back(b); } /*Dettach from the process*/ ptrace(PTRACE_DETACH, this->pid, NULL, NULL); /*Close file descriptors*/ mem_fd != -1 && close(mem_fd); maps_fd && fclose(maps_fd); return true; } int main(int argc, char **argv){ char *plugins_list = NULL; int ch; bool only_show_plugins = false; MemoryDumper *md = new MemoryDumper(); /*Get all those args!*/ while((ch = getopt(argc, argv, "f:p:l:sh")) != -1){ switch(ch){ case 'f': if(md->init(optarg) == false){ delete md; return EXIT_FAILURE; } break; case 'p': if(md->init(atoi(optarg)) == false){ delete md; return EXIT_FAILURE; } break; case 'l': plugins_list = optarg; break; case 's': only_show_plugins = true; break; case 'h': printf("Available options:\n"); printf("\tf <file path> - File path of the file you want to scan\n"); printf("\tp <pid> - PID of the process you want to dump\n"); printf("\tl <list,of,plugins | all> - Load only certain plugins, comma separated\n"); printf("\ts - Show available plugins\n"); printf("\th - Show this help\n"); } } if(only_show_plugins){ printf("Available plugins:\n"); } md->initPlugins(plugins_list); if(only_show_plugins){ delete md; return EXIT_SUCCESS; } if(md->from_file){ md->getChunksFromFile(); }else if(md->from_process){ md->getChunksFromProcess(); } for(vector<struct plugin_t *>::iterator plugins_iter = md->plugins->begin(); plugins_iter != md->plugins->end(); ++plugins_iter){ for(vector<Bits *>::iterator chunks_iter = md->chunks->begin(); chunks_iter != md->chunks->end(); ++chunks_iter){ void *(*f)(Bits *); f = (void *(*)(Bits *)) dlsym((*plugins_iter)->hndl, "process"); f(*chunks_iter); } } delete md; return EXIT_SUCCESS; }
Use namespacing
Use namespacing
C++
unlicense
alexandernst/memory-dumper
410b1debff6efc755487f8c2a53b374be9b1172c
src/llvm/PointsTo.cpp
src/llvm/PointsTo.cpp
#include <llvm/IR/Value.h> #include <llvm/IR/Constants.h> #include <llvm/IR/IntrinsicInst.h> #include <llvm/IR/Instruction.h> #include <llvm/IR/Module.h> #include <llvm/Support/raw_ostream.h> #include "LLVMDependenceGraph.h" #include "PointsTo.h" #include "AnalysisGeneric.h" using namespace llvm; namespace dg { namespace analysis { LLVMPointsToAnalysis::LLVMPointsToAnalysis(LLVMDependenceGraph *dg) : DataFlowAnalysis<LLVMNode>(dg->getEntryBB(), DATAFLOW_INTERPROCEDURAL), dg(dg) { Module *m = dg->getModule(); // set data layout DL = m->getDataLayout(); handleGlobals(); } bool LLVMPointsToAnalysis::handleAllocaInst(LLVMNode *node) { // every global is a pointer MemoryObj *& mo = node->getMemoryObj(); if (!mo) { mo = new MemoryObj(node); node->addPointsTo(mo); return true; } return false; } LLVMNode *LLVMPointsToAnalysis::getOperand(LLVMNode *node, const Value *val, unsigned int idx) { // ok, before calling this we call llvm::Value::getOperand() to get val // and in node->getOperand() we call it too. It is small overhead, but just // to know where to optimize when going to extrems LLVMNode *op = node->getOperand(idx); if (op) return op; if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(val)) { op = new LLVMNode(val); // FIXME add these nodes somewhere, // so that we can delete them later // set points-to sets Pointer ptr = getConstantExprPointer(CE); //MemoryObj *&mo = op->getMemoryObj(); //mo = new MemoryObj(op); op->addPointsTo(ptr); } else if (isa<Argument>(val)) { LLVMDGParameters *params = dg->getParameters(); if (!params) { // This is probably not an argument from out dg? // Is it possible? Or there's a bug errs() << "No params for dg with argument: " << *val << "\n"; abort(); } LLVMDGParameter *p = params->find(val); // XXX is it always the input param? if (p) op = p->in; } else { errs() << "ERR: Unsupported operand: " << *val << "\n"; abort(); } assert(op && "Did not set op"); // set new operand node->setOperand(op, idx); return op; } static bool handleStoreInstPtr(LLVMNode *valNode, LLVMNode *ptrNode) { bool changed = false; // iterate over points to locations of pointer node // FIXME what if the memory location is undefined? // in that case it has no points-to set and we're // loosing information for (auto ptr : ptrNode->getPointsTo()) { // if we're storing a pointer, make obj[offset] // points to the same locations as the valNode for (auto valptr : valNode->getPointsTo()) changed |= ptr.obj->addPointsTo(ptr.offset, valptr); } return changed; } bool LLVMPointsToAnalysis::handleStoreInst(const StoreInst *Inst, LLVMNode *node) { // get ptrNode before checking if value type is pointer type, // because the pointer operand can be ConstantExpr and in getOperand() // we resolve its points-to set LLVMNode *ptrNode = getOperand(node, Inst->getPointerOperand(), 0); const Value *valOp = Inst->getValueOperand(); if (!valOp->getType()->isPointerTy()) return false; LLVMNode *valNode = getOperand(node, valOp, 1); assert(ptrNode && "No ptr node"); assert(valNode && "No val node"); return handleStoreInstPtr(valNode, ptrNode); } Pointer LLVMPointsToAnalysis::getConstantExprPointer(const ConstantExpr *CE) { return dg::analysis::getConstantExprPointer(CE, dg, DL); } static bool handleLoadInstPtr(const Pointer& ptr, LLVMNode *node) { bool changed = false; // load of pointer makes this node point // to the same values as ptrNode if (ptr.isNull() || ptr.obj->isUnknown()) changed |= node->addPointsTo(ptr); else { for (auto memptr : ptr.obj->pointsTo[ptr.offset]) changed |= node->addPointsTo(memptr); if (ptr.obj->pointsTo.count(UNKNOWN_OFFSET) != 0) for (auto memptr : ptr.obj->pointsTo[UNKNOWN_OFFSET]) changed |= node->addPointsTo(memptr); } return changed; } static bool handleLoadInstPointsTo(LLVMNode *ptrNode, LLVMNode *node) { bool changed = false; // get values that are referenced by pointer and // store them as values of this load (or as pointsTo // if the load it pointer) for (auto ptr : ptrNode->getPointsTo()) changed |= handleLoadInstPtr(ptr, node); return changed; } bool LLVMPointsToAnalysis::handleLoadInst(const LoadInst *Inst, LLVMNode *node) { if (!Inst->getType()->isPointerTy()) return false; LLVMNode *ptrNode = getOperand(node, Inst->getPointerOperand(), 0); assert(ptrNode && "No ptr node"); return handleLoadInstPointsTo(ptrNode, node); } static bool addPtrWithOffset(LLVMNode *ptrNode, LLVMNode *node, uint64_t offset, const DataLayout *DL) { bool changed = false; Offset off = offset; uint64_t size; const Value *ptrVal; Type *Ty; for (auto ptr : ptrNode->getPointsTo()) { if (ptr.obj->isUnknown() || ptr.offset.isUnknown()) // don't store unknown with different offsets, changed |= node->addPointsTo(ptr.obj); else { ptrVal = ptr.obj->node->getKey(); Ty = ptrVal->getType()->getContainedType(0); off += ptr.offset; size = DL->getTypeAllocSize(Ty); // ivalid offset might mean we're cycling due to some // cyclic dependency if (*off >= size) { errs() << "INFO: cropping GEP, off > size: " << *off << " " << size << " Type: " << *Ty << "\n"; changed |= node->addPointsTo(ptr.obj, UNKNOWN_OFFSET); } else changed |= node->addPointsTo(ptr.obj, off); } } return changed; } bool LLVMPointsToAnalysis::handleGepInst(const GetElementPtrInst *Inst, LLVMNode *node) { bool changed = false; APInt offset(64, 0); LLVMNode *ptrNode = node->getOperand(0); assert(ptrNode && "Do not have GEP ptr node"); if (Inst->accumulateConstantOffset(*DL, offset)) { if (offset.isIntN(64)) return addPtrWithOffset(ptrNode, node, offset.getZExtValue(), DL); else errs() << "WARN: GEP offset greater that 64-bit\n"; // fall-through to UNKNOWN_OFFSET in this case } for (auto ptr : ptrNode->getPointsTo()) // UKNOWN_OFFSET + something is still unknown changed |= node->addPointsTo(ptr.obj, UNKNOWN_OFFSET); return changed; } // @CE is ConstantExpr initializer // @node is global's node bool LLVMPointsToAnalysis::addGlobalPointsTo(const Constant *C, LLVMNode *node, uint64_t off) { Pointer ptr (nullptr, 0); MemoryObj *mo = node->getMemoryObj(); assert(mo && "Global has no mo"); if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { ptr = getConstantExprPointer(CE); } else if (isa<ConstantPointerNull>(C)) { // pointer is null already, do nothing } else { // it is a pointer to somewhere (we check that it is a pointer // before calling this method), so just get where LLVMNode *ptrNode = dg->getNode(C); assert(ptrNode && "Do not have node for pointer initializer of global"); ptr.obj = ptrNode->getMemoryObj(); } return mo->addPointsTo(off, ptr); } bool LLVMPointsToAnalysis::handleCallInst(const CallInst *Inst, LLVMNode *node) { bool changed = false; Type *Ty = Inst->getType(); bool isptr; // function is undefined? if (!node->hasSubgraphs() && Ty->isPointerTy()) { MemoryObj *& mo = node->getMemoryObj(); if (!mo) { mo = new MemoryObj(nullptr); node->addPointsTo(mo); return true; } return false; } LLVMNode **operands = node->getOperands(); for (auto sub : node->getSubgraphs()) { LLVMDGParameters *formal = sub->getParameters(); if (!formal) // no arguments continue; const Function *subfunc = dyn_cast<Function>(sub->getEntry()->getKey()); assert(subfunc && "Entry is not a llvm::Function"); // handle values for arguments int i = 1; for (auto I = subfunc->arg_begin(), E = subfunc->arg_end(); I != E; ++I, ++i) { isptr = I->getType()->isPointerTy(); if (!isptr) continue; LLVMDGParameter *p = formal->find(&*I); if (!p) { errs() << "ERR: no such formal param: " << *I << "\n"; continue; } LLVMNode *op = operands[i]; if (!op) { errs() << "ERR: no operand for actual param of formal param: " << *I << "\n"; continue; } for (const Pointer& ptr : op->getPointsTo()) changed |= p->in->addPointsTo(ptr); } if (!Ty->isPointerTy()) return changed; // handle return values LLVMNode *retval = sub->getExit(); // this is artificial return value, the real // are control dependent on it for (auto I = retval->rev_control_begin(), E = retval->rev_control_end(); I != E; ++I) { // we should iterate only over return inst assert(isa<ReturnInst>((*I)->getKey())); for (auto ptr : (*I)->getPointsTo()) changed |= node->addPointsTo(ptr); } } // what about llvm intrinsic functions like llvm.memset? // we could handle those return changed; } bool LLVMPointsToAnalysis::handleBitCastInst(const BitCastInst *Inst, LLVMNode *node) { bool changed = false; LLVMNode *op = getOperand(node, Inst->stripPointerCasts(), 0); if (!op) { errs() << "WARN: Cast without operand " << *Inst << "\n"; return false; } if (!Inst->getType()->isPointerTy()) return false; if (Inst->isLosslessCast()) { for (auto ptr : op->getPointsTo()) { changed |= node->addPointsTo(ptr); } } else errs() << "WARN: Not a loss less cast unhandled" << *Inst << "\n"; return changed; } bool LLVMPointsToAnalysis::handleReturnInst(const ReturnInst *Inst, LLVMNode *node) { bool changed = false; LLVMNode *val = node->getOperand(0); const Value *llvmval; (void) Inst; if (!val) return false; llvmval = val->getKey(); if (!llvmval->getType()->isPointerTy()) return false; if (val->hasUnknownValue()) return node->setUnknownValue(); for (auto ptr : val->getPointsTo()) changed |= node->addPointsTo(ptr); // call-site will take the values, // since we do not have references to parent // graphs return changed; } static bool handleGlobal(const Value *Inst, LLVMNode *node) { // we don't care about non pointers right now if (!Inst->getType()->isPointerTy()) return false; // every global points to some memory MemoryObj *& mo = node->getMemoryObj(); if (!mo) { mo = new MemoryObj(node); node->addPointsTo(mo); return true; } return false; } void LLVMPointsToAnalysis::handleGlobals() { // do we have the globals at all? if (!dg->ownsGlobalNodes()) return; for (auto it : *dg->getGlobalNodes()) handleGlobal(it.first, it.second); // initialize globals for (auto it : *dg->getGlobalNodes()) { const GlobalVariable *GV = cast<GlobalVariable>(it.first); if (GV->hasInitializer() && !GV->isExternallyInitialized()) { const Constant *C = GV->getInitializer(); uint64_t off = 0; Type *Ty; // we must handle ConstantExpr here, becaues the operand of the // ConstantExpr is the right object that we'd get in addGlobalPointsTo // using getConstantExprPointer(), but the offset would be wrong (always 0) // which can be broken e. g. with this C code: // const char *str = "Im ugly string" + 5; if (isa<ConstantExpr>(C)) addGlobalPointsTo(C, it.second, off); else if (C->getType()->isAggregateType()) { for (auto I = C->op_begin(), E = C->op_end(); I != E; ++I) { const Value *val = *I; Ty = val->getType(); if (Ty->isPointerTy()) { addGlobalPointsTo(cast<Constant>(val), it.second, off); } off += DL->getTypeAllocSize(Ty); } } } } } bool LLVMPointsToAnalysis::runOnNode(LLVMNode *node) { bool changed = false; const Value *val = node->getKey(); if (isa<AllocaInst>(val)) { changed |= handleAllocaInst(node); } else if (const StoreInst *Inst = dyn_cast<StoreInst>(val)) { changed |= handleStoreInst(Inst, node); } else if (const LoadInst *Inst = dyn_cast<LoadInst>(val)) { changed |= handleLoadInst(Inst, node); } else if (const GetElementPtrInst *Inst = dyn_cast<GetElementPtrInst>(val)) { changed |= handleGepInst(Inst, node); } else if (const CallInst *Inst = dyn_cast<CallInst>(val)) { changed |= handleCallInst(Inst, node); } else if (const ReturnInst *Inst = dyn_cast<ReturnInst>(val)) { changed |= handleReturnInst(Inst, node); } else if (const BitCastInst *Inst = dyn_cast<BitCastInst>(val)) { changed |= handleBitCastInst(Inst, node); } else { const Instruction *I = dyn_cast<Instruction>(val); assert(I && "Not an Instruction?"); if (I->mayReadOrWriteMemory()) errs() << "WARN: Unhandled instruction: " << *val << "\n"; } return changed; } } // namespace analysis } // namespace dg
#include <llvm/IR/Value.h> #include <llvm/IR/Constants.h> #include <llvm/IR/IntrinsicInst.h> #include <llvm/IR/Instruction.h> #include <llvm/IR/Module.h> #include <llvm/Support/raw_ostream.h> #include "LLVMDependenceGraph.h" #include "PointsTo.h" #include "AnalysisGeneric.h" using namespace llvm; namespace dg { namespace analysis { LLVMPointsToAnalysis::LLVMPointsToAnalysis(LLVMDependenceGraph *dg) : DataFlowAnalysis<LLVMNode>(dg->getEntryBB(), DATAFLOW_INTERPROCEDURAL), dg(dg) { Module *m = dg->getModule(); // set data layout DL = m->getDataLayout(); handleGlobals(); } bool LLVMPointsToAnalysis::handleAllocaInst(LLVMNode *node) { // every global is a pointer MemoryObj *& mo = node->getMemoryObj(); if (!mo) { mo = new MemoryObj(node); node->addPointsTo(mo); return true; } return false; } LLVMNode *LLVMPointsToAnalysis::getOperand(LLVMNode *node, const Value *val, unsigned int idx) { // ok, before calling this we call llvm::Value::getOperand() to get val // and in node->getOperand() we call it too. It is small overhead, but just // to know where to optimize when going to extrems LLVMNode *op = node->getOperand(idx); if (op) return op; if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(val)) { op = new LLVMNode(val); // FIXME add these nodes somewhere, // so that we can delete them later // set points-to sets Pointer ptr = getConstantExprPointer(CE); //MemoryObj *&mo = op->getMemoryObj(); //mo = new MemoryObj(op); op->addPointsTo(ptr); } else if (isa<Argument>(val)) { // get dg of this graph, because we can be in subprocedure LLVMDependenceGraph *thisdg = node->getDG(); LLVMDGParameters *params = thisdg->getParameters(); if (!params) { // This is probably not an argument from out dg? // Is it possible? Or there's a bug errs() << "No params for dg with argument: " << *val << "\n"; abort(); } LLVMDGParameter *p = params->find(val); // XXX is it always the input param? if (p) op = p->in; } else { errs() << "ERR: Unsupported operand: " << *val << "\n"; abort(); } assert(op && "Did not set op"); // set new operand node->setOperand(op, idx); return op; } static bool handleStoreInstPtr(LLVMNode *valNode, LLVMNode *ptrNode) { bool changed = false; // iterate over points to locations of pointer node // FIXME what if the memory location is undefined? // in that case it has no points-to set and we're // loosing information for (auto ptr : ptrNode->getPointsTo()) { // if we're storing a pointer, make obj[offset] // points to the same locations as the valNode for (auto valptr : valNode->getPointsTo()) changed |= ptr.obj->addPointsTo(ptr.offset, valptr); } return changed; } bool LLVMPointsToAnalysis::handleStoreInst(const StoreInst *Inst, LLVMNode *node) { // get ptrNode before checking if value type is pointer type, // because the pointer operand can be ConstantExpr and in getOperand() // we resolve its points-to set LLVMNode *ptrNode = getOperand(node, Inst->getPointerOperand(), 0); const Value *valOp = Inst->getValueOperand(); if (!valOp->getType()->isPointerTy()) return false; LLVMNode *valNode = getOperand(node, valOp, 1); assert(ptrNode && "No ptr node"); assert(valNode && "No val node"); return handleStoreInstPtr(valNode, ptrNode); } Pointer LLVMPointsToAnalysis::getConstantExprPointer(const ConstantExpr *CE) { return dg::analysis::getConstantExprPointer(CE, dg, DL); } static bool handleLoadInstPtr(const Pointer& ptr, LLVMNode *node) { bool changed = false; // load of pointer makes this node point // to the same values as ptrNode if (ptr.isNull() || ptr.obj->isUnknown()) changed |= node->addPointsTo(ptr); else { for (auto memptr : ptr.obj->pointsTo[ptr.offset]) changed |= node->addPointsTo(memptr); if (ptr.obj->pointsTo.count(UNKNOWN_OFFSET) != 0) for (auto memptr : ptr.obj->pointsTo[UNKNOWN_OFFSET]) changed |= node->addPointsTo(memptr); } return changed; } static bool handleLoadInstPointsTo(LLVMNode *ptrNode, LLVMNode *node) { bool changed = false; // get values that are referenced by pointer and // store them as values of this load (or as pointsTo // if the load it pointer) for (auto ptr : ptrNode->getPointsTo()) changed |= handleLoadInstPtr(ptr, node); return changed; } bool LLVMPointsToAnalysis::handleLoadInst(const LoadInst *Inst, LLVMNode *node) { if (!Inst->getType()->isPointerTy()) return false; LLVMNode *ptrNode = getOperand(node, Inst->getPointerOperand(), 0); assert(ptrNode && "No ptr node"); return handleLoadInstPointsTo(ptrNode, node); } static bool addPtrWithOffset(LLVMNode *ptrNode, LLVMNode *node, uint64_t offset, const DataLayout *DL) { bool changed = false; Offset off = offset; uint64_t size; const Value *ptrVal; Type *Ty; for (auto ptr : ptrNode->getPointsTo()) { if (ptr.obj->isUnknown() || ptr.offset.isUnknown()) // don't store unknown with different offsets, changed |= node->addPointsTo(ptr.obj); else { ptrVal = ptr.obj->node->getKey(); Ty = ptrVal->getType()->getContainedType(0); off += ptr.offset; size = DL->getTypeAllocSize(Ty); // ivalid offset might mean we're cycling due to some // cyclic dependency if (*off >= size) { errs() << "INFO: cropping GEP, off > size: " << *off << " " << size << " Type: " << *Ty << "\n"; changed |= node->addPointsTo(ptr.obj, UNKNOWN_OFFSET); } else changed |= node->addPointsTo(ptr.obj, off); } } return changed; } bool LLVMPointsToAnalysis::handleGepInst(const GetElementPtrInst *Inst, LLVMNode *node) { bool changed = false; APInt offset(64, 0); LLVMNode *ptrNode = node->getOperand(0); assert(ptrNode && "Do not have GEP ptr node"); if (Inst->accumulateConstantOffset(*DL, offset)) { if (offset.isIntN(64)) return addPtrWithOffset(ptrNode, node, offset.getZExtValue(), DL); else errs() << "WARN: GEP offset greater that 64-bit\n"; // fall-through to UNKNOWN_OFFSET in this case } for (auto ptr : ptrNode->getPointsTo()) // UKNOWN_OFFSET + something is still unknown changed |= node->addPointsTo(ptr.obj, UNKNOWN_OFFSET); return changed; } // @CE is ConstantExpr initializer // @node is global's node bool LLVMPointsToAnalysis::addGlobalPointsTo(const Constant *C, LLVMNode *node, uint64_t off) { Pointer ptr (nullptr, 0); MemoryObj *mo = node->getMemoryObj(); assert(mo && "Global has no mo"); if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { ptr = getConstantExprPointer(CE); } else if (isa<ConstantPointerNull>(C)) { // pointer is null already, do nothing } else { // it is a pointer to somewhere (we check that it is a pointer // before calling this method), so just get where LLVMNode *ptrNode = dg->getNode(C); assert(ptrNode && "Do not have node for pointer initializer of global"); ptr.obj = ptrNode->getMemoryObj(); } return mo->addPointsTo(off, ptr); } bool LLVMPointsToAnalysis::handleCallInst(const CallInst *Inst, LLVMNode *node) { bool changed = false; Type *Ty = Inst->getType(); bool isptr; // function is undefined? if (!node->hasSubgraphs() && Ty->isPointerTy()) { MemoryObj *& mo = node->getMemoryObj(); if (!mo) { mo = new MemoryObj(nullptr); node->addPointsTo(mo); return true; } return false; } LLVMNode **operands = node->getOperands(); for (auto sub : node->getSubgraphs()) { LLVMDGParameters *formal = sub->getParameters(); if (!formal) // no arguments continue; const Function *subfunc = dyn_cast<Function>(sub->getEntry()->getKey()); assert(subfunc && "Entry is not a llvm::Function"); // handle values for arguments int i = 1; for (auto I = subfunc->arg_begin(), E = subfunc->arg_end(); I != E; ++I, ++i) { isptr = I->getType()->isPointerTy(); if (!isptr) continue; LLVMDGParameter *p = formal->find(&*I); if (!p) { errs() << "ERR: no such formal param: " << *I << "\n"; continue; } LLVMNode *op = operands[i]; if (!op) { errs() << "ERR: no operand for actual param of formal param: " << *I << "\n"; continue; } for (const Pointer& ptr : op->getPointsTo()) changed |= p->in->addPointsTo(ptr); } if (!Ty->isPointerTy()) return changed; // handle return values LLVMNode *retval = sub->getExit(); // this is artificial return value, the real // are control dependent on it for (auto I = retval->rev_control_begin(), E = retval->rev_control_end(); I != E; ++I) { // we should iterate only over return inst assert(isa<ReturnInst>((*I)->getKey())); for (auto ptr : (*I)->getPointsTo()) changed |= node->addPointsTo(ptr); } } // what about llvm intrinsic functions like llvm.memset? // we could handle those return changed; } bool LLVMPointsToAnalysis::handleBitCastInst(const BitCastInst *Inst, LLVMNode *node) { bool changed = false; LLVMNode *op = getOperand(node, Inst->stripPointerCasts(), 0); if (!op) { errs() << "WARN: Cast without operand " << *Inst << "\n"; return false; } if (!Inst->getType()->isPointerTy()) return false; if (Inst->isLosslessCast()) { for (auto ptr : op->getPointsTo()) { changed |= node->addPointsTo(ptr); } } else errs() << "WARN: Not a loss less cast unhandled" << *Inst << "\n"; return changed; } bool LLVMPointsToAnalysis::handleReturnInst(const ReturnInst *Inst, LLVMNode *node) { bool changed = false; LLVMNode *val = node->getOperand(0); const Value *llvmval; (void) Inst; if (!val) return false; llvmval = val->getKey(); if (!llvmval->getType()->isPointerTy()) return false; if (val->hasUnknownValue()) return node->setUnknownValue(); for (auto ptr : val->getPointsTo()) changed |= node->addPointsTo(ptr); // call-site will take the values, // since we do not have references to parent // graphs return changed; } static bool handleGlobal(const Value *Inst, LLVMNode *node) { // we don't care about non pointers right now if (!Inst->getType()->isPointerTy()) return false; // every global points to some memory MemoryObj *& mo = node->getMemoryObj(); if (!mo) { mo = new MemoryObj(node); node->addPointsTo(mo); return true; } return false; } void LLVMPointsToAnalysis::handleGlobals() { // do we have the globals at all? if (!dg->ownsGlobalNodes()) return; for (auto it : *dg->getGlobalNodes()) handleGlobal(it.first, it.second); // initialize globals for (auto it : *dg->getGlobalNodes()) { const GlobalVariable *GV = cast<GlobalVariable>(it.first); if (GV->hasInitializer() && !GV->isExternallyInitialized()) { const Constant *C = GV->getInitializer(); uint64_t off = 0; Type *Ty; // we must handle ConstantExpr here, becaues the operand of the // ConstantExpr is the right object that we'd get in addGlobalPointsTo // using getConstantExprPointer(), but the offset would be wrong (always 0) // which can be broken e. g. with this C code: // const char *str = "Im ugly string" + 5; if (isa<ConstantExpr>(C)) addGlobalPointsTo(C, it.second, off); else if (C->getType()->isAggregateType()) { for (auto I = C->op_begin(), E = C->op_end(); I != E; ++I) { const Value *val = *I; Ty = val->getType(); if (Ty->isPointerTy()) { addGlobalPointsTo(cast<Constant>(val), it.second, off); } off += DL->getTypeAllocSize(Ty); } } } } } bool LLVMPointsToAnalysis::runOnNode(LLVMNode *node) { bool changed = false; const Value *val = node->getKey(); if (isa<AllocaInst>(val)) { changed |= handleAllocaInst(node); } else if (const StoreInst *Inst = dyn_cast<StoreInst>(val)) { changed |= handleStoreInst(Inst, node); } else if (const LoadInst *Inst = dyn_cast<LoadInst>(val)) { changed |= handleLoadInst(Inst, node); } else if (const GetElementPtrInst *Inst = dyn_cast<GetElementPtrInst>(val)) { changed |= handleGepInst(Inst, node); } else if (const CallInst *Inst = dyn_cast<CallInst>(val)) { changed |= handleCallInst(Inst, node); } else if (const ReturnInst *Inst = dyn_cast<ReturnInst>(val)) { changed |= handleReturnInst(Inst, node); } else if (const BitCastInst *Inst = dyn_cast<BitCastInst>(val)) { changed |= handleBitCastInst(Inst, node); } else { const Instruction *I = dyn_cast<Instruction>(val); assert(I && "Not an Instruction?"); if (I->mayReadOrWriteMemory()) errs() << "WARN: Unhandled instruction: " << *val << "\n"; } return changed; } } // namespace analysis } // namespace dg
fix bug from previous commit
points-to: fix bug from previous commit comment in code Signed-off-by: Marek Chalupa <[email protected]>
C++
mit
mchalupa/dg,mchalupa/dg,mchalupa/dg,mchalupa/dg
b083d753f68c5ac595dc4700936d784e7521bfd3
include/eigenpy/user-type.hpp
include/eigenpy/user-type.hpp
// // Copyright (c) 2020 INRIA // #ifndef __eigenpy_user_type_hpp__ #define __eigenpy_user_type_hpp__ #include "eigenpy/fwd.hpp" #include "eigenpy/numpy-type.hpp" #include "eigenpy/register.hpp" namespace eigenpy { namespace internal { template<typename T, int type_code = NumpyEquivalentType<T>::type_code> struct SpecialMethods { static void copyswap(void * /*dst*/, void * /*src*/, int /*swap*/, void * /*arr*/) {}; static PyObject * getitem(void * /*ip*/, void * /*ap*/) { return NULL; }; static int setitem(PyObject * /*op*/, void * /*ov*/, void * /*ap*/) { return -1; } static void copyswapn(void * /*dest*/, long /*dstride*/, void * /*src*/, long /*sstride*/, long /*n*/, int /*swap*/, void * /*arr*/) {}; static npy_bool nonzero(void * /*ip*/, void * /*array*/) { return (npy_bool)false; }; static void dotfunc(void * /*ip0_*/, npy_intp /*is0*/, void * /*ip1_*/, npy_intp /*is1*/, void * /*op*/, npy_intp /*n*/, void * /*arr*/); // static void cast(void * /*from*/, void * /*to*/, npy_intp /*n*/, void * /*fromarr*/, void * /*toarr*/) {}; }; template<typename T> struct SpecialMethods<T,NPY_USERDEF> { static void copyswap(void * dst, void * src, int swap, void * /*arr*/) { // std::cout << "copyswap" << std::endl; if (src != NULL) { T & t1 = *static_cast<T*>(dst); T & t2 = *static_cast<T*>(src); t1 = t2; } if(swap) { T & t1 = *static_cast<T*>(dst); T & t2 = *static_cast<T*>(src); std::swap(t1,t2); } } static PyObject * getitem(void * ip, void * ap) { // std::cout << "getitem" << std::endl; PyArrayObject * py_array = static_cast<PyArrayObject *>(ap); if((py_array==NULL) || PyArray_ISBEHAVED_RO(py_array)) { T * elt_ptr = static_cast<T*>(ip); bp::object m(boost::ref(*elt_ptr)); Py_INCREF(m.ptr()); return m.ptr(); } else { T * elt_ptr = static_cast<T*>(ip); bp::object m(boost::ref(*elt_ptr)); Py_INCREF(m.ptr()); return m.ptr(); } } static int setitem(PyObject * src_obj, void * dest_ptr, void * array) { // std::cout << "setitem" << std::endl; if(array == NULL) { eigenpy::Exception("Cannot retrieve the type stored in the array."); return -1; } PyArrayObject * py_array = static_cast<PyArrayObject *>(array); PyArray_Descr * descr = PyArray_DTYPE(py_array); PyTypeObject * array_scalar_type = descr->typeobj; PyTypeObject * src_obj_type = Py_TYPE(src_obj); if(array_scalar_type != src_obj_type) { return -1; } bp::extract<T&> extract_src_obj(src_obj); if(!extract_src_obj.check()) { std::stringstream ss; ss << "The input type is of wrong type. "; ss << "The expected type is " << bp::type_info(typeid(T)).name() << std::endl; eigenpy::Exception(ss.str()); return -1; } const T & src = extract_src_obj(); T & dest = *static_cast<T*>(dest_ptr); dest = src; return 0; } static void copyswapn(void * dst, long dstride, void * src, long sstride, long n, int swap, void * array) { // std::cout << "copyswapn" << std::endl; char *dstptr = static_cast<char*>(dst); char *srcptr = static_cast<char*>(src); PyArrayObject * py_array = static_cast<PyArrayObject *>(array); PyArray_CopySwapFunc * copyswap = PyArray_DESCR(py_array)->f->copyswap; for (npy_intp i = 0; i < n; i++) { copyswap(dstptr, srcptr, swap, array); dstptr += dstride; srcptr += sstride; } } static npy_bool nonzero(void * ip, void * array) { // std::cout << "nonzero" << std::endl; static const T ZeroValue = T(0); PyArrayObject * py_array = static_cast<PyArrayObject *>(array); if(py_array == NULL || PyArray_ISBEHAVED_RO(py_array)) { const T & value = *static_cast<T*>(ip); return (npy_bool)(value != ZeroValue); } else { T tmp_value; PyArray_DESCR(py_array)->f->copyswap(&tmp_value, ip, PyArray_ISBYTESWAPPED(py_array), array); return (npy_bool)(tmp_value != ZeroValue); } } static void dotfunc(void * ip0_, npy_intp is0, void * ip1_, npy_intp is1, void * op, npy_intp n, void * /*arr*/) { T res = T(0); char *ip0 = (char*)ip0_, *ip1 = (char*)ip1_; npy_intp i; for(i = 0; i < n; i++) { res += *static_cast<T*>(static_cast<void*>(ip0)) * *static_cast<T*>(static_cast<void*>(ip1)); ip0 += is0; ip1 += is1; } *static_cast<T*>(op) = res; } // static void cast(void * from, void * to, npy_intp n, void * fromarr, void * toarr) // { // } }; } // namespace internal template<typename Scalar> int registerNewType(PyTypeObject * py_type_ptr = NULL) { // Check whether the type is a Numpy native type. // In this case, the registration is not required. if(isNumpyNativeType<Scalar>()) return NumpyEquivalentType<Scalar>::type_code; // Retrieve the registered type for the current Scalar if(py_type_ptr == NULL) { // retrive the type from Boost.Python py_type_ptr = Register::getPyType<Scalar>(); } if(Register::isRegistered(py_type_ptr)) return Register::getTypeCode(py_type_ptr); // the type is already registered PyArray_GetItemFunc * getitem = &internal::SpecialMethods<Scalar>::getitem; PyArray_SetItemFunc * setitem = &internal::SpecialMethods<Scalar>::setitem; PyArray_NonzeroFunc * nonzero = &internal::SpecialMethods<Scalar>::nonzero; PyArray_CopySwapFunc * copyswap = &internal::SpecialMethods<Scalar>::copyswap; PyArray_CopySwapNFunc * copyswapn = reinterpret_cast<PyArray_CopySwapNFunc*>(&internal::SpecialMethods<Scalar>::copyswapn); PyArray_DotFunc * dotfunc = &internal::SpecialMethods<Scalar>::dotfunc; // PyArray_CastFunc * cast = &internal::SpecialMethods<Scalar>::cast; int code = Register::registerNewType(py_type_ptr, &typeid(Scalar), sizeof(Scalar), getitem, setitem, nonzero, copyswap, copyswapn, dotfunc); return code; } } // namespace eigenpy #endif // __eigenpy_user_type_hpp__
// // Copyright (c) 2020 INRIA // #ifndef __eigenpy_user_type_hpp__ #define __eigenpy_user_type_hpp__ #include "eigenpy/fwd.hpp" #include "eigenpy/numpy-type.hpp" #include "eigenpy/register.hpp" namespace eigenpy { namespace internal { template<typename T, int type_code = NumpyEquivalentType<T>::type_code> struct SpecialMethods { inline static void copyswap(void * /*dst*/, void * /*src*/, int /*swap*/, void * /*arr*/) /*{}*/; inline static PyObject * getitem(void * /*ip*/, void * /*ap*/) /*{ return NULL; }*/; inline static int setitem(PyObject * /*op*/, void * /*ov*/, void * /*ap*/) /*{ return -1; }*/; inline static void copyswapn(void * /*dest*/, long /*dstride*/, void * /*src*/, long /*sstride*/, long /*n*/, int /*swap*/, void * /*arr*/) /*{}*/; inline static npy_bool nonzero(void * /*ip*/, void * /*array*/) /*{ return (npy_bool)false; }*/; inline static void dotfunc(void * /*ip0_*/, npy_intp /*is0*/, void * /*ip1_*/, npy_intp /*is1*/, void * /*op*/, npy_intp /*n*/, void * /*arr*/); // static void cast(void * /*from*/, void * /*to*/, npy_intp /*n*/, void * /*fromarr*/, void * /*toarr*/) {}; }; template<typename T> struct SpecialMethods<T,NPY_USERDEF> { inline static void copyswap(void * dst, void * src, int swap, void * /*arr*/) { // std::cout << "copyswap" << std::endl; if (src != NULL) { T & t1 = *static_cast<T*>(dst); T & t2 = *static_cast<T*>(src); t1 = t2; } if(swap) { T & t1 = *static_cast<T*>(dst); T & t2 = *static_cast<T*>(src); std::swap(t1,t2); } } inline static PyObject * getitem(void * ip, void * ap) { // std::cout << "getitem" << std::endl; PyArrayObject * py_array = static_cast<PyArrayObject *>(ap); if((py_array==NULL) || PyArray_ISBEHAVED_RO(py_array)) { T * elt_ptr = static_cast<T*>(ip); bp::object m(boost::ref(*elt_ptr)); Py_INCREF(m.ptr()); return m.ptr(); } else { T * elt_ptr = static_cast<T*>(ip); bp::object m(boost::ref(*elt_ptr)); Py_INCREF(m.ptr()); return m.ptr(); } } inline static int setitem(PyObject * src_obj, void * dest_ptr, void * array) { // std::cout << "setitem" << std::endl; if(array == NULL) { eigenpy::Exception("Cannot retrieve the type stored in the array."); return -1; } PyArrayObject * py_array = static_cast<PyArrayObject *>(array); PyArray_Descr * descr = PyArray_DTYPE(py_array); PyTypeObject * array_scalar_type = descr->typeobj; PyTypeObject * src_obj_type = Py_TYPE(src_obj); if(array_scalar_type != src_obj_type) { return -1; } bp::extract<T&> extract_src_obj(src_obj); if(!extract_src_obj.check()) { std::stringstream ss; ss << "The input type is of wrong type. "; ss << "The expected type is " << bp::type_info(typeid(T)).name() << std::endl; eigenpy::Exception(ss.str()); return -1; } const T & src = extract_src_obj(); T & dest = *static_cast<T*>(dest_ptr); dest = src; return 0; } inline static void copyswapn(void * dst, long dstride, void * src, long sstride, long n, int swap, void * array) { // std::cout << "copyswapn" << std::endl; char *dstptr = static_cast<char*>(dst); char *srcptr = static_cast<char*>(src); PyArrayObject * py_array = static_cast<PyArrayObject *>(array); PyArray_CopySwapFunc * copyswap = PyArray_DESCR(py_array)->f->copyswap; for (npy_intp i = 0; i < n; i++) { copyswap(dstptr, srcptr, swap, array); dstptr += dstride; srcptr += sstride; } } inline static npy_bool nonzero(void * ip, void * array) { // std::cout << "nonzero" << std::endl; static const T ZeroValue = T(0); PyArrayObject * py_array = static_cast<PyArrayObject *>(array); if(py_array == NULL || PyArray_ISBEHAVED_RO(py_array)) { const T & value = *static_cast<T*>(ip); return (npy_bool)(value != ZeroValue); } else { T tmp_value; PyArray_DESCR(py_array)->f->copyswap(&tmp_value, ip, PyArray_ISBYTESWAPPED(py_array), array); return (npy_bool)(tmp_value != ZeroValue); } } inline static void dotfunc(void * ip0_, npy_intp is0, void * ip1_, npy_intp is1, void * op, npy_intp n, void * /*arr*/) { T res = T(0); char *ip0 = (char*)ip0_, *ip1 = (char*)ip1_; npy_intp i; for(i = 0; i < n; i++) { res += *static_cast<T*>(static_cast<void*>(ip0)) * *static_cast<T*>(static_cast<void*>(ip1)); ip0 += is0; ip1 += is1; } *static_cast<T*>(op) = res; } // static void cast(void * from, void * to, npy_intp n, void * fromarr, void * toarr) // { // } }; } // namespace internal template<typename Scalar> int registerNewType(PyTypeObject * py_type_ptr = NULL) { // Check whether the type is a Numpy native type. // In this case, the registration is not required. if(isNumpyNativeType<Scalar>()) return NumpyEquivalentType<Scalar>::type_code; // Retrieve the registered type for the current Scalar if(py_type_ptr == NULL) { // retrive the type from Boost.Python py_type_ptr = Register::getPyType<Scalar>(); } if(Register::isRegistered(py_type_ptr)) return Register::getTypeCode(py_type_ptr); // the type is already registered PyArray_GetItemFunc * getitem = &internal::SpecialMethods<Scalar>::getitem; PyArray_SetItemFunc * setitem = &internal::SpecialMethods<Scalar>::setitem; PyArray_NonzeroFunc * nonzero = &internal::SpecialMethods<Scalar>::nonzero; PyArray_CopySwapFunc * copyswap = &internal::SpecialMethods<Scalar>::copyswap; PyArray_CopySwapNFunc * copyswapn = reinterpret_cast<PyArray_CopySwapNFunc*>(&internal::SpecialMethods<Scalar>::copyswapn); PyArray_DotFunc * dotfunc = &internal::SpecialMethods<Scalar>::dotfunc; // PyArray_CastFunc * cast = &internal::SpecialMethods<Scalar>::cast; int code = Register::registerNewType(py_type_ptr, &typeid(Scalar), sizeof(Scalar), getitem, setitem, nonzero, copyswap, copyswapn, dotfunc); return code; } } // namespace eigenpy #endif // __eigenpy_user_type_hpp__
add inline
core: add inline
C++
bsd-2-clause
stack-of-tasks/eigenpy,stack-of-tasks/eigenpy
a2b048786d74aa0fb4107de4c5a1af27e896cee7
src/logger/FassLog.cc
src/logger/FassLog.cc
/** * FassLog.h * * Author: Sara Vallero * Author: Valentina Zaccolo */ #include "FassLog.h" #include "Log.h" Log * FassLog::logger;
/** * Copyright © 2017 INFN Torino - INDIGO-DataCloud * * 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 "FassLog.h" #include "Log.h" Log * FassLog::logger;
Update FassLog.cc
Update FassLog.cc
C++
apache-2.0
indigo-dc/one-fass,indigo-dc/one-fass,indigo-dc/one-fass,indigo-dc/one-fass
67f36aa24da2b2fec9b9c0ba996599d4f9c10f89
include/libtorrent/config.hpp
include/libtorrent/config.hpp
/* Copyright (c) 2005, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TORRENT_CONFIG_HPP_INCLUDED #define TORRENT_CONFIG_HPP_INCLUDED #include <boost/config.hpp> #include <boost/version.hpp> #ifndef WIN32 #define __STDC_FORMAT_MACROS #include <inttypes.h> #endif #ifndef PRId64 #ifdef _WIN32 #define PRId64 "I64d" #else #define PRId64 "lld" #endif #endif #if defined(__GNUC__) && __GNUC__ >= 4 #define TORRENT_DEPRECATED __attribute__ ((deprecated)) # if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED) # define TORRENT_EXPORT __attribute__ ((visibility("default"))) # else # define TORRENT_EXPORT # endif #elif defined(__GNUC__) # define TORRENT_EXPORT #elif defined(BOOST_MSVC) #pragma warning(disable: 4258) #pragma warning(disable: 4251) # if defined(TORRENT_BUILDING_SHARED) # define TORRENT_EXPORT __declspec(dllexport) # elif defined(TORRENT_LINKING_SHARED) # define TORRENT_EXPORT __declspec(dllimport) # else # define TORRENT_EXPORT # endif #else # define TORRENT_EXPORT #endif #ifndef TORRENT_DEPRECATED #define TORRENT_DEPRECATED #endif // set up defines for target environments #if (defined __APPLE__ && __MACH__) || defined __FreeBSD__ || defined __NetBSD__ \ || defined __OpenBSD__ || defined __bsdi__ || defined __DragonFly__ \ || defined __FreeBSD_kernel__ #define TORRENT_BSD #elif defined __linux__ #define TORRENT_LINUX #elif defined WIN32 #define TORRENT_WINDOWS #elif defined sun || defined __sun #define TORRENT_SOLARIS #else #warning unkown OS, assuming BSD #define TORRENT_BSD #endif #define TORRENT_USE_IPV6 1 #define TORRENT_USE_MLOCK 1 #define TORRENT_USE_READV 1 #define TORRENT_USE_WRITEV 1 #ifdef TORRENT_DEBUG #define TORRENT_USE_IOSTREAM 1 #else #define TORRENT_USE_IOSTREAM 0 #endif // should wpath or path be used? #if defined UNICODE && !defined BOOST_FILESYSTEM_NARROW_ONLY \ && BOOST_VERSION >= 103400 && !defined __APPLE__ #define TORRENT_USE_WPATH 1 #else #define TORRENT_USE_WPATH 0 #endif #ifdef TORRENT_WINDOWS // this is the maximum number of characters in a // path element / filename on windows #define NAME_MAX 255 #define snprintf sprintf_s #define strtoll _strtoi64 #endif #if (defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)) && !defined (TORRENT_UPNP_LOGGING) #define TORRENT_UPNP_LOGGING #endif #if !TORRENT_USE_WPATH && defined TORRENT_LINUX // libiconv presnce, not implemented yet #define TORRENT_USE_LOCALE_FILENAMES 1 #else #define TORRENT_USE_LOCALE_FILENAMES 0 #endif #if !defined(TORRENT_READ_HANDLER_MAX_SIZE) # define TORRENT_READ_HANDLER_MAX_SIZE 100 #endif #if !defined(TORRENT_WRITE_HANDLER_MAX_SIZE) # define TORRENT_WRITE_HANDLER_MAX_SIZE 100 #endif #endif // TORRENT_CONFIG_HPP_INCLUDED
/* Copyright (c) 2005, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TORRENT_CONFIG_HPP_INCLUDED #define TORRENT_CONFIG_HPP_INCLUDED #include <boost/config.hpp> #include <boost/version.hpp> #ifndef WIN32 #define __STDC_FORMAT_MACROS #include <inttypes.h> #endif #ifndef PRId64 #ifdef _WIN32 #define PRId64 "I64d" #else #define PRId64 "lld" #endif #endif #if defined(__GNUC__) && __GNUC__ >= 4 #define TORRENT_DEPRECATED __attribute__ ((deprecated)) # if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED) # define TORRENT_EXPORT __attribute__ ((visibility("default"))) # else # define TORRENT_EXPORT # endif #elif defined(__GNUC__) # define TORRENT_EXPORT #elif defined(BOOST_MSVC) #pragma warning(disable: 4258) #pragma warning(disable: 4251) # if defined(TORRENT_BUILDING_SHARED) # define TORRENT_EXPORT __declspec(dllexport) # elif defined(TORRENT_LINKING_SHARED) # define TORRENT_EXPORT __declspec(dllimport) # else # define TORRENT_EXPORT # endif #else # define TORRENT_EXPORT #endif #ifndef TORRENT_DEPRECATED #define TORRENT_DEPRECATED #endif // set up defines for target environments #if (defined __APPLE__ && __MACH__) || defined __FreeBSD__ || defined __NetBSD__ \ || defined __OpenBSD__ || defined __bsdi__ || defined __DragonFly__ \ || defined __FreeBSD_kernel__ #define TORRENT_BSD #elif defined __linux__ #define TORRENT_LINUX #elif defined WIN32 #define TORRENT_WINDOWS #elif defined sun || defined __sun #define TORRENT_SOLARIS #else #warning unkown OS, assuming BSD #define TORRENT_BSD #endif #define TORRENT_USE_IPV6 1 #define TORRENT_USE_MLOCK 1 #define TORRENT_USE_READV 1 #define TORRENT_USE_WRITEV 1 #ifdef TORRENT_DEBUG #define TORRENT_USE_IOSTREAM 1 #else #define TORRENT_USE_IOSTREAM 0 #endif // should wpath or path be used? #if defined UNICODE && !defined BOOST_FILESYSTEM_NARROW_ONLY \ && BOOST_VERSION >= 103400 && !defined __APPLE__ #define TORRENT_USE_WPATH 1 #else #define TORRENT_USE_WPATH 0 #endif #ifdef TORRENT_WINDOWS // this is the maximum number of characters in a // path element / filename on windows #define NAME_MAX 255 #define snprintf sprintf_s #define strtoll _strtoi64 #endif #if (defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)) && !defined (TORRENT_UPNP_LOGGING) #define TORRENT_UPNP_LOGGING #endif #if !TORRENT_USE_WPATH && defined TORRENT_LINUX // libiconv presnce, not implemented yet #define TORRENT_USE_LOCALE_FILENAMES 1 #else #define TORRENT_USE_LOCALE_FILENAMES 0 #endif #if !defined(TORRENT_READ_HANDLER_MAX_SIZE) # define TORRENT_READ_HANDLER_MAX_SIZE 256 #endif #if !defined(TORRENT_WRITE_HANDLER_MAX_SIZE) # define TORRENT_WRITE_HANDLER_MAX_SIZE 256 #endif #endif // TORRENT_CONFIG_HPP_INCLUDED
Use a safer default handler storage size until we can figure out some good platform specific defaults.
Use a safer default handler storage size until we can figure out some good platform specific defaults.
C++
bsd-3-clause
mildred/rasterbar-libtorrent,mrmichalis/libtorrent-code,mildred/rasterbar-libtorrent,mrmichalis/libtorrent-code,mildred/rasterbar-libtorrent,mildred/rasterbar-libtorrent,mrmichalis/libtorrent-code,mrmichalis/libtorrent-code,mrmichalis/libtorrent-code,mrmichalis/libtorrent-code,mildred/rasterbar-libtorrent,mildred/rasterbar-libtorrent
3b99b0a1fe909af5dcd7f588aac6d79a008724d4
include/libtorrent/config.hpp
include/libtorrent/config.hpp
/* Copyright (c) 2005, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TORRENT_CONFIG_HPP_INCLUDED #define TORRENT_CONFIG_HPP_INCLUDED #include <boost/config.hpp> #include <boost/version.hpp> #include <stdio.h> // for snprintf #include <stdlib.h> // for _TRUNCATE (windows) #include <stdarg.h> #ifndef WIN32 #define __STDC_FORMAT_MACROS #include <inttypes.h> #endif #ifndef PRId64 #ifdef _WIN32 #define PRId64 "I64d" #else #define PRId64 "lld" #endif #endif #if defined(__GNUC__) && __GNUC__ >= 4 #define TORRENT_DEPRECATED __attribute__ ((deprecated)) # if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED) # define TORRENT_EXPORT __attribute__ ((visibility("default"))) # else # define TORRENT_EXPORT # endif #elif defined(__GNUC__) # define TORRENT_EXPORT #elif defined(BOOST_MSVC) #pragma warning(disable: 4258) #pragma warning(disable: 4251) # if defined(TORRENT_BUILDING_SHARED) # define TORRENT_EXPORT __declspec(dllexport) # elif defined(TORRENT_LINKING_SHARED) # define TORRENT_EXPORT __declspec(dllimport) # else # define TORRENT_EXPORT # endif #else # define TORRENT_EXPORT #endif #ifndef TORRENT_DEPRECATED #define TORRENT_DEPRECATED #endif // set up defines for target environments #if (defined __APPLE__ && __MACH__) || defined __FreeBSD__ || defined __NetBSD__ \ || defined __OpenBSD__ || defined __bsdi__ || defined __DragonFly__ \ || defined __FreeBSD_kernel__ #define TORRENT_BSD #elif defined __linux__ #define TORRENT_LINUX #elif defined __MINGW32__ #define TORRENT_MINGW #elif defined WIN32 #define TORRENT_WINDOWS #elif defined sun || defined __sun #define TORRENT_SOLARIS #else #warning unkown OS, assuming BSD #define TORRENT_BSD #endif #define TORRENT_USE_IPV6 1 #define TORRENT_USE_MLOCK 1 #define TORRENT_USE_READV 1 #define TORRENT_USE_WRITEV 1 #define TORRENT_USE_IOSTREAM 1 // should wpath or path be used? #if defined UNICODE && !defined BOOST_FILESYSTEM_NARROW_ONLY \ && BOOST_VERSION >= 103400 && !defined __APPLE__ #define TORRENT_USE_WPATH 1 #else #define TORRENT_USE_WPATH 0 #endif // set this to 1 to disable all floating point operations // (disables some float-dependent APIs) #define TORRENT_NO_FPU 1 #ifdef TORRENT_WINDOWS #include <stdarg.h> // this is the maximum number of characters in a // path element / filename on windows #define NAME_MAX 255 inline int snprintf(char* buf, int len, char const* fmt, ...) { va_list lp; va_start(lp, fmt); return vsnprintf_s(buf, len, _TRUNCATE, fmt, lp); } #define strtoll _strtoi64 #else #include <limits.h> #endif #if (defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)) && !defined (TORRENT_UPNP_LOGGING) #define TORRENT_UPNP_LOGGING #endif #if !TORRENT_USE_WPATH && defined TORRENT_LINUX // libiconv presnce, not implemented yet #define TORRENT_USE_LOCALE_FILENAMES 1 #else #define TORRENT_USE_LOCALE_FILENAMES 0 #endif #if !defined(TORRENT_READ_HANDLER_MAX_SIZE) # define TORRENT_READ_HANDLER_MAX_SIZE 256 #endif #if !defined(TORRENT_WRITE_HANDLER_MAX_SIZE) # define TORRENT_WRITE_HANDLER_MAX_SIZE 256 #endif #if defined _MSC_VER && _MSC_VER <= 1200 #define for if (false) {} else for #endif // determine what timer implementation we can use #if defined(__MACH__) #define TORRENT_USE_ABSOLUTE_TIME 1 #elif defined(_WIN32) #define TORRENT_USE_QUERY_PERFORMANCE_TIMER 1 #elif defined(_POSIX_MONOTONIC_CLOCK) && _POSIX_MONOTONIC_CLOCK >= 0 #define TORRENT_USE_CLOCK_GETTIME 1 #else #define TORRENT_USE_BOOST_DATE_TIME 1 #endif #endif // TORRENT_CONFIG_HPP_INCLUDED
/* Copyright (c) 2005, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TORRENT_CONFIG_HPP_INCLUDED #define TORRENT_CONFIG_HPP_INCLUDED #include <boost/config.hpp> #include <boost/version.hpp> #include <stdio.h> // for snprintf #include <stdlib.h> // for _TRUNCATE (windows) #include <stdarg.h> #ifndef WIN32 #define __STDC_FORMAT_MACROS #include <inttypes.h> #endif #ifndef PRId64 #ifdef _WIN32 #define PRId64 "I64d" #else #define PRId64 "lld" #endif #endif #if defined(__GNUC__) && __GNUC__ >= 4 #define TORRENT_DEPRECATED __attribute__ ((deprecated)) # if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED) # define TORRENT_EXPORT __attribute__ ((visibility("default"))) # else # define TORRENT_EXPORT # endif #elif defined(__GNUC__) # define TORRENT_EXPORT #elif defined(BOOST_MSVC) #pragma warning(disable: 4258) #pragma warning(disable: 4251) # if defined(TORRENT_BUILDING_SHARED) # define TORRENT_EXPORT __declspec(dllexport) # elif defined(TORRENT_LINKING_SHARED) # define TORRENT_EXPORT __declspec(dllimport) # else # define TORRENT_EXPORT # endif #else # define TORRENT_EXPORT #endif #ifndef TORRENT_DEPRECATED #define TORRENT_DEPRECATED #endif // set up defines for target environments #if (defined __APPLE__ && __MACH__) || defined __FreeBSD__ || defined __NetBSD__ \ || defined __OpenBSD__ || defined __bsdi__ || defined __DragonFly__ \ || defined __FreeBSD_kernel__ #define TORRENT_BSD #elif defined __linux__ #define TORRENT_LINUX #elif defined __MINGW32__ #define TORRENT_MINGW #elif defined WIN32 #define TORRENT_WINDOWS #elif defined sun || defined __sun #define TORRENT_SOLARIS #else #warning unkown OS, assuming BSD #define TORRENT_BSD #endif #define TORRENT_USE_IPV6 1 #define TORRENT_USE_MLOCK 1 #define TORRENT_USE_READV 1 #define TORRENT_USE_WRITEV 1 #define TORRENT_USE_IOSTREAM 1 // should wpath or path be used? #if defined UNICODE && !defined BOOST_FILESYSTEM_NARROW_ONLY \ && BOOST_VERSION >= 103400 && !defined __APPLE__ #define TORRENT_USE_WPATH 1 #else #define TORRENT_USE_WPATH 0 #endif // set this to 1 to disable all floating point operations // (disables some float-dependent APIs) #define TORRENT_NO_FPU 0 #ifdef TORRENT_WINDOWS #include <stdarg.h> // this is the maximum number of characters in a // path element / filename on windows #define NAME_MAX 255 inline int snprintf(char* buf, int len, char const* fmt, ...) { va_list lp; va_start(lp, fmt); return vsnprintf_s(buf, len, _TRUNCATE, fmt, lp); } #define strtoll _strtoi64 #else #include <limits.h> #endif #if (defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)) && !defined (TORRENT_UPNP_LOGGING) #define TORRENT_UPNP_LOGGING #endif #if !TORRENT_USE_WPATH && defined TORRENT_LINUX // libiconv presnce, not implemented yet #define TORRENT_USE_LOCALE_FILENAMES 1 #else #define TORRENT_USE_LOCALE_FILENAMES 0 #endif #if !defined(TORRENT_READ_HANDLER_MAX_SIZE) # define TORRENT_READ_HANDLER_MAX_SIZE 256 #endif #if !defined(TORRENT_WRITE_HANDLER_MAX_SIZE) # define TORRENT_WRITE_HANDLER_MAX_SIZE 256 #endif #if defined _MSC_VER && _MSC_VER <= 1200 #define for if (false) {} else for #endif // determine what timer implementation we can use #if defined(__MACH__) #define TORRENT_USE_ABSOLUTE_TIME 1 #elif defined(_WIN32) #define TORRENT_USE_QUERY_PERFORMANCE_TIMER 1 #elif defined(_POSIX_MONOTONIC_CLOCK) && _POSIX_MONOTONIC_CLOCK >= 0 #define TORRENT_USE_CLOCK_GETTIME 1 #else #define TORRENT_USE_BOOST_DATE_TIME 1 #endif #endif // TORRENT_CONFIG_HPP_INCLUDED
enable floating point API by default
enable floating point API by default git-svn-id: 6ed3528c1be4534134272ad6dd050eeaa1f628d3@3729 f43f7eb3-cfe1-5f9d-1b5f-e45aa6702bda
C++
bsd-3-clause
steeve/libtorrent,steeve/libtorrent,steeve/libtorrent,steeve/libtorrent,steeve/libtorrent,steeve/libtorrent
a0723e810e06683e184891297cd50a33ff52a6e3
gpu/command_buffer/service/texture_definition.cc
gpu/command_buffer/service/texture_definition.cc
// Copyright 2014 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 "gpu/command_buffer/service/texture_definition.h" #include <list> #include "base/memory/linked_ptr.h" #include "base/memory/scoped_ptr.h" #include "base/synchronization/lock.h" #include "gpu/command_buffer/service/texture_manager.h" #include "ui/gl/gl_image.h" #include "ui/gl/gl_implementation.h" #include "ui/gl/scoped_binders.h" #if !defined(OS_MACOSX) #include "ui/gl/gl_fence_egl.h" #include "ui/gl/gl_surface_egl.h" #endif namespace gpu { namespace gles2 { namespace { class GLImageSync : public gfx::GLImage { public: explicit GLImageSync( const scoped_refptr<NativeImageBuffer>& buffer); // Implement GLImage. virtual void Destroy() OVERRIDE; virtual gfx::Size GetSize() OVERRIDE; virtual bool BindTexImage(unsigned target) OVERRIDE; virtual void ReleaseTexImage(unsigned target) OVERRIDE; virtual void WillUseTexImage() OVERRIDE; virtual void WillModifyTexImage() OVERRIDE; virtual void DidModifyTexImage() OVERRIDE; virtual void DidUseTexImage() OVERRIDE; virtual void SetReleaseAfterUse() OVERRIDE; protected: virtual ~GLImageSync(); private: scoped_refptr<NativeImageBuffer> buffer_; DISALLOW_COPY_AND_ASSIGN(GLImageSync); }; GLImageSync::GLImageSync(const scoped_refptr<NativeImageBuffer>& buffer) : buffer_(buffer) { if (buffer) buffer->AddClient(this); } GLImageSync::~GLImageSync() { if (buffer_) buffer_->RemoveClient(this); } void GLImageSync::Destroy() {} gfx::Size GLImageSync::GetSize() { NOTREACHED(); return gfx::Size(); } bool GLImageSync::BindTexImage(unsigned target) { NOTREACHED(); return false; } void GLImageSync::ReleaseTexImage(unsigned target) { NOTREACHED(); } void GLImageSync::WillUseTexImage() { if (buffer_) buffer_->WillRead(this); } void GLImageSync::DidUseTexImage() { if (buffer_) buffer_->DidRead(this); } void GLImageSync::WillModifyTexImage() { if (buffer_) buffer_->WillWrite(this); } void GLImageSync::DidModifyTexImage() { if (buffer_) buffer_->DidWrite(this); } void GLImageSync::SetReleaseAfterUse() { NOTREACHED(); } #if !defined(OS_MACOSX) class NativeImageBufferEGL : public NativeImageBuffer { public: static scoped_refptr<NativeImageBufferEGL> Create(GLuint texture_id); private: NativeImageBufferEGL(EGLDisplay display, EGLImageKHR image); virtual ~NativeImageBufferEGL(); virtual void AddClient(gfx::GLImage* client) OVERRIDE; virtual void RemoveClient(gfx::GLImage* client) OVERRIDE; virtual bool IsClient(gfx::GLImage* client) OVERRIDE; virtual void BindToTexture(GLenum target) OVERRIDE; virtual void WillRead(gfx::GLImage* client) OVERRIDE; virtual void WillWrite(gfx::GLImage* client) OVERRIDE; virtual void DidRead(gfx::GLImage* client) OVERRIDE; virtual void DidWrite(gfx::GLImage* client) OVERRIDE; EGLDisplay egl_display_; EGLImageKHR egl_image_; base::Lock lock_; struct ClientInfo { ClientInfo(gfx::GLImage* client); ~ClientInfo(); gfx::GLImage* client; bool needs_wait_before_read; linked_ptr<gfx::GLFence> read_fence; }; std::list<ClientInfo> client_infos_; scoped_ptr<gfx::GLFence> write_fence_; gfx::GLImage* write_client_; DISALLOW_COPY_AND_ASSIGN(NativeImageBufferEGL); }; scoped_refptr<NativeImageBufferEGL> NativeImageBufferEGL::Create( GLuint texture_id) { EGLDisplay egl_display = gfx::GLSurfaceEGL::GetHardwareDisplay(); EGLContext egl_context = eglGetCurrentContext(); DCHECK_NE(EGL_NO_CONTEXT, egl_context); DCHECK_NE(EGL_NO_DISPLAY, egl_display); DCHECK(glIsTexture(texture_id)); DCHECK(gfx::g_driver_egl.ext.b_EGL_KHR_image_base && gfx::g_driver_egl.ext.b_EGL_KHR_gl_texture_2D_image && gfx::g_driver_gl.ext.b_GL_OES_EGL_image && gfx::g_driver_egl.ext.b_EGL_KHR_fence_sync); const EGLint egl_attrib_list[] = { EGL_GL_TEXTURE_LEVEL_KHR, 0, EGL_IMAGE_PRESERVED_KHR, EGL_TRUE, EGL_NONE}; EGLClientBuffer egl_buffer = reinterpret_cast<EGLClientBuffer>(texture_id); EGLenum egl_target = EGL_GL_TEXTURE_2D_KHR; // TODO EGLImageKHR egl_image = eglCreateImageKHR( egl_display, egl_context, egl_target, egl_buffer, egl_attrib_list); if (egl_image == EGL_NO_IMAGE_KHR) return NULL; return new NativeImageBufferEGL(egl_display, egl_image); } NativeImageBufferEGL::ClientInfo::ClientInfo(gfx::GLImage* client) : client(client), needs_wait_before_read(true) {} NativeImageBufferEGL::ClientInfo::~ClientInfo() {} NativeImageBufferEGL::NativeImageBufferEGL(EGLDisplay display, EGLImageKHR image) : NativeImageBuffer(), egl_display_(display), egl_image_(image), write_fence_(new gfx::GLFenceEGL(true)), write_client_(NULL) { DCHECK(egl_display_ != EGL_NO_DISPLAY); DCHECK(egl_image_ != EGL_NO_IMAGE_KHR); } NativeImageBufferEGL::~NativeImageBufferEGL() { DCHECK(client_infos_.empty()); if (egl_image_ != EGL_NO_IMAGE_KHR) eglDestroyImageKHR(egl_display_, egl_image_); } void NativeImageBufferEGL::AddClient(gfx::GLImage* client) { base::AutoLock lock(lock_); client_infos_.push_back(ClientInfo(client)); } void NativeImageBufferEGL::RemoveClient(gfx::GLImage* client) { base::AutoLock lock(lock_); if (write_client_ == client) write_client_ = NULL; for (std::list<ClientInfo>::iterator it = client_infos_.begin(); it != client_infos_.end(); it++) { if (it->client == client) { client_infos_.erase(it); return; } } NOTREACHED(); } bool NativeImageBufferEGL::IsClient(gfx::GLImage* client) { base::AutoLock lock(lock_); for (std::list<ClientInfo>::iterator it = client_infos_.begin(); it != client_infos_.end(); it++) { if (it->client == client) return true; } return false; } void NativeImageBufferEGL::BindToTexture(GLenum target) { DCHECK(egl_image_ != EGL_NO_IMAGE_KHR); glEGLImageTargetTexture2DOES(target, egl_image_); DCHECK_EQ(static_cast<EGLint>(EGL_SUCCESS), eglGetError()); DCHECK_EQ(static_cast<GLenum>(GL_NO_ERROR), glGetError()); } void NativeImageBufferEGL::WillRead(gfx::GLImage* client) { base::AutoLock lock(lock_); if (!write_fence_.get() || write_client_ == client) return; for (std::list<ClientInfo>::iterator it = client_infos_.begin(); it != client_infos_.end(); it++) { if (it->client == client) { if (it->needs_wait_before_read) { it->needs_wait_before_read = false; write_fence_->ServerWait(); } return; } } NOTREACHED(); } void NativeImageBufferEGL::WillWrite(gfx::GLImage* client) { base::AutoLock lock(lock_); if (write_client_ != client) write_fence_->ServerWait(); for (std::list<ClientInfo>::iterator it = client_infos_.begin(); it != client_infos_.end(); it++) { if (it->read_fence.get() && it->client != client) it->read_fence->ServerWait(); } } void NativeImageBufferEGL::DidRead(gfx::GLImage* client) { base::AutoLock lock(lock_); for (std::list<ClientInfo>::iterator it = client_infos_.begin(); it != client_infos_.end(); it++) { if (it->client == client) { it->read_fence = make_linked_ptr(new gfx::GLFenceEGL(true)); return; } } NOTREACHED(); } void NativeImageBufferEGL::DidWrite(gfx::GLImage* client) { base::AutoLock lock(lock_); // Sharing semantics require the client to flush in order to make changes // visible to other clients. write_fence_.reset(new gfx::GLFenceEGL(false)); write_client_ = client; for (std::list<ClientInfo>::iterator it = client_infos_.begin(); it != client_infos_.end(); it++) { it->needs_wait_before_read = true; } } #endif class NativeImageBufferStub : public NativeImageBuffer { public: NativeImageBufferStub() : NativeImageBuffer() {} private: virtual ~NativeImageBufferStub() {} virtual void AddClient(gfx::GLImage* client) OVERRIDE {} virtual void RemoveClient(gfx::GLImage* client) OVERRIDE {} virtual bool IsClient(gfx::GLImage* client) OVERRIDE { return true; } virtual void BindToTexture(GLenum target) OVERRIDE {} virtual void WillRead(gfx::GLImage* client) OVERRIDE {} virtual void WillWrite(gfx::GLImage* client) OVERRIDE {} virtual void DidRead(gfx::GLImage* client) OVERRIDE {} virtual void DidWrite(gfx::GLImage* client) OVERRIDE {} DISALLOW_COPY_AND_ASSIGN(NativeImageBufferStub); }; } // anonymous namespace // static scoped_refptr<NativeImageBuffer> NativeImageBuffer::Create(GLuint texture_id) { switch (gfx::GetGLImplementation()) { #if !defined(OS_MACOSX) case gfx::kGLImplementationEGLGLES2: return NativeImageBufferEGL::Create(texture_id); #endif case gfx::kGLImplementationMockGL: return new NativeImageBufferStub; default: NOTREACHED(); return NULL; } } TextureDefinition::LevelInfo::LevelInfo(GLenum target, GLenum internal_format, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, bool cleared) : target(target), internal_format(internal_format), width(width), height(height), depth(depth), border(border), format(format), type(type), cleared(cleared) {} TextureDefinition::LevelInfo::~LevelInfo() {} TextureDefinition::TextureDefinition( GLenum target, Texture* texture, unsigned int version, const scoped_refptr<NativeImageBuffer>& image_buffer) : version_(version), target_(target), image_buffer_(image_buffer ? image_buffer : NativeImageBuffer::Create( texture->service_id())), min_filter_(texture->min_filter()), mag_filter_(texture->mag_filter()), wrap_s_(texture->wrap_s()), wrap_t_(texture->wrap_t()), usage_(texture->usage()), immutable_(texture->IsImmutable()) { // TODO DCHECK(!texture->level_infos_.empty()); DCHECK(!texture->level_infos_[0].empty()); DCHECK(!texture->NeedsMips()); DCHECK(texture->level_infos_[0][0].width); DCHECK(texture->level_infos_[0][0].height); scoped_refptr<gfx::GLImage> gl_image(new GLImageSync(image_buffer_)); texture->SetLevelImage(NULL, target, 0, gl_image); // TODO: all levels level_infos_.clear(); const Texture::LevelInfo& level = texture->level_infos_[0][0]; LevelInfo info(level.target, level.internal_format, level.width, level.height, level.depth, level.border, level.format, level.type, level.cleared); std::vector<LevelInfo> infos; infos.push_back(info); level_infos_.push_back(infos); } TextureDefinition::~TextureDefinition() { } Texture* TextureDefinition::CreateTexture() const { if (!image_buffer_) return NULL; GLuint texture_id; glGenTextures(1, &texture_id); Texture* texture(new Texture(texture_id)); UpdateTexture(texture); return texture; } void TextureDefinition::UpdateTexture(Texture* texture) const { gfx::ScopedTextureBinder texture_binder(target_, texture->service_id()); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, min_filter_); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, mag_filter_); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrap_s_); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrap_t_); if (image_buffer_) image_buffer_->BindToTexture(target_); // We have to make sure the changes are visible to other clients in this share // group. As far as the clients are concerned, the mailbox semantics only // demand a single flush from the client after changes are first made, // and it is not visible to them when another share group boundary is crossed. // We could probably track this and be a bit smarter about when to flush // though. glFlush(); texture->level_infos_.resize(1); for (size_t i = 0; i < level_infos_.size(); i++) { const LevelInfo& base_info = level_infos_[i][0]; const size_t levels_needed = TextureManager::ComputeMipMapCount( base_info.target, base_info.width, base_info.height, base_info.depth); DCHECK(level_infos_.size() <= levels_needed); texture->level_infos_[0].resize(levels_needed); for (size_t n = 0; n < level_infos_.size(); n++) { const LevelInfo& info = level_infos_[i][n]; texture->SetLevelInfo(NULL, info.target, i, info.internal_format, info.width, info.height, info.depth, info.border, info.format, info.type, info.cleared); } } if (image_buffer_) texture->SetLevelImage(NULL, target_, 0, new GLImageSync(image_buffer_)); texture->target_ = target_; texture->SetImmutable(immutable_); texture->min_filter_ = min_filter_; texture->mag_filter_ = mag_filter_; texture->wrap_s_ = wrap_s_; texture->wrap_t_ = wrap_t_; texture->usage_ = usage_; } bool TextureDefinition::Matches(const Texture* texture) const { DCHECK(target_ == texture->target()); if (texture->min_filter_ != min_filter_ || texture->mag_filter_ != mag_filter_ || texture->wrap_s_ != wrap_s_ || texture->wrap_t_ != wrap_t_) { return false; } // All structural changes should have orphaned the texture. if (image_buffer_ && !texture->GetLevelImage(texture->target(), 0)) return false; return true; } } // namespace gles2 } // namespace gpu
// Copyright 2014 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 "gpu/command_buffer/service/texture_definition.h" #include <list> #include "base/memory/linked_ptr.h" #include "base/memory/scoped_ptr.h" #include "base/synchronization/lock.h" #include "gpu/command_buffer/service/texture_manager.h" #include "ui/gl/gl_image.h" #include "ui/gl/gl_implementation.h" #include "ui/gl/scoped_binders.h" #if !defined(OS_MACOSX) #include "ui/gl/gl_fence_egl.h" #include "ui/gl/gl_surface_egl.h" #endif namespace gpu { namespace gles2 { namespace { class GLImageSync : public gfx::GLImage { public: explicit GLImageSync(const scoped_refptr<NativeImageBuffer>& buffer, const gfx::Size& size); // Implement GLImage. virtual void Destroy() OVERRIDE; virtual gfx::Size GetSize() OVERRIDE; virtual bool BindTexImage(unsigned target) OVERRIDE; virtual void ReleaseTexImage(unsigned target) OVERRIDE; virtual void WillUseTexImage() OVERRIDE; virtual void WillModifyTexImage() OVERRIDE; virtual void DidModifyTexImage() OVERRIDE; virtual void DidUseTexImage() OVERRIDE; virtual void SetReleaseAfterUse() OVERRIDE; protected: virtual ~GLImageSync(); private: scoped_refptr<NativeImageBuffer> buffer_; gfx::Size size_; DISALLOW_COPY_AND_ASSIGN(GLImageSync); }; GLImageSync::GLImageSync(const scoped_refptr<NativeImageBuffer>& buffer, const gfx::Size& size) : buffer_(buffer), size_(size) { if (buffer) buffer->AddClient(this); } GLImageSync::~GLImageSync() { if (buffer_) buffer_->RemoveClient(this); } void GLImageSync::Destroy() {} gfx::Size GLImageSync::GetSize() { return size_; } bool GLImageSync::BindTexImage(unsigned target) { NOTREACHED(); return false; } void GLImageSync::ReleaseTexImage(unsigned target) { NOTREACHED(); } void GLImageSync::WillUseTexImage() { if (buffer_) buffer_->WillRead(this); } void GLImageSync::DidUseTexImage() { if (buffer_) buffer_->DidRead(this); } void GLImageSync::WillModifyTexImage() { if (buffer_) buffer_->WillWrite(this); } void GLImageSync::DidModifyTexImage() { if (buffer_) buffer_->DidWrite(this); } void GLImageSync::SetReleaseAfterUse() { NOTREACHED(); } #if !defined(OS_MACOSX) class NativeImageBufferEGL : public NativeImageBuffer { public: static scoped_refptr<NativeImageBufferEGL> Create(GLuint texture_id); private: NativeImageBufferEGL(EGLDisplay display, EGLImageKHR image); virtual ~NativeImageBufferEGL(); virtual void AddClient(gfx::GLImage* client) OVERRIDE; virtual void RemoveClient(gfx::GLImage* client) OVERRIDE; virtual bool IsClient(gfx::GLImage* client) OVERRIDE; virtual void BindToTexture(GLenum target) OVERRIDE; virtual void WillRead(gfx::GLImage* client) OVERRIDE; virtual void WillWrite(gfx::GLImage* client) OVERRIDE; virtual void DidRead(gfx::GLImage* client) OVERRIDE; virtual void DidWrite(gfx::GLImage* client) OVERRIDE; EGLDisplay egl_display_; EGLImageKHR egl_image_; base::Lock lock_; struct ClientInfo { ClientInfo(gfx::GLImage* client); ~ClientInfo(); gfx::GLImage* client; bool needs_wait_before_read; linked_ptr<gfx::GLFence> read_fence; }; std::list<ClientInfo> client_infos_; scoped_ptr<gfx::GLFence> write_fence_; gfx::GLImage* write_client_; DISALLOW_COPY_AND_ASSIGN(NativeImageBufferEGL); }; scoped_refptr<NativeImageBufferEGL> NativeImageBufferEGL::Create( GLuint texture_id) { EGLDisplay egl_display = gfx::GLSurfaceEGL::GetHardwareDisplay(); EGLContext egl_context = eglGetCurrentContext(); DCHECK_NE(EGL_NO_CONTEXT, egl_context); DCHECK_NE(EGL_NO_DISPLAY, egl_display); DCHECK(glIsTexture(texture_id)); DCHECK(gfx::g_driver_egl.ext.b_EGL_KHR_image_base && gfx::g_driver_egl.ext.b_EGL_KHR_gl_texture_2D_image && gfx::g_driver_gl.ext.b_GL_OES_EGL_image && gfx::g_driver_egl.ext.b_EGL_KHR_fence_sync); const EGLint egl_attrib_list[] = { EGL_GL_TEXTURE_LEVEL_KHR, 0, EGL_IMAGE_PRESERVED_KHR, EGL_TRUE, EGL_NONE}; EGLClientBuffer egl_buffer = reinterpret_cast<EGLClientBuffer>(texture_id); EGLenum egl_target = EGL_GL_TEXTURE_2D_KHR; // TODO EGLImageKHR egl_image = eglCreateImageKHR( egl_display, egl_context, egl_target, egl_buffer, egl_attrib_list); if (egl_image == EGL_NO_IMAGE_KHR) return NULL; return new NativeImageBufferEGL(egl_display, egl_image); } NativeImageBufferEGL::ClientInfo::ClientInfo(gfx::GLImage* client) : client(client), needs_wait_before_read(true) {} NativeImageBufferEGL::ClientInfo::~ClientInfo() {} NativeImageBufferEGL::NativeImageBufferEGL(EGLDisplay display, EGLImageKHR image) : NativeImageBuffer(), egl_display_(display), egl_image_(image), write_fence_(new gfx::GLFenceEGL(true)), write_client_(NULL) { DCHECK(egl_display_ != EGL_NO_DISPLAY); DCHECK(egl_image_ != EGL_NO_IMAGE_KHR); } NativeImageBufferEGL::~NativeImageBufferEGL() { DCHECK(client_infos_.empty()); if (egl_image_ != EGL_NO_IMAGE_KHR) eglDestroyImageKHR(egl_display_, egl_image_); } void NativeImageBufferEGL::AddClient(gfx::GLImage* client) { base::AutoLock lock(lock_); client_infos_.push_back(ClientInfo(client)); } void NativeImageBufferEGL::RemoveClient(gfx::GLImage* client) { base::AutoLock lock(lock_); if (write_client_ == client) write_client_ = NULL; for (std::list<ClientInfo>::iterator it = client_infos_.begin(); it != client_infos_.end(); it++) { if (it->client == client) { client_infos_.erase(it); return; } } NOTREACHED(); } bool NativeImageBufferEGL::IsClient(gfx::GLImage* client) { base::AutoLock lock(lock_); for (std::list<ClientInfo>::iterator it = client_infos_.begin(); it != client_infos_.end(); it++) { if (it->client == client) return true; } return false; } void NativeImageBufferEGL::BindToTexture(GLenum target) { DCHECK(egl_image_ != EGL_NO_IMAGE_KHR); glEGLImageTargetTexture2DOES(target, egl_image_); DCHECK_EQ(static_cast<EGLint>(EGL_SUCCESS), eglGetError()); DCHECK_EQ(static_cast<GLenum>(GL_NO_ERROR), glGetError()); } void NativeImageBufferEGL::WillRead(gfx::GLImage* client) { base::AutoLock lock(lock_); if (!write_fence_.get() || write_client_ == client) return; for (std::list<ClientInfo>::iterator it = client_infos_.begin(); it != client_infos_.end(); it++) { if (it->client == client) { if (it->needs_wait_before_read) { it->needs_wait_before_read = false; write_fence_->ServerWait(); } return; } } NOTREACHED(); } void NativeImageBufferEGL::WillWrite(gfx::GLImage* client) { base::AutoLock lock(lock_); if (write_client_ != client) write_fence_->ServerWait(); for (std::list<ClientInfo>::iterator it = client_infos_.begin(); it != client_infos_.end(); it++) { if (it->read_fence.get() && it->client != client) it->read_fence->ServerWait(); } } void NativeImageBufferEGL::DidRead(gfx::GLImage* client) { base::AutoLock lock(lock_); for (std::list<ClientInfo>::iterator it = client_infos_.begin(); it != client_infos_.end(); it++) { if (it->client == client) { it->read_fence = make_linked_ptr(new gfx::GLFenceEGL(true)); return; } } NOTREACHED(); } void NativeImageBufferEGL::DidWrite(gfx::GLImage* client) { base::AutoLock lock(lock_); // Sharing semantics require the client to flush in order to make changes // visible to other clients. write_fence_.reset(new gfx::GLFenceEGL(false)); write_client_ = client; for (std::list<ClientInfo>::iterator it = client_infos_.begin(); it != client_infos_.end(); it++) { it->needs_wait_before_read = true; } } #endif class NativeImageBufferStub : public NativeImageBuffer { public: NativeImageBufferStub() : NativeImageBuffer() {} private: virtual ~NativeImageBufferStub() {} virtual void AddClient(gfx::GLImage* client) OVERRIDE {} virtual void RemoveClient(gfx::GLImage* client) OVERRIDE {} virtual bool IsClient(gfx::GLImage* client) OVERRIDE { return true; } virtual void BindToTexture(GLenum target) OVERRIDE {} virtual void WillRead(gfx::GLImage* client) OVERRIDE {} virtual void WillWrite(gfx::GLImage* client) OVERRIDE {} virtual void DidRead(gfx::GLImage* client) OVERRIDE {} virtual void DidWrite(gfx::GLImage* client) OVERRIDE {} DISALLOW_COPY_AND_ASSIGN(NativeImageBufferStub); }; } // anonymous namespace // static scoped_refptr<NativeImageBuffer> NativeImageBuffer::Create(GLuint texture_id) { switch (gfx::GetGLImplementation()) { #if !defined(OS_MACOSX) case gfx::kGLImplementationEGLGLES2: return NativeImageBufferEGL::Create(texture_id); #endif case gfx::kGLImplementationMockGL: return new NativeImageBufferStub; default: NOTREACHED(); return NULL; } } TextureDefinition::LevelInfo::LevelInfo(GLenum target, GLenum internal_format, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, bool cleared) : target(target), internal_format(internal_format), width(width), height(height), depth(depth), border(border), format(format), type(type), cleared(cleared) {} TextureDefinition::LevelInfo::~LevelInfo() {} TextureDefinition::TextureDefinition( GLenum target, Texture* texture, unsigned int version, const scoped_refptr<NativeImageBuffer>& image_buffer) : version_(version), target_(target), image_buffer_(image_buffer ? image_buffer : NativeImageBuffer::Create( texture->service_id())), min_filter_(texture->min_filter()), mag_filter_(texture->mag_filter()), wrap_s_(texture->wrap_s()), wrap_t_(texture->wrap_t()), usage_(texture->usage()), immutable_(texture->IsImmutable()) { // TODO DCHECK(!texture->level_infos_.empty()); DCHECK(!texture->level_infos_[0].empty()); DCHECK(!texture->NeedsMips()); DCHECK(texture->level_infos_[0][0].width); DCHECK(texture->level_infos_[0][0].height); scoped_refptr<gfx::GLImage> gl_image( new GLImageSync(image_buffer_, gfx::Size(texture->level_infos_[0][0].width, texture->level_infos_[0][0].height))); texture->SetLevelImage(NULL, target, 0, gl_image); // TODO: all levels level_infos_.clear(); const Texture::LevelInfo& level = texture->level_infos_[0][0]; LevelInfo info(level.target, level.internal_format, level.width, level.height, level.depth, level.border, level.format, level.type, level.cleared); std::vector<LevelInfo> infos; infos.push_back(info); level_infos_.push_back(infos); } TextureDefinition::~TextureDefinition() { } Texture* TextureDefinition::CreateTexture() const { if (!image_buffer_) return NULL; GLuint texture_id; glGenTextures(1, &texture_id); Texture* texture(new Texture(texture_id)); UpdateTexture(texture); return texture; } void TextureDefinition::UpdateTexture(Texture* texture) const { gfx::ScopedTextureBinder texture_binder(target_, texture->service_id()); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, min_filter_); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, mag_filter_); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrap_s_); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrap_t_); if (image_buffer_) image_buffer_->BindToTexture(target_); // We have to make sure the changes are visible to other clients in this share // group. As far as the clients are concerned, the mailbox semantics only // demand a single flush from the client after changes are first made, // and it is not visible to them when another share group boundary is crossed. // We could probably track this and be a bit smarter about when to flush // though. glFlush(); texture->level_infos_.resize(1); for (size_t i = 0; i < level_infos_.size(); i++) { const LevelInfo& base_info = level_infos_[i][0]; const size_t levels_needed = TextureManager::ComputeMipMapCount( base_info.target, base_info.width, base_info.height, base_info.depth); DCHECK(level_infos_.size() <= levels_needed); texture->level_infos_[0].resize(levels_needed); for (size_t n = 0; n < level_infos_.size(); n++) { const LevelInfo& info = level_infos_[i][n]; texture->SetLevelInfo(NULL, info.target, i, info.internal_format, info.width, info.height, info.depth, info.border, info.format, info.type, info.cleared); } } if (image_buffer_) { texture->SetLevelImage( NULL, target_, 0, new GLImageSync( image_buffer_, gfx::Size(level_infos_[0][0].width, level_infos_[0][0].height))); } texture->target_ = target_; texture->SetImmutable(immutable_); texture->min_filter_ = min_filter_; texture->mag_filter_ = mag_filter_; texture->wrap_s_ = wrap_s_; texture->wrap_t_ = wrap_t_; texture->usage_ = usage_; } bool TextureDefinition::Matches(const Texture* texture) const { DCHECK(target_ == texture->target()); if (texture->min_filter_ != min_filter_ || texture->mag_filter_ != mag_filter_ || texture->wrap_s_ != wrap_s_ || texture->wrap_t_ != wrap_t_) { return false; } // All structural changes should have orphaned the texture. if (image_buffer_ && !texture->GetLevelImage(texture->target(), 0)) return false; return true; } } // namespace gles2 } // namespace gpu
Fix GLImageSync::GetSize() to return actual texture size
Fix GLImageSync::GetSize() to return actual texture size BUG= Review URL: https://codereview.chromium.org/344483006 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@280734 0039d316-1c4b-4281-b951-d872f2087c98
C++
bsd-3-clause
hgl888/chromium-crosswalk-efl,bright-sparks/chromium-spacewalk,chuan9/chromium-crosswalk,fujunwei/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,crosswalk-project/chromium-crosswalk-efl,bright-sparks/chromium-spacewalk,M4sse/chromium.src,mohamed--abdel-maksoud/chromium.src,Fireblend/chromium-crosswalk,M4sse/chromium.src,PeterWangIntel/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,M4sse/chromium.src,Jonekee/chromium.src,hgl888/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,dushu1203/chromium.src,fujunwei/chromium-crosswalk,krieger-od/nwjs_chromium.src,TheTypoMaster/chromium-crosswalk,axinging/chromium-crosswalk,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk-efl,fujunwei/chromium-crosswalk,Jonekee/chromium.src,hgl888/chromium-crosswalk-efl,Fireblend/chromium-crosswalk,Fireblend/chromium-crosswalk,dushu1203/chromium.src,ondra-novak/chromium.src,krieger-od/nwjs_chromium.src,TheTypoMaster/chromium-crosswalk,bright-sparks/chromium-spacewalk,hgl888/chromium-crosswalk,krieger-od/nwjs_chromium.src,ltilve/chromium,bright-sparks/chromium-spacewalk,M4sse/chromium.src,Chilledheart/chromium,Chilledheart/chromium,littlstar/chromium.src,ondra-novak/chromium.src,fujunwei/chromium-crosswalk,ltilve/chromium,dednal/chromium.src,fujunwei/chromium-crosswalk,Jonekee/chromium.src,Chilledheart/chromium,Jonekee/chromium.src,PeterWangIntel/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,Chilledheart/chromium,hgl888/chromium-crosswalk,hgl888/chromium-crosswalk,jaruba/chromium.src,crosswalk-project/chromium-crosswalk-efl,hgl888/chromium-crosswalk-efl,ondra-novak/chromium.src,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk-efl,dednal/chromium.src,Just-D/chromium-1,crosswalk-project/chromium-crosswalk-efl,ondra-novak/chromium.src,dushu1203/chromium.src,axinging/chromium-crosswalk,Pluto-tv/chromium-crosswalk,Fireblend/chromium-crosswalk,chuan9/chromium-crosswalk,krieger-od/nwjs_chromium.src,mohamed--abdel-maksoud/chromium.src,Pluto-tv/chromium-crosswalk,bright-sparks/chromium-spacewalk,jaruba/chromium.src,dednal/chromium.src,krieger-od/nwjs_chromium.src,ltilve/chromium,fujunwei/chromium-crosswalk,krieger-od/nwjs_chromium.src,markYoungH/chromium.src,littlstar/chromium.src,chuan9/chromium-crosswalk,dednal/chromium.src,fujunwei/chromium-crosswalk,markYoungH/chromium.src,Just-D/chromium-1,PeterWangIntel/chromium-crosswalk,dushu1203/chromium.src,Just-D/chromium-1,axinging/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,krieger-od/nwjs_chromium.src,Just-D/chromium-1,littlstar/chromium.src,dushu1203/chromium.src,jaruba/chromium.src,Chilledheart/chromium,markYoungH/chromium.src,hgl888/chromium-crosswalk-efl,PeterWangIntel/chromium-crosswalk,littlstar/chromium.src,dushu1203/chromium.src,krieger-od/nwjs_chromium.src,dushu1203/chromium.src,jaruba/chromium.src,M4sse/chromium.src,chuan9/chromium-crosswalk,bright-sparks/chromium-spacewalk,hgl888/chromium-crosswalk-efl,Jonekee/chromium.src,ltilve/chromium,axinging/chromium-crosswalk,Fireblend/chromium-crosswalk,Fireblend/chromium-crosswalk,chuan9/chromium-crosswalk,markYoungH/chromium.src,crosswalk-project/chromium-crosswalk-efl,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk,Jonekee/chromium.src,littlstar/chromium.src,dushu1203/chromium.src,TheTypoMaster/chromium-crosswalk,markYoungH/chromium.src,markYoungH/chromium.src,jaruba/chromium.src,crosswalk-project/chromium-crosswalk-efl,hgl888/chromium-crosswalk,M4sse/chromium.src,hgl888/chromium-crosswalk-efl,markYoungH/chromium.src,hgl888/chromium-crosswalk,ltilve/chromium,Chilledheart/chromium,PeterWangIntel/chromium-crosswalk,ondra-novak/chromium.src,PeterWangIntel/chromium-crosswalk,ondra-novak/chromium.src,PeterWangIntel/chromium-crosswalk,Chilledheart/chromium,M4sse/chromium.src,Pluto-tv/chromium-crosswalk,bright-sparks/chromium-spacewalk,mohamed--abdel-maksoud/chromium.src,M4sse/chromium.src,M4sse/chromium.src,dushu1203/chromium.src,axinging/chromium-crosswalk,Just-D/chromium-1,ltilve/chromium,TheTypoMaster/chromium-crosswalk,markYoungH/chromium.src,jaruba/chromium.src,Fireblend/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,bright-sparks/chromium-spacewalk,krieger-od/nwjs_chromium.src,markYoungH/chromium.src,Chilledheart/chromium,dednal/chromium.src,PeterWangIntel/chromium-crosswalk,hgl888/chromium-crosswalk,hgl888/chromium-crosswalk-efl,Jonekee/chromium.src,dednal/chromium.src,Pluto-tv/chromium-crosswalk,axinging/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,bright-sparks/chromium-spacewalk,TheTypoMaster/chromium-crosswalk,axinging/chromium-crosswalk,Just-D/chromium-1,hgl888/chromium-crosswalk-efl,fujunwei/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,littlstar/chromium.src,TheTypoMaster/chromium-crosswalk,ltilve/chromium,Fireblend/chromium-crosswalk,littlstar/chromium.src,Jonekee/chromium.src,littlstar/chromium.src,jaruba/chromium.src,Chilledheart/chromium,dednal/chromium.src,Just-D/chromium-1,Just-D/chromium-1,axinging/chromium-crosswalk,jaruba/chromium.src,Jonekee/chromium.src,krieger-od/nwjs_chromium.src,chuan9/chromium-crosswalk,markYoungH/chromium.src,ondra-novak/chromium.src,M4sse/chromium.src,krieger-od/nwjs_chromium.src,crosswalk-project/chromium-crosswalk-efl,chuan9/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,M4sse/chromium.src,mohamed--abdel-maksoud/chromium.src,Jonekee/chromium.src,jaruba/chromium.src,Jonekee/chromium.src,jaruba/chromium.src,chuan9/chromium-crosswalk,dednal/chromium.src,axinging/chromium-crosswalk,hgl888/chromium-crosswalk,Pluto-tv/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,Pluto-tv/chromium-crosswalk,Fireblend/chromium-crosswalk,dednal/chromium.src,Just-D/chromium-1,axinging/chromium-crosswalk,dushu1203/chromium.src,axinging/chromium-crosswalk,dednal/chromium.src,fujunwei/chromium-crosswalk,ondra-novak/chromium.src,Pluto-tv/chromium-crosswalk,ltilve/chromium,TheTypoMaster/chromium-crosswalk,markYoungH/chromium.src,ltilve/chromium,jaruba/chromium.src,mohamed--abdel-maksoud/chromium.src,mohamed--abdel-maksoud/chromium.src,Pluto-tv/chromium-crosswalk,ondra-novak/chromium.src,dednal/chromium.src,dushu1203/chromium.src
ece1584d4ddc38c929ab2a6de1c88db3af8a06d6
include/libtorrent/socket.hpp
include/libtorrent/socket.hpp
/* Copyright (c) 2003, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TORRENT_SOCKET_HPP_INCLUDED #define TORRENT_SOCKET_HPP_INCLUDED #ifdef _MSC_VER #pragma warning(push, 1) #endif // if building as Objective C++, asio's template // parameters Protocol has to be renamed to avoid // colliding with keywords #ifdef __OBJC__ #define Protocol Protocol_ #endif #if defined TORRENT_WINDOWS || defined TORRENT_CYGWIN // asio assumes that the windows error codes are defined already #include <winsock2.h> #endif #include <boost/version.hpp> #if BOOST_VERSION < 103500 #include <asio/ip/tcp.hpp> #include <asio/ip/udp.hpp> #include <asio/write.hpp> #include <asio/read.hpp> #else #include <boost/asio/ip/tcp.hpp> #include <boost/asio/ip/udp.hpp> #include <boost/asio/write.hpp> #include <boost/asio/read.hpp> #endif #ifdef __OBJC__ #undef Protocol #endif #ifdef _MSC_VER #pragma warning(pop) #endif namespace libtorrent { #if BOOST_VERSION < 103500 using ::asio::ip::tcp; using ::asio::ip::udp; using ::asio::async_write; using ::asio::async_read; typedef ::asio::ip::tcp::socket stream_socket; typedef ::asio::ip::udp::socket datagram_socket; typedef ::asio::ip::tcp::acceptor socket_acceptor; #else using boost::asio::ip::tcp; using boost::asio::ip::udp; using boost::asio::async_write; using boost::asio::async_read; typedef boost::asio::ip::tcp::socket stream_socket; typedef boost::asio::ip::udp::socket datagram_socket; typedef boost::asio::ip::tcp::acceptor socket_acceptor; namespace asio = boost::asio; #endif #if TORRENT_USE_IPV6 struct v6only { v6only(bool enable): m_value(enable) {} template<class Protocol> int level(Protocol const&) const { return IPPROTO_IPV6; } template<class Protocol> int name(Protocol const&) const { return IPV6_V6ONLY; } template<class Protocol> int const* data(Protocol const&) const { return &m_value; } template<class Protocol> size_t size(Protocol const&) const { return sizeof(m_value); } int m_value; }; #endif #ifdef TORRENT_WINDOWS #ifndef IPV6_PROTECTION_LEVEL #define IPV6_PROTECTION_LEVEL 30 #endif struct v6_protection_level { v6_protection_level(int level): m_value(level) {} template<class Protocol> int level(Protocol const&) const { return IPPROTO_IPV6; } template<class Protocol> int name(Protocol const&) const { return IPV6_PROTECTION_LEVEL; } template<class Protocol> int const* data(Protocol const&) const { return &m_value; } template<class Protocol> size_t size(Protocol const&) const { return sizeof(m_value); } int m_value; }; #endif struct type_of_service { type_of_service(char val): m_value(val) {} template<class Protocol> int level(Protocol const&) const { return IPPROTO_IP; } template<class Protocol> int name(Protocol const&) const { return IP_TOS; } template<class Protocol> char const* data(Protocol const&) const { return &m_value; } template<class Protocol> size_t size(Protocol const&) const { return sizeof(m_value); } char m_value; }; #if defined IP_DONTFRAG || defined IP_MTU_DISCOVER || defined IP_DONTFRAGMENT #define TORRENT_HAS_DONT_FRAGMENT #endif #ifdef TORRENT_HAS_DONT_FRAGMENT struct dont_fragment { dont_fragment(bool val) #ifdef IP_PMTUDISCOVER_DO : m_value(val ? IP_PMTUDISC_DO : IP_PMTUDISC_DONT) {} #else : m_value(val) {} #endif template<class Protocol> int level(Protocol const&) const { return IPPROTO_IP; } template<class Protocol> int name(Protocol const&) const #if defined IP_DONTFRAG { return IP_DONTFRAG; } #elif defined IP_MTU_DISCOVER { return IP_MTU_DISCOVER; } #elif defined IP_DONTFRAGMENT { return IP_DONTFRAGMENT; } #else {} #endif template<class Protocol> char const* data(Protocol const&) const { return &m_value; } template<class Protocol> size_t size(Protocol const&) const { return sizeof(m_value); } int m_value; }; #endif // TORRENT_HAS_DONT_FRAGMENT } #endif // TORRENT_SOCKET_HPP_INCLUDED
/* Copyright (c) 2003, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TORRENT_SOCKET_HPP_INCLUDED #define TORRENT_SOCKET_HPP_INCLUDED #ifdef _MSC_VER #pragma warning(push, 1) #endif // if building as Objective C++, asio's template // parameters Protocol has to be renamed to avoid // colliding with keywords #ifdef __OBJC__ #define Protocol Protocol_ #endif #if defined TORRENT_WINDOWS || defined TORRENT_CYGWIN // asio assumes that the windows error codes are defined already #include <winsock2.h> #endif #include <boost/version.hpp> #if BOOST_VERSION < 103500 #include <asio/ip/tcp.hpp> #include <asio/ip/udp.hpp> #include <asio/write.hpp> #include <asio/read.hpp> #else #include <boost/asio/ip/tcp.hpp> #include <boost/asio/ip/udp.hpp> #include <boost/asio/write.hpp> #include <boost/asio/read.hpp> #endif #ifdef __OBJC__ #undef Protocol #endif #ifdef _MSC_VER #pragma warning(pop) #endif namespace libtorrent { #if BOOST_VERSION < 103500 using ::asio::ip::tcp; using ::asio::ip::udp; using ::asio::async_write; using ::asio::async_read; typedef ::asio::ip::tcp::socket stream_socket; typedef ::asio::ip::udp::socket datagram_socket; typedef ::asio::ip::tcp::acceptor socket_acceptor; #else using boost::asio::ip::tcp; using boost::asio::ip::udp; using boost::asio::async_write; using boost::asio::async_read; typedef boost::asio::ip::tcp::socket stream_socket; typedef boost::asio::ip::udp::socket datagram_socket; typedef boost::asio::ip::tcp::acceptor socket_acceptor; namespace asio = boost::asio; #endif #if TORRENT_USE_IPV6 struct v6only { v6only(bool enable): m_value(enable) {} template<class Protocol> int level(Protocol const&) const { return IPPROTO_IPV6; } template<class Protocol> int name(Protocol const&) const { return IPV6_V6ONLY; } template<class Protocol> int const* data(Protocol const&) const { return &m_value; } template<class Protocol> size_t size(Protocol const&) const { return sizeof(m_value); } int m_value; }; #endif #ifdef TORRENT_WINDOWS #ifndef IPV6_PROTECTION_LEVEL #define IPV6_PROTECTION_LEVEL 30 #endif struct v6_protection_level { v6_protection_level(int level): m_value(level) {} template<class Protocol> int level(Protocol const&) const { return IPPROTO_IPV6; } template<class Protocol> int name(Protocol const&) const { return IPV6_PROTECTION_LEVEL; } template<class Protocol> int const* data(Protocol const&) const { return &m_value; } template<class Protocol> size_t size(Protocol const&) const { return sizeof(m_value); } int m_value; }; #endif struct type_of_service { type_of_service(char val): m_value(val) {} template<class Protocol> int level(Protocol const&) const { return IPPROTO_IP; } template<class Protocol> int name(Protocol const&) const { return IP_TOS; } template<class Protocol> char const* data(Protocol const&) const { return &m_value; } template<class Protocol> size_t size(Protocol const&) const { return sizeof(m_value); } char m_value; }; #if defined IP_DONTFRAG || defined IP_MTU_DISCOVER || defined IP_DONTFRAGMENT #define TORRENT_HAS_DONT_FRAGMENT #endif #ifdef TORRENT_HAS_DONT_FRAGMENT struct dont_fragment { dont_fragment(bool val) #ifdef IP_PMTUDISCOVER_DO : m_value(val ? IP_PMTUDISC_DO : IP_PMTUDISC_DONT) {} #else : m_value(val) {} #endif template<class Protocol> int level(Protocol const&) const { return IPPROTO_IP; } template<class Protocol> int name(Protocol const&) const #if defined IP_DONTFRAG { return IP_DONTFRAG; } #elif defined IP_MTU_DISCOVER { return IP_MTU_DISCOVER; } #elif defined IP_DONTFRAGMENT { return IP_DONTFRAGMENT; } #else {} #endif template<class Protocol> int const* data(Protocol const&) const { return &m_value; } template<class Protocol> size_t size(Protocol const&) const { return sizeof(m_value); } int m_value; }; #endif // TORRENT_HAS_DONT_FRAGMENT } #endif // TORRENT_SOCKET_HPP_INCLUDED
fix msvc build
fix msvc build git-svn-id: c33880c105b4082c86d872cc05f56ac71c9e5733@4984 f43f7eb3-cfe1-5f9d-1b5f-e45aa6702bda
C++
bsd-3-clause
steeve/libtorrent,steeve/libtorrent,steeve/libtorrent,steeve/libtorrent,steeve/libtorrent,steeve/libtorrent