text
stringlengths
54
60.6k
<commit_before>//============================================================================== // Single cell simulation view graph panel plot widget //============================================================================== #include "singlecellsimulationviewgraphpanelplotwidget.h" //============================================================================== #include <QApplication> #include <QClipboard> #include <QMouseEvent> //============================================================================== #include <float.h> //============================================================================== #include "qwt_painter.h" #include "qwt_plot_canvas.h" #include "qwt_plot_curve.h" #include "qwt_plot_directpainter.h" #include "qwt_plot_grid.h" #include "qwt_plot_renderer.h" #include "qwt_scale_div.h" //============================================================================== namespace OpenCOR { namespace SingleCellSimulationView { //============================================================================== SingleCellSimulationViewGraphPanelPlotWidget::SingleCellSimulationViewGraphPanelPlotWidget(QWidget *pParent) : QwtPlot(pParent), mTraces(QList<QwtPlotCurve *>()), mAction(None), mOriginPoint(QPoint()) { // Get ourselves a direct painter mDirectPainter = new QwtPlotDirectPainter(this); // Speedup painting on X11 systems // Note: this can only be done on X11 systems... if (QwtPainter::isX11GraphicsSystem()) canvas()->setAttribute(Qt::WA_PaintOnScreen, true); // Customise ourselves a bit setCanvasBackground(Qt::white); // We don't want a frame around ourselves qobject_cast<QwtPlotCanvas *>(canvas())->setFrameShape(QFrame::NoFrame); // Attach a grid to ourselves QwtPlotGrid *grid = new QwtPlotGrid(); grid->setMajorPen(Qt::gray, 0, Qt::DotLine); grid->attach(this); } //============================================================================== SingleCellSimulationViewGraphPanelPlotWidget::~SingleCellSimulationViewGraphPanelPlotWidget() { // Delete some internal objects removeTraces(); delete mDirectPainter; } //============================================================================== bool SingleCellSimulationViewGraphPanelPlotWidget::eventFilter(QObject *pObject, QEvent *pEvent) { // Default handling of the event bool res = QwtPlot::eventFilter(pObject, pEvent); // We want to handle a double mouse click, but for some reasons to override // mouseDoubleClickEvent() doesn't work, so... if(pEvent->type() == QEvent::MouseButtonDblClick) handleMouseDoubleClickEvent(static_cast<QMouseEvent *>(pEvent)); // We are all done, so... return res; } //============================================================================== void SingleCellSimulationViewGraphPanelPlotWidget::handleMouseDoubleClickEvent(QMouseEvent *pEvent) { // Copy the contents of the plot to the clipboard, in case we double-clicked // using the left mouse button if (pEvent->button() == Qt::LeftButton) { // Render the plot to an image QwtPlotRenderer renderer; QImage image = QImage(size(), QImage::Format_ARGB32_Premultiplied); QPainter painter(&image); renderer.render(this, &painter, rect()); // Set the image to the clipboard QApplication::clipboard()->setImage(image); } } //============================================================================== void SingleCellSimulationViewGraphPanelPlotWidget::rescaleAxes(const double &pXScalingFactor, const double &pYScalingFactor) { // Rescale the given axis using the given scaling factor QwtScaleDiv xScaleDiv = axisScaleDiv(QwtPlot::xBottom); double xCenter = xScaleDiv.lowerBound()+0.5*xScaleDiv.range(); double xRangeOverTwo = 0.5*pXScalingFactor*xScaleDiv.range(); double xAxisMin = xCenter-xRangeOverTwo; double xAxisMax = xCenter+xRangeOverTwo; QwtScaleDiv yScaleDiv = axisScaleDiv(QwtPlot::yLeft); double yCenter = yScaleDiv.lowerBound()+0.5*yScaleDiv.range(); double yRangeOverTwo = 0.5*pYScalingFactor*yScaleDiv.range(); double yAxisMin = yCenter-yRangeOverTwo; double yAxisMax = yCenter+yRangeOverTwo; setAxisScale(QwtPlot::xBottom, xAxisMin, xAxisMax); setAxisScale(QwtPlot::yLeft, yAxisMin, yAxisMax); } //============================================================================== void SingleCellSimulationViewGraphPanelPlotWidget::mouseMoveEvent(QMouseEvent *pEvent) { // Default handling of the event QwtPlot::mouseMoveEvent(pEvent); // Carry out the action switch (mAction) { case Zoom: { // Determine the scaling factor for our X axis static const double ScalingFactor = 0.95; int deltaX = pEvent->pos().x()-mOriginPoint.x(); double xScalingFactor = ScalingFactor; if (!deltaX) xScalingFactor = 1.0; else if (deltaX < 0) xScalingFactor = 1.0/xScalingFactor; // Determine the scaling factor for our Y axis int deltaY = pEvent->pos().y()-mOriginPoint.y(); double yScalingFactor = ScalingFactor; if (!deltaY) yScalingFactor = 1.0; else if (deltaY < 0) yScalingFactor = 1.0/yScalingFactor; // Rescale and replot ourselves, as well as reset our point of origin, // if needed if (deltaX || deltaY) { rescaleAxes(xScalingFactor, yScalingFactor); replot(); mOriginPoint = pEvent->pos(); } break; } default: // None ; } } //============================================================================== void SingleCellSimulationViewGraphPanelPlotWidget::mousePressEvent(QMouseEvent *pEvent) { // Default handling of the event QwtPlot::mousePressEvent(pEvent); // Check which action we can carry out if ( (pEvent->button() == Qt::RightButton) && (pEvent->modifiers() == Qt::NoModifier)) { // We want to zoom in/out mAction = Zoom; } else { // None of the actions we can carry out, so... mAction = None; return; } // Keep track of the mouse position and make sure that we track the mouse mOriginPoint = pEvent->pos(); setMouseTracking(true); } //============================================================================== void SingleCellSimulationViewGraphPanelPlotWidget::mouseReleaseEvent(QMouseEvent *pEvent) { // Default handling of the event QwtPlot::mouseReleaseEvent(pEvent); // Check whether we need to carry out an action if (mAction == None) return; // Stop tracking the mouse setMouseTracking(false); // We are done carrying out an action, so... mAction = None; } //============================================================================== void SingleCellSimulationViewGraphPanelPlotWidget::wheelEvent(QWheelEvent *pEvent) { // Default handling of the event QwtPlot::wheelEvent(pEvent); // The only action we support using the wheel is zooming in/out, but this // requires no modifiers being used if (pEvent->modifiers() != Qt::NoModifier) return; // Determine the zoom factor, making sure that it's valid static const double OneOverOneHundredAndTwenty = 1.0/120.0; double scalingFactor = qPow(0.9, qAbs(pEvent->delta()*OneOverOneHundredAndTwenty)); if ((scalingFactor == 0.0) || (scalingFactor == 1.0)) return; if (pEvent->delta() > 0) scalingFactor = 1.0/scalingFactor; // Rescale our two axes rescaleAxes(scalingFactor, scalingFactor); // Replot ourselves replot(); } //============================================================================== QwtPlotCurve * SingleCellSimulationViewGraphPanelPlotWidget::addTrace(double *pX, double *pY, const qulonglong &pOriginalSize) { // Create a new trace QwtPlotCurve *res = new QwtPlotCurve(); // Customise it a bit res->setRenderHint(QwtPlotItem::RenderAntialiased); res->setPen(QPen(Qt::darkBlue)); // Populate our trace res->setRawSamples(pX, pY, pOriginalSize); // Attach it to ourselves res->attach(this); // Add it to our list of traces mTraces << res; // Replot ourselves, but only if needed if (pOriginalSize) { replot(); // Make sure that it gets replotted immediately // Note: this is needed when running a simulation since, otherwise, // replotting won't occur, so... qApp->processEvents(); } // Return it to the caller return res; } //============================================================================== void SingleCellSimulationViewGraphPanelPlotWidget::removeTrace(QwtPlotCurve *pTrace, const bool &pReplot) { // Make sure that we have a trace if (!pTrace) return; // Detach and then delete the trace pTrace->detach(); delete pTrace; // Stop tracking the trace mTraces.removeOne(pTrace); // Replot ourselves, if needed if (pReplot) replot(); } //============================================================================== void SingleCellSimulationViewGraphPanelPlotWidget::removeTraces() { // Remove any existing trace foreach (QwtPlotCurve *trace, mTraces) removeTrace(trace, false); // Replot ourselves replot(); } //============================================================================== void SingleCellSimulationViewGraphPanelPlotWidget::drawTraceSegment(QwtPlotCurve *pTrace, const qulonglong &pFrom, const qulonglong &pTo) { // Make sure that we have a trace segment to draw if (pFrom == pTo) return; // Determine the Y min/max of our new data double yMin = DBL_MAX; double yMax = -DBL_MAX; for (qulonglong i = pFrom; i <= pTo; ++i) { double yVal = pTrace->data()->sample(i).y(); yMin = qMin(yMin, yVal); yMax = qMax(yMax, yVal); } // Check which trace segment we are dealing with and whether our Y axis can // handle the Y min/max of our new data if ( !pFrom || (yMin < axisScaleDiv(QwtPlot::yLeft).lowerBound()) || (yMax > axisScaleDiv(QwtPlot::yLeft).upperBound())) // Either it's our first trace segment and/or our Y axis cannot handle // the Y min/max of our new data, so replot ourselves replot(); else // Our Y axis can handle the Y min/max of our new data, so just draw our // new trace segment mDirectPainter->drawSeries(pTrace, pFrom, pTo); } //============================================================================== void SingleCellSimulationViewGraphPanelPlotWidget::replot() { // Replot ourselves, making sure that our axes get rescaled (if needed) setAutoReplot(true); QwtPlot::replot(); setAutoReplot(false); } //============================================================================== } // namespace SingleCellSimulationView } // namespace OpenCOR //============================================================================== // End of file //============================================================================== <commit_msg>Some minor cleaning up (#112).<commit_after>//============================================================================== // Single cell simulation view graph panel plot widget //============================================================================== #include "singlecellsimulationviewgraphpanelplotwidget.h" //============================================================================== #include <QApplication> #include <QClipboard> #include <QMouseEvent> //============================================================================== #include <float.h> //============================================================================== #include "qwt_painter.h" #include "qwt_plot_canvas.h" #include "qwt_plot_curve.h" #include "qwt_plot_directpainter.h" #include "qwt_plot_grid.h" #include "qwt_plot_renderer.h" #include "qwt_scale_div.h" //============================================================================== namespace OpenCOR { namespace SingleCellSimulationView { //============================================================================== SingleCellSimulationViewGraphPanelPlotWidget::SingleCellSimulationViewGraphPanelPlotWidget(QWidget *pParent) : QwtPlot(pParent), mTraces(QList<QwtPlotCurve *>()), mAction(None), mOriginPoint(QPoint()) { // Get ourselves a direct painter mDirectPainter = new QwtPlotDirectPainter(this); // Speedup painting on X11 systems // Note: this can only be done on X11 systems... if (QwtPainter::isX11GraphicsSystem()) canvas()->setAttribute(Qt::WA_PaintOnScreen, true); // Customise ourselves a bit setCanvasBackground(Qt::white); // We don't want a frame around ourselves qobject_cast<QwtPlotCanvas *>(canvas())->setFrameShape(QFrame::NoFrame); // Attach a grid to ourselves QwtPlotGrid *grid = new QwtPlotGrid(); grid->setMajorPen(Qt::gray, 0, Qt::DotLine); grid->attach(this); } //============================================================================== SingleCellSimulationViewGraphPanelPlotWidget::~SingleCellSimulationViewGraphPanelPlotWidget() { // Delete some internal objects removeTraces(); delete mDirectPainter; } //============================================================================== bool SingleCellSimulationViewGraphPanelPlotWidget::eventFilter(QObject *pObject, QEvent *pEvent) { // Default handling of the event bool res = QwtPlot::eventFilter(pObject, pEvent); // We want to handle a double mouse click, but for some reasons to override // mouseDoubleClickEvent() doesn't work, so... if(pEvent->type() == QEvent::MouseButtonDblClick) handleMouseDoubleClickEvent(static_cast<QMouseEvent *>(pEvent)); // We are all done, so... return res; } //============================================================================== void SingleCellSimulationViewGraphPanelPlotWidget::handleMouseDoubleClickEvent(QMouseEvent *pEvent) { // Copy the contents of the plot to the clipboard, in case we double-clicked // using the left mouse button if (pEvent->button() == Qt::LeftButton) { // Render the plot to an image QwtPlotRenderer renderer; QImage image = QImage(size(), QImage::Format_ARGB32_Premultiplied); QPainter painter(&image); renderer.render(this, &painter, rect()); // Set the image to the clipboard QApplication::clipboard()->setImage(image); } } //============================================================================== void SingleCellSimulationViewGraphPanelPlotWidget::rescaleAxes(const double &pXScalingFactor, const double &pYScalingFactor) { // Rescale the axes using the given scaling factors QwtScaleDiv xScaleDiv = axisScaleDiv(QwtPlot::xBottom); double xCenter = xScaleDiv.lowerBound()+0.5*xScaleDiv.range(); double xRangeOverTwo = 0.5*pXScalingFactor*xScaleDiv.range(); double xAxisMin = xCenter-xRangeOverTwo; double xAxisMax = xCenter+xRangeOverTwo; QwtScaleDiv yScaleDiv = axisScaleDiv(QwtPlot::yLeft); double yCenter = yScaleDiv.lowerBound()+0.5*yScaleDiv.range(); double yRangeOverTwo = 0.5*pYScalingFactor*yScaleDiv.range(); double yAxisMin = yCenter-yRangeOverTwo; double yAxisMax = yCenter+yRangeOverTwo; setAxisScale(QwtPlot::xBottom, xAxisMin, xAxisMax); setAxisScale(QwtPlot::yLeft, yAxisMin, yAxisMax); } //============================================================================== void SingleCellSimulationViewGraphPanelPlotWidget::mouseMoveEvent(QMouseEvent *pEvent) { // Default handling of the event QwtPlot::mouseMoveEvent(pEvent); // Carry out the action switch (mAction) { case Zoom: { // Determine the scaling factor for our X axis static const double ScalingFactor = 0.95; int deltaX = pEvent->pos().x()-mOriginPoint.x(); double xScalingFactor = ScalingFactor; if (!deltaX) xScalingFactor = 1.0; else if (deltaX < 0) xScalingFactor = 1.0/xScalingFactor; // Determine the scaling factor for our Y axis int deltaY = pEvent->pos().y()-mOriginPoint.y(); double yScalingFactor = ScalingFactor; if (!deltaY) yScalingFactor = 1.0; else if (deltaY < 0) yScalingFactor = 1.0/yScalingFactor; // Rescale and replot ourselves, as well as reset our point of origin, // if needed if (deltaX || deltaY) { rescaleAxes(xScalingFactor, yScalingFactor); replot(); mOriginPoint = pEvent->pos(); } break; } default: // None ; } } //============================================================================== void SingleCellSimulationViewGraphPanelPlotWidget::mousePressEvent(QMouseEvent *pEvent) { // Default handling of the event QwtPlot::mousePressEvent(pEvent); // Check which action we can carry out if ( (pEvent->button() == Qt::RightButton) && (pEvent->modifiers() == Qt::NoModifier)) { // We want to zoom in/out mAction = Zoom; } else { // None of the actions we can carry out, so... mAction = None; return; } // Keep track of the mouse position and make sure that we track the mouse mOriginPoint = pEvent->pos(); setMouseTracking(true); } //============================================================================== void SingleCellSimulationViewGraphPanelPlotWidget::mouseReleaseEvent(QMouseEvent *pEvent) { // Default handling of the event QwtPlot::mouseReleaseEvent(pEvent); // Check whether we need to carry out an action if (mAction == None) return; // Stop tracking the mouse setMouseTracking(false); // We are done carrying out an action, so... mAction = None; } //============================================================================== void SingleCellSimulationViewGraphPanelPlotWidget::wheelEvent(QWheelEvent *pEvent) { // Default handling of the event QwtPlot::wheelEvent(pEvent); // The only action we support using the wheel is zooming in/out, but this // requires no modifiers being used if (pEvent->modifiers() != Qt::NoModifier) return; // Determine the zoom factor, making sure that it's valid static const double OneOverOneHundredAndTwenty = 1.0/120.0; double scalingFactor = qPow(0.9, qAbs(pEvent->delta()*OneOverOneHundredAndTwenty)); if ((scalingFactor == 0.0) || (scalingFactor == 1.0)) return; if (pEvent->delta() > 0) scalingFactor = 1.0/scalingFactor; // Rescale our two axes rescaleAxes(scalingFactor, scalingFactor); // Replot ourselves replot(); } //============================================================================== QwtPlotCurve * SingleCellSimulationViewGraphPanelPlotWidget::addTrace(double *pX, double *pY, const qulonglong &pOriginalSize) { // Create a new trace QwtPlotCurve *res = new QwtPlotCurve(); // Customise it a bit res->setRenderHint(QwtPlotItem::RenderAntialiased); res->setPen(QPen(Qt::darkBlue)); // Populate our trace res->setRawSamples(pX, pY, pOriginalSize); // Attach it to ourselves res->attach(this); // Add it to our list of traces mTraces << res; // Replot ourselves, but only if needed if (pOriginalSize) { replot(); // Make sure that it gets replotted immediately // Note: this is needed when running a simulation since, otherwise, // replotting won't occur, so... qApp->processEvents(); } // Return it to the caller return res; } //============================================================================== void SingleCellSimulationViewGraphPanelPlotWidget::removeTrace(QwtPlotCurve *pTrace, const bool &pReplot) { // Make sure that we have a trace if (!pTrace) return; // Detach and then delete the trace pTrace->detach(); delete pTrace; // Stop tracking the trace mTraces.removeOne(pTrace); // Replot ourselves, if needed if (pReplot) replot(); } //============================================================================== void SingleCellSimulationViewGraphPanelPlotWidget::removeTraces() { // Remove any existing trace foreach (QwtPlotCurve *trace, mTraces) removeTrace(trace, false); // Replot ourselves replot(); } //============================================================================== void SingleCellSimulationViewGraphPanelPlotWidget::drawTraceSegment(QwtPlotCurve *pTrace, const qulonglong &pFrom, const qulonglong &pTo) { // Make sure that we have a trace segment to draw if (pFrom == pTo) return; // Determine the Y min/max of our new data double yMin = DBL_MAX; double yMax = -DBL_MAX; for (qulonglong i = pFrom; i <= pTo; ++i) { double yVal = pTrace->data()->sample(i).y(); yMin = qMin(yMin, yVal); yMax = qMax(yMax, yVal); } // Check which trace segment we are dealing with and whether our Y axis can // handle the Y min/max of our new data if ( !pFrom || (yMin < axisScaleDiv(QwtPlot::yLeft).lowerBound()) || (yMax > axisScaleDiv(QwtPlot::yLeft).upperBound())) // Either it's our first trace segment and/or our Y axis cannot handle // the Y min/max of our new data, so replot ourselves replot(); else // Our Y axis can handle the Y min/max of our new data, so just draw our // new trace segment mDirectPainter->drawSeries(pTrace, pFrom, pTo); } //============================================================================== void SingleCellSimulationViewGraphPanelPlotWidget::replot() { // Replot ourselves, making sure that our axes get rescaled (if needed) setAutoReplot(true); QwtPlot::replot(); setAutoReplot(false); } //============================================================================== } // namespace SingleCellSimulationView } // namespace OpenCOR //============================================================================== // End of file //============================================================================== <|endoftext|>
<commit_before>//============================================================================================================= /** * @file main.cpp * @author Christoph Dinh <chdinh@nmr.mgh.harvard.edu>; * Matti Hamalainen <msh@nmr.mgh.harvard.edu> * @version 1.0 * @date July, 2012 * * @section LICENSE * * Copyright (C) 2012, Christoph Dinh and Matti Hamalainen. 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 Massachusetts General Hospital 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 MASSACHUSETTS GENERAL HOSPITAL 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. * * * @brief Implements the main() application function. * */ //************************************************************************************************************* //============================================================================================================= // INCLUDES //============================================================================================================= #include <rtCommunication/communicationmanager.h> //************************************************************************************************************* //============================================================================================================= // STL INCLUDES //============================================================================================================= #include <stdio.h> //************************************************************************************************************* //============================================================================================================= // QT INCLUDES //============================================================================================================= #include <QtCore/QCoreApplication> #include <QDebug> //************************************************************************************************************* //============================================================================================================= // USED NAMESPACES //============================================================================================================= //using namespace MNEUNITTESTS; using namespace RTCOMMUNICATIONLIB; //************************************************************************************************************* //============================================================================================================= // Methods //============================================================================================================= //************************************************************************************************************* //============================================================================================================= // MAIN //============================================================================================================= //============================================================================================================= /** * The function main marks the entry point of the program. * By default, main has the storage class extern. * * @param [in] argc (argument count) is an integer that indicates how many arguments were entered on the command line when the program was started. * @param [in] argv (argument vector) is an array of pointers to arrays of character objects. The array objects are null-terminated strings, representing the arguments that were entered on the command line when the program was started. * @return the value that was set to exit() (which is 0 if exit() is called via quit()). */ int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); bool testResult; QString jsonTestCommand = "{" " \"encoding\": \"UTF-8\"," " \"name\": \"Neuromag\"," " \"Commands\": {" " \"help\": [ \"param1\", \"param2\", \"param3\" ]," " \"start\": [ \"param1\", \"param2\", \"param3\" ]" " }" "}"; CommunicationManager t_comManager(jsonTestCommand.toLatin1()); qDebug() << t_comManager.m_jsonDocumentOrigin.toJson(); return a.exec(); } <commit_msg>JSON example<commit_after>//============================================================================================================= /** * @file main.cpp * @author Christoph Dinh <chdinh@nmr.mgh.harvard.edu>; * Matti Hamalainen <msh@nmr.mgh.harvard.edu> * @version 1.0 * @date July, 2012 * * @section LICENSE * * Copyright (C) 2012, Christoph Dinh and Matti Hamalainen. 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 Massachusetts General Hospital 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 MASSACHUSETTS GENERAL HOSPITAL 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. * * * @brief Implements the main() application function. * */ //************************************************************************************************************* //============================================================================================================= // INCLUDES //============================================================================================================= #include <rtCommunication/communicationmanager.h> //************************************************************************************************************* //============================================================================================================= // STL INCLUDES //============================================================================================================= #include <stdio.h> //************************************************************************************************************* //============================================================================================================= // QT INCLUDES //============================================================================================================= #include <QtCore/QCoreApplication> #include <QDebug> //************************************************************************************************************* //============================================================================================================= // USED NAMESPACES //============================================================================================================= //using namespace MNEUNITTESTS; using namespace RTCOMMUNICATIONLIB; //************************************************************************************************************* //============================================================================================================= // Methods //============================================================================================================= //************************************************************************************************************* //============================================================================================================= // MAIN //============================================================================================================= //============================================================================================================= /** * The function main marks the entry point of the program. * By default, main has the storage class extern. * * @param [in] argc (argument count) is an integer that indicates how many arguments were entered on the command line when the program was started. * @param [in] argv (argument vector) is an array of pointers to arrays of character objects. The array objects are null-terminated strings, representing the arguments that were entered on the command line when the program was started. * @return the value that was set to exit() (which is 0 if exit() is called via quit()). */ int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); bool testResult; QString jsonTestCommand = "{" " \"encoding\": \"UTF-8\"," " \"name\": \"Neuromag\"," " \"Commands\": {" " \"help\": [" " {" " \"param1\": \"int\"," " \"param2\": \"string\"" " }" " ]," " \"start\": [" " {" " \"param1\": \"int\"," " \"param2\": \"string\"" " }" " ]" " }" "}"; CommunicationManager t_comManager(jsonTestCommand.toLatin1()); qDebug() << t_comManager.m_jsonDocumentOrigin.toJson(); return a.exec(); } <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <limits.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <list> #include <string> #include <utility> #include "fpdfsdk/include/fpdf_dataavail.h" #include "fpdfsdk/include/fpdf_ext.h" #include "fpdfsdk/include/fpdfformfill.h" #include "fpdfsdk/include/fpdftext.h" #include "fpdfsdk/include/fpdfview.h" #include "v8/include/v8.h" #ifdef _WIN32 #define snprintf _snprintf /* in Windows, rb for open and read binary file */ #define FOPEN_READ "rb" #else #define FOPEN_READ "r" #endif static void WritePpm(const char* pdf_name, int num, const char* buffer, int stride, int width, int height) { if (stride < 0 || width < 0 || height < 0) return; if (height > 0 && width > INT_MAX / height) return; int out_len = width * height; if (out_len > INT_MAX / 3) return; out_len *= 3; char filename[256]; snprintf(filename, sizeof(filename), "%s.%d.ppm", pdf_name, num); FILE* fp = fopen(filename, "w"); if (!fp) return; fprintf(fp, "P6\n# PDF test render\n%d %d\n255\n", width, height); // Source data is B, G, R, unused. // Dest data is R, G, B. char* result = new char[out_len]; if (result) { for (int h = 0; h < height; ++h) { const char* src_line = buffer + (stride * h); char* dest_line = result + (width * h * 3); for (int w = 0; w < width; ++w) { // R dest_line[w * 3] = src_line[(w * 4) + 2]; // G dest_line[(w * 3) + 1] = src_line[(w * 4) + 1]; // B dest_line[(w * 3) + 2] = src_line[w * 4]; } } fwrite(result, out_len, 1, fp); delete [] result; } fclose(fp); } int Form_Alert(IPDF_JSPLATFORM*, FPDF_WIDESTRING, FPDF_WIDESTRING, int, int) { printf("Form_Alert called.\n"); return 0; } void Unsupported_Handler(UNSUPPORT_INFO*, int type) { std::string feature = "Unknown"; switch (type) { case FPDF_UNSP_DOC_XFAFORM: feature = "XFA"; break; case FPDF_UNSP_DOC_PORTABLECOLLECTION: feature = "Portfolios_Packages"; break; case FPDF_UNSP_DOC_ATTACHMENT: case FPDF_UNSP_ANNOT_ATTACHMENT: feature = "Attachment"; break; case FPDF_UNSP_DOC_SECURITY: feature = "Rights_Management"; break; case FPDF_UNSP_DOC_SHAREDREVIEW: feature = "Shared_Review"; break; case FPDF_UNSP_DOC_SHAREDFORM_ACROBAT: case FPDF_UNSP_DOC_SHAREDFORM_FILESYSTEM: case FPDF_UNSP_DOC_SHAREDFORM_EMAIL: feature = "Shared_Form"; break; case FPDF_UNSP_ANNOT_3DANNOT: feature = "3D"; break; case FPDF_UNSP_ANNOT_MOVIE: feature = "Movie"; break; case FPDF_UNSP_ANNOT_SOUND: feature = "Sound"; break; case FPDF_UNSP_ANNOT_SCREEN_MEDIA: case FPDF_UNSP_ANNOT_SCREEN_RICHMEDIA: feature = "Screen"; break; case FPDF_UNSP_ANNOT_SIG: feature = "Digital_Signature"; break; } printf("Unsupported feature: %s.\n", feature.c_str()); } bool ParseCommandLine(int argc, const char* argv[], bool* write_images, std::list<const char*>* files) { *write_images = false; files->clear(); int cur_arg = 1; if (cur_arg < argc && strcmp(argv[cur_arg], "--write_images") == 0) { *write_images = true; cur_arg++; } if (cur_arg >= argc) return false; for (int i = cur_arg; i < argc; i++) files->push_back(argv[i]); return true; } class TestLoader { public: TestLoader(const char* pBuf, size_t len); const char* m_pBuf; size_t m_Len; }; TestLoader::TestLoader(const char* pBuf, size_t len) : m_pBuf(pBuf), m_Len(len) { } int Get_Block(void* param, unsigned long pos, unsigned char* pBuf, unsigned long size) { TestLoader* pLoader = (TestLoader*) param; if (pos + size < pos || pos + size > pLoader->m_Len) return 0; memcpy(pBuf, pLoader->m_pBuf + pos, size); return 1; } bool Is_Data_Avail(FX_FILEAVAIL* pThis, size_t offset, size_t size) { return true; } void Add_Segment(FX_DOWNLOADHINTS* pThis, size_t offset, size_t size) { } void RenderPdf(const char* name, const char* pBuf, size_t len, bool write_images) { printf("Rendering PDF file %s.\n", name); IPDF_JSPLATFORM platform_callbacks; memset(&platform_callbacks, '\0', sizeof(platform_callbacks)); platform_callbacks.version = 1; platform_callbacks.app_alert = Form_Alert; FPDF_FORMFILLINFO form_callbacks; memset(&form_callbacks, '\0', sizeof(form_callbacks)); form_callbacks.version = 1; form_callbacks.m_pJsPlatform = &platform_callbacks; TestLoader loader(pBuf, len); FPDF_FILEACCESS file_access; memset(&file_access, '\0', sizeof(file_access)); file_access.m_FileLen = len; file_access.m_GetBlock = Get_Block; file_access.m_Param = &loader; FX_FILEAVAIL file_avail; memset(&file_avail, '\0', sizeof(file_avail)); file_avail.version = 1; file_avail.IsDataAvail = Is_Data_Avail; FX_DOWNLOADHINTS hints; memset(&hints, '\0', sizeof(hints)); hints.version = 1; hints.AddSegment = Add_Segment; FPDF_DOCUMENT doc; FPDF_AVAIL pdf_avail = FPDFAvail_Create(&file_avail, &file_access); (void) FPDFAvail_IsDocAvail(pdf_avail, &hints); if (!FPDFAvail_IsLinearized(pdf_avail)) { printf("Non-linearized path...\n"); doc = FPDF_LoadCustomDocument(&file_access, NULL); } else { printf("Linearized path...\n"); doc = FPDFAvail_GetDocument(pdf_avail, NULL); } (void) FPDF_GetDocPermissions(doc); (void) FPDFAvail_IsFormAvail(pdf_avail, &hints); FPDF_FORMHANDLE form = FPDFDOC_InitFormFillEnviroument(doc, &form_callbacks); FPDF_SetFormFieldHighlightColor(form, 0, 0xFFE4DD); FPDF_SetFormFieldHighlightAlpha(form, 100); int first_page = FPDFAvail_GetFirstPageNum(doc); (void) FPDFAvail_IsPageAvail(pdf_avail, first_page, &hints); int page_count = FPDF_GetPageCount(doc); for (int i = 0; i < page_count; ++i) { (void) FPDFAvail_IsPageAvail(pdf_avail, i, &hints); } FORM_DoDocumentJSAction(form); FORM_DoDocumentOpenAction(form); for (int i = 0; i < page_count; ++i) { FPDF_PAGE page = FPDF_LoadPage(doc, i); FPDF_TEXTPAGE text_page = FPDFText_LoadPage(page); FORM_OnAfterLoadPage(page, form); FORM_DoPageAAction(page, form, FPDFPAGE_AACTION_OPEN); int width = static_cast<int>(FPDF_GetPageWidth(page)); int height = static_cast<int>(FPDF_GetPageHeight(page)); FPDF_BITMAP bitmap = FPDFBitmap_Create(width, height, 0); FPDFBitmap_FillRect(bitmap, 0, 0, width, height, 255, 255, 255, 255); FPDF_RenderPageBitmap(bitmap, page, 0, 0, width, height, 0, 0); FPDF_FFLDraw(form, bitmap, page, 0, 0, width, height, 0, 0); if (write_images) { const char* buffer = reinterpret_cast<const char*>( FPDFBitmap_GetBuffer(bitmap)); int stride = FPDFBitmap_GetStride(bitmap); WritePpm(name, i, buffer, stride, width, height); } FPDFBitmap_Destroy(bitmap); FORM_DoPageAAction(page, form, FPDFPAGE_AACTION_CLOSE); FORM_OnBeforeClosePage(page, form); FPDFText_ClosePage(text_page); FPDF_ClosePage(page); } FORM_DoDocumentAAction(form, FPDFDOC_AACTION_WC); FPDFDOC_ExitFormFillEnviroument(form); FPDF_CloseDocument(doc); FPDFAvail_Destroy(pdf_avail); printf("Loaded, parsed and rendered %d pages.\n", page_count); } int main(int argc, const char* argv[]) { v8::V8::InitializeICU(); bool write_images = false; std::list<const char*> files; if (!ParseCommandLine(argc, argv, &write_images, &files)) { printf("Usage is: test [--write_images] /path/to/pdf\n"); printf("--write_images - to write page images <pdf-name>.<page-number>.ppm\n"); return 1; } FPDF_InitLibrary(NULL); UNSUPPORT_INFO unsuppored_info; memset(&unsuppored_info, '\0', sizeof(unsuppored_info)); unsuppored_info.version = 1; unsuppored_info.FSDK_UnSupport_Handler = Unsupported_Handler; FSDK_SetUnSpObjProcessHandler(&unsuppored_info); while (!files.empty()) { const char* filename = files.front(); files.pop_front(); FILE* file = fopen(filename, FOPEN_READ); if (!file) { fprintf(stderr, "Failed to open: %s\n", filename); continue; } (void) fseek(file, 0, SEEK_END); size_t len = ftell(file); (void) fseek(file, 0, SEEK_SET); char* pBuf = (char*) malloc(len); size_t ret = fread(pBuf, 1, len, file); (void) fclose(file); if (ret != len) { fprintf(stderr, "Failed to read: %s\n", filename); } else { RenderPdf(filename, pBuf, len, write_images); } free(pBuf); } FPDF_DestroyLibrary(); return 0; } <commit_msg>Switch include paths to fpdfsdk back to be relative so that pdfium_test can be built from a Chromium checkout.<commit_after>// 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 <limits.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <list> #include <string> #include <utility> #include "../fpdfsdk/include/fpdf_dataavail.h" #include "../fpdfsdk/include/fpdf_ext.h" #include "../fpdfsdk/include/fpdfformfill.h" #include "../fpdfsdk/include/fpdftext.h" #include "../fpdfsdk/include/fpdfview.h" #include "v8/include/v8.h" #ifdef _WIN32 #define snprintf _snprintf /* in Windows, rb for open and read binary file */ #define FOPEN_READ "rb" #else #define FOPEN_READ "r" #endif static void WritePpm(const char* pdf_name, int num, const char* buffer, int stride, int width, int height) { if (stride < 0 || width < 0 || height < 0) return; if (height > 0 && width > INT_MAX / height) return; int out_len = width * height; if (out_len > INT_MAX / 3) return; out_len *= 3; char filename[256]; snprintf(filename, sizeof(filename), "%s.%d.ppm", pdf_name, num); FILE* fp = fopen(filename, "w"); if (!fp) return; fprintf(fp, "P6\n# PDF test render\n%d %d\n255\n", width, height); // Source data is B, G, R, unused. // Dest data is R, G, B. char* result = new char[out_len]; if (result) { for (int h = 0; h < height; ++h) { const char* src_line = buffer + (stride * h); char* dest_line = result + (width * h * 3); for (int w = 0; w < width; ++w) { // R dest_line[w * 3] = src_line[(w * 4) + 2]; // G dest_line[(w * 3) + 1] = src_line[(w * 4) + 1]; // B dest_line[(w * 3) + 2] = src_line[w * 4]; } } fwrite(result, out_len, 1, fp); delete [] result; } fclose(fp); } int Form_Alert(IPDF_JSPLATFORM*, FPDF_WIDESTRING, FPDF_WIDESTRING, int, int) { printf("Form_Alert called.\n"); return 0; } void Unsupported_Handler(UNSUPPORT_INFO*, int type) { std::string feature = "Unknown"; switch (type) { case FPDF_UNSP_DOC_XFAFORM: feature = "XFA"; break; case FPDF_UNSP_DOC_PORTABLECOLLECTION: feature = "Portfolios_Packages"; break; case FPDF_UNSP_DOC_ATTACHMENT: case FPDF_UNSP_ANNOT_ATTACHMENT: feature = "Attachment"; break; case FPDF_UNSP_DOC_SECURITY: feature = "Rights_Management"; break; case FPDF_UNSP_DOC_SHAREDREVIEW: feature = "Shared_Review"; break; case FPDF_UNSP_DOC_SHAREDFORM_ACROBAT: case FPDF_UNSP_DOC_SHAREDFORM_FILESYSTEM: case FPDF_UNSP_DOC_SHAREDFORM_EMAIL: feature = "Shared_Form"; break; case FPDF_UNSP_ANNOT_3DANNOT: feature = "3D"; break; case FPDF_UNSP_ANNOT_MOVIE: feature = "Movie"; break; case FPDF_UNSP_ANNOT_SOUND: feature = "Sound"; break; case FPDF_UNSP_ANNOT_SCREEN_MEDIA: case FPDF_UNSP_ANNOT_SCREEN_RICHMEDIA: feature = "Screen"; break; case FPDF_UNSP_ANNOT_SIG: feature = "Digital_Signature"; break; } printf("Unsupported feature: %s.\n", feature.c_str()); } bool ParseCommandLine(int argc, const char* argv[], bool* write_images, std::list<const char*>* files) { *write_images = false; files->clear(); int cur_arg = 1; if (cur_arg < argc && strcmp(argv[cur_arg], "--write_images") == 0) { *write_images = true; cur_arg++; } if (cur_arg >= argc) return false; for (int i = cur_arg; i < argc; i++) files->push_back(argv[i]); return true; } class TestLoader { public: TestLoader(const char* pBuf, size_t len); const char* m_pBuf; size_t m_Len; }; TestLoader::TestLoader(const char* pBuf, size_t len) : m_pBuf(pBuf), m_Len(len) { } int Get_Block(void* param, unsigned long pos, unsigned char* pBuf, unsigned long size) { TestLoader* pLoader = (TestLoader*) param; if (pos + size < pos || pos + size > pLoader->m_Len) return 0; memcpy(pBuf, pLoader->m_pBuf + pos, size); return 1; } bool Is_Data_Avail(FX_FILEAVAIL* pThis, size_t offset, size_t size) { return true; } void Add_Segment(FX_DOWNLOADHINTS* pThis, size_t offset, size_t size) { } void RenderPdf(const char* name, const char* pBuf, size_t len, bool write_images) { printf("Rendering PDF file %s.\n", name); IPDF_JSPLATFORM platform_callbacks; memset(&platform_callbacks, '\0', sizeof(platform_callbacks)); platform_callbacks.version = 1; platform_callbacks.app_alert = Form_Alert; FPDF_FORMFILLINFO form_callbacks; memset(&form_callbacks, '\0', sizeof(form_callbacks)); form_callbacks.version = 1; form_callbacks.m_pJsPlatform = &platform_callbacks; TestLoader loader(pBuf, len); FPDF_FILEACCESS file_access; memset(&file_access, '\0', sizeof(file_access)); file_access.m_FileLen = len; file_access.m_GetBlock = Get_Block; file_access.m_Param = &loader; FX_FILEAVAIL file_avail; memset(&file_avail, '\0', sizeof(file_avail)); file_avail.version = 1; file_avail.IsDataAvail = Is_Data_Avail; FX_DOWNLOADHINTS hints; memset(&hints, '\0', sizeof(hints)); hints.version = 1; hints.AddSegment = Add_Segment; FPDF_DOCUMENT doc; FPDF_AVAIL pdf_avail = FPDFAvail_Create(&file_avail, &file_access); (void) FPDFAvail_IsDocAvail(pdf_avail, &hints); if (!FPDFAvail_IsLinearized(pdf_avail)) { printf("Non-linearized path...\n"); doc = FPDF_LoadCustomDocument(&file_access, NULL); } else { printf("Linearized path...\n"); doc = FPDFAvail_GetDocument(pdf_avail, NULL); } (void) FPDF_GetDocPermissions(doc); (void) FPDFAvail_IsFormAvail(pdf_avail, &hints); FPDF_FORMHANDLE form = FPDFDOC_InitFormFillEnviroument(doc, &form_callbacks); FPDF_SetFormFieldHighlightColor(form, 0, 0xFFE4DD); FPDF_SetFormFieldHighlightAlpha(form, 100); int first_page = FPDFAvail_GetFirstPageNum(doc); (void) FPDFAvail_IsPageAvail(pdf_avail, first_page, &hints); int page_count = FPDF_GetPageCount(doc); for (int i = 0; i < page_count; ++i) { (void) FPDFAvail_IsPageAvail(pdf_avail, i, &hints); } FORM_DoDocumentJSAction(form); FORM_DoDocumentOpenAction(form); for (int i = 0; i < page_count; ++i) { FPDF_PAGE page = FPDF_LoadPage(doc, i); FPDF_TEXTPAGE text_page = FPDFText_LoadPage(page); FORM_OnAfterLoadPage(page, form); FORM_DoPageAAction(page, form, FPDFPAGE_AACTION_OPEN); int width = static_cast<int>(FPDF_GetPageWidth(page)); int height = static_cast<int>(FPDF_GetPageHeight(page)); FPDF_BITMAP bitmap = FPDFBitmap_Create(width, height, 0); FPDFBitmap_FillRect(bitmap, 0, 0, width, height, 255, 255, 255, 255); FPDF_RenderPageBitmap(bitmap, page, 0, 0, width, height, 0, 0); FPDF_FFLDraw(form, bitmap, page, 0, 0, width, height, 0, 0); if (write_images) { const char* buffer = reinterpret_cast<const char*>( FPDFBitmap_GetBuffer(bitmap)); int stride = FPDFBitmap_GetStride(bitmap); WritePpm(name, i, buffer, stride, width, height); } FPDFBitmap_Destroy(bitmap); FORM_DoPageAAction(page, form, FPDFPAGE_AACTION_CLOSE); FORM_OnBeforeClosePage(page, form); FPDFText_ClosePage(text_page); FPDF_ClosePage(page); } FORM_DoDocumentAAction(form, FPDFDOC_AACTION_WC); FPDFDOC_ExitFormFillEnviroument(form); FPDF_CloseDocument(doc); FPDFAvail_Destroy(pdf_avail); printf("Loaded, parsed and rendered %d pages.\n", page_count); } int main(int argc, const char* argv[]) { v8::V8::InitializeICU(); bool write_images = false; std::list<const char*> files; if (!ParseCommandLine(argc, argv, &write_images, &files)) { printf("Usage is: test [--write_images] /path/to/pdf\n"); printf("--write_images - to write page images <pdf-name>.<page-number>.ppm\n"); return 1; } FPDF_InitLibrary(NULL); UNSUPPORT_INFO unsuppored_info; memset(&unsuppored_info, '\0', sizeof(unsuppored_info)); unsuppored_info.version = 1; unsuppored_info.FSDK_UnSupport_Handler = Unsupported_Handler; FSDK_SetUnSpObjProcessHandler(&unsuppored_info); while (!files.empty()) { const char* filename = files.front(); files.pop_front(); FILE* file = fopen(filename, FOPEN_READ); if (!file) { fprintf(stderr, "Failed to open: %s\n", filename); continue; } (void) fseek(file, 0, SEEK_END); size_t len = ftell(file); (void) fseek(file, 0, SEEK_SET); char* pBuf = (char*) malloc(len); size_t ret = fread(pBuf, 1, len, file); (void) fclose(file); if (ret != len) { fprintf(stderr, "Failed to read: %s\n", filename); } else { RenderPdf(filename, pBuf, len, write_images); } free(pBuf); } FPDF_DestroyLibrary(); return 0; } <|endoftext|>
<commit_before>// Copyright (c) 2014 Arista Networks, Inc. All rights reserved. // Arista Networks, Inc. Confidential and Proprietary. #include "eos/iterator.h" #include "eos/decap_group.h" #include "eos/mpls_route.h" namespace eos { template <typename T, typename Impl> inline iter_base<T, Impl>::iter_base(Impl * const impl) : impl(impl) { } template <typename T, typename Impl> inline iter_base<T, Impl>::iter_base(iter_base<T, Impl> const & other) : impl(0) { } template <typename T, typename Impl> inline iter_base<T, Impl>::~iter_base() { } template <typename T, typename Impl> inline iter_base<T, Impl>& iter_base<T, Impl>::operator++() { return *this; } template <typename T, typename Impl> inline bool iter_base<T, Impl>::operator==(const iter_base<T, Impl> & rhs) const { return impl == rhs.impl; } template <typename T, typename Impl> inline bool iter_base<T, Impl>::operator!=(const iter_base<T, Impl> & rhs) const { return impl != rhs.impl; } template <typename T, typename Impl> inline T iter_base<T, Impl>::operator*() { return T(); } template <typename T, typename Impl> inline iter_base<T, Impl>::operator bool() const { return false; } template class iter_base<decap_group_t, decap_group_iter_impl>; template class iter_base<mpls_route_t, mpls_route_iter_impl>; } <commit_msg>@1654806 Add iterator stubs that I somehow forgot to commit in @1654329.<commit_after>// Copyright (c) 2014 Arista Networks, Inc. All rights reserved. // Arista Networks, Inc. Confidential and Proprietary. #include "eos/decap_group.h" #include "eos/eth_intf.h" #include "eos/eth_phy_intf.h" #include "eos/intf.h" #include "eos/iterator.h" #include "eos/mpls_route.h" namespace eos { template <typename T, typename Impl> inline iter_base<T, Impl>::iter_base(Impl * const impl) : impl(impl) { } template <typename T, typename Impl> inline iter_base<T, Impl>::iter_base(iter_base<T, Impl> const & other) : impl(0) { } template <typename T, typename Impl> inline iter_base<T, Impl>::~iter_base() { } template <typename T, typename Impl> inline iter_base<T, Impl>& iter_base<T, Impl>::operator++() { return *this; } template <typename T, typename Impl> inline bool iter_base<T, Impl>::operator==(const iter_base<T, Impl> & rhs) const { return impl == rhs.impl; } template <typename T, typename Impl> inline bool iter_base<T, Impl>::operator!=(const iter_base<T, Impl> & rhs) const { return impl != rhs.impl; } template <typename T, typename Impl> inline T iter_base<T, Impl>::operator*() { return T(); } template <typename T, typename Impl> inline iter_base<T, Impl>::operator bool() const { return false; } template class iter_base<intf_id_t, intf_iter_impl>; template class iter_base<intf_id_t, eth_intf_iter_impl>; template class iter_base<intf_id_t, eth_phy_intf_iter_impl>; template class iter_base<decap_group_t, decap_group_iter_impl>; template class iter_base<mpls_route_t, mpls_route_iter_impl>; } <|endoftext|>
<commit_before>#include "System.h" #include "Display.h" Console c(USART2, 115200); #include "Interface.h" #include "Signals.h" const int SHORT_DELAY = 1000; extern Display tft; Screen mainScreen = Screen(&tft); Screen settingsScreen = Screen(&tft); extern "C" void TIM3_IRQHandler(void) { if (TIM_GetITStatus (TIM3, TIM_IT_Update) != RESET) { TIM_ClearITPendingBit(TIM3, TIM_IT_Update); int val = ecg.read(); } } extern "C" void TIM4_IRQHandler(void) { if (TIM_GetITStatus (TIM4, TIM_IT_Update) != RESET) { TIM_ClearITPendingBit(TIM4, TIM_IT_Update); int val = nibp.read(); /* c.print(val); */ /* c.print("\n"); */ } } void MainScreenInit(void){ tft.fillScreen(RA8875_BLACK); tft.showGrid(); mainScreen.initialDraw(); } void SettingsScreenInit(void){ tft.fillScreen(RA8875_BLACK); tft.showGrid(); settingsScreen.initialDraw(); } void systemInit() { adcInit(); tft.startup(); composeMainScreen(mainScreen); composeSettingsScreen(settingsScreen); connectSignalsToScreen(mainScreen); enableSignalAcquisition(); } int main(void) { c.configure(); c.print("\n"); /* c.print("Starting FreePulse...\n"); */ systemInit(); /* c.print("Welcome!\n"); */ while (1) { MainScreenInit(); delay(SHORT_DELAY); tft.clearTouchEvents(); while (currentMode == home) { mainScreen.update(SHORT_DELAY); mainScreen.readTouch(); tft.drawPixel(tft.touch_points[0],tft.touch_points[1], RA8875_WHITE); } if (currentMode == settings) { SettingsScreenInit(); delay(SHORT_DELAY); tft.clearTouchEvents(); while (currentMode == settings) { settingsScreen.update(SHORT_DELAY); settingsScreen.readTouch(); tft.drawPixel(tft.touch_points[0],tft.touch_points[1], RA8875_WHITE); } } } return 0; } <commit_msg>Fix another stray include error<commit_after>#include "System.h" #include "Display.h" Console c(USART2, 115200); #include "interface.h" #include "Signals.h" const int SHORT_DELAY = 1000; extern Display tft; Screen mainScreen = Screen(&tft); Screen settingsScreen = Screen(&tft); extern "C" void TIM3_IRQHandler(void) { if (TIM_GetITStatus (TIM3, TIM_IT_Update) != RESET) { TIM_ClearITPendingBit(TIM3, TIM_IT_Update); int val = ecg.read(); } } extern "C" void TIM4_IRQHandler(void) { if (TIM_GetITStatus (TIM4, TIM_IT_Update) != RESET) { TIM_ClearITPendingBit(TIM4, TIM_IT_Update); int val = nibp.read(); /* c.print(val); */ /* c.print("\n"); */ } } void MainScreenInit(void){ tft.fillScreen(RA8875_BLACK); tft.showGrid(); mainScreen.initialDraw(); } void SettingsScreenInit(void){ tft.fillScreen(RA8875_BLACK); tft.showGrid(); settingsScreen.initialDraw(); } void systemInit() { adcInit(); tft.startup(); composeMainScreen(mainScreen); composeSettingsScreen(settingsScreen); connectSignalsToScreen(mainScreen); enableSignalAcquisition(); } int main(void) { c.configure(); c.print("\n"); /* c.print("Starting FreePulse...\n"); */ systemInit(); /* c.print("Welcome!\n"); */ while (1) { MainScreenInit(); delay(SHORT_DELAY); tft.clearTouchEvents(); while (currentMode == home) { mainScreen.update(SHORT_DELAY); mainScreen.readTouch(); tft.drawPixel(tft.touch_points[0],tft.touch_points[1], RA8875_WHITE); } if (currentMode == settings) { SettingsScreenInit(); delay(SHORT_DELAY); tft.clearTouchEvents(); while (currentMode == settings) { settingsScreen.update(SHORT_DELAY); settingsScreen.readTouch(); tft.drawPixel(tft.touch_points[0],tft.touch_points[1], RA8875_WHITE); } } } return 0; } <|endoftext|>
<commit_before>/* * fMBT, free Model Based Testing tool * Copyright (c) 2011, Intel Corporation. * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope 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 St - Fifth Floor, Boston, MA 02110-1301 USA. * */ #ifndef __lst_xrules_hh__ #define __lst_xrules_hh__ #include "model.hh" #include <map> #include <string> class Lts_xrules : public Model { public: Lts_xrules(Log&l, std::string params): Model(l, params) {} virtual bool reset(); virtual int execute(int action); virtual int getprops(int** props); virtual void push(); virtual void pop(); virtual int getActions(int** actions); // vireessä olevat tapahtumat virtual int getIActions(int** actions); // Vireessä olevat syöte tapahtumat. NULL ja 0 == DEADLOCK. virtual bool init(); void add_file(unsigned int index,std::string& filename); void add_result_action(std::string* name); void add_component(unsigned int index,std::string& name); void print_root_par(); virtual std::string stringify(); virtual Model* down(unsigned int a) { if (a>=lts.size()) { return NULL; } return lts[a]; } protected: void compose(); void prop_create(); std::vector<int> pzero; std::vector<int> tprops; /* type, which contains component number (1 = "general_camera.lsts") * and action number (within the component) * So comp(1,2) refers to action number 2 in the component 1. */ typedef std::pair<int, int> comp; /* * The structure. * * parent: for root node NULL * actions: result actions for the node. * vmap: maps <component, action> to next node. * count: last update count * added_count: previous time the node was active * active_next: list for active nodes. * me: <component, action>. Information about the node. * parent->vmap[this.me] points to this * */ struct par { par() { count=0;added_count=0;root_count=NULL; }; par(struct par* p) { parent = p; root_count = p->root_count; count=0; added_count=0; root_count=NULL; }; struct par* parent; std::vector<int> actions; std::map<comp, struct par*> vmap; /* for parallel composition structure cleanup */ unsigned count; unsigned* root_count; unsigned added_count; struct par* active_next; comp me; }; /* Bob maps <component,action> to the sturcture */ std::multimap<comp,struct par*> bob; /* */ bool parent_active_par(struct par* par); /* debug print.. */ void print_par(struct par* pa); void print_par(std::ostringstream& t,std::string name, struct par* pa); /* Replaced by model_names std::vector<std::string> lts_filenames; */ std::vector<Model*> lts; /* Root structure */ struct par root_par; /* current sturcture. Used when loading .xrules */ struct par* cur_par; /* head of the active list */ struct par* active_root; /* Do we need to compose or not */ int valid; /* Result actions, if valid */ std::vector<int> res_actions; /* Result input actions, if valid */ std::vector<int> res_iactions; /* pointers to THE structure. Accessed by result action. * Note. We support only deterministic results. */ std::vector<struct par*> res_nodes; /* Api compatibility */ int* _res_actions; int* _res_iactions; }; #endif <commit_msg>Add missing virtual destructor<commit_after>/* * fMBT, free Model Based Testing tool * Copyright (c) 2011, Intel Corporation. * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope 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 St - Fifth Floor, Boston, MA 02110-1301 USA. * */ #ifndef __lst_xrules_hh__ #define __lst_xrules_hh__ #include "model.hh" #include <map> #include <string> class Lts_xrules : public Model { public: Lts_xrules(Log&l, std::string params): Model(l, params) {} virtual ~Lts_xrules() {} // leaks memory. virtual bool reset(); virtual int execute(int action); virtual int getprops(int** props); virtual void push(); virtual void pop(); virtual int getActions(int** actions); // vireessä olevat tapahtumat virtual int getIActions(int** actions); // Vireessä olevat syöte tapahtumat. NULL ja 0 == DEADLOCK. virtual bool init(); void add_file(unsigned int index,std::string& filename); void add_result_action(std::string* name); void add_component(unsigned int index,std::string& name); void print_root_par(); virtual std::string stringify(); virtual Model* down(unsigned int a) { if (a>=lts.size()) { return NULL; } return lts[a]; } protected: void compose(); void prop_create(); std::vector<int> pzero; std::vector<int> tprops; /* type, which contains component number (1 = "general_camera.lsts") * and action number (within the component) * So comp(1,2) refers to action number 2 in the component 1. */ typedef std::pair<int, int> comp; /* * The structure. * * parent: for root node NULL * actions: result actions for the node. * vmap: maps <component, action> to next node. * count: last update count * added_count: previous time the node was active * active_next: list for active nodes. * me: <component, action>. Information about the node. * parent->vmap[this.me] points to this * */ struct par { par() { count=0;added_count=0;root_count=NULL; }; par(struct par* p) { parent = p; root_count = p->root_count; count=0; added_count=0; root_count=NULL; }; struct par* parent; std::vector<int> actions; std::map<comp, struct par*> vmap; /* for parallel composition structure cleanup */ unsigned count; unsigned* root_count; unsigned added_count; struct par* active_next; comp me; }; /* Bob maps <component,action> to the sturcture */ std::multimap<comp,struct par*> bob; /* */ bool parent_active_par(struct par* par); /* debug print.. */ void print_par(struct par* pa); void print_par(std::ostringstream& t,std::string name, struct par* pa); /* Replaced by model_names std::vector<std::string> lts_filenames; */ std::vector<Model*> lts; /* Root structure */ struct par root_par; /* current sturcture. Used when loading .xrules */ struct par* cur_par; /* head of the active list */ struct par* active_root; /* Do we need to compose or not */ int valid; /* Result actions, if valid */ std::vector<int> res_actions; /* Result input actions, if valid */ std::vector<int> res_iactions; /* pointers to THE structure. Accessed by result action. * Note. We support only deterministic results. */ std::vector<struct par*> res_nodes; /* Api compatibility */ int* _res_actions; int* _res_iactions; }; #endif <|endoftext|>
<commit_before>/// @file /// @author Ivan Vucica /// @version 2.0 /// /// @section LICENSE /// /// This program is free software; you can redistribute it and/or modify it under /// the terms of the BSD license: http://www.opensource.org/licenses/bsd-license.php #if HAVE_COREAUDIO #include <AudioUnit/AudioUnit.h> #if MAC_OS_X_VERSION_MAX_ALLOWED <= 1050 #include <AudioUnit/AUNTComponent.h> #endif #include <hltypes/harray.h> #include <hltypes/hstring.h> #include <hltypes/util.h> #include "CoreAudio_AudioManager.h" #include "CoreAudio_Player.h" #include "Source.h" #include "Buffer.h" #include "xal.h" namespace xal { // MARK: - // MARK: Constructor and its helper functions #define CA_INIT_ASSERTION_EX(assertion, message, returnvalue) \ if (!(assertion)) \ { \ xal::log("Unable to initialize CoreAudio: " message); \ return returnvalue; \ } #define CA_INIT_ASSERTION(assertion, message) CA_INIT_ASSERTION_EX(assertion, message, /*void*/) CoreAudio_AudioManager::CoreAudio_AudioManager(chstr systemName, unsigned long backendId, bool threaded, float updateTime, chstr deviceName) : AudioManager(systemName, backendId, threaded, updateTime, deviceName) { xal::log("initializing CoreAudio"); // set up threads before moving on if (threaded) { this->_setupThread(); } OSErr result = noErr; // find output audio unit AudioComponent outputComponent = this->_findOutputComponent(); CA_INIT_ASSERTION(outputComponent != NULL, "FindNextComponent returned NULL"); // open the output audio unit and initialize it result = AudioComponentInstanceNew (outputComponent, &outputAudioUnit); CA_INIT_ASSERTION(result == noErr, "OpenAComponent() failed for output audio unit"); result = AudioUnitInitialize(outputAudioUnit); CA_INIT_ASSERTION(result == noErr, "AudioUnitInitialize() failed for output audio unit"); // tell output audio unit what we will connect to it, // and assign the callback to generate the data result = this->_connectAudioUnit(); CA_INIT_ASSERTION(result == noErr, "_connectAudioUnit() failed"); this->enabled = true; // start! // // FIXME // // // move to init() method which needs to be // launched AFTER constructor. // some coreaudio-callbacked code needs to use xal::mgr result = AudioOutputUnitStart(outputAudioUnit); CA_INIT_ASSERTION(result == noErr, "AudioUnitOutputStart() failed"); } AudioComponent CoreAudio_AudioManager::_findOutputComponent() { AudioComponentDescription outputComponentDescription; memset(&outputComponentDescription, 0, sizeof(outputComponentDescription)); outputComponentDescription.componentType = kAudioUnitType_Output; #if !TARGET_OS_IPHONE outputComponentDescription.componentSubType = kAudioUnitSubType_DefaultOutput; #else outputComponentDescription.componentSubType = kAudioUnitSubType_RemoteIO; #endif outputComponentDescription.componentManufacturer = kAudioUnitManufacturer_Apple; outputComponentDescription.componentFlags = 0; outputComponentDescription.componentFlagsMask = 0; return AudioComponentFindNext (NULL, &outputComponentDescription); } OSStatus CoreAudio_AudioManager::_connectAudioUnit() { OSStatus result; // tell the output audio unit what input will we connect to it // also, fill member variable with format description /* AudioStreamBasicDescription unitDescription; */ memset(&unitDescription, 0, sizeof(unitDescription)); unitDescription.mFormatID = kAudioFormatLinearPCM; unitDescription.mFormatFlags = kLinearPCMFormatFlagIsPacked | kLinearPCMFormatFlagIsSignedInteger; unitDescription.mChannelsPerFrame = 2; unitDescription.mSampleRate = 44100; unitDescription.mBitsPerChannel = 16; unitDescription.mFramesPerPacket = 1; unitDescription.mBytesPerFrame = unitDescription.mBitsPerChannel * unitDescription.mChannelsPerFrame / 8; unitDescription.mBytesPerPacket = unitDescription.mBytesPerFrame * unitDescription.mFramesPerPacket; result = AudioUnitSetProperty (outputAudioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &unitDescription, sizeof (unitDescription)); CA_INIT_ASSERTION_EX(result == noErr, "AudioUnitSetProperty() failed to set input format for output audio unit", result); // assign callback struct AURenderCallbackStruct callback; memset(&callback, 0, sizeof(callback)); callback.inputProc = _mixAudio; callback.inputProcRefCon = this; result = AudioUnitSetProperty (outputAudioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &callback, sizeof(callback)); CA_INIT_ASSERTION_EX(result == noErr, "AudioUnitSetProperty() failed to set callback for output audio unit", result); return noErr; } // MARK: - // MARK: Destructor CoreAudio_AudioManager::~CoreAudio_AudioManager() { xal::log("destroying CoreAudio"); /* SDL_PauseAudio(1); SDL_CloseAudio(); SDL_QuitSubSystem(SDL_INIT_AUDIO); delete [] this->buffer; */ } // MARK: - // MARK: Rest of audio manager code Player* CoreAudio_AudioManager::_createAudioPlayer(Sound* sound, Buffer* buffer) { return new CoreAudio_Player(sound, buffer); } OSStatus CoreAudio_AudioManager::mixAudio(void *inRefCon, AudioUnitRenderActionFlags *ioActionFlags, const AudioTimeStamp *inTimeStamp, UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList *ioData) { this->_lock(); size_t length; int i; void *ptr; AudioBuffer *abuf; // hack: // we will render only one buffer. ioData->mNumberBuffers = 1; for (i = 0; i < ioData->mNumberBuffers; i++) { abuf = &ioData->mBuffers[i]; length = abuf->mDataByteSize; ptr = abuf->mData; memset(ptr, 0, length); bool first = true; foreach (Player*, it, this->players) { ((CoreAudio_Player*)(*it))->mixAudio((unsigned char*)ptr, length, first); first = false; } } this->_unlock(); return noErr; } OSStatus CoreAudio_AudioManager::_mixAudio(void *inRefCon, AudioUnitRenderActionFlags *ioActionFlags, const AudioTimeStamp *inTimeStamp, UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList *ioData) { if(!xal::mgr) return 0; return ((CoreAudio_AudioManager*)xal::mgr)->mixAudio(inRefCon, ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData); } void CoreAudio_AudioManager::_convertStream(Buffer* buffer, unsigned char** stream, int *streamSize) { if (buffer->getBitsPerSample() != unitDescription.mBitsPerChannel || buffer->getChannels() != unitDescription.mChannelsPerFrame || buffer->getSamplingRate() != unitDescription.mSampleRate) { printf("INPUT STREAM SIZE: %d\n", *streamSize); // describe the input format's description AudioStreamBasicDescription inputDescription; memset(&inputDescription, 0, sizeof(inputDescription)); inputDescription.mFormatID = kAudioFormatLinearPCM; inputDescription.mFormatFlags = kLinearPCMFormatFlagIsPacked | kLinearPCMFormatFlagIsSignedInteger; inputDescription.mChannelsPerFrame = buffer->getChannels(); inputDescription.mSampleRate = buffer->getSamplingRate(); inputDescription.mBitsPerChannel = buffer->getBitsPerSample(); inputDescription.mBytesPerFrame = (inputDescription.mBitsPerChannel * inputDescription.mChannelsPerFrame) / 8; inputDescription.mFramesPerPacket = 1; //*streamSize / inputDescription.mBytesPerFrame; inputDescription.mBytesPerPacket = inputDescription.mBytesPerFrame * inputDescription.mFramesPerPacket; printf("INPUT : %lu bytes per packet for sample rate %g, channels %d\n", inputDescription.mBytesPerPacket, inputDescription.mSampleRate, inputDescription.mChannelsPerFrame); // copy conversion output format's description from the // output audio unit's description. // then adjust framesPerPacket to match the input we'll be passing. // framecount of our input stream is based on the input bytecount. // output stream will have same number of frames, but different // number of bytes. AudioStreamBasicDescription outputDescription = unitDescription; outputDescription.mFramesPerPacket = 1; //inputDescription.mFramesPerPacket; outputDescription.mBytesPerPacket = outputDescription.mBytesPerFrame * outputDescription.mFramesPerPacket; printf("OUTPUT : %lu bytes per packet for sample rate %g, channels %d\n", outputDescription.mBytesPerPacket, outputDescription.mSampleRate, outputDescription.mChannelsPerFrame); // create an audio converter AudioConverterRef audioConverter; OSStatus acCreationResult = AudioConverterNew(&inputDescription, &outputDescription, &audioConverter); printf("Created audio converter %p (status: %d)\n", audioConverter, acCreationResult); if(!audioConverter) { // bail out free(*stream); *streamSize = 0; *stream = (unsigned char*)malloc(0); return; } // calculate number of bytes required for output of input stream. // allocate buffer of adequate size. UInt32 outputBytes = outputDescription.mBytesPerPacket * (*streamSize / inputDescription.mBytesPerFrame); // outputDescription.mFramesPerPacket * outputDescription.mBytesPerFrame; unsigned char *outputBuffer = (unsigned char*)malloc(outputBytes); memset(outputBuffer, 0, outputBytes); printf("OUTPUT BYTES : %d\n", outputBytes); // describe input data we'll pass into converter AudioBuffer inputBuffer; inputBuffer.mNumberChannels = inputDescription.mChannelsPerFrame; inputBuffer.mDataByteSize = *streamSize; inputBuffer.mData = *stream; // describe output data buffers into which we can receive data. AudioBufferList outputBufferList; outputBufferList.mNumberBuffers = 1; outputBufferList.mBuffers[0].mNumberChannels = outputDescription.mChannelsPerFrame; outputBufferList.mBuffers[0].mDataByteSize = outputBytes; outputBufferList.mBuffers[0].mData = outputBuffer; // set output data packet size UInt32 outputDataPacketSize = outputDescription.mBytesPerPacket; // convert OSStatus result = AudioConverterFillComplexBuffer(audioConverter, /* AudioConverterRef inAudioConverter */ CoreAudio_AudioManager::_converterComplexInputDataProc, /* AudioConverterComplexInputDataProc inInputDataProc */ &inputBuffer, /* void *inInputDataProcUserData */ &outputDataPacketSize, /* UInt32 *ioOutputDataPacketSize */ &outputBufferList, /* AudioBufferList *outOutputData */ NULL /* AudioStreamPacketDescription *outPacketDescription */ ); printf("Result: %d wheee\n", result); // change "stream" to describe our output buffer. // even if error occured, we'd rather have silence than unconverted audio. free(*stream); *stream = outputBuffer; *streamSize = outputBytes; // dispose of the audio converter AudioConverterDispose(audioConverter); } } OSStatus CoreAudio_AudioManager::_converterComplexInputDataProc(AudioConverterRef inAudioConverter, UInt32* ioNumberDataPackets, AudioBufferList* ioData, AudioStreamPacketDescription** ioDataPacketDescription, void* inUserData) { printf("Converter\n"); if(*ioNumberDataPackets != 1) { xal::log("_converterComplexInputDataProc cannot provide input data; invalid number of packets requested"); *ioNumberDataPackets = 0; ioData->mNumberBuffers = 0; return -50; } *ioNumberDataPackets = 1; ioData->mNumberBuffers = 1; ioData->mBuffers[0] = *(AudioBuffer*)inUserData; *ioDataPacketDescription = NULL; return 0; } } #endif<commit_msg>Got first chunk of data to be sample-rate-converted under Core Audio.<commit_after>/// @file /// @author Ivan Vucica /// @version 2.0 /// /// @section LICENSE /// /// This program is free software; you can redistribute it and/or modify it under /// the terms of the BSD license: http://www.opensource.org/licenses/bsd-license.php #if HAVE_COREAUDIO #include <AudioUnit/AudioUnit.h> #if MAC_OS_X_VERSION_MAX_ALLOWED <= 1050 #include <AudioUnit/AUNTComponent.h> #endif #include <hltypes/harray.h> #include <hltypes/hstring.h> #include <hltypes/util.h> #include "CoreAudio_AudioManager.h" #include "CoreAudio_Player.h" #include "Source.h" #include "Buffer.h" #include "xal.h" namespace xal { // MARK: - // MARK: Constructor and its helper functions #define CA_INIT_ASSERTION_EX(assertion, message, returnvalue) \ if (!(assertion)) \ { \ xal::log("Unable to initialize CoreAudio: " message); \ return returnvalue; \ } #define CA_INIT_ASSERTION(assertion, message) CA_INIT_ASSERTION_EX(assertion, message, /*void*/) CoreAudio_AudioManager::CoreAudio_AudioManager(chstr systemName, unsigned long backendId, bool threaded, float updateTime, chstr deviceName) : AudioManager(systemName, backendId, threaded, updateTime, deviceName) { xal::log("initializing CoreAudio"); // set up threads before moving on if (threaded) { this->_setupThread(); } OSErr result = noErr; // find output audio unit AudioComponent outputComponent = this->_findOutputComponent(); CA_INIT_ASSERTION(outputComponent != NULL, "FindNextComponent returned NULL"); // open the output audio unit and initialize it result = AudioComponentInstanceNew (outputComponent, &outputAudioUnit); CA_INIT_ASSERTION(result == noErr, "OpenAComponent() failed for output audio unit"); result = AudioUnitInitialize(outputAudioUnit); CA_INIT_ASSERTION(result == noErr, "AudioUnitInitialize() failed for output audio unit"); // tell output audio unit what we will connect to it, // and assign the callback to generate the data result = this->_connectAudioUnit(); CA_INIT_ASSERTION(result == noErr, "_connectAudioUnit() failed"); this->enabled = true; // start! // // FIXME // // // move to init() method which needs to be // launched AFTER constructor. // some coreaudio-callbacked code needs to use xal::mgr result = AudioOutputUnitStart(outputAudioUnit); CA_INIT_ASSERTION(result == noErr, "AudioUnitOutputStart() failed"); } AudioComponent CoreAudio_AudioManager::_findOutputComponent() { AudioComponentDescription outputComponentDescription; memset(&outputComponentDescription, 0, sizeof(outputComponentDescription)); outputComponentDescription.componentType = kAudioUnitType_Output; #if !TARGET_OS_IPHONE outputComponentDescription.componentSubType = kAudioUnitSubType_DefaultOutput; #else outputComponentDescription.componentSubType = kAudioUnitSubType_RemoteIO; #endif outputComponentDescription.componentManufacturer = kAudioUnitManufacturer_Apple; outputComponentDescription.componentFlags = 0; outputComponentDescription.componentFlagsMask = 0; return AudioComponentFindNext (NULL, &outputComponentDescription); } OSStatus CoreAudio_AudioManager::_connectAudioUnit() { OSStatus result; // tell the output audio unit what input will we connect to it // also, fill member variable with format description /* AudioStreamBasicDescription unitDescription; */ memset(&unitDescription, 0, sizeof(unitDescription)); unitDescription.mFormatID = kAudioFormatLinearPCM; unitDescription.mFormatFlags = kLinearPCMFormatFlagIsPacked | kLinearPCMFormatFlagIsSignedInteger; unitDescription.mChannelsPerFrame = 2; unitDescription.mSampleRate = 44100; unitDescription.mBitsPerChannel = 16; unitDescription.mFramesPerPacket = 1; unitDescription.mBytesPerFrame = unitDescription.mBitsPerChannel * unitDescription.mChannelsPerFrame / 8; unitDescription.mBytesPerPacket = unitDescription.mBytesPerFrame * unitDescription.mFramesPerPacket; result = AudioUnitSetProperty (outputAudioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &unitDescription, sizeof (unitDescription)); CA_INIT_ASSERTION_EX(result == noErr, "AudioUnitSetProperty() failed to set input format for output audio unit", result); // assign callback struct AURenderCallbackStruct callback; memset(&callback, 0, sizeof(callback)); callback.inputProc = _mixAudio; callback.inputProcRefCon = this; result = AudioUnitSetProperty (outputAudioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &callback, sizeof(callback)); CA_INIT_ASSERTION_EX(result == noErr, "AudioUnitSetProperty() failed to set callback for output audio unit", result); return noErr; } // MARK: - // MARK: Destructor CoreAudio_AudioManager::~CoreAudio_AudioManager() { xal::log("destroying CoreAudio"); /* SDL_PauseAudio(1); SDL_CloseAudio(); SDL_QuitSubSystem(SDL_INIT_AUDIO); delete [] this->buffer; */ } // MARK: - // MARK: Rest of audio manager code Player* CoreAudio_AudioManager::_createAudioPlayer(Sound* sound, Buffer* buffer) { return new CoreAudio_Player(sound, buffer); } OSStatus CoreAudio_AudioManager::mixAudio(void *inRefCon, AudioUnitRenderActionFlags *ioActionFlags, const AudioTimeStamp *inTimeStamp, UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList *ioData) { this->_lock(); size_t length; int i; void *ptr; AudioBuffer *abuf; // hack: // we will render only one buffer. ioData->mNumberBuffers = 1; for (i = 0; i < ioData->mNumberBuffers; i++) { abuf = &ioData->mBuffers[i]; length = abuf->mDataByteSize; ptr = abuf->mData; memset(ptr, 0, length); bool first = true; foreach (Player*, it, this->players) { ((CoreAudio_Player*)(*it))->mixAudio((unsigned char*)ptr, length, first); first = false; } } this->_unlock(); return noErr; } OSStatus CoreAudio_AudioManager::_mixAudio(void *inRefCon, AudioUnitRenderActionFlags *ioActionFlags, const AudioTimeStamp *inTimeStamp, UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList *ioData) { if(!xal::mgr) return 0; return ((CoreAudio_AudioManager*)xal::mgr)->mixAudio(inRefCon, ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData); } void CoreAudio_AudioManager::_convertStream(Buffer* buffer, unsigned char** stream, int *streamSize) { if (buffer->getBitsPerSample() != unitDescription.mBitsPerChannel || buffer->getChannels() != unitDescription.mChannelsPerFrame || buffer->getSamplingRate() != unitDescription.mSampleRate) { printf("INPUT STREAM SIZE: %d\n", *streamSize); // describe the input format's description AudioStreamBasicDescription inputDescription; memset(&inputDescription, 0, sizeof(inputDescription)); inputDescription.mFormatID = kAudioFormatLinearPCM; inputDescription.mFormatFlags = kLinearPCMFormatFlagIsPacked | kLinearPCMFormatFlagIsSignedInteger; inputDescription.mChannelsPerFrame = buffer->getChannels(); inputDescription.mSampleRate = buffer->getSamplingRate(); inputDescription.mBitsPerChannel = buffer->getBitsPerSample(); inputDescription.mBytesPerFrame = (inputDescription.mBitsPerChannel * inputDescription.mChannelsPerFrame) / 8; inputDescription.mFramesPerPacket = 1; //*streamSize / inputDescription.mBytesPerFrame; inputDescription.mBytesPerPacket = inputDescription.mBytesPerFrame * inputDescription.mFramesPerPacket; printf("INPUT : %lu bytes per packet for sample rate %g, channels %d\n", inputDescription.mBytesPerPacket, inputDescription.mSampleRate, inputDescription.mChannelsPerFrame); // copy conversion output format's description from the // output audio unit's description. // then adjust framesPerPacket to match the input we'll be passing. // framecount of our input stream is based on the input bytecount. // output stream will have same number of frames, but different // number of bytes. AudioStreamBasicDescription outputDescription = unitDescription; outputDescription.mFramesPerPacket = 1; //inputDescription.mFramesPerPacket; outputDescription.mBytesPerPacket = outputDescription.mBytesPerFrame * outputDescription.mFramesPerPacket; printf("OUTPUT : %lu bytes per packet for sample rate %g, channels %d\n", outputDescription.mBytesPerPacket, outputDescription.mSampleRate, outputDescription.mChannelsPerFrame); // create an audio converter AudioConverterRef audioConverter; OSStatus acCreationResult = AudioConverterNew(&inputDescription, &outputDescription, &audioConverter); printf("Created audio converter %p (status: %d)\n", audioConverter, acCreationResult); if(!audioConverter) { // bail out free(*stream); *streamSize = 0; *stream = (unsigned char*)malloc(0); return; } // calculate number of bytes required for output of input stream. // allocate buffer of adequate size. UInt32 outputBytes = outputDescription.mBytesPerPacket * (*streamSize / inputDescription.mBytesPerFrame); // outputDescription.mFramesPerPacket * outputDescription.mBytesPerFrame; unsigned char *outputBuffer = (unsigned char*)malloc(outputBytes); memset(outputBuffer, 0, outputBytes); printf("OUTPUT BYTES : %d\n", outputBytes); // describe input data we'll pass into converter AudioBuffer inputBuffer; inputBuffer.mNumberChannels = inputDescription.mChannelsPerFrame; inputBuffer.mDataByteSize = *streamSize; inputBuffer.mData = *stream; // describe output data buffers into which we can receive data. AudioBufferList outputBufferList; outputBufferList.mNumberBuffers = 1; outputBufferList.mBuffers[0].mNumberChannels = outputDescription.mChannelsPerFrame; outputBufferList.mBuffers[0].mDataByteSize = outputBytes; outputBufferList.mBuffers[0].mData = outputBuffer; // set output data packet size UInt32 outputDataPacketSize = outputBytes; printf("Output data packet size %d\n", outputDataPacketSize); // convert OSStatus result = AudioConverterFillComplexBuffer(audioConverter, /* AudioConverterRef inAudioConverter */ CoreAudio_AudioManager::_converterComplexInputDataProc, /* AudioConverterComplexInputDataProc inInputDataProc */ &inputBuffer, /* void *inInputDataProcUserData */ &outputDataPacketSize, /* UInt32 *ioOutputDataPacketSize */ &outputBufferList, /* AudioBufferList *outOutputData */ NULL /* AudioStreamPacketDescription *outPacketDescription */ ); printf("Result: %d wheee\n", result); // change "stream" to describe our output buffer. // even if error occured, we'd rather have silence than unconverted audio. free(*stream); *stream = outputBuffer; *streamSize = outputBytes; // dispose of the audio converter AudioConverterDispose(audioConverter); } } OSStatus CoreAudio_AudioManager::_converterComplexInputDataProc(AudioConverterRef inAudioConverter, UInt32* ioNumberDataPackets, AudioBufferList* ioData, AudioStreamPacketDescription** ioDataPacketDescription, void* inUserData) { printf("Converter\n"); if(ioDataPacketDescription) { xal::log("_converterComplexInputDataProc cannot provide input data; it doesn't know how to provide packet descriptions"); *ioDataPacketDescription = NULL; *ioNumberDataPackets = 0; ioData->mNumberBuffers = 0; return 501; } /* if(*ioNumberDataPackets != 1) { xal::log("_converterComplexInputDataProc cannot provide input data; invalid number of packets requested"); *ioNumberDataPackets = 0; ioData->mNumberBuffers = 0; return 500; } */ printf("number of data packets %d\n", *ioNumberDataPackets); printf("number of buffers %d\n", ioData->mNumberBuffers); ioData->mNumberBuffers = 1; ioData->mBuffers[0] = *(AudioBuffer*)inUserData; return 0; } } #endif<|endoftext|>
<commit_before>/****************************************************************************** * Fake Frog * * An Arduino-based project to build a frog-shaped temperature logger. * * Author: David Lougheed. Copyright 2017. * ******************************************************************************/ #define VERSION "0.1.0" // Includes #include <Arduino.h> #include <Wire.h> #include <LiquidCrystal.h> #include <SD.h> #include <RTClib.h> // Compile-Time Settings #define SERIAL_LOGGING true // Log to the serial display for debug. #define FILE_LOGGING true // Log to file on SD card. (recommended) #define DISPLAY_ENABLED true // Show menus and information on an LCD. #define NUM_SAMPLES 10 // Samples get averaged to reduce noise. #define SAMPLE_DELAY 10 // Milliseconds between samples. #define READING_INTERVAL 60 // Seconds between readings. // Hardware Settings // - The data logging shield uses A4, A5, and digital pins 10, 11, 12, and 13. #define THERMISTOR_PIN A0 #define THERMISTOR_SERIES_RES 10000 #define THERMISTOR_RES_NOM 10000 // Nominal resistance, R0. #define THERMISTOR_B_COEFF 3950 // Beta coefficient of the thermistor. #define THERMISTOR_TEMP_NOM 25 // Nominal temperature of R0. #define SD_CARD_PIN 10 #define RTC_PIN_1 A4 #define RTC_PIN_2 A5 #define LCD_PIN_RS 4 #define LCD_PIN_EN 5 #define LCD_PIN_DB4 6 #define LCD_PIN_DB5 7 #define LCD_PIN_DB6 8 #define LCD_PIN_DB7 9 #define LCD_ROWS 2 #define LCD_COLUMNS 16 #define RTC_TYPE RTC_PCF8523 // Other Compile-Time Constants #define MAX_LOG_FILES 1000 #define MAX_DATA_FILES 1000 // Globals bool serial_logging_started = false; // - Files File log_file; File data_file; // - Hardware Objects RTC_TYPE rtc; LiquidCrystal* lcd; // - Data Point Variables // (to save memory, use global data point variables) DateTime now; char formatted_timestamp[] = "0000-00-00T00:00:00"; char* temperature_string = (char*) malloc(sizeof(char) * 8); char* data_file_entry_buffer = (char*) malloc(sizeof(char) * 50); double latest_resistance; double latest_temperature; /* DISPLAY MODES (ALL WITH LOGGING) 0: Idle 1: Information (clock, space usage) 2: RTC Editor */ uint8_t display_mode = 0; uint16_t i; // 16-bit iterator uint8_t timer = 0; // Counts seconds // Utility Methods // Log a generic message. void log(const char* msg, bool with_newline = true) { if (SERIAL_LOGGING) { if(!serial_logging_started) { Serial.begin(9600); Serial.println(); serial_logging_started = true; } if (with_newline) { Serial.println(msg); } else { Serial.print(msg); } } if (FILE_LOGGING) { if (log_file) { if (with_newline) { log_file.println(msg); } else { log_file.print(msg); } log_file.flush(); } } } // Log an error message. Uses standard log method, then hangs forever. void log_error(const char* msg, bool with_newline = true) { log(msg, with_newline); while (true); // Loop forever } void update_screen() { if (DISPLAY_ENABLED && lcd) { lcd->clear(); switch (display_mode) { case 1: lcd->print("TBD"); break; case 2: lcd->print("TBD"); break; case 0: default: break; } } } void switch_display_mode(uint8_t m) { display_mode = m; update_screen(); } // Data Methods // Update the global formatted timestamp string with the contents of 'now'. void update_formatted_timestamp() { sprintf(formatted_timestamp, "%u-%u-%uT%u:%u:%u", now.year(), now.month(), now.day(), now.hour(), now.minute(), now.second()); } double resistance_to_temperature(double resistance) { // Formula: T = 1/(1/B * ln(R/R_0) + (1/T0)) - 273.15 (celcius) return 1 / ((log(resistance / THERMISTOR_RES_NOM) / THERMISTOR_B_COEFF) + 1 / (THERMISTOR_TEMP_NOM + 273.15)) - 273.15; } void take_reading() { now = rtc.now(); latest_resistance = 0; for (i = 0; i < NUM_SAMPLES; i++) { latest_resistance += (double) analogRead(THERMISTOR_PIN); delay(SAMPLE_DELAY); } // Formulas: R = sr / (1023 / mean_of_samples - 1) // sr = thermistor series resistance latest_resistance = THERMISTOR_SERIES_RES / (1023 / (latest_resistance / NUM_SAMPLES) - 1); // Resistance latest_temperature = resistance_to_temperature(latest_resistance); // TODO: Error calculations } void save_reading_to_card() { if (data_file) { update_formatted_timestamp(); dtostrf(latest_temperature, 5, 2, temperature_string); sprintf(data_file_entry_buffer, "%s,%s", temperature_string, formatted_timestamp); data_file.println(data_file_entry_buffer); data_file.flush(); } } // Main Methods void setup() { // TODO: Set up pins // SET UP EXTERNAL ANALOG VOLTAGE REFERENCE // Typically from 3.3V Arduino supply. This reduces the voltage noise seen // from reading analog values. analogReference(EXTERNAL); // INITIALIZE SD CARD log("Initializing SD card... ", false); pinMode(SD_CARD_PIN, OUTPUT); if (!SD.begin()) { log_error("Failed."); } log("Done."); // SET UP LOG FILE if (FILE_LOGGING) { log("Creating log file... ", false); char log_file_name[] = "log_000.txt"; for (i = 0; i < MAX_LOG_FILES; i++) { // Increment until we can find a log file slot. // Need to add 32 to get ASCII number characters. log_file_name[6] = i / 100 + 32; log_file_name[7] = i / 10 + 32; log_file_name[8] = i % 10 + 32; if (!SD.exists(log_file_name)) { log_file = SD.open(log_file_name, FILE_WRITE); break; } } if (log_file) { log("Done."); } else { log_error("Failed."); } } // SET UP RTC log("Initializing RTC...", false); Wire.begin(); if (!rtc.begin()) { log_error("Failed."); } log("Done."); // TODO: Calibrate RTC // SET UP DATA FILE log("Creating data file..."); char data_file_name[] = "data_000.csv"; for (i = 0; i < MAX_DATA_FILES; i++) { // Increment until we can find a data file slot. // Need to add 32 to get ASCII digit characters. data_file_name[6] = i / 100 + 32; data_file_name[7] = i / 10 + 32; data_file_name[8] = i % 10 + 32; if (!SD.exists(data_file_name)) { data_file = SD.open(data_file_name, FILE_WRITE); break; } } if (data_file) { log("Done."); } else { log_error("Failed."); } // PRINT DATA FILE CSV HEADERS data_file.println("Timestamp,Temperature"); data_file.flush(); // SET UP LCD if (DISPLAY_ENABLED) { lcd = new LiquidCrystal(LCD_PIN_RS, LCD_PIN_EN, LCD_PIN_DB4, LCD_PIN_DB5, LCD_PIN_DB6, LCD_PIN_DB7); lcd->begin(LCD_COLUMNS, LCD_ROWS); } // Finished everything! now = rtc.now(); update_formatted_timestamp(); log("Data logger started at ", false); log(formatted_timestamp, false); log(". Software version: ", false); log(VERSION); } void loop() { if (timer == READING_INTERVAL) { timer = 0; take_reading(); save_reading_to_card(); } timer++; delay(1000); } <commit_msg>Make loop delay time depend on how much time was taken during the body of the loop.<commit_after>/****************************************************************************** * Fake Frog * * An Arduino-based project to build a frog-shaped temperature logger. * * Author: David Lougheed. Copyright 2017. * ******************************************************************************/ #define VERSION "0.1.0" // Includes #include <Arduino.h> #include <Wire.h> #include <LiquidCrystal.h> #include <SD.h> #include <RTClib.h> // Compile-Time Settings #define SERIAL_LOGGING true // Log to the serial display for debug. #define FILE_LOGGING true // Log to file on SD card. (recommended) #define DISPLAY_ENABLED true // Show menus and information on an LCD. #define NUM_SAMPLES 10 // Samples get averaged to reduce noise. #define SAMPLE_DELAY 10 // Milliseconds between samples. #define READING_INTERVAL 60 // Seconds between readings. // Hardware Settings // - The data logging shield uses A4, A5, and digital pins 10, 11, 12, and 13. #define THERMISTOR_PIN A0 #define THERMISTOR_SERIES_RES 10000 #define THERMISTOR_RES_NOM 10000 // Nominal resistance, R0. #define THERMISTOR_B_COEFF 3950 // Beta coefficient of the thermistor. #define THERMISTOR_TEMP_NOM 25 // Nominal temperature of R0. #define SD_CARD_PIN 10 #define RTC_PIN_1 A4 #define RTC_PIN_2 A5 #define LCD_PIN_RS 4 #define LCD_PIN_EN 5 #define LCD_PIN_DB4 6 #define LCD_PIN_DB5 7 #define LCD_PIN_DB6 8 #define LCD_PIN_DB7 9 #define LCD_ROWS 2 #define LCD_COLUMNS 16 #define RTC_TYPE RTC_PCF8523 // Other Compile-Time Constants #define MAX_LOG_FILES 1000 #define MAX_DATA_FILES 1000 // Globals bool serial_logging_started = false; // - Files File log_file; File data_file; // - Hardware Objects RTC_TYPE rtc; LiquidCrystal* lcd; // - Data Point Variables // (to save memory, use global data point variables) DateTime now; char formatted_timestamp[] = "0000-00-00T00:00:00"; char* temperature_string = (char*) malloc(sizeof(char) * 8); char* data_file_entry_buffer = (char*) malloc(sizeof(char) * 50); double latest_resistance; double latest_temperature; /* DISPLAY MODES (ALL WITH LOGGING) 0: Idle 1: Information (clock, space usage) 2: RTC Editor */ uint8_t display_mode = 0; uint16_t i; // 16-bit iterator uint8_t timer = 0; // Counts seconds uint32_t milli_timer = 0; // Counts time taken to do a loop // Utility Methods // Log a generic message. void log(const char* msg, bool with_newline = true) { if (SERIAL_LOGGING) { if(!serial_logging_started) { Serial.begin(9600); Serial.println(); serial_logging_started = true; } if (with_newline) { Serial.println(msg); } else { Serial.print(msg); } } if (FILE_LOGGING) { if (log_file) { if (with_newline) { log_file.println(msg); } else { log_file.print(msg); } log_file.flush(); } } } // Log an error message. Uses standard log method, then hangs forever. void log_error(const char* msg, bool with_newline = true) { log(msg, with_newline); while (true); // Loop forever } void update_screen() { if (DISPLAY_ENABLED && lcd) { lcd->clear(); switch (display_mode) { case 1: lcd->print("TBD"); break; case 2: lcd->print("TBD"); break; case 0: default: break; } } } void switch_display_mode(uint8_t m) { display_mode = m; update_screen(); } // Data Methods // Update the global formatted timestamp string with the contents of 'now'. void update_formatted_timestamp() { sprintf(formatted_timestamp, "%u-%u-%uT%u:%u:%u", now.year(), now.month(), now.day(), now.hour(), now.minute(), now.second()); } double resistance_to_temperature(double resistance) { // Formula: T = 1/(1/B * ln(R/R_0) + (1/T0)) - 273.15 (celcius) return 1 / ((log(resistance / THERMISTOR_RES_NOM) / THERMISTOR_B_COEFF) + 1 / (THERMISTOR_TEMP_NOM + 273.15)) - 273.15; } void take_reading() { now = rtc.now(); latest_resistance = 0; for (i = 0; i < NUM_SAMPLES; i++) { latest_resistance += (double) analogRead(THERMISTOR_PIN); delay(SAMPLE_DELAY); } // Formulas: R = sr / (1023 / mean_of_samples - 1) // sr = thermistor series resistance latest_resistance = THERMISTOR_SERIES_RES / (1023 / (latest_resistance / NUM_SAMPLES) - 1); // Resistance latest_temperature = resistance_to_temperature(latest_resistance); // TODO: Error calculations } void save_reading_to_card() { if (data_file) { update_formatted_timestamp(); dtostrf(latest_temperature, 5, 2, temperature_string); sprintf(data_file_entry_buffer, "%s,%s", temperature_string, formatted_timestamp); data_file.println(data_file_entry_buffer); data_file.flush(); } } // Main Methods void setup() { // TODO: Set up pins // SET UP EXTERNAL ANALOG VOLTAGE REFERENCE // Typically from 3.3V Arduino supply. This reduces the voltage noise seen // from reading analog values. analogReference(EXTERNAL); // INITIALIZE SD CARD log("Initializing SD card... ", false); pinMode(SD_CARD_PIN, OUTPUT); if (!SD.begin()) { log_error("Failed."); } log("Done."); // SET UP LOG FILE if (FILE_LOGGING) { log("Creating log file... ", false); char log_file_name[] = "log_000.txt"; for (i = 0; i < MAX_LOG_FILES; i++) { // Increment until we can find a log file slot. // Need to add 32 to get ASCII number characters. log_file_name[6] = i / 100 + 32; log_file_name[7] = i / 10 + 32; log_file_name[8] = i % 10 + 32; if (!SD.exists(log_file_name)) { log_file = SD.open(log_file_name, FILE_WRITE); break; } } if (log_file) { log("Done."); } else { log_error("Failed."); } } // SET UP RTC log("Initializing RTC...", false); Wire.begin(); if (!rtc.begin()) { log_error("Failed."); } log("Done."); // TODO: Calibrate RTC // SET UP DATA FILE log("Creating data file..."); char data_file_name[] = "data_000.csv"; for (i = 0; i < MAX_DATA_FILES; i++) { // Increment until we can find a data file slot. // Need to add 32 to get ASCII digit characters. data_file_name[6] = i / 100 + 32; data_file_name[7] = i / 10 + 32; data_file_name[8] = i % 10 + 32; if (!SD.exists(data_file_name)) { data_file = SD.open(data_file_name, FILE_WRITE); break; } } if (data_file) { log("Done."); } else { log_error("Failed."); } // PRINT DATA FILE CSV HEADERS data_file.println("Timestamp,Temperature"); data_file.flush(); // SET UP LCD if (DISPLAY_ENABLED) { lcd = new LiquidCrystal(LCD_PIN_RS, LCD_PIN_EN, LCD_PIN_DB4, LCD_PIN_DB5, LCD_PIN_DB6, LCD_PIN_DB7); lcd->begin(LCD_COLUMNS, LCD_ROWS); } // Finished everything! now = rtc.now(); update_formatted_timestamp(); log("Data logger started at ", false); log(formatted_timestamp, false); log(". Software version: ", false); log(VERSION); } void loop() { milli_timer = millis(); if (timer == READING_INTERVAL) { timer = 0; take_reading(); save_reading_to_card(); } timer++; delay(1000 - (millis() - milli_timer)); // 1 second between loops } <|endoftext|>
<commit_before>#include <iostream> // std::cout, std::cerr #include <cstdlib> // EXIT_SUCCESS #include <vector> // std::vector<> #include <algorithm> // std::min() #include <cmath> // std::pow(), std::sqrt(), std::sin() #include <exception> // std::exception #include <string> // std::string #include <opencv2/imgproc/imgproc.hpp> // cv::cvtColor(), CV_BGR2RGB cv::threshold(), // cv::findContours(), cv::drawContours(), // cv::THRESH_BINARY, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE #include <opencv2/highgui/highgui.hpp> // cv::imread(), CV_LOAD_IMAGE_COLOR, cv::WINDOW_NORMAL, // cv::imshow(), cv::waitKey(), cv::namedWindow() // cv::Mat, cv::Scalar, cv::Vec4i, cv::Point #include <boost/math/special_functions/sign.hpp> // boost::math::sign() #if defined(__gnu_linux__) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" #elif defined(__clang__) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" #endif #include <boost/math/constants/constants.hpp> // boost::math::constants::pi<>() #include <boost/program_options/options_description.hpp> // boost::program_options::options_description, // boost::program_options::value<> #include <boost/program_options/variables_map.hpp> // boost::program_options::variables_map, // boost::program_options::store(), // boost::program_options::notify() #include <boost/program_options/parsers.hpp> // boost::program_options::cmd_line::parser #include <boost/filesystem/operations.hpp> // boost::filesystem::exists() #if defined(__gnu_linux__) #pragma GCC diagnostic pop #elif defined(__clang__) #pragma clang diagnostic pop #endif typedef unsigned char uchar; typedef std::vector<std::vector<double>> levelset; /** * @brief Creates a level set with rectangular zero level set * @param u Empty level set (will be modified) * @param w Width of the level set matrix * @param h Height of the level set matrix * @param l Offset in pixels from the underlying image borders * @return 0 if success * 1 if the given level set is not empty */ int levelset_rect(levelset & u, int w, int h, int l) { if(! u.empty()) return 1; u.reserve(h); std::vector<double> tb_row(w, -1); std::vector<double> m_row(w, 1); std::fill(m_row.begin(), m_row.begin() + l, -1); std::fill(m_row.rbegin(), m_row.rbegin() + l, -1); for(int i = 0; i < l; ++i) u.push_back(tb_row); for(int i = l; i < h - l; ++i) u.push_back(m_row); for(int i = h - l; i < h; ++i) u.push_back(tb_row); return 0; } /** * @brief Creates a level set with circular zero level set * @param u Empty level set (will be modified) * @param w Width of the level set matrix * @param h Height of the level set matrix * @param d Diameter of the circle in relative units * Its value must be within (0, 1); 1 indicates that * the diameter is minimum of the image dimensions * @return 0 if success, * 1 if the given level set is not empty * 2 if the diameter is invalid */ int levelset_circ(levelset & u, int w, int h, double d) { if(! u.empty()) return 1; if(d < 0 || d > 1) return 2; const int r = std::min(w, h) * d / 2; const int mid_x = w / 2; const int mid_y = h / 2; u.reserve(h); for(int i = 0; i < h; ++i) { std::vector<double> row(w, -1); for(int j = 0; j < w; ++j) { const double d = std::sqrt(std::pow(mid_x - i, 2) + std::pow(mid_y - j, 2)); if(d < r) row[j] = 1; } u.push_back(row); } return 0; } /** * @brief Creates a level set with a checkerboard pattern at zero level * The zero level set is found via the formula * @f[ $ \mathrm{sign}\sin\Big(\frac{x}{5}\Big)\sin\Big(\frac{y}{5}\Big) $ @f]. * @param u Empty level set (will be modified) * @param w Width of the level set matrix * @param h Height of the level set matrix * @return 0 if success * 1 if the given level set is not empty */ int levelset_checkerboard(levelset & u, int w, int h) { if(! u.empty()) return 1; u.reserve(h); const double pi = boost::math::constants::pi<double>(); for(int i = 0; i < h; ++i) { std::vector<double> row; row.reserve(w); for(int j = 0; j < w; ++j) row.push_back(boost::math::sign(std::sin(pi * i / 5) * std::sin(pi * j / 5))); u.push_back(row); } return 0; } /** * @brief Creates a contour from the level set. * In the contour matrix, the negative values are replaced by 0, * whereas the positive values are replaced by 255. * This convention is kept in mind later on. * @param u Level set * @return Contour * @sa draw_contour */ cv::Mat levelset2contour(const levelset & u) { const int h = u.size(); const int w = u.at(0).size(); cv::Mat c(h, w, CV_8UC1); for(int i = 0; i < h; ++i) { for(int j = 0; j < w; ++j) { const double val = u.at(i).at(j); c.at<uchar>(i, j) = val <= 0 ? 0 : 255; } } return c; } /** * @brief Draws the zero level set on a given image * @param dst The image where the contour is placed. * @param u The level set, the zero level of which is plotted. * @return 0 * @sa levelset2contour */ int draw_contour(cv::Mat & dst, const levelset & u) { cv::Mat th; std::vector<std::vector<cv::Point>> cs; std::vector<cv::Vec4i> hier; cv::Mat c = levelset2contour(u); cv::threshold(c, th, 100, 255, cv::THRESH_BINARY); cv::findContours(th, cs, hier, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE); int idx = 0; for(; idx >= 0; idx = hier[idx][0]) { cv::Scalar color(255, 0, 0); // blue cv::drawContours(dst, cs, idx, color, 1, 8, hier); } return 0; } int main(int argc, char ** argv) { /// @todo add lambda1 and lambda2 as vector arguments std::string input_filename; double mu, nu; try { namespace po = boost::program_options; po::options_description desc("Allowed options"); desc.add_options() ("help,h", "produce help message") ("input,i", po::value<std::string>(&input_filename), "input image") ("mu", po::value<double>(&mu) -> default_value(0.5), "length penalty parameter") ("nu", po::value<double>(&nu) -> default_value(0), "area penalty parameter") ; po::variables_map vm; po::store(po::command_line_parser(argc, argv).options(desc).run(), vm); po::notify(vm); if(vm.count("help")) { std::cout << desc << "\n"; return EXIT_SUCCESS; } if(! vm.count("input")) { std::cerr << "\nError: you have to specify input file name!\n\n" << desc << "\n"; return EXIT_FAILURE; } if(vm.count("input")) { if(! boost::filesystem::exists(input_filename)) { std::cerr << "\nError: file \"" << input_filename << "\" does not exists!\n\n" << desc << "\n"; return EXIT_FAILURE; } } } catch(std::exception & e) { std::cerr << "error: " << e.what() << "n"; return EXIT_FAILURE; } const cv::Mat _img = cv::imread(input_filename, CV_LOAD_IMAGE_COLOR); if(! _img.data) { std::cerr << "\nError on opening " << input_filename <<" " << "(probably not an image)!\n\n"; return EXIT_FAILURE; } cv::Mat img; cv::cvtColor(_img, img, CV_BGR2RGB); const int h = img.rows; const int w = img.cols; levelset u; //levelset_rect(u, w, h, 4); //levelset_circ(u, w, h, 0.5); levelset_checkerboard(u, w, h); cv::Mat nw_img = img.clone(); draw_contour(nw_img, u); cv::namedWindow("Display window", cv::WINDOW_NORMAL); cv::imshow("Display window", img); cv::waitKey(1000); std::cout << "R" << static_cast<int>(img.at<cv::Vec3b>(0, 0)[0]) << " " "G" << static_cast<int>(img.at<cv::Vec3b>(0, 0)[1]) << " " "B" << static_cast<int>(img.at<cv::Vec3b>(0, 0)[2]) << "\n"; cv::imshow("Display window", nw_img); cv::waitKey(0); return EXIT_SUCCESS; } <commit_msg>Added grayscale option to Chan-Vese.<commit_after>#include <iostream> // std::cout, std::cerr #include <cstdlib> // EXIT_SUCCESS #include <vector> // std::vector<> #include <algorithm> // std::min() #include <cmath> // std::pow(), std::sqrt(), std::sin() #include <exception> // std::exception #include <string> // std::string #include <opencv2/imgproc/imgproc.hpp> // cv::cvtColor(), CV_BGR2RGB cv::threshold(), // cv::findContours(), cv::drawContours(), // cv::THRESH_BINARY, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE #include <opencv2/highgui/highgui.hpp> // cv::imread(), CV_LOAD_IMAGE_COLOR, cv::WINDOW_NORMAL, // cv::imshow(), cv::waitKey(), cv::namedWindow() // cv::Mat, cv::Scalar, cv::Vec4i, cv::Point #include <boost/math/special_functions/sign.hpp> // boost::math::sign() #if defined(__gnu_linux__) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" #elif defined(__clang__) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" #endif #include <boost/math/constants/constants.hpp> // boost::math::constants::pi<>() #include <boost/program_options/options_description.hpp> // boost::program_options::options_description, // boost::program_options::value<> #include <boost/program_options/variables_map.hpp> // boost::program_options::variables_map, // boost::program_options::store(), // boost::program_options::notify() #include <boost/program_options/parsers.hpp> // boost::program_options::cmd_line::parser #include <boost/filesystem/operations.hpp> // boost::filesystem::exists() #if defined(__gnu_linux__) #pragma GCC diagnostic pop #elif defined(__clang__) #pragma clang diagnostic pop #endif typedef unsigned char uchar; typedef std::vector<std::vector<double>> levelset; /** * @brief Creates a level set with rectangular zero level set * @param u Empty level set (will be modified) * @param w Width of the level set matrix * @param h Height of the level set matrix * @param l Offset in pixels from the underlying image borders * @return 0 if success * 1 if the given level set is not empty */ int levelset_rect(levelset & u, int w, int h, int l) { if(! u.empty()) return 1; u.reserve(h); std::vector<double> tb_row(w, -1); std::vector<double> m_row(w, 1); std::fill(m_row.begin(), m_row.begin() + l, -1); std::fill(m_row.rbegin(), m_row.rbegin() + l, -1); for(int i = 0; i < l; ++i) u.push_back(tb_row); for(int i = l; i < h - l; ++i) u.push_back(m_row); for(int i = h - l; i < h; ++i) u.push_back(tb_row); return 0; } /** * @brief Creates a level set with circular zero level set * @param u Empty level set (will be modified) * @param w Width of the level set matrix * @param h Height of the level set matrix * @param d Diameter of the circle in relative units * Its value must be within (0, 1); 1 indicates that * the diameter is minimum of the image dimensions * @return 0 if success, * 1 if the given level set is not empty * 2 if the diameter is invalid */ int levelset_circ(levelset & u, int w, int h, double d) { if(! u.empty()) return 1; if(d < 0 || d > 1) return 2; const int r = std::min(w, h) * d / 2; const int mid_x = w / 2; const int mid_y = h / 2; u.reserve(h); for(int i = 0; i < h; ++i) { std::vector<double> row(w, -1); for(int j = 0; j < w; ++j) { const double d = std::sqrt(std::pow(mid_x - i, 2) + std::pow(mid_y - j, 2)); if(d < r) row[j] = 1; } u.push_back(row); } return 0; } /** * @brief Creates a level set with a checkerboard pattern at zero level * The zero level set is found via the formula * @f[ $ \mathrm{sign}\sin\Big(\frac{x}{5}\Big)\sin\Big(\frac{y}{5}\Big) $ @f]. * @param u Empty level set (will be modified) * @param w Width of the level set matrix * @param h Height of the level set matrix * @return 0 if success * 1 if the given level set is not empty */ int levelset_checkerboard(levelset & u, int w, int h) { if(! u.empty()) return 1; u.reserve(h); const double pi = boost::math::constants::pi<double>(); for(int i = 0; i < h; ++i) { std::vector<double> row; row.reserve(w); for(int j = 0; j < w; ++j) row.push_back(boost::math::sign(std::sin(pi * i / 5) * std::sin(pi * j / 5))); u.push_back(row); } return 0; } /** * @brief Creates a contour from the level set. * In the contour matrix, the negative values are replaced by 0, * whereas the positive values are replaced by 255. * This convention is kept in mind later on. * @param u Level set * @return Contour * @sa draw_contour */ cv::Mat levelset2contour(const levelset & u) { const int h = u.size(); const int w = u.at(0).size(); cv::Mat c(h, w, CV_8UC1); for(int i = 0; i < h; ++i) { for(int j = 0; j < w; ++j) { const double val = u.at(i).at(j); c.at<uchar>(i, j) = val <= 0 ? 0 : 255; } } return c; } /** * @brief Draws the zero level set on a given image * @param dst The image where the contour is placed. * @param u The level set, the zero level of which is plotted. * @return 0 * @sa levelset2contour */ int draw_contour(cv::Mat & dst, const levelset & u) { cv::Mat th; std::vector<std::vector<cv::Point>> cs; std::vector<cv::Vec4i> hier; cv::Mat c = levelset2contour(u); cv::threshold(c, th, 100, 255, cv::THRESH_BINARY); cv::findContours(th, cs, hier, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE); int idx = 0; for(; idx >= 0; idx = hier[idx][0]) { cv::Scalar color(255, 0, 0); // blue cv::drawContours(dst, cs, idx, color, 1, 8, hier); } return 0; } int main(int argc, char ** argv) { ///-- @todo add lambda1 and lambda2 as vector arguments std::string input_filename; double mu, nu; bool grayscale = false; try { namespace po = boost::program_options; po::options_description desc("Allowed options"); desc.add_options() ("help,h", "this message") ("input,i", po::value<std::string>(&input_filename), "input image") ("mu", po::value<double>(&mu) -> default_value(0.5), "length penalty parameter") ("nu", po::value<double>(&nu) -> default_value(0), "area penalty parameter") ("grayscale,g", "read in as grayscale") ; po::variables_map vm; po::store(po::command_line_parser(argc, argv).options(desc).run(), vm); po::notify(vm); if(vm.count("help")) { std::cout << desc << "\n"; return EXIT_SUCCESS; } if(! vm.count("input")) { std::cerr << "\nError: you have to specify input file name!\n\n" << desc << "\n"; return EXIT_FAILURE; } if(vm.count("input")) { if(! boost::filesystem::exists(input_filename)) { std::cerr << "\nError: file \"" << input_filename << "\" does not exists!\n\n" << desc << "\n"; return EXIT_FAILURE; } } if(vm.count("grayscale")) { grayscale = true; } } catch(std::exception & e) { std::cerr << "error: " << e.what() << "n"; return EXIT_FAILURE; } ///-- Read the image (grayscale or BGR? RGB? BGR? help) cv::Mat _img; if(grayscale) _img = cv::imread(input_filename, CV_LOAD_IMAGE_GRAYSCALE); else _img = cv::imread(input_filename, CV_LOAD_IMAGE_COLOR); if(! _img.data) { std::cerr << "\nError on opening " << input_filename <<" " << "(probably not an image)!\n\n"; return EXIT_FAILURE; } ///-- Second conversion needed if we want to display a colored contour /// on a grayscale image cv::Mat img; if(grayscale) cv::cvtColor(_img, img, CV_GRAY2RGB); else img = _img; ///-- Determine the constants const int h = img.rows; const int w = img.cols; const int nof_channels = grayscale ? 1 : img.channels(); ///-- Construct the level set levelset u; levelset_checkerboard(u, w, h); ///-- Split the channels std::vector<cv::Mat> channels; channels.reserve(nof_channels); cv::split(img, channels); ///-- Display the zero level set cv::Mat nw_img = img.clone(); draw_contour(nw_img, u); cv::namedWindow("Display window", cv::WINDOW_NORMAL); cv::imshow("Display window", img); cv::waitKey(1000); cv::imshow("Display window", nw_img); cv::waitKey(0); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>#include <iostream> #include "main.hpp" #include "system/printer.hpp" #ifndef OBJ_PATH #define OBJ_PATH "share/cube.obj" #endif #ifndef VERT_PATH #define VERT_PATH "share/fallback.vert" #endif #ifndef FRAG_PATH #define FRAG_PATH "share/shade.frag" #endif int main(int argc, const char **argv) { using namespace Util; if(glfwInit() == 0) { std::cout << "Failed to initialize GLFW " << glfwGetVersionString() << std::endl; return 1; } const char *obj_fname, *vert_fname, *frag_fname; if(argc >= 2) obj_fname = argv[1]; else obj_fname = OBJ_PATH; if(argc >= 3) vert_fname = argv[2]; else vert_fname = VERT_PATH; if(argc >= 4) frag_fname = argv[3]; else frag_fname = FRAG_PATH; std::atomic_bool alive(true); Control::control ctl(alive, obj_fname, vert_fname, frag_fname); if(alive) { using namespace System; Printer<5> printer; std::string cols[]{"GLFW", "OpenGL"}, rows[]{"", "Major", "Minor", "Revision"}; int versions[6]{0}; glfwGetVersion(&versions[0], &versions[2], &versions[4]); glGetIntegerv(GL_MAJOR_VERSION, &versions[1]); glGetIntegerv(GL_MINOR_VERSION, &versions[3]); printer.push(&rows[0], &rows[0]+4).level() .push<int, 3, 2>(versions, &cols[0], &cols[0]+2).level(); std::cout << printer << std::endl; task::init(alive, &ctl); } else { std::cout << "Initialization of control failed." << std::endl; for(auto err : ctl.errors) { std::cout << err << std::endl; } return 1; } if(alive) { task::run(alive, &ctl); } else { std::cout << "Control failed while running." << std::endl; for(auto err : ctl.errors) { std::cout << err << std::endl; } } glfwTerminate(); return 0; } <commit_msg>Added printout of paths<commit_after>#include <iostream> #include "main.hpp" #include "system/printer.hpp" #ifndef OBJ_PATH #define OBJ_PATH "share/cube.obj" #endif #ifndef MTL_PATH #define MTL_PATH "share/cube.mtl" #endif #ifndef VERT_PATH #define VERT_PATH "share/fallback.vert" #endif #ifndef FRAG_PATH #define FRAG_PATH "share/shade.frag" #endif int main(int argc, const char **argv) { using namespace Util; if(glfwInit() == 0) { std::cout << "Failed to initialize GLFW " << glfwGetVersionString() << std::endl; return 1; } const char *obj_fname, *mtl_fname, *vert_fname, *frag_fname; if(argc >= 2) obj_fname = argv[1]; else obj_fname = OBJ_PATH; if(argc >= 3) mtl_fname = argv[2]; else mtl_fname = MTL_PATH; if(argc >= 4) vert_fname = argv[3]; else vert_fname = VERT_PATH; if(argc >= 5) frag_fname = argv[4]; else frag_fname = FRAG_PATH; std::atomic_bool alive(true); Control::control ctl(alive, obj_fname, vert_fname, frag_fname); if(alive) { using namespace System; Printer<6> printer; std::string cols[]{"GLFW", "OpenGL", "Path"}, rows[]{"", "Major", "Minor", "Revision", "", "", "Wavefront obj", "Wavefront mtl", "Vertex shader", "Fragment shader", ""}, paths[]{obj_fname, mtl_fname, vert_fname, frag_fname}; int versions[6]{0}; glfwGetVersion(&versions[0], &versions[2], &versions[4]); glGetIntegerv(GL_MAJOR_VERSION, &versions[1]); glGetIntegerv(GL_MINOR_VERSION, &versions[3]); printer.push(&rows[0], &rows[5]).level() .push<int, 3, 2>(versions, &cols[0], &cols[2]).level() .insert(0, Printer_Base::repeat(3)).level() .push(&rows[5], &rows[5]+6).level() .push<std::string, 4, 1, 31>(paths, &cols[2], &cols[3]+1).level(); std::cout << printer << std::endl; task::init(alive, &ctl); } else { std::cout << "Initialization of control failed." << std::endl; for(auto err : ctl.errors) { std::cout << err << std::endl; } return 1; } if(alive) { task::run(alive, &ctl); } else { std::cout << "Control failed while running." << std::endl; for(auto err : ctl.errors) { std::cout << err << std::endl; } } glfwTerminate(); return 0; } <|endoftext|>
<commit_before>/* * Copyright 2013 Matthew Harvey * * 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. */ // TODO MEDIUM PRIORITY Under KDE (at least on Mageia) the way I have set // up the widths of ComboBox and TextCtrl and wxButton (in various // controls in which these feature), where they are // supposed to be the same height, they actually turn out to be slightly // different heights. However even if I manually set them all to the same // hard-coded height number, they still seem to come out different heights // on KDE. It doesn't make a lot of sense. // TODO MEDIUM PRIORITY Tooltips aren't showing on Windows. /// TODO MEDIUM PRIORITY The database file should perhaps have a checksum to // guard against its contents changing other than via the application. // TODO HIGH PRIORITY Facilitate automatic checking for updates from user's // machine, or else provide an easy way for users to sign up to a mailing // list that keeps them informed about updates. Also note we had to manually // add "SetOverwrite on" to the CMake NSIS template file, to ensure the // generated installer will overwrite existing files when doing updates. This // is not ideal. // TODO HIGH PRIORITY Create a decent icon for the application. We want this // in both .ico form (for Windows executable icon) and .xpm // form (for icon for Frame). Note, when I exported my // "token icon" using GIMP to .ico format, and later used this // to create a double-clickable icon in Windows, only the text // on the icon appeared, and the background image became // transparent for some reason. Furthermore, when set as the // large in-windows icon in the CPack/NSIS installer, the icon // wasn't showing at all. Once decent icon is created, also make sure it is // pulled into the wxBitmap in SetupWizard. // TODO HIGH PRIORITY Make the GUI display acceptably on smaller screen // i.e. laptop. // TODO MEDIUM PRIORITY Startup time under Windows is really slow, even when // compiled in Release mode. // TODO MEDIUM PRIORITY Give user the option to export to CSV. // TODO LOW PRIORITY Allow export/import to/from .qif (?) format. // TODO MEDIUM PRIORITY Allow window borders to be dragged around, especially // for DraftJournalListCtrl. This make it easier for users on laptops. // TODO HIGH PRIORITY User guide. Write it using Sphinx. // TODO HIGH PRIORITY Incorporate "make user_guide" into CMakeLists.txt with // target that runs Sphinx to make user guide and then compile into application. // The "make install" and "make package" targets also need to be adjusted // so that help files will be installed to appropriate locations on the target // system. // TODO MEDIUM PRIORITY When the user creates a new file, ask if they want to // create a shortcut to the file on their Desktop (assuming they didn't // actually create the file in their desktop). #include "app.hpp" #include <wx/app.h> wxIMPLEMENT_APP(dcm::App); <commit_msg>Dummy commit, to note that I tested previous commit's bug fix attempt on Windows and didn't work.<commit_after>/* * Copyright 2013 Matthew Harvey * * 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. */ // TODO MEDIUM PRIORITY Under KDE (at least on Mageia) the way I have set // up the widths of ComboBox and TextCtrl and wxButton (in various // controls in which these feature), where they are // supposed to be the same height, they actually turn out to be slightly // different heights. However even if I manually set them all to the same // hard-coded height number, they still seem to come out different heights // on KDE. It doesn't make a lot of sense. // TODO MEDIUM PRIORITY Tooltips aren't showing on Windows. /// TODO MEDIUM PRIORITY The database file should perhaps have a checksum to // guard against its contents changing other than via the application. // TODO HIGH PRIORITY Facilitate automatic checking for updates from user's // machine, or else provide an easy way for users to sign up to a mailing // list that keeps them informed about updates. Also note we had to manually // add "SetOverwrite on" to the CMake NSIS template file, to ensure the // generated installer will overwrite existing files when doing updates. This // is not ideal. // TODO HIGH PRIORITY Create a decent icon for the application. We want this // in both .ico form (for Windows executable icon) and .xpm // form (for icon for Frame). Note, when I exported my // "token icon" using GIMP to .ico format, and later used this // to create a double-clickable icon in Windows, only the text // on the icon appeared, and the background image became // transparent for some reason. Furthermore, when set as the // large in-windows icon in the CPack/NSIS installer, the icon // wasn't showing at all. Once decent icon is created, also make sure it is // pulled into the wxBitmap in SetupWizard. // TODO HIGH PRIORITY Make the GUI display acceptably on smaller screen // i.e. laptop. // TODO MEDIUM PRIORITY Startup time under Windows is really slow, even when // compiled in Release mode. // TODO MEDIUM PRIORITY Give user the option to export to CSV. // TODO LOW PRIORITY Allow export/import to/from .qif (?) format. // TODO MEDIUM PRIORITY Allow window borders to be dragged around, especially // for DraftJournalListCtrl. This make it easier for users on laptops. // TODO HIGH PRIORITY User guide. Write it using Sphinx. // TODO HIGH PRIORITY Incorporate "make user_guide" into CMakeLists.txt with // target that runs Sphinx to make user guide and then compile into application. // The "make install" and "make package" targets also need to be adjusted // so that help files will be installed to appropriate locations on the target // system. // TODO MEDIUM PRIORITY When the user creates a new file, ask if they want to // create a shortcut to the file on their Desktop (assuming they didn't // actually create the file in their desktop). #include "app.hpp" #include <wx/app.h> wxIMPLEMENT_APP(dcm::App); <|endoftext|>
<commit_before>#include <string.h> #include <stdio.h> #include <netinet/in.h> #include <linux/netfilter.h> #include <libnetfilter_queue/libnetfilter_queue.h> #include <algorithm> #include <thread> #include <mutex> #include <condition_variable> struct packet { u_int32_t id; nfq_q_handle *qh; u_int32_t data_len; unsigned char *data; }; const u_int32_t MAX_LEN = 1500; unsigned char * res_buf; std::mutex read_mutex; std::mutex write_mutex; std::condition_variable read_condition; std::condition_variable write_condition; const size_t RING_BUFFER_SIZE = 5; packet ring_buffer[RING_BUFFER_SIZE]; volatile size_t first = 0; volatile size_t last = 0; u_int32_t get_packet_id(nfq_data *nfa) { nfqnl_msg_packet_hdr *ph = nfq_get_msg_packet_hdr(nfa); if (ph) { return ntohl(ph->packet_id); } else { return 0; } } size_t next(size_t current) { return (current + 1) % RING_BUFFER_SIZE; } bool is_full() { printf("call is_full\n"); return next(last) == first; } bool is_empty() { printf("call is_empty\n"); return first == last; } void add_packet(int id, nfq_q_handle *qh, u_int32_t data_len, unsigned char *data) { std::unique_lock<std::mutex> lock(write_mutex); while (is_full()) { write_condition.wait(lock); } packet *p = &ring_buffer[last]; p->id = id; p->qh = qh; p->data_len = data_len; if (p->data) { delete[] p->data; } p->data = data; last = next(last); read_condition.notify_one(); } packet *get_packet() { std::unique_lock<std::mutex> lock(read_mutex); while (is_empty()) { read_condition.wait(lock); } packet *p = &ring_buffer[first]; first = next(first); write_condition.notify_one(); return p; } int cb(nfq_q_handle *qh, nfgenmsg *nfmsg, nfq_data *nfa, void *data) { u_int32_t id = get_packet_id(nfa); unsigned char *buf; int len = nfq_get_payload(nfa, &buf); u_int32_t res_len = std::max(MAX_LEN, (u_int32_t) len); unsigned char *res_buf = new unsigned char[res_len]; memcpy(res_buf, buf, len); u_int32_t diff = res_len - len; memset(res_buf + len, 0, diff); add_packet(id, qh, res_len, res_buf); return 0; } int process_packets() { while (true) { printf("entering callback\n"); packet *p = get_packet(); nfq_set_verdict(p->qh, p->id, NF_ACCEPT, p->data_len, p->data); } } int main(int argc, char **argv) { res_buf = new unsigned char[MAX_LEN]; char buf[4096]; nfq_handle *h; nfq_q_handle *qh; int fd; int rv; printf("opening library handle\n"); h = nfq_open(); if (!h) { fprintf(stderr, "error during nfq_open()\n"); exit(1); } printf("unbinding existing nf_queue handler for AF_INET (if any)\n"); if (nfq_unbind_pf(h, AF_INET) < 0) { fprintf(stderr, "error during nfq_unbind_pf()\n"); exit(1); } printf("binding nfnetlink_queue as nf_queue handler for AF_INET\n"); if (nfq_bind_pf(h, AF_INET) < 0) { fprintf(stderr, "error during nfq_bind_pf()\n"); exit(1); } printf("binding this socket to queue '0'\n"); qh = nfq_create_queue(h, 0, &cb, NULL); if (!qh) { fprintf(stderr, "error during nfq_create_queue()\n"); exit(1); } printf("setting copy_packet mode\n"); if (nfq_set_mode(qh, NFQNL_COPY_PACKET, 0xffff) < 0) { fprintf(stderr, "can't set packet_copy mode\n"); exit(1); } fd = nfq_fd(h); std::thread t(process_packets); while ((rv = recv(fd, buf, sizeof(buf), 0)) && rv >= 0) { printf("pkt received\n"); nfq_handle_packet(h, buf, rv); } t.join(); printf("unbinding from queue 0\n"); nfq_destroy_queue(qh); #ifdef INSANE /* normally, applications SHOULD NOT issue this command, since * it detaches other programs/sockets from AF_INET, too ! */ printf("unbinding from AF_INET\n"); nfq_unbind_pf(h, AF_INET); #endif printf("closing library handle\n"); nfq_close(h); exit(0); } <commit_msg>sending empty packet<commit_after>#include <string.h> #include <stdio.h> #include <netinet/in.h> #include <linux/netfilter.h> #include <libnetfilter_queue/libnetfilter_queue.h> #include <algorithm> #include <thread> #include <mutex> #include <condition_variable> #include <arpa/inet.h> #include <linux/if_packet.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <sys/ioctl.h> #include <sys/socket.h> #include <net/if.h> #include <netinet/ip.h> #include <netinet/ether.h> #define MY_DEST_MAC0 0x00 #define MY_DEST_MAC1 0x00 #define MY_DEST_MAC2 0x00 #define MY_DEST_MAC3 0x00 #define MY_DEST_MAC4 0x00 #define MY_DEST_MAC5 0x00 #define DEFAULT_IF "eth0" #define BUF_SIZ 1024 static int sum_words(u_int16_t *buf, int nwords) { register u_int32_t sum = 0; while (nwords >= 16) { sum += (u_int16_t) ntohs(*buf++); sum += (u_int16_t) ntohs(*buf++); sum += (u_int16_t) ntohs(*buf++); sum += (u_int16_t) ntohs(*buf++); sum += (u_int16_t) ntohs(*buf++); sum += (u_int16_t) ntohs(*buf++); sum += (u_int16_t) ntohs(*buf++); sum += (u_int16_t) ntohs(*buf++); sum += (u_int16_t) ntohs(*buf++); sum += (u_int16_t) ntohs(*buf++); sum += (u_int16_t) ntohs(*buf++); sum += (u_int16_t) ntohs(*buf++); sum += (u_int16_t) ntohs(*buf++); sum += (u_int16_t) ntohs(*buf++); sum += (u_int16_t) ntohs(*buf++); sum += (u_int16_t) ntohs(*buf++); nwords -= 16; } while (nwords--) sum += (u_int16_t) ntohs(*buf++); return(sum); } void ip_checksum(struct ip *ip) { register u_int32_t sum; ip->ip_sum = 0; sum = sum_words((u_int16_t *) ip, ip->ip_hl << 1); sum = (sum >> 16) + (sum & 0xFFFF); sum += (sum >> 16); sum = ~sum; ip->ip_sum = htons(sum); } int sockfd; struct ifreq if_mac; struct sockaddr_ll socket_address; void init_socket() { struct ifreq if_idx; char ifName[IFNAMSIZ]; strcpy(ifName, DEFAULT_IF); /* Open RAW socket to send on */ if ((sockfd = socket(AF_PACKET, SOCK_RAW, IPPROTO_RAW)) == -1) { perror("socket"); exit(1); } /* Get the index of the interface to send on */ memset(&if_idx, 0, sizeof(struct ifreq)); strncpy(if_idx.ifr_name, ifName, IFNAMSIZ-1); if (ioctl(sockfd, SIOCGIFINDEX, &if_idx) < 0) { perror("SIOCGIFINDEX"); exit(1); } /* Get the MAC address of the interface to send on */ memset(&if_mac, 0, sizeof(struct ifreq)); strncpy(if_mac.ifr_name, ifName, IFNAMSIZ-1); if (ioctl(sockfd, SIOCGIFHWADDR, &if_mac) < 0) { perror("SIOCGIFHWADDR"); exit(1); } /* Index of the network device */ socket_address.sll_ifindex = if_idx.ifr_ifindex; /* Address length*/ socket_address.sll_halen = ETH_ALEN; /* Destination MAC */ socket_address.sll_addr[0] = MY_DEST_MAC0; socket_address.sll_addr[1] = MY_DEST_MAC1; socket_address.sll_addr[2] = MY_DEST_MAC2; socket_address.sll_addr[3] = MY_DEST_MAC3; socket_address.sll_addr[4] = MY_DEST_MAC4; socket_address.sll_addr[5] = MY_DEST_MAC5; } void send_empty_packet(in_addr src, in_addr dst) { int tx_len = 0; char sendbuf[BUF_SIZ]; struct ether_header *eh = (struct ether_header *) sendbuf; struct ip *ip = (struct ip *) (sendbuf + sizeof(struct ether_header)); /* Construct the Ethernet header */ memset(sendbuf, 0, BUF_SIZ); /* Ethernet header */ eh->ether_shost[0] = ((uint8_t *)&if_mac.ifr_hwaddr.sa_data)[0]; eh->ether_shost[1] = ((uint8_t *)&if_mac.ifr_hwaddr.sa_data)[1]; eh->ether_shost[2] = ((uint8_t *)&if_mac.ifr_hwaddr.sa_data)[2]; eh->ether_shost[3] = ((uint8_t *)&if_mac.ifr_hwaddr.sa_data)[3]; eh->ether_shost[4] = ((uint8_t *)&if_mac.ifr_hwaddr.sa_data)[4]; eh->ether_shost[5] = ((uint8_t *)&if_mac.ifr_hwaddr.sa_data)[5]; eh->ether_dhost[0] = MY_DEST_MAC0; eh->ether_dhost[1] = MY_DEST_MAC1; eh->ether_dhost[2] = MY_DEST_MAC2; eh->ether_dhost[3] = MY_DEST_MAC3; eh->ether_dhost[4] = MY_DEST_MAC4; eh->ether_dhost[5] = MY_DEST_MAC5; /* Ethertype field */ eh->ether_type = htons(ETH_P_IP); tx_len += sizeof(struct ether_header); /* Packet data */ tx_len += 4; ip->ip_hl = 5; ip->ip_v = 4; ip->ip_len = htons(sizeof(struct iphdr)); ip->ip_id = 0; ip->ip_off = 0; ip->ip_ttl = 40; ip->ip_p = 253; ip->ip_src = src; ip->ip_dst = dst; inet_aton("192.168.1.106", &ip->ip_dst); ip_checksum(ip); tx_len += sizeof(struct ip); /* Send packet */ if (sendto(sockfd, sendbuf, tx_len, 0, (struct sockaddr*)&socket_address, sizeof(struct sockaddr_ll)) < 0) printf("Send failed\n"); } struct packet { u_int32_t id; nfq_q_handle *qh; u_int32_t data_len; unsigned char *data; }; const u_int32_t MAX_LEN = 1500; unsigned char * res_buf; std::mutex read_mutex; std::mutex write_mutex; std::condition_variable read_condition; std::condition_variable write_condition; const size_t RING_BUFFER_SIZE = 5; packet ring_buffer[RING_BUFFER_SIZE]; volatile size_t first = 0; volatile size_t last = 0; u_int32_t get_packet_id(nfq_data *nfa) { nfqnl_msg_packet_hdr *ph = nfq_get_msg_packet_hdr(nfa); if (ph) { return ntohl(ph->packet_id); } else { return 0; } } size_t next(size_t current) { return (current + 1) % RING_BUFFER_SIZE; } bool is_full() { printf("call is_full\n"); return next(last) == first; } bool is_empty() { printf("call is_empty\n"); return first == last; } void add_packet(int id, nfq_q_handle *qh, u_int32_t data_len, unsigned char *data) { std::unique_lock<std::mutex> lock(write_mutex); while (is_full()) { write_condition.wait(lock); } packet *p = &ring_buffer[last]; p->id = id; p->qh = qh; p->data_len = data_len; if (p->data) { delete[] p->data; } p->data = data; last = next(last); read_condition.notify_one(); } packet *get_packet() { std::unique_lock<std::mutex> lock(read_mutex); while (is_empty()) { read_condition.wait(lock); } packet *p = &ring_buffer[first]; first = next(first); write_condition.notify_one(); return p; } int cb(nfq_q_handle *qh, nfgenmsg *nfmsg, nfq_data *nfa, void *data) { u_int32_t id = get_packet_id(nfa); unsigned char *buf; int len = nfq_get_payload(nfa, &buf); u_int32_t res_len = std::max(MAX_LEN, (u_int32_t) len); unsigned char *res_buf = new unsigned char[res_len]; memcpy(res_buf, buf, len); u_int32_t diff = res_len - len; memset(res_buf + len, 0, diff); ip *ip_ = (ip *) buf; if (ip_->ip_p == 253) { exit(1); } printf("%s", inet_ntoa(ip_->ip_dst)); add_packet(id, qh, res_len, res_buf); return 0; } int process_packets() { while (true) { printf("entering callback\n"); packet *p = get_packet(); ip *ip_ = (ip *) p->data; send_empty_packet(ip_->ip_src, ip_->ip_dst); nfq_set_verdict(p->qh, p->id, NF_ACCEPT, p->data_len, p->data); } } int main(int argc, char **argv) { init_socket(); res_buf = new unsigned char[MAX_LEN]; char buf[4096]; nfq_handle *h; nfq_q_handle *qh; int fd; int rv; printf("opening library handle\n"); h = nfq_open(); if (!h) { fprintf(stderr, "error during nfq_open()\n"); exit(1); } printf("unbinding existing nf_queue handler for AF_INET (if any)\n"); if (nfq_unbind_pf(h, AF_INET) < 0) { fprintf(stderr, "error during nfq_unbind_pf()\n"); exit(1); } printf("binding nfnetlink_queue as nf_queue handler for AF_INET\n"); if (nfq_bind_pf(h, AF_INET) < 0) { fprintf(stderr, "error during nfq_bind_pf()\n"); exit(1); } printf("binding this socket to queue '0'\n"); qh = nfq_create_queue(h, 0, &cb, NULL); if (!qh) { fprintf(stderr, "error during nfq_create_queue()\n"); exit(1); } printf("setting copy_packet mode\n"); if (nfq_set_mode(qh, NFQNL_COPY_PACKET, 0xffff) < 0) { fprintf(stderr, "can't set packet_copy mode\n"); exit(1); } fd = nfq_fd(h); std::thread t(process_packets); while ((rv = recv(fd, buf, sizeof(buf), 0)) && rv >= 0) { printf("pkt received\n"); nfq_handle_packet(h, buf, rv); } t.join(); printf("unbinding from queue 0\n"); nfq_destroy_queue(qh); #ifdef INSANE /* normally, applications SHOULD NOT issue this command, since * it detaches other programs/sockets from AF_INET, too ! */ printf("unbinding from AF_INET\n"); nfq_unbind_pf(h, AF_INET); #endif printf("closing library handle\n"); nfq_close(h); exit(0); } <|endoftext|>
<commit_before>#include <iostream> #include <vlc/libvlc.h> #include <vlc/libvlc_media.h> void vlcMetaPrint(const char* prefix, libvlc_media_t* media, libvlc_meta_t meta) { libvlc_media_parse(media); char *str = libvlc_media_get_meta(media, meta); if (str) { std::cout << prefix << ": " << str << std::endl; free(str); } } int main(int argc, char *argv[]) { if (argc != 2) { std::cerr << "Please specify exactly a single file." << std::endl; exit(EXIT_FAILURE); } libvlc_instance_t *vlcInstance = libvlc_new(0, nullptr); if (!vlcInstance) { std::cerr << "Could not initialise VLC" << std::endl; exit(EXIT_FAILURE); } libvlc_media_t* media = libvlc_media_new_path(vlcInstance, argv[1]); if (!media) { std::cerr << "Could not initialise media" << std::endl; exit(EXIT_FAILURE); } libvlc_media_parse(media); vlcMetaPrint("Artist", media, libvlc_meta_Artist); vlcMetaPrint("Title", media, libvlc_meta_Title); vlcMetaPrint("Genre", media, libvlc_meta_Genre); vlcMetaPrint("Copyright", media, libvlc_meta_Copyright); vlcMetaPrint("Album", media, libvlc_meta_Album); vlcMetaPrint("Track no:", media, libvlc_meta_TrackNumber); vlcMetaPrint("Description", media, libvlc_meta_Description); vlcMetaPrint("Rating", media, libvlc_meta_Rating); vlcMetaPrint("Date", media, libvlc_meta_Date); vlcMetaPrint("Setting", media, libvlc_meta_Setting); vlcMetaPrint("URL", media, libvlc_meta_URL); vlcMetaPrint("Language", media, libvlc_meta_Language); // FIXME: Is this present on any file metadata? // vlcMetaPrint("", media, libvlc_meta_NowPlaying); vlcMetaPrint("Publisher", media, libvlc_meta_Publisher); vlcMetaPrint("EncodedBy", media, libvlc_meta_EncodedBy); vlcMetaPrint("Artwork URL", media, libvlc_meta_ArtworkURL); vlcMetaPrint("Track ID", media, libvlc_meta_TrackID); vlcMetaPrint("Track total", media, libvlc_meta_TrackTotal); vlcMetaPrint("Director", media, libvlc_meta_Director); vlcMetaPrint("Season", media, libvlc_meta_Season); vlcMetaPrint("Episode", media, libvlc_meta_Episode); vlcMetaPrint("ShowName", media, libvlc_meta_ShowName); vlcMetaPrint("Actors", media, libvlc_meta_Actors); #ifdef HAVE_VLC_ALBUMARTIST vlcMetaPrint("AlbumArtist", media, libvlc_meta_AlbumArtist); #endif libvlc_media_release(media); libvlc_release(vlcInstance); } <commit_msg>Add duration information<commit_after>#include <iostream> #include <vlc/libvlc.h> #include <vlc/libvlc_media.h> void vlcMetaPrint(const char* prefix, libvlc_media_t* media, libvlc_meta_t meta) { libvlc_media_parse(media); char *str = libvlc_media_get_meta(media, meta); if (str) { std::cout << prefix << ": " << str << std::endl; free(str); } } int main(int argc, char *argv[]) { if (argc != 2) { std::cerr << "Please specify exactly a single file." << std::endl; exit(EXIT_FAILURE); } libvlc_instance_t *vlcInstance = libvlc_new(0, nullptr); if (!vlcInstance) { std::cerr << "Could not initialise VLC" << std::endl; exit(EXIT_FAILURE); } libvlc_media_t* media = libvlc_media_new_path(vlcInstance, argv[1]); if (!media) { std::cerr << "Could not initialise media" << std::endl; exit(EXIT_FAILURE); } libvlc_media_parse(media); libvlc_time_t duration = libvlc_media_get_duration(media); if (duration > 0) { std::cout << "Duration: " << duration / 1000.0 << "s" << std::endl; } vlcMetaPrint("Artist", media, libvlc_meta_Artist); vlcMetaPrint("Title", media, libvlc_meta_Title); vlcMetaPrint("Genre", media, libvlc_meta_Genre); vlcMetaPrint("Copyright", media, libvlc_meta_Copyright); vlcMetaPrint("Album", media, libvlc_meta_Album); vlcMetaPrint("Track no:", media, libvlc_meta_TrackNumber); vlcMetaPrint("Description", media, libvlc_meta_Description); vlcMetaPrint("Rating", media, libvlc_meta_Rating); vlcMetaPrint("Date", media, libvlc_meta_Date); vlcMetaPrint("Setting", media, libvlc_meta_Setting); vlcMetaPrint("URL", media, libvlc_meta_URL); vlcMetaPrint("Language", media, libvlc_meta_Language); // FIXME: Is this present on any file metadata? // vlcMetaPrint("", media, libvlc_meta_NowPlaying); vlcMetaPrint("Publisher", media, libvlc_meta_Publisher); vlcMetaPrint("EncodedBy", media, libvlc_meta_EncodedBy); vlcMetaPrint("Artwork URL", media, libvlc_meta_ArtworkURL); vlcMetaPrint("Track ID", media, libvlc_meta_TrackID); vlcMetaPrint("Track total", media, libvlc_meta_TrackTotal); vlcMetaPrint("Director", media, libvlc_meta_Director); vlcMetaPrint("Season", media, libvlc_meta_Season); vlcMetaPrint("Episode", media, libvlc_meta_Episode); vlcMetaPrint("ShowName", media, libvlc_meta_ShowName); vlcMetaPrint("Actors", media, libvlc_meta_Actors); #ifdef HAVE_VLC_ALBUMARTIST vlcMetaPrint("AlbumArtist", media, libvlc_meta_AlbumArtist); #endif libvlc_media_release(media); libvlc_release(vlcInstance); } <|endoftext|>
<commit_before> #include <stdio.h> #include <stdlib.h> #include <cstdio> #include <cstdlib> #include <iostream> #include <string> #include <string.h> #include "Kmp.h" #include "BoyerMoore.h" #include "support/StopWatch.h" using namespace StringMatch; #ifndef _DEBUG const size_t Iterations = 5000000; #else const size_t Iterations = 10000; #endif // // See: http://volnitsky.com/project/str_search/index.html // static const char * szSearchText[] = { "Here is a sample example.", "8'E . It consists of a number of low-lying, largely mangrove covered islands covering an area of around 665 km^2. " "The population of Bakassi is the subject of some dispute, but is generally put at between 150,000 and 300,000 people." }; static const char * szPatterns[] = { "sample", "example", "islands", "around", "subject", "between", "people", "between 150,000" }; template <typename algorithm_type> void StringMatch_test() { typedef algorithm_type::Pattern pattern_type; const char pattern_text_1[] = "sample"; char pattern_text_2[] = "a sample"; printf("-----------------------------------------------------------\n"); printf(" UnitTest: %s)\n", typeid(algorithm_type).name()); printf("-----------------------------------------------------------\n\n"); test::StopWatch sw; int sum, index_of; pattern_type pattern; pattern.prepare("example"); sum = 0; sw.start(); for (size_t i = 0; i < Iterations; ++i) { index_of = pattern.match("Here is a sample example."); sum += index_of; } sw.stop(); pattern.display_test(index_of, sum, sw.getElapsedMillisec()); pattern_type pattern1(pattern_text_1); //pattern1.prepare(pattern_text_1); sum = 0; sw.start(); for (size_t i = 0; i < Iterations; ++i) { index_of = pattern1.match("Here is a sample example."); sum += index_of; } sw.stop(); pattern1.display_test(index_of, sum, sw.getElapsedMillisec()); pattern_type pattern2(pattern_text_2); //pattern2.prepare(pattern_text_2); sum = 0; sw.start(); for (size_t i = 0; i < Iterations; ++i) { index_of = pattern2.match("Here is a sample example."); sum += index_of; } sw.stop(); pattern2.display_test(index_of, sum, sw.getElapsedMillisec()); } template <typename algorithm_type> void StringMatch_benchmark() { typedef algorithm_type::Pattern pattern_type; test::StopWatch sw; int sum; static const size_t iters = Iterations / (sm_countof(szSearchText) * sm_countof(szPatterns)); printf("-----------------------------------------------------------\n"); printf(" Benchmark: %s)\n", typeid(algorithm_type).name()); printf("-----------------------------------------------------------\n\n"); pattern_type pattern[sm_countof(szPatterns)]; for (int i = 0; i < sm_countof(szPatterns); ++i) { pattern[i].prepare(szPatterns[i]); } StringRef search_text[sm_countof(szSearchText)]; for (int i = 0; i < sm_countof(szSearchText); ++i) { search_text[i].set_ref(szSearchText[i], strlen(szSearchText[i])); } sum = 0; sw.start(); for (size_t loop = 0; loop < iters; ++loop) { for (int i = 0; i < sm_countof(szSearchText); ++i) { for (int j = 0; j < sm_countof(szPatterns); ++j) { int index_of = pattern[j].match(search_text[i]); sum += index_of; } } } sw.stop(); printf("sum: %12d, time spent: %0.3f ms\n\n", sum, sw.getElapsedMillisec()); } int main(int argc, char * argv[]) { StringMatch_test<AnsiString::Kmp>(); StringMatch_test<AnsiString::BoyerMoore>(); StringMatch_benchmark<AnsiString::Kmp>(); StringMatch_benchmark<AnsiString::BoyerMoore>(); ::system("pause"); return 0; } <commit_msg>Added StringMatch_examples();<commit_after> #include <stdio.h> #include <stdlib.h> #include <cstdio> #include <cstdlib> #include <iostream> #include <string> #include <string.h> #include "Kmp.h" #include "BoyerMoore.h" #include "support/StopWatch.h" using namespace StringMatch; #ifndef _DEBUG const size_t Iterations = 5000000; #else const size_t Iterations = 10000; #endif // // See: http://volnitsky.com/project/str_search/index.html // static const char * szSearchText[] = { "Here is a sample example.", "8'E . It consists of a number of low-lying, largely mangrove covered islands covering an area of around 665 km^2. " "The population of Bakassi is the subject of some dispute, but is generally put at between 150,000 and 300,000 people." }; static const char * szPatterns[] = { "sample", "example", "islands", "around", "subject", "between", "people", "between 150,000" }; void StringMatch_examples() { // Usage 1 { AnsiString::Kmp::Pattern p; p.prepare("example"); int pos = p.match("Here is a sample example."); } // Usage 2 { AnsiString::Kmp::Pattern p("example"); int pos = p.match("Here is a sample example."); } // Usage 3 { AnsiString::Kmp::Pattern p("example"); AnsiString::Kmp::Matcher m; int pos = m.find("Here is a sample example.", p); } // Usage 4 { AnsiString::Kmp::Pattern p1("example"); AnsiString::Kmp::Pattern p2("sample"); AnsiString::Kmp::Matcher m("Here is a sample example."); int pos1 = m.find(p1); int pos2 = m.find(p2); } // Usage 5 { AnsiString::Kmp::Pattern p1("example"); AnsiString::Kmp::Pattern p2("sample"); AnsiString::Kmp::Matcher m; m.set_text("Here is a sample example."); int pos1 = m.find(p1); int pos2 = m.find(p2); } } template <typename algorithm_type> void StringMatch_test() { typedef algorithm_type::Pattern pattern_type; const char pattern_text_1[] = "sample"; char pattern_text_2[] = "a sample"; printf("-----------------------------------------------------------\n"); printf(" UnitTest: %s)\n", typeid(algorithm_type).name()); printf("-----------------------------------------------------------\n\n"); test::StopWatch sw; int sum, index_of; pattern_type pattern; pattern.prepare("example"); sum = 0; sw.start(); for (size_t i = 0; i < Iterations; ++i) { index_of = pattern.match("Here is a sample example."); sum += index_of; } sw.stop(); pattern.display_test(index_of, sum, sw.getElapsedMillisec()); pattern_type pattern1(pattern_text_1); //pattern1.prepare(pattern_text_1); sum = 0; sw.start(); for (size_t i = 0; i < Iterations; ++i) { index_of = pattern1.match("Here is a sample example."); sum += index_of; } sw.stop(); pattern1.display_test(index_of, sum, sw.getElapsedMillisec()); pattern_type pattern2(pattern_text_2); //pattern2.prepare(pattern_text_2); sum = 0; sw.start(); for (size_t i = 0; i < Iterations; ++i) { index_of = pattern2.match("Here is a sample example."); sum += index_of; } sw.stop(); pattern2.display_test(index_of, sum, sw.getElapsedMillisec()); } template <typename algorithm_type> void StringMatch_benchmark() { typedef algorithm_type::Pattern pattern_type; test::StopWatch sw; int sum; static const size_t iters = Iterations / (sm_countof(szSearchText) * sm_countof(szPatterns)); printf("-----------------------------------------------------------\n"); printf(" Benchmark: %s)\n", typeid(algorithm_type).name()); printf("-----------------------------------------------------------\n\n"); pattern_type pattern[sm_countof(szPatterns)]; for (int i = 0; i < sm_countof(szPatterns); ++i) { pattern[i].prepare(szPatterns[i]); } StringRef search_text[sm_countof(szSearchText)]; for (int i = 0; i < sm_countof(szSearchText); ++i) { search_text[i].set_ref(szSearchText[i], strlen(szSearchText[i])); } sum = 0; sw.start(); for (size_t loop = 0; loop < iters; ++loop) { for (int i = 0; i < sm_countof(szSearchText); ++i) { for (int j = 0; j < sm_countof(szPatterns); ++j) { int index_of = pattern[j].match(search_text[i]); sum += index_of; } } } sw.stop(); printf("sum: %12d, time spent: %0.3f ms\n\n", sum, sw.getElapsedMillisec()); } int main(int argc, char * argv[]) { StringMatch_examples(); StringMatch_test<AnsiString::Kmp>(); StringMatch_test<AnsiString::BoyerMoore>(); StringMatch_benchmark<AnsiString::Kmp>(); StringMatch_benchmark<AnsiString::BoyerMoore>(); ::system("pause"); return 0; } <|endoftext|>
<commit_before>/*- * Copyright (C) 2008-2009 by Maxim Ignatenko * gelraen.ua@gmail.com * * All rights reserved. * * * * Redistribution and use in source and binary forms, with or without * * modification, are permitted provided that the following conditions * * are met: * * * Redistributions of source code must retain the above copyright * * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * * notice, this list of conditions and the following disclaimer in * * the documentation and/or other materials provided with the * * distribution. * * * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * * 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. * * * $Id$ */ #include "defs.h" #include <iostream> #include <translator.h> #include <config.h> #include <dcclient.h> #include <ircclient.h> #include <sys/select.h> #include <unistd.h> #include <fcntl.h> #include "../config.h" #include <cstdlib> #include <cstdio> #include <fstream> #include <sys/stat.h> using namespace std; void usage(); void version(); bool writepid(const string& pidfile); int main(int argc,char *argv[]) { Config conf; Translator trans; IRCClient irc; DCClient dc; string conffile=CONFFILE; string pidfile; bool daemonize=true; string logfile; int loglevel; bool bloglevel=false; // specified in command line? if (argc==1) { usage(); return 0; } char ch; while((ch = getopt(argc, argv, "dc:l:L:p:h")) != -1) { switch (ch) { case 'd': daemonize=false; break; case 'c': conffile=optarg; break; case 'l': logfile=optarg; break; case 'L': bloglevel=true; loglevel=(int)strtol(optarg, (char **)NULL, 10); break; case 'p': pidfile=optarg; break; case 'h': case '?': default: usage(); return(0); } } if (!conf.ReadFromFile(conffile)) { LOG(log::error, "Failed to load config. Exiting", true); return 1; } LogLevel= bloglevel ? loglevel : conf.m_loglevel; if (!logfile.empty()) { conf.m_sLogFile=logfile; } if (!pidfile.empty()) { conf.m_pidfile=pidfile; } if (daemonize) { if (daemon(1,0)==-1) // close fd's 0-2 { LOG(log::error, "daemon() failed, exiting", true); return 1; } if (!initlog(conf.m_bSyslog,conf.m_sLogFile)) { LOG(log::error,"Unable to initalize logging"); } } if (!conf.m_pidfile.empty()&&!writepid(conf.m_pidfile)) { LOG(log::error,"Unable to write pidfile", true); } if (!irc.setConfig(conf)) { LOG(log::error,"Incorrect config for IRC", true); return 1; } if (!dc.setConfig(conf)) { LOG(log::error,"Incorrect config for DC++", true); return 1; } string str; LOG(log::notice,"Connecting to IRC... "); if (!irc.Connect()) { LOG(log::error,"ERROR"); return 2; } else LOG(log::notice,"OK"); LOG(log::notice,"Connecting to DC++... "); if (!dc.Connect()) { LOG(log::error,"ERROR"); return 2; } else LOG(log::notice,"OK"); // now recreate config, cause DC hub may change our nickname conf=Config(irc.getConfig(),dc.getConfig(),conf); if (!trans.setConfig(conf)) { LOG(log::error,"Incorrect config for Translator"); return 1; } fd_set rset; int max=0,t; for(;;) { // recreate rset FD_ZERO(&rset); t=irc.FdSet(rset); max=(t>max)?t:max; t=dc.FdSet(rset); max=(t>max)?t:max; select(max+1,&rset,NULL,NULL,NULL); while(irc.readCommand(str)) { if (trans.IRCtoDC(str,str)) { dc.writeCommand(str); } } if (!dc.isLoggedIn()) { LOG(log::warning, "DC++ connection closed. Trying to reconnect..."); dc.Connect(); } while(dc.readCommand(str)) { if (trans.DCtoIRC(str,str)) { irc.writeCommand(str); } } if (!irc.isLoggedIn()) { LOG(log::warning,"IRC connection closed. Trying to reconnect..."); irc.Connect(); } } return 0; } void usage() { version(); cout << endl; cout << "Options:" << endl; cout << " -h - show this help message" << endl; cout << " -c file - specify path to config file" << endl; cout << " -l file - override path to logfile specified in config" << endl; cout << " -L num - override loglevel" << endl; cout << " -p file - override path to pidfile specified in config" << endl; cout << " -d - do not go in background, all logging goes to stderr" << endl; cout << endl; } void version() { cout << PACKAGE << " " << VERSION << endl; } bool writepid(const string& pidfile) { ofstream pid(pidfile.c_str()); if (pid.bad()) return false; pid << getpid() << endl; return true; } <commit_msg>Start normally if no parameters given at command line<commit_after>/*- * Copyright (C) 2008-2009 by Maxim Ignatenko * gelraen.ua@gmail.com * * All rights reserved. * * * * Redistribution and use in source and binary forms, with or without * * modification, are permitted provided that the following conditions * * are met: * * * Redistributions of source code must retain the above copyright * * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * * notice, this list of conditions and the following disclaimer in * * the documentation and/or other materials provided with the * * distribution. * * * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * * 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. * * * $Id$ */ #include "defs.h" #include <iostream> #include <translator.h> #include <config.h> #include <dcclient.h> #include <ircclient.h> #include <sys/select.h> #include <unistd.h> #include <fcntl.h> #include "../config.h" #include <cstdlib> #include <cstdio> #include <fstream> #include <sys/stat.h> using namespace std; void usage(); void version(); bool writepid(const string& pidfile); int main(int argc,char *argv[]) { Config conf; Translator trans; IRCClient irc; DCClient dc; string conffile=CONFFILE; string pidfile; bool daemonize=true; string logfile; int loglevel; bool bloglevel=false; // specified in command line? char ch; while((ch = getopt(argc, argv, "dc:l:L:p:h")) != -1) { switch (ch) { case 'd': daemonize=false; break; case 'c': conffile=optarg; break; case 'l': logfile=optarg; break; case 'L': bloglevel=true; loglevel=(int)strtol(optarg, (char **)NULL, 10); break; case 'p': pidfile=optarg; break; case 'h': case '?': default: usage(); return(0); } } if (!conf.ReadFromFile(conffile)) { LOG(log::error, "Failed to load config. Exiting", true); return 1; } LogLevel= bloglevel ? loglevel : conf.m_loglevel; if (!logfile.empty()) { conf.m_sLogFile=logfile; } if (!pidfile.empty()) { conf.m_pidfile=pidfile; } if (daemonize) { if (daemon(1,0)==-1) // close fd's 0-2 { LOG(log::error, "daemon() failed, exiting", true); return 1; } if (!initlog(conf.m_bSyslog,conf.m_sLogFile)) { LOG(log::error,"Unable to initalize logging"); } } if (!conf.m_pidfile.empty()&&!writepid(conf.m_pidfile)) { LOG(log::error,"Unable to write pidfile", true); } if (!irc.setConfig(conf)) { LOG(log::error,"Incorrect config for IRC", true); return 1; } if (!dc.setConfig(conf)) { LOG(log::error,"Incorrect config for DC++", true); return 1; } string str; LOG(log::notice,"Connecting to IRC... "); if (!irc.Connect()) { LOG(log::error,"ERROR"); return 2; } else LOG(log::notice,"OK"); LOG(log::notice,"Connecting to DC++... "); if (!dc.Connect()) { LOG(log::error,"ERROR"); return 2; } else LOG(log::notice,"OK"); // now recreate config, cause DC hub may change our nickname conf=Config(irc.getConfig(),dc.getConfig(),conf); if (!trans.setConfig(conf)) { LOG(log::error,"Incorrect config for Translator"); return 1; } fd_set rset; int max=0,t; for(;;) { // recreate rset FD_ZERO(&rset); t=irc.FdSet(rset); max=(t>max)?t:max; t=dc.FdSet(rset); max=(t>max)?t:max; select(max+1,&rset,NULL,NULL,NULL); while(irc.readCommand(str)) { if (trans.IRCtoDC(str,str)) { dc.writeCommand(str); } } if (!dc.isLoggedIn()) { LOG(log::warning, "DC++ connection closed. Trying to reconnect..."); dc.Connect(); } while(dc.readCommand(str)) { if (trans.DCtoIRC(str,str)) { irc.writeCommand(str); } } if (!irc.isLoggedIn()) { LOG(log::warning,"IRC connection closed. Trying to reconnect..."); irc.Connect(); } } return 0; } void usage() { version(); cout << endl; cout << "Options:" << endl; cout << " -h - show this help message" << endl; cout << " -c file - specify path to config file" << endl; cout << " -l file - override path to logfile specified in config" << endl; cout << " -L num - override loglevel" << endl; cout << " -p file - override path to pidfile specified in config" << endl; cout << " -d - do not go in background, all logging goes to stderr" << endl; cout << endl; } void version() { cout << PACKAGE << " " << VERSION << endl; } bool writepid(const string& pidfile) { ofstream pid(pidfile.c_str()); if (pid.bad()) return false; pid << getpid() << endl; return true; } <|endoftext|>
<commit_before>#include <memory> #include <iostream> #include <string> #include <sstream> #include <functional> #include <utility> #include <unordered_map> #include <vector> #include <nan.h> #include <v8.h> #include <uv.h> #include "log.h" #include "queue.h" #include "status.h" #include "result.h" #include "worker/worker_thread.h" using v8::Local; using v8::Value; using v8::Object; using v8::String; using v8::Number; using v8::Uint32; using v8::Function; using v8::FunctionTemplate; using v8::Array; using std::shared_ptr; using std::unique_ptr; using std::string; using std::ostringstream; using std::endl; using std::unordered_map; using std::vector; using std::move; using std::make_pair; static void handle_events_helper(uv_async_t *handle); class Main { public: Main() : worker_thread{&event_handler} { int err; next_command_id = 0; next_channel_id = NULL_CHANNEL_ID + 1; err = uv_async_init(uv_default_loop(), &event_handler, handle_events_helper); if (err) return; worker_thread.run(); } Result<> send_worker_command( const CommandAction action, const std::string &&root, unique_ptr<Nan::Callback> callback, ChannelID channel_id = NULL_CHANNEL_ID ) { CommandID command_id = next_command_id; CommandPayload command_payload(next_command_id, action, move(root), channel_id); Message command_message(move(command_payload)); pending_callbacks.emplace(command_id, move(callback)); next_command_id++; LOGGER << "Sending command " << command_message << " to worker thread." << endl; return worker_thread.send(move(command_message)); } void use_main_log_file(string &&main_log_file) { Logger::to_file(main_log_file.c_str()); } Result<> use_worker_log_file(string &&worker_log_file, unique_ptr<Nan::Callback> callback) { return send_worker_command(COMMAND_LOG_FILE, move(worker_log_file), move(callback)); } Result<> watch(string &&root, unique_ptr<Nan::Callback> ack_callback, unique_ptr<Nan::Callback> event_callback) { ChannelID channel_id = next_channel_id; next_channel_id++; channel_callbacks.emplace(channel_id, move(event_callback)); return send_worker_command(COMMAND_ADD, move(root), move(ack_callback), channel_id); } Result<> unwatch(ChannelID channel_id, unique_ptr<Nan::Callback> ack_callback) { string root; Result<> r = send_worker_command(COMMAND_REMOVE, move(root), move(ack_callback), channel_id); auto maybe_event_callback = channel_callbacks.find(channel_id); if (maybe_event_callback == channel_callbacks.end()) { LOGGER << "Channel " << channel_id << " already has no event callback." << endl; return ok_result(); } channel_callbacks.erase(maybe_event_callback); return r; } void handle_events() { Nan::HandleScope scope; Result< unique_ptr<vector<Message>> > rr = worker_thread.receive_all(); if (rr.is_error()) { LOGGER << "Unable to receive messages from the worker thread: " << rr << "." << endl; return; } unique_ptr<vector<Message>> &accepted = rr.get_value(); if (!accepted) { // No events to process. return; } unordered_map<ChannelID, vector<Local<Object>>> to_deliver; for (auto it = accepted->begin(); it != accepted->end(); ++it) { const AckPayload *ack_message = it->as_ack(); if (ack_message) { LOGGER << "Received ack message " << *it << "." << endl; auto maybe_callback = pending_callbacks.find(ack_message->get_key()); if (maybe_callback == pending_callbacks.end()) { LOGGER << "Ignoring unexpected ack " << *it << "." << endl; continue; } unique_ptr<Nan::Callback> callback = move(maybe_callback->second); pending_callbacks.erase(maybe_callback); ChannelID channel_id = ack_message->get_channel_id(); if (channel_id != NULL_CHANNEL_ID) { if (ack_message->was_successful()) { Local<Value> argv[] = {Nan::Null(), Nan::New<Number>(channel_id)}; callback->Call(2, argv); } else { Local<Value> err = Nan::Error(ack_message->get_message().c_str()); Local<Value> argv[] = {err, Nan::Null()}; callback->Call(2, argv); } } else { callback->Call(0, nullptr); } continue; } const FileSystemPayload *filesystem_message = it->as_filesystem(); if (filesystem_message) { LOGGER << "Received filesystem event message " << *it << "." << endl; ChannelID channel_id = filesystem_message->get_channel_id(); Local<Object> js_event = Nan::New<Object>(); js_event->Set( Nan::New<String>("actionType").ToLocalChecked(), Nan::New<Number>(static_cast<int>(filesystem_message->get_filesystem_action())) ); js_event->Set( Nan::New<String>("entryKind").ToLocalChecked(), Nan::New<Number>(static_cast<int>(filesystem_message->get_entry_kind())) ); js_event->Set( Nan::New<String>("oldPath").ToLocalChecked(), Nan::New<String>(filesystem_message->get_old_path()).ToLocalChecked() ); js_event->Set( Nan::New<String>("newPath").ToLocalChecked(), Nan::New<String>(filesystem_message->get_new_path()).ToLocalChecked() ); to_deliver[channel_id].push_back(js_event); continue; } LOGGER << "Received unexpected message " << *it << "." << endl; } for (auto it = to_deliver.begin(); it != to_deliver.end(); ++it) { ChannelID channel_id = it->first; vector<Local<Object>> js_events = it->second; auto maybe_callback = channel_callbacks.find(channel_id); if (maybe_callback == channel_callbacks.end()) { LOGGER << "Ignoring unexpected filesystem event channel " << channel_id << "." << endl; continue; } shared_ptr<Nan::Callback> callback = maybe_callback->second; LOGGER << "Dispatching " << js_events.size() << " event(s) on channel " << channel_id << " to node callbacks." << endl; Local<Array> js_array = Nan::New<Array>(js_events.size()); int index = 0; for (auto et = js_events.begin(); et != js_events.end(); ++et) { js_array->Set(index, *et); index++; } Local<Value> argv[] = { Nan::Null(), js_array }; callback->Call(2, argv); } } void collect_status(Status &status) { status.pending_callback_count = pending_callbacks.size(); status.channel_callback_count = channel_callbacks.size(); worker_thread.collect_status(status); } private: uv_async_t event_handler; WorkerThread worker_thread; CommandID next_command_id; ChannelID next_channel_id; unordered_map<CommandID, unique_ptr<Nan::Callback>> pending_callbacks; unordered_map<ChannelID, shared_ptr<Nan::Callback>> channel_callbacks; }; static Main instance; static void handle_events_helper(uv_async_t *handle) { instance.handle_events(); } static bool get_string_option(Local<Object>& options, const char *key_name, string &out) { Nan::HandleScope scope; const Local<String> key = Nan::New<String>(key_name).ToLocalChecked(); Nan::MaybeLocal<Value> as_maybe_value = Nan::Get(options, key); if (as_maybe_value.IsEmpty()) { return true; } Local<Value> as_value = as_maybe_value.ToLocalChecked(); if (as_value->IsUndefined()) { return true; } if (!as_value->IsString()) { ostringstream message; message << "configure() option " << key_name << " must be a String"; Nan::ThrowError(message.str().c_str()); return false; } Nan::Utf8String as_string(as_value); if (*as_string == nullptr) { ostringstream message; message << "configure() option " << key_name << " must be a valid UTF-8 String"; Nan::ThrowError(message.str().c_str()); return false; } out.assign(*as_string, as_string.length()); return true; } void configure(const Nan::FunctionCallbackInfo<Value> &info) { string main_log_file; string worker_log_file; bool async = false; Nan::MaybeLocal<Object> maybe_options = Nan::To<Object>(info[0]); if (maybe_options.IsEmpty()) { Nan::ThrowError("configure() requires an option object"); return; } Local<Object> options = maybe_options.ToLocalChecked(); if (!get_string_option(options, "mainLogFile", main_log_file)) return; if (!get_string_option(options, "workerLogFile", worker_log_file)) return; unique_ptr<Nan::Callback> callback(new Nan::Callback(info[1].As<Function>())); if (!main_log_file.empty()) { instance.use_main_log_file(move(main_log_file)); } if (!worker_log_file.empty()) { Result<> r = instance.use_worker_log_file(move(worker_log_file), move(callback)); if (r.is_error()) { Nan::ThrowError(r.get_error().c_str()); return; } async = true; } if (!async) { callback->Call(0, 0); } } void watch(const Nan::FunctionCallbackInfo<Value> &info) { if (info.Length() != 3) { return Nan::ThrowError("watch() requires three arguments"); } Nan::MaybeLocal<String> maybe_root = Nan::To<String>(info[0]); if (maybe_root.IsEmpty()) { Nan::ThrowError("watch() requires a string as argument one"); return; } Local<String> root_v8_string = maybe_root.ToLocalChecked(); Nan::Utf8String root_utf8(root_v8_string); if (*root_utf8 == nullptr) { Nan::ThrowError("watch() argument one must be a valid UTF-8 string"); return; } string root_str(*root_utf8, root_utf8.length()); unique_ptr<Nan::Callback> ack_callback(new Nan::Callback(info[1].As<Function>())); unique_ptr<Nan::Callback> event_callback(new Nan::Callback(info[2].As<Function>())); Result<> r = instance.watch(move(root_str), move(ack_callback), move(event_callback)); if (r.is_error()) { Nan::ThrowError(r.get_error().c_str()); } } void unwatch(const Nan::FunctionCallbackInfo<Value> &info) { if (info.Length() != 2) { Nan::ThrowError("watch() requires two arguments"); return; } Nan::Maybe<uint32_t> maybe_channel_id = Nan::To<uint32_t>(info[0]); if (maybe_channel_id.IsNothing()) { Nan::ThrowError("unwatch() requires a channel ID as its first argument"); return; } ChannelID channel_id = static_cast<ChannelID>(maybe_channel_id.FromJust()); unique_ptr<Nan::Callback> ack_callback(new Nan::Callback(info[1].As<Function>())); Result<> r = instance.unwatch(channel_id, move(ack_callback)); if (r.is_error()) { Nan::ThrowError(r.get_error().c_str()); } } void status(const Nan::FunctionCallbackInfo<Value> &info) { Status status; instance.collect_status(status); Local<Object> status_object = Nan::New<Object>(); Nan::Set( status_object, Nan::New<String>("pendingCallbackCount").ToLocalChecked(), Nan::New<Uint32>(static_cast<uint32_t>(status.pending_callback_count)) ); Nan::Set( status_object, Nan::New<String>("channelCallbackCount").ToLocalChecked(), Nan::New<Uint32>(static_cast<uint32_t>(status.channel_callback_count)) ); Nan::Set( status_object, Nan::New<String>("workerThreadOk").ToLocalChecked(), Nan::New<String>(status.worker_thread_ok).ToLocalChecked() ); Nan::Set( status_object, Nan::New<String>("workerInSize").ToLocalChecked(), Nan::New<Uint32>(static_cast<uint32_t>(status.worker_in_size)) ); Nan::Set( status_object, Nan::New<String>("workerInOk").ToLocalChecked(), Nan::New<String>(status.worker_in_ok).ToLocalChecked() ); Nan::Set( status_object, Nan::New<String>("workerOutSize").ToLocalChecked(), Nan::New<Uint32>(static_cast<uint32_t>(status.worker_out_size)) ); Nan::Set( status_object, Nan::New<String>("workerOutOk").ToLocalChecked(), Nan::New<String>(status.worker_out_ok).ToLocalChecked() ); info.GetReturnValue().Set(status_object); } void initialize(Local<Object> exports) { Nan::Set( exports, Nan::New<String>("configure").ToLocalChecked(), Nan::GetFunction(Nan::New<FunctionTemplate>(configure)).ToLocalChecked() ); Nan::Set( exports, Nan::New<String>("watch").ToLocalChecked(), Nan::GetFunction(Nan::New<FunctionTemplate>(watch)).ToLocalChecked() ); Nan::Set( exports, Nan::New<String>("unwatch").ToLocalChecked(), Nan::GetFunction(Nan::New<FunctionTemplate>(unwatch)).ToLocalChecked() ); Nan::Set( exports, Nan::New<String>("status").ToLocalChecked(), Nan::GetFunction(Nan::New<FunctionTemplate>(status)).ToLocalChecked() ); } NODE_MODULE(watcher, initialize); <commit_msg>Disable main and worker logs<commit_after>#include <memory> #include <iostream> #include <string> #include <sstream> #include <functional> #include <utility> #include <unordered_map> #include <vector> #include <nan.h> #include <v8.h> #include <uv.h> #include "log.h" #include "queue.h" #include "status.h" #include "result.h" #include "worker/worker_thread.h" using v8::Local; using v8::Value; using v8::Object; using v8::String; using v8::Number; using v8::Uint32; using v8::Function; using v8::FunctionTemplate; using v8::Array; using std::shared_ptr; using std::unique_ptr; using std::string; using std::ostringstream; using std::endl; using std::unordered_map; using std::vector; using std::move; using std::make_pair; static void handle_events_helper(uv_async_t *handle); class Main { public: Main() : worker_thread{&event_handler} { int err; next_command_id = 0; next_channel_id = NULL_CHANNEL_ID + 1; err = uv_async_init(uv_default_loop(), &event_handler, handle_events_helper); if (err) return; worker_thread.run(); } Result<> send_worker_command( const CommandAction action, const std::string &&root, unique_ptr<Nan::Callback> callback, ChannelID channel_id = NULL_CHANNEL_ID ) { CommandID command_id = next_command_id; CommandPayload command_payload(next_command_id, action, move(root), channel_id); Message command_message(move(command_payload)); pending_callbacks.emplace(command_id, move(callback)); next_command_id++; LOGGER << "Sending command " << command_message << " to worker thread." << endl; return worker_thread.send(move(command_message)); } void use_main_log_file(string &&main_log_file) { Logger::to_file(main_log_file.c_str()); } void disable_main_log() { Logger::disable(); } Result<> use_worker_log_file(string &&worker_log_file, unique_ptr<Nan::Callback> callback) { return send_worker_command(COMMAND_LOG_FILE, move(worker_log_file), move(callback)); } Result<> disable_worker_log(unique_ptr<Nan::Callback> callback) { return send_worker_command(COMMAND_LOG_DISABLE, "", move(callback)); } Result<> watch(string &&root, unique_ptr<Nan::Callback> ack_callback, unique_ptr<Nan::Callback> event_callback) { ChannelID channel_id = next_channel_id; next_channel_id++; channel_callbacks.emplace(channel_id, move(event_callback)); return send_worker_command(COMMAND_ADD, move(root), move(ack_callback), channel_id); } Result<> unwatch(ChannelID channel_id, unique_ptr<Nan::Callback> ack_callback) { string root; Result<> r = send_worker_command(COMMAND_REMOVE, move(root), move(ack_callback), channel_id); auto maybe_event_callback = channel_callbacks.find(channel_id); if (maybe_event_callback == channel_callbacks.end()) { LOGGER << "Channel " << channel_id << " already has no event callback." << endl; return ok_result(); } channel_callbacks.erase(maybe_event_callback); return r; } void handle_events() { Nan::HandleScope scope; Result< unique_ptr<vector<Message>> > rr = worker_thread.receive_all(); if (rr.is_error()) { LOGGER << "Unable to receive messages from the worker thread: " << rr << "." << endl; return; } unique_ptr<vector<Message>> &accepted = rr.get_value(); if (!accepted) { // No events to process. return; } unordered_map<ChannelID, vector<Local<Object>>> to_deliver; for (auto it = accepted->begin(); it != accepted->end(); ++it) { const AckPayload *ack_message = it->as_ack(); if (ack_message) { LOGGER << "Received ack message " << *it << "." << endl; auto maybe_callback = pending_callbacks.find(ack_message->get_key()); if (maybe_callback == pending_callbacks.end()) { LOGGER << "Ignoring unexpected ack " << *it << "." << endl; continue; } unique_ptr<Nan::Callback> callback = move(maybe_callback->second); pending_callbacks.erase(maybe_callback); ChannelID channel_id = ack_message->get_channel_id(); if (channel_id != NULL_CHANNEL_ID) { if (ack_message->was_successful()) { Local<Value> argv[] = {Nan::Null(), Nan::New<Number>(channel_id)}; callback->Call(2, argv); } else { Local<Value> err = Nan::Error(ack_message->get_message().c_str()); Local<Value> argv[] = {err, Nan::Null()}; callback->Call(2, argv); } } else { callback->Call(0, nullptr); } continue; } const FileSystemPayload *filesystem_message = it->as_filesystem(); if (filesystem_message) { LOGGER << "Received filesystem event message " << *it << "." << endl; ChannelID channel_id = filesystem_message->get_channel_id(); Local<Object> js_event = Nan::New<Object>(); js_event->Set( Nan::New<String>("actionType").ToLocalChecked(), Nan::New<Number>(static_cast<int>(filesystem_message->get_filesystem_action())) ); js_event->Set( Nan::New<String>("entryKind").ToLocalChecked(), Nan::New<Number>(static_cast<int>(filesystem_message->get_entry_kind())) ); js_event->Set( Nan::New<String>("oldPath").ToLocalChecked(), Nan::New<String>(filesystem_message->get_old_path()).ToLocalChecked() ); js_event->Set( Nan::New<String>("newPath").ToLocalChecked(), Nan::New<String>(filesystem_message->get_new_path()).ToLocalChecked() ); to_deliver[channel_id].push_back(js_event); continue; } LOGGER << "Received unexpected message " << *it << "." << endl; } for (auto it = to_deliver.begin(); it != to_deliver.end(); ++it) { ChannelID channel_id = it->first; vector<Local<Object>> js_events = it->second; auto maybe_callback = channel_callbacks.find(channel_id); if (maybe_callback == channel_callbacks.end()) { LOGGER << "Ignoring unexpected filesystem event channel " << channel_id << "." << endl; continue; } shared_ptr<Nan::Callback> callback = maybe_callback->second; LOGGER << "Dispatching " << js_events.size() << " event(s) on channel " << channel_id << " to node callbacks." << endl; Local<Array> js_array = Nan::New<Array>(js_events.size()); int index = 0; for (auto et = js_events.begin(); et != js_events.end(); ++et) { js_array->Set(index, *et); index++; } Local<Value> argv[] = { Nan::Null(), js_array }; callback->Call(2, argv); } } void collect_status(Status &status) { status.pending_callback_count = pending_callbacks.size(); status.channel_callback_count = channel_callbacks.size(); worker_thread.collect_status(status); } private: uv_async_t event_handler; WorkerThread worker_thread; CommandID next_command_id; ChannelID next_channel_id; unordered_map<CommandID, unique_ptr<Nan::Callback>> pending_callbacks; unordered_map<ChannelID, shared_ptr<Nan::Callback>> channel_callbacks; }; static Main instance; static void handle_events_helper(uv_async_t *handle) { instance.handle_events(); } static bool get_string_option(Local<Object>& options, const char *key_name, string &out) { Nan::HandleScope scope; const Local<String> key = Nan::New<String>(key_name).ToLocalChecked(); Nan::MaybeLocal<Value> as_maybe_value = Nan::Get(options, key); if (as_maybe_value.IsEmpty()) { return true; } Local<Value> as_value = as_maybe_value.ToLocalChecked(); if (as_value->IsUndefined()) { return true; } if (!as_value->IsString()) { ostringstream message; message << "configure() option " << key_name << " must be a String"; Nan::ThrowError(message.str().c_str()); return false; } Nan::Utf8String as_string(as_value); if (*as_string == nullptr) { ostringstream message; message << "configure() option " << key_name << " must be a valid UTF-8 String"; Nan::ThrowError(message.str().c_str()); return false; } out.assign(*as_string, as_string.length()); return true; } void configure(const Nan::FunctionCallbackInfo<Value> &info) { string main_log_file; string worker_log_file; bool async = false; Nan::MaybeLocal<Object> maybe_options = Nan::To<Object>(info[0]); if (maybe_options.IsEmpty()) { Nan::ThrowError("configure() requires an option object"); return; } Local<Object> options = maybe_options.ToLocalChecked(); if (!get_string_option(options, "mainLogFile", main_log_file)) return; if (!get_string_option(options, "workerLogFile", worker_log_file)) return; unique_ptr<Nan::Callback> callback(new Nan::Callback(info[1].As<Function>())); if (!main_log_file.empty()) { instance.use_main_log_file(move(main_log_file)); } if (!worker_log_file.empty()) { Result<> r = instance.use_worker_log_file(move(worker_log_file), move(callback)); if (r.is_error()) { Nan::ThrowError(r.get_error().c_str()); return; } async = true; } if (!async) { callback->Call(0, 0); } } void watch(const Nan::FunctionCallbackInfo<Value> &info) { if (info.Length() != 3) { return Nan::ThrowError("watch() requires three arguments"); } Nan::MaybeLocal<String> maybe_root = Nan::To<String>(info[0]); if (maybe_root.IsEmpty()) { Nan::ThrowError("watch() requires a string as argument one"); return; } Local<String> root_v8_string = maybe_root.ToLocalChecked(); Nan::Utf8String root_utf8(root_v8_string); if (*root_utf8 == nullptr) { Nan::ThrowError("watch() argument one must be a valid UTF-8 string"); return; } string root_str(*root_utf8, root_utf8.length()); unique_ptr<Nan::Callback> ack_callback(new Nan::Callback(info[1].As<Function>())); unique_ptr<Nan::Callback> event_callback(new Nan::Callback(info[2].As<Function>())); Result<> r = instance.watch(move(root_str), move(ack_callback), move(event_callback)); if (r.is_error()) { Nan::ThrowError(r.get_error().c_str()); } } void unwatch(const Nan::FunctionCallbackInfo<Value> &info) { if (info.Length() != 2) { Nan::ThrowError("watch() requires two arguments"); return; } Nan::Maybe<uint32_t> maybe_channel_id = Nan::To<uint32_t>(info[0]); if (maybe_channel_id.IsNothing()) { Nan::ThrowError("unwatch() requires a channel ID as its first argument"); return; } ChannelID channel_id = static_cast<ChannelID>(maybe_channel_id.FromJust()); unique_ptr<Nan::Callback> ack_callback(new Nan::Callback(info[1].As<Function>())); Result<> r = instance.unwatch(channel_id, move(ack_callback)); if (r.is_error()) { Nan::ThrowError(r.get_error().c_str()); } } void status(const Nan::FunctionCallbackInfo<Value> &info) { Status status; instance.collect_status(status); Local<Object> status_object = Nan::New<Object>(); Nan::Set( status_object, Nan::New<String>("pendingCallbackCount").ToLocalChecked(), Nan::New<Uint32>(static_cast<uint32_t>(status.pending_callback_count)) ); Nan::Set( status_object, Nan::New<String>("channelCallbackCount").ToLocalChecked(), Nan::New<Uint32>(static_cast<uint32_t>(status.channel_callback_count)) ); Nan::Set( status_object, Nan::New<String>("workerThreadOk").ToLocalChecked(), Nan::New<String>(status.worker_thread_ok).ToLocalChecked() ); Nan::Set( status_object, Nan::New<String>("workerInSize").ToLocalChecked(), Nan::New<Uint32>(static_cast<uint32_t>(status.worker_in_size)) ); Nan::Set( status_object, Nan::New<String>("workerInOk").ToLocalChecked(), Nan::New<String>(status.worker_in_ok).ToLocalChecked() ); Nan::Set( status_object, Nan::New<String>("workerOutSize").ToLocalChecked(), Nan::New<Uint32>(static_cast<uint32_t>(status.worker_out_size)) ); Nan::Set( status_object, Nan::New<String>("workerOutOk").ToLocalChecked(), Nan::New<String>(status.worker_out_ok).ToLocalChecked() ); info.GetReturnValue().Set(status_object); } void initialize(Local<Object> exports) { Nan::Set( exports, Nan::New<String>("configure").ToLocalChecked(), Nan::GetFunction(Nan::New<FunctionTemplate>(configure)).ToLocalChecked() ); Nan::Set( exports, Nan::New<String>("watch").ToLocalChecked(), Nan::GetFunction(Nan::New<FunctionTemplate>(watch)).ToLocalChecked() ); Nan::Set( exports, Nan::New<String>("unwatch").ToLocalChecked(), Nan::GetFunction(Nan::New<FunctionTemplate>(unwatch)).ToLocalChecked() ); Nan::Set( exports, Nan::New<String>("status").ToLocalChecked(), Nan::GetFunction(Nan::New<FunctionTemplate>(status)).ToLocalChecked() ); } NODE_MODULE(watcher, initialize); <|endoftext|>
<commit_before>#include <iostream> #include <string> #include <vector> #include <map> #include <set> #include <iomanip> #include <fstream> #include <sstream> #include <stdlib.h> #include <float.h> #include "parameters.h" #include "interval.h" #include "distt.h" #include "structure.h" #include "read.h" #include "partition.h" #include "LBP.h" #include "ploidy.h" #include <boost/program_options.hpp> // //Infering the CNV profile under SV graphical model //Loopy Belief Propagation //Do the phasing for both SNP and SV // // //ALL RIGHTS RESEARVED YANGLI9@ILLINOIS.EDU // // //#define THRESHHOLD 40 using namespace std; namespace po = boost::program_options; map<string, map<int, int> > isolatedSNP; map<string, map<int, string> > SNP_LINK; map<string, map<int, double> > SNP_1000G; vector<observe> ALL_SNP; map<string, map<interval, string> >LIST, SV_LIST, LONE; vector<string> chr_vec; //store chr name with sorted chr size, handle large chr fist! map<string, int> RANGE_b, RANGE_e; // store the genome size information vector<int> REF_ALT_FLAG; // if the higher coverage is from reference or alt allele map<string, map<int, CA> > SV_list; map<string, map<int, int> > SV_list_link; // chr->pos->region_id map<string, map<int, int> > SV_list_CNV; map<CA, CA> LINK; // Linking SVs map<CA, int> SV_region_id; map<string, vector<site> > JOB_LIST;// storing segments map<string, map<interval, region_numbers> > regionCov; // coverage of each region set<site>SV_FLAG_L, SV_FLAG_R, LO_L, LO_R; // the orientation of SV. L stands for -; R stands for + map<site, map<hidden_state, double> > prob_matrix_1, prob_matrix_2;// inward_maxtrix, _prob_matrix_2, _prob_matrix_1; map<string, vector<interval> >Linear_region;// group of JOB_LIST map<string, vector<Linear_region_info> >Linear_region_info_vec; string version = "0.21"; string BIN; string SVfile, SNPfile, GAPfile;//(argv[1]); ifstream input_snp_link;//(argv[4]); ifstream input5;//(argv[5]); int sys_flag; // = atoi(argv[9]); double BB; int thread;// number of threads string MODE;// RUN mode static int usage(){ cout << "Program: Weaver Version \t" << version << endl; cout << "ALL\tPLOIDY\tLITE\n"; } int main_lite(); int main_ploidy(); int main_opt(int argc, char *argv[]){ po::options_description generic("Weaver options"); generic.add_options() ("VERSION,V", "print version string") ("FASTA,f", po::value<string>(), "[MANDATORY] reference fasta file") ("1KG,k", po::value<string>(), "1000G phase 1 haplotype file") ("THREAD,p", po::value<int>(), "[DEFAULT 1] number of threads") ("SNP,s", po::value<string>(), "[MANDATORY] SNP") ("SV,S", po::value<string>(), "[MANDATORY] SV") ("WIG,w", po::value<string>(), "[MANDATORY] WIG") ("GAP,g", po::value<string>(), "[DEFAULT Weaver/data/] GAP") ("MAP,m", po::value<string>(), "[DEFAULT Weaver/data/] Mappability") ("SNPLINK,l", po::value<string>(), "SNP LINK") ("SNPLINK1KG,L", po::value<string>(), "SNP LINK 1KG") ("NORMAL,n", po::value<double>(), "normal") ("TUMOR,t", po::value<double>(), "tumor") ("RUNFLAG,r", po::value<int>(), "[MANDATORY] run flag 1: from start; 0: region files already there") ("help,h", "print help message") ; if(argc <= 1){ cout << generic << "\n"; exit(0); } po::variables_map vm;// po::store(po::command_line_parser(argc, argv).options(generic).allow_unregistered().run(), vm); po::notify(vm); Normal_cov_limit = 2; if (vm.count("help")) { cout << generic << "\n"; return 1; } if (vm.count("THREAD")) { cout << "THREAD was set to " << vm["THREAD"].as<int>() << ".\n"; thread = vm["THREAD"].as<int>(); } else{ cout << "THREAD = 8\n"; thread = 8; } if (vm.count("FASTA")) { cout << "FASTA was set to " << vm["FASTA"].as<string>() << ".\n"; FA = vm["FASTA"].as<string>(); } else{ cout << "reference not set\t-f\n"; exit(0); } if (vm.count("WIG")) { cout << "WIG was set to " << vm["WIG"].as<string>() << ".\n"; wig = vm["WIG"].as<string>(); } else{ cout << "wiggle not set\t-w\n"; exit(0); } if (vm.count("MAP")) { cout << "MAP was set to " << vm["MAP"].as<string>() << ".\n"; mapbd = vm["MAP"].as<string>(); } else{ cout << "Mappability not set\t-w\n"; exit(0); } if (vm.count("SV")) { cout << "SV was set to " << vm["SV"].as<string>() << ".\n"; SVfile = vm["SV"].as<string>(); } else{ cout << "SV not set\t-S\n"; exit(0); } if (vm.count("SNP")) { cout << "SNP was set to " << vm["SNP"].as<string>() << ".\n"; SNPfile = vm["SNP"].as<string>(); } else{ cout << "SNP not set\t-s\n"; exit(0); } if (vm.count("GAP")) { cout << "GAP was set to " << vm["GAP"].as<string>() << ".\n"; GAPfile = vm["GAP"].as<string>(); } else{ cout << "GAP not set\t-g\nUsing default GAP file\t"; GAPfile = BIN + "/../data/GAP_20140416_num"; cout << GAPfile << endl; } if (vm.count("RUNFLAG")) { cout << "RUNFLAG was set to " << vm["RUNFLAG"].as<int>() << ".\n"; sys_flag = vm["RUNFLAG"].as<int>(); } else{ cout << "RUNFLAG not set\t-t\n"; exit(0); } if(MODE == "RUN" || MODE == "LITE"){ if (vm.count("TUMOR")) { cout << "TUMOR coverage was set to " << vm["TUMOR"].as<double>() << ".\n"; BB = vm["TUMOR"].as<double>(); } else{ cout << "TUMOR not set\t-t\n"; exit(0); } if (vm.count("NORMAL")) { cout << "NORMAL was set to " << vm["NORMAL"].as<double>() << ".\n"; Normal_cov_limit = vm["NORMAL"].as<double>(); } else{ cout << "NORMAL not set\t-n\n"; exit(0); } } if(MODE == "PLOIDY"){ main_ploidy(); } if(MODE == "LITE"){ main_lite(); } return 0; } int main_ploidy(){ // Estimate the ploidy ifstream input1(SVfile); ifstream input2(SNPfile); ifstream input3(GAPfile); readRange(input3, RANGE_b, RANGE_e, LIST, chr_vec); readSV(input1, RANGE_b, RANGE_e, LIST, LONE, SV_LIST, SV_list, LINK); readSNP(input2, RANGE_b, RANGE_e, ALL_SNP, REF_ALT_FLAG, isolatedSNP, LIST); Partition( LIST, JOB_LIST, SV_FLAG_L, SV_FLAG_R, LONE, LO_L, LO_R, regionCov, ALL_SNP, RANGE_b, isolatedSNP, SV_list, BIN, FA, mapbd, thread, sys_flag); Job_partition( JOB_LIST, SV_FLAG_L, SV_FLAG_R, LO_L, LO_R, SV_list_link, SV_list_CNV, Linear_region, Linear_region_info_vec ); new_Estimate_ploidy(BB, JOB_LIST, hap_coverage_lowerbound, hap_coverage_upperbound, Linear_region, Linear_region_info_vec, regionCov, ALL_SNP, thread); cout << "Estimated cancer haplotype coverage:\t" << best_cov << "\n"; cout << "Estimated normal haplotype coverage:\t" << best_norm << "\n"; return 0; } int main_lite(){ // Core program with SNP phasing disabled ifstream input1(SVfile); ifstream input2(SNPfile); ifstream input3(GAPfile); readRange(input3, RANGE_b, RANGE_e, LIST, chr_vec); readSV(input1, RANGE_b, RANGE_e, LIST, LONE, SV_LIST, SV_list, LINK); readSNP(input2, RANGE_b, RANGE_e, ALL_SNP, REF_ALT_FLAG, isolatedSNP, LIST); // readSNP_link(input_snp_link, SNP_LINK); // readSNP_link_1000G(input5,SNP_1000G); // //Initial partition of the genome Partition( LIST, JOB_LIST, SV_FLAG_L, SV_FLAG_R, LONE, LO_L, LO_R, regionCov, ALL_SNP, RANGE_b, isolatedSNP, SV_list, BIN, FA, mapbd, thread, sys_flag); //Building the cancer genome graph Job_partition( JOB_LIST, SV_FLAG_L, SV_FLAG_R, LO_L, LO_R, SV_list_link, SV_list_CNV, Linear_region, Linear_region_info_vec ); //Estimate the ploidy, normal fraction Estimate_ploidy(BB, JOB_LIST, hap_coverage_lowerbound, hap_coverage_upperbound, Linear_region, Linear_region_info_vec, regionCov, ALL_SNP, thread); //Annotated simple del and dups findSimpleLink(LINK, SV_list_link, Linear_region); //Fast initialization of node states in LBP Viterbi_new(JOB_LIST, regionCov, SNP_LINK, SNP_1000G, ALL_SNP, SV_FLAG_L, SV_FLAG_R, LO_L, LO_R, SV_list_CNV, REF_ALT_FLAG, SV_region_id, thread, SV_list, LINK, chr_vec); //core LBP step to estimate SV copy number. With multiple implimentations LoopyBeliefPropagation( JOB_LIST, SV_list_CNV, SV_list_link, SV_list, LINK , prob_matrix_1, prob_matrix_2, Linear_region, thread); //Lite version disable SNP phasing. Viterbi_lite(JOB_LIST, regionCov, SNP_LINK, SNP_1000G, ALL_SNP, SV_FLAG_L, SV_FLAG_R, LO_L, LO_R, SV_list_CNV, REF_ALT_FLAG, SV_region_id, thread, SV_list, LINK, Linear_region); //Final report the ASCNG and ASCNS final_report(JOB_LIST, SV_FLAG_L, SV_FLAG_R, SV_list, LINK, ALL_SNP); return 0; } int main(int argc, char *argv[]){ if(argc <= 1){ usage(); exit(0); } string bin = argv[0]; BIN = bin.substr(0, bin.rfind("/")+1); //cout << BIN << endl; MODE = string(argv[1]); //RUN MODE //PLOIDY: Estimate ploidy //LITE: SNP phasing disabled, much faster cout << "RUN MODE\t" << MODE << endl; return main_opt(argc-1,argv+1); exit(0); } <commit_msg>README changes<commit_after>#include <iostream> #include <string> #include <vector> #include <map> #include <set> #include <iomanip> #include <fstream> #include <sstream> #include <stdlib.h> #include <float.h> #include "parameters.h" #include "interval.h" #include "distt.h" #include "structure.h" #include "read.h" #include "partition.h" #include "LBP.h" #include "ploidy.h" #include <boost/program_options.hpp> // //Infering the CNV profile under SV graphical model //Loopy Belief Propagation //Do the phasing for both SNP and SV // // //ALL RIGHTS RESEARVED YANGLI9@ILLINOIS.EDU // // //#define THRESHHOLD 40 using namespace std; namespace po = boost::program_options; map<string, map<int, int> > isolatedSNP; map<string, map<int, string> > SNP_LINK; map<string, map<int, double> > SNP_1000G; vector<observe> ALL_SNP; map<string, map<interval, string> >LIST, SV_LIST, LONE; vector<string> chr_vec; //store chr name with sorted chr size, handle large chr fist! map<string, int> RANGE_b, RANGE_e; // store the genome size information vector<int> REF_ALT_FLAG; // if the higher coverage is from reference or alt allele map<string, map<int, CA> > SV_list; map<string, map<int, int> > SV_list_link; // chr->pos->region_id map<string, map<int, int> > SV_list_CNV; map<CA, CA> LINK; // Linking SVs map<CA, int> SV_region_id; map<string, vector<site> > JOB_LIST;// storing segments map<string, map<interval, region_numbers> > regionCov; // coverage of each region set<site>SV_FLAG_L, SV_FLAG_R, LO_L, LO_R; // the orientation of SV. L stands for -; R stands for + map<site, map<hidden_state, double> > prob_matrix_1, prob_matrix_2;// inward_maxtrix, _prob_matrix_2, _prob_matrix_1; map<string, vector<interval> >Linear_region;// group of JOB_LIST map<string, vector<Linear_region_info> >Linear_region_info_vec; string version = "0.21"; string BIN; string SVfile, SNPfile, GAPfile;//(argv[1]); ifstream input_snp_link;//(argv[4]); ifstream input5;//(argv[5]); int sys_flag; // = atoi(argv[9]); double BB; int thread;// number of threads string MODE;// RUN mode static int usage(){ cout << "Program: Weaver Version \t" << version << endl; cout << "ALL\tPLOIDY\tLITE\n"; } int main_lite(); int main_ploidy(); int main_opt(int argc, char *argv[]){ po::options_description generic("Weaver options"); generic.add_options() ("VERSION,V", "print version string") ("FASTA,f", po::value<string>(), "[MANDATORY] reference fasta file") ("1KG,k", po::value<string>(), "1000G phase 1 haplotype file") ("THREAD,p", po::value<int>(), "[DEFAULT 1] number of threads") ("SNP,s", po::value<string>(), "[MANDATORY] SNP") ("SV,S", po::value<string>(), "[MANDATORY] SV") ("WIG,w", po::value<string>(), "[MANDATORY] WIG") ("GAP,g", po::value<string>(), "[DEFAULT Weaver/data/] GAP") ("MAP,m", po::value<string>(), "[DEFAULT Weaver/data/] Mappability") ("SNPLINK,l", po::value<string>(), "SNP LINK") ("SNPLINK1KG,L", po::value<string>(), "SNP LINK 1KG") ("NORMAL,n", po::value<double>(), "normal") ("TUMOR,t", po::value<double>(), "tumor") ("RUNFLAG,r", po::value<int>(), "[MANDATORY] run flag 1: from start; 0: region files already there") ("help,h", "print help message") ; if(argc <= 1){ cout << generic << "\n"; exit(0); } po::variables_map vm;// po::store(po::command_line_parser(argc, argv).options(generic).allow_unregistered().run(), vm); po::notify(vm); Normal_cov_limit = 2; if (vm.count("help")) { cout << generic << "\n"; return 1; } if (vm.count("THREAD")) { cout << "THREAD was set to " << vm["THREAD"].as<int>() << ".\n"; thread = vm["THREAD"].as<int>(); } else{ cout << "THREAD = 8\n"; thread = 8; } if (vm.count("FASTA")) { cout << "FASTA was set to " << vm["FASTA"].as<string>() << ".\n"; FA = vm["FASTA"].as<string>(); } else{ cout << "reference not set\t-f\n"; exit(0); } if (vm.count("WIG")) { cout << "WIG was set to " << vm["WIG"].as<string>() << ".\n"; wig = vm["WIG"].as<string>(); } else{ cout << "wiggle not set\t-w\n"; exit(0); } if (vm.count("MAP")) { cout << "MAP was set to " << vm["MAP"].as<string>() << ".\n"; mapbd = vm["MAP"].as<string>(); } else{ cout << "Mappability not set\t-w\n"; exit(0); } if (vm.count("SV")) { cout << "SV was set to " << vm["SV"].as<string>() << ".\n"; SVfile = vm["SV"].as<string>(); } else{ cout << "SV not set\t-S\n"; exit(0); } if (vm.count("SNP")) { cout << "SNP was set to " << vm["SNP"].as<string>() << ".\n"; SNPfile = vm["SNP"].as<string>(); } else{ cout << "SNP not set\t-s\n"; exit(0); } if (vm.count("GAP")) { cout << "GAP was set to " << vm["GAP"].as<string>() << ".\n"; GAPfile = vm["GAP"].as<string>(); } else{ cout << "GAP not set\t-g\nUsing default GAP file\t"; GAPfile = BIN + "/../data/GAP_20140416_num"; cout << GAPfile << endl; } if (vm.count("RUNFLAG")) { cout << "RUNFLAG was set to " << vm["RUNFLAG"].as<int>() << ".\n"; sys_flag = vm["RUNFLAG"].as<int>(); } else{ cout << "RUNFLAG not set\t-t\n"; exit(0); } if(MODE == "RUN" || MODE == "LITE"){ if (vm.count("TUMOR")) { cout << "TUMOR coverage was set to " << vm["TUMOR"].as<double>() << ".\n"; BB = vm["TUMOR"].as<double>(); } else{ cout << "TUMOR not set\t-t\n"; exit(0); } if (vm.count("NORMAL")) { cout << "NORMAL was set to " << vm["NORMAL"].as<double>() << ".\n"; Normal_cov_limit = vm["NORMAL"].as<double>(); } else{ cout << "NORMAL not set\t-n\n"; exit(0); } } if(MODE == "PLOIDY"){ main_ploidy(); } if(MODE == "LITE"){ main_lite(); } return 0; } int main_ploidy(){ // Estimate the ploidy ifstream input1(SVfile); ifstream input2(SNPfile); ifstream input3(GAPfile); readRange(input3, RANGE_b, RANGE_e, LIST, chr_vec); readSV(input1, RANGE_b, RANGE_e, LIST, LONE, SV_LIST, SV_list, LINK); readSNP(input2, RANGE_b, RANGE_e, ALL_SNP, REF_ALT_FLAG, isolatedSNP, LIST); Partition( LIST, JOB_LIST, SV_FLAG_L, SV_FLAG_R, LONE, LO_L, LO_R, regionCov, ALL_SNP, RANGE_b, isolatedSNP, SV_list, BIN, FA, mapbd, thread, sys_flag); Job_partition( JOB_LIST, SV_FLAG_L, SV_FLAG_R, LO_L, LO_R, SV_list_link, SV_list_CNV, Linear_region, Linear_region_info_vec ); Estimate_ploidy(BB, JOB_LIST, hap_coverage_lowerbound, hap_coverage_upperbound, Linear_region, Linear_region_info_vec, regionCov, ALL_SNP, thread); cout << "Estimated cancer haplotype coverage:\t" << best_cov << "\n"; cout << "Estimated normal haplotype coverage:\t" << best_norm << "\n"; return 0; } int main_lite(){ // Core program with SNP phasing disabled ifstream input1(SVfile); ifstream input2(SNPfile); ifstream input3(GAPfile); readRange(input3, RANGE_b, RANGE_e, LIST, chr_vec); readSV(input1, RANGE_b, RANGE_e, LIST, LONE, SV_LIST, SV_list, LINK); readSNP(input2, RANGE_b, RANGE_e, ALL_SNP, REF_ALT_FLAG, isolatedSNP, LIST); // readSNP_link(input_snp_link, SNP_LINK); // readSNP_link_1000G(input5,SNP_1000G); // //Initial partition of the genome Partition( LIST, JOB_LIST, SV_FLAG_L, SV_FLAG_R, LONE, LO_L, LO_R, regionCov, ALL_SNP, RANGE_b, isolatedSNP, SV_list, BIN, FA, mapbd, thread, sys_flag); //Building the cancer genome graph Job_partition( JOB_LIST, SV_FLAG_L, SV_FLAG_R, LO_L, LO_R, SV_list_link, SV_list_CNV, Linear_region, Linear_region_info_vec ); //Estimate the ploidy, normal fraction Estimate_ploidy(BB, JOB_LIST, hap_coverage_lowerbound, hap_coverage_upperbound, Linear_region, Linear_region_info_vec, regionCov, ALL_SNP, thread); //Annotated simple del and dups findSimpleLink(LINK, SV_list_link, Linear_region); //Fast initialization of node states in LBP Viterbi_new(JOB_LIST, regionCov, SNP_LINK, SNP_1000G, ALL_SNP, SV_FLAG_L, SV_FLAG_R, LO_L, LO_R, SV_list_CNV, REF_ALT_FLAG, SV_region_id, thread, SV_list, LINK, chr_vec); //core LBP step to estimate SV copy number. With multiple implimentations LoopyBeliefPropagation( JOB_LIST, SV_list_CNV, SV_list_link, SV_list, LINK , prob_matrix_1, prob_matrix_2, Linear_region, thread); //Lite version disable SNP phasing. Viterbi_lite(JOB_LIST, regionCov, SNP_LINK, SNP_1000G, ALL_SNP, SV_FLAG_L, SV_FLAG_R, LO_L, LO_R, SV_list_CNV, REF_ALT_FLAG, SV_region_id, thread, SV_list, LINK, Linear_region); //Final report the ASCNG and ASCNS final_report(JOB_LIST, SV_FLAG_L, SV_FLAG_R, SV_list, LINK, ALL_SNP); return 0; } int main(int argc, char *argv[]){ if(argc <= 1){ usage(); exit(0); } string bin = argv[0]; BIN = bin.substr(0, bin.rfind("/")+1); //cout << BIN << endl; MODE = string(argv[1]); //RUN MODE //PLOIDY: Estimate ploidy //LITE: SNP phasing disabled, much faster cout << "RUN MODE\t" << MODE << endl; return main_opt(argc-1,argv+1); exit(0); } <|endoftext|>
<commit_before>// chrlauncher // Copyright (c) 2015-2018 Henry++ #ifndef __MAIN_H__ #define __MAIN_H__ #include <windows.h> #include <commctrl.h> #include "resource.hpp" #include "app.hpp" // config #define WM_TRAYICON WM_APP + 1 #define UID 2008 // libs #pragma comment(lib, "version.lib") struct STATIC_DATA { HANDLE hthread_check = nullptr; HANDLE stop_evt = nullptr; }; struct BROWSER_INFORMATION { bool is_autodownload = false; bool is_bringtofront = false; bool is_forcecheck = false; bool is_waitdownloadend = false; bool is_isdownloaded = false; bool is_isinstalled = false; time_t timestamp = 0; INT check_period = 0; UINT architecture = 0; WCHAR current_version[32] = {0}; WCHAR new_version[32] = {0}; WCHAR name[64] = {0}; WCHAR name_full[64] = {0}; WCHAR type[64] = {0}; WCHAR cache_path[512] = {0}; WCHAR binary_dir[512] = {0}; WCHAR binary_path[512] = {0}; WCHAR download_url[512] = {0}; WCHAR urls[1024] = {0}; WCHAR args[2048] = {0}; }; #endif // __MAIN_H__ <commit_msg>cleanup<commit_after>// chrlauncher // Copyright (c) 2015-2018 Henry++ #ifndef __MAIN_H__ #define __MAIN_H__ #include <windows.h> #include <commctrl.h> #include "resource.hpp" #include "app.hpp" // config #define WM_TRAYICON WM_APP + 1 #define UID 2008 // libs #pragma comment(lib, "version.lib") struct BROWSER_INFORMATION { bool is_autodownload = false; bool is_bringtofront = false; bool is_forcecheck = false; bool is_waitdownloadend = false; bool is_isdownloaded = false; bool is_isinstalled = false; time_t timestamp = 0; INT check_period = 0; UINT architecture = 0; WCHAR current_version[32] = {0}; WCHAR new_version[32] = {0}; WCHAR name[64] = {0}; WCHAR name_full[64] = {0}; WCHAR type[64] = {0}; WCHAR cache_path[512] = {0}; WCHAR binary_dir[512] = {0}; WCHAR binary_path[512] = {0}; WCHAR download_url[512] = {0}; WCHAR urls[1024] = {0}; WCHAR args[2048] = {0}; }; #endif // __MAIN_H__ <|endoftext|>
<commit_before>/* * Blink * Turns on an LED on for one second, * then off for one second, repeatedly. */ #include "Arduino.h" // Set LED_BUILTIN if it is not defined by Arduino framework // #define LED_BUILTIN 13 void setup() { // initialize LED digital pin as an output. pinMode(LED_BUILTIN, OUTPUT); } void loop() { // turn the LED on (HIGH is the voltage level) digitalWrite(LED_BUILTIN, HIGH); // wait for a second delay(1000); // turn the LED off by making the voltage LOW digitalWrite(LED_BUILTIN, LOW); // wait for a second delay(1000); } <commit_msg>Stop LED blink :bulb:<commit_after>/* * Blink * Turns on an LED on for one second, * then off for one second, repeatedly. */ #include "Arduino.h" // Set LED_BUILTIN if it is not defined by Arduino framework // #define LED_BUILTIN 13 void setup() { // initialize LED digital pin as an output. pinMode(LED_BUILTIN, OUTPUT); } void loop() { // turn the LED on (HIGH is the voltage level) // digitalWrite(LED_BUILTIN, HIGH); // wait for a second delay(1000); // turn the LED off by making the voltage LOW digitalWrite(LED_BUILTIN, LOW); // wait for a second delay(1000); } <|endoftext|>
<commit_before> // This file is part of node-lmdb, the Node.js binding for lmdb // Copyright (c) 2013 Timur Kristóf // Licensed to you under the terms of the MIT license // // 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 "node-lmdb.h" #include <string.h> #include <stdio.h> void setupExportMisc(Handle<Object> exports) { Local<Object> versionObj = Nan::New<Object>(); int major, minor, patch; char *str = mdb_version(&major, &minor, &patch); versionObj->Set(Nan::New<String>("versionString").ToLocalChecked(), Nan::New<String>(str).ToLocalChecked()); versionObj->Set(Nan::New<String>("major").ToLocalChecked(), Nan::New<Integer>(major)); versionObj->Set(Nan::New<String>("minor").ToLocalChecked(), Nan::New<Integer>(minor)); versionObj->Set(Nan::New<String>("patch").ToLocalChecked(), Nan::New<Integer>(patch)); exports->Set(Nan::New<String>("version").ToLocalChecked(), versionObj); } void setFlagFromValue(int *flags, int flag, const char *name, bool defaultValue, Local<Object> options) { Local<Value> opt = options->Get(Nan::New<String>(name).ToLocalChecked()); if (opt->IsBoolean() ? opt->BooleanValue() : defaultValue) { *flags |= flag; } } argtokey_callback_t argToKey(const Local<Value> &val, MDB_val &key, bool keyIsUint32) { // Check key type if (keyIsUint32 && !val->IsUint32()) { Nan::ThrowError("Invalid key. keyIsUint32 specified on the database, but the given key was not an unsigned 32-bit integer"); return nullptr; } if (!keyIsUint32 && !val->IsString()) { Nan::ThrowError("Invalid key. String key expected, because keyIsUint32 isn't specified on the database."); return nullptr; } // Handle uint32_t key if (keyIsUint32) { uint32_t *v = new uint32_t; *v = val->Uint32Value(); key.mv_size = sizeof(uint32_t); key.mv_data = v; return ([](MDB_val &key) -> void { delete (uint32_t*)key.mv_data; }); } // Handle string key CustomExternalStringResource::writeTo(val->ToString(), &key); return ([](MDB_val &key) -> void { delete[] (uint16_t*)key.mv_data; }); return nullptr; } Local<Value> keyToHandle(MDB_val &key, bool keyIsUint32) { if (keyIsUint32) { return Nan::New<Integer>(*((uint32_t*)key.mv_data)); } else { return valToString(key); } } Local<Value> valToString(MDB_val &data) { auto resource = new CustomExternalStringResource(&data); auto str = Nan::New<v8::String>(resource); return str.ToLocalChecked(); } Local<Value> valToBinary(MDB_val &data) { // FIXME: It'd be better not to copy buffers, but I'm not sure // about the ownership semantics of MDB_val, so let' be safe. return Nan::CopyBuffer( (char*)data.mv_data, data.mv_size ).ToLocalChecked(); } Local<Value> valToNumber(MDB_val &data) { return Nan::New<Number>(*((double*)data.mv_data)); } Local<Value> valToBoolean(MDB_val &data) { return Nan::New<Boolean>(*((bool*)data.mv_data)); } void consoleLog(const char *msg) { Local<String> str = Nan::New("console.log('").ToLocalChecked(); str = String::Concat(str, Nan::New<String>(msg).ToLocalChecked()); str = String::Concat(str, Nan::New("');").ToLocalChecked()); Local<Script> script = Nan::CompileScript(str).ToLocalChecked(); Nan::RunScript(script); } void consoleLog(Local<Value> val) { Local<String> str = Nan::New<String>("console.log('").ToLocalChecked(); str = String::Concat(str, val->ToString()); str = String::Concat(str, Nan::New<String>("');").ToLocalChecked()); Local<Script> script = Nan::CompileScript(str).ToLocalChecked(); Nan::RunScript(script); } void consoleLogN(int n) { char c[20]; memset(c, 0, 20 * sizeof(char)); sprintf(c, "%d", n); consoleLog(c); } /* Writing string to LMDB. Making LMDB compatible with other languages by converting strings to UTF-8. Alas, this means no zero-copy semantics because strings are UTF-16 in Javascript. */ void CustomExternalStringResource::writeTo(Handle<String> str, MDB_val *val) { String::Utf8Value utf8(str); char *inp = *utf8; int len = strlen(inp); char *d = new char[len]; strcpy(d, inp); val->mv_data = d; val->mv_size = len; } /* Reading string from LMDB. It will be utf-8 encoded, so decoding here into utf-16. */ CustomExternalStringResource::CustomExternalStringResource(MDB_val *val) { // appending '\0' to input to feed into String::New char *tmp = new char[val->mv_size + 1]; memcpy(tmp, val->mv_data, val->mv_size); tmp[val->mv_size] = 0; // convert utf8 -> utf16 Local<String> jsString = String::New(tmp); delete [] tmp; // write into output buffer int len = jsString->Length(); uint16_t *d = new uint16_t[len + 1]; jsString->Write(d); this->d = d; this->l = len + 1; } CustomExternalStringResource::~CustomExternalStringResource() { // TODO: alter this if zero-copy semantics is reintroduced above delete [] d; } void CustomExternalStringResource::Dispose() { // No need to do anything, the data is owned by LMDB, not us // But actually need to delete the string resource itself: // the docs say that "The default implementation will use the delete operator." // while initially I thought this means using delete on the string, // apparently they meant just calling the destructor of this class. delete this; } const uint16_t *CustomExternalStringResource::data() const { return this->d; } size_t CustomExternalStringResource::length() const { return this->l; } <commit_msg>More off-by-one magic<commit_after> // This file is part of node-lmdb, the Node.js binding for lmdb // Copyright (c) 2013 Timur Kristóf // Licensed to you under the terms of the MIT license // // 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 "node-lmdb.h" #include <string.h> #include <stdio.h> void setupExportMisc(Handle<Object> exports) { Local<Object> versionObj = Nan::New<Object>(); int major, minor, patch; char *str = mdb_version(&major, &minor, &patch); versionObj->Set(Nan::New<String>("versionString").ToLocalChecked(), Nan::New<String>(str).ToLocalChecked()); versionObj->Set(Nan::New<String>("major").ToLocalChecked(), Nan::New<Integer>(major)); versionObj->Set(Nan::New<String>("minor").ToLocalChecked(), Nan::New<Integer>(minor)); versionObj->Set(Nan::New<String>("patch").ToLocalChecked(), Nan::New<Integer>(patch)); exports->Set(Nan::New<String>("version").ToLocalChecked(), versionObj); } void setFlagFromValue(int *flags, int flag, const char *name, bool defaultValue, Local<Object> options) { Local<Value> opt = options->Get(Nan::New<String>(name).ToLocalChecked()); if (opt->IsBoolean() ? opt->BooleanValue() : defaultValue) { *flags |= flag; } } argtokey_callback_t argToKey(const Local<Value> &val, MDB_val &key, bool keyIsUint32) { // Check key type if (keyIsUint32 && !val->IsUint32()) { Nan::ThrowError("Invalid key. keyIsUint32 specified on the database, but the given key was not an unsigned 32-bit integer"); return nullptr; } if (!keyIsUint32 && !val->IsString()) { Nan::ThrowError("Invalid key. String key expected, because keyIsUint32 isn't specified on the database."); return nullptr; } // Handle uint32_t key if (keyIsUint32) { uint32_t *v = new uint32_t; *v = val->Uint32Value(); key.mv_size = sizeof(uint32_t); key.mv_data = v; return ([](MDB_val &key) -> void { delete (uint32_t*)key.mv_data; }); } // Handle string key CustomExternalStringResource::writeTo(val->ToString(), &key); return ([](MDB_val &key) -> void { delete[] (uint16_t*)key.mv_data; }); return nullptr; } Local<Value> keyToHandle(MDB_val &key, bool keyIsUint32) { if (keyIsUint32) { return Nan::New<Integer>(*((uint32_t*)key.mv_data)); } else { return valToString(key); } } Local<Value> valToString(MDB_val &data) { auto resource = new CustomExternalStringResource(&data); auto str = Nan::New<v8::String>(resource); return str.ToLocalChecked(); } Local<Value> valToBinary(MDB_val &data) { // FIXME: It'd be better not to copy buffers, but I'm not sure // about the ownership semantics of MDB_val, so let' be safe. return Nan::CopyBuffer( (char*)data.mv_data, data.mv_size ).ToLocalChecked(); } Local<Value> valToNumber(MDB_val &data) { return Nan::New<Number>(*((double*)data.mv_data)); } Local<Value> valToBoolean(MDB_val &data) { return Nan::New<Boolean>(*((bool*)data.mv_data)); } void consoleLog(const char *msg) { Local<String> str = Nan::New("console.log('").ToLocalChecked(); str = String::Concat(str, Nan::New<String>(msg).ToLocalChecked()); str = String::Concat(str, Nan::New("');").ToLocalChecked()); Local<Script> script = Nan::CompileScript(str).ToLocalChecked(); Nan::RunScript(script); } void consoleLog(Local<Value> val) { Local<String> str = Nan::New<String>("console.log('").ToLocalChecked(); str = String::Concat(str, val->ToString()); str = String::Concat(str, Nan::New<String>("');").ToLocalChecked()); Local<Script> script = Nan::CompileScript(str).ToLocalChecked(); Nan::RunScript(script); } void consoleLogN(int n) { char c[20]; memset(c, 0, 20 * sizeof(char)); sprintf(c, "%d", n); consoleLog(c); } /* Writing string to LMDB. Making LMDB compatible with other languages by converting strings to UTF-8. Alas, this means no zero-copy semantics because strings are UTF-16 in Javascript. */ void CustomExternalStringResource::writeTo(Handle<String> str, MDB_val *val) { String::Utf8Value utf8(str); char *inp = *utf8; int len = strlen(inp); char *d = new char[len + 1]; strcpy(d, inp); val->mv_data = d; val->mv_size = len; } /* Reading string from LMDB. It will be utf-8 encoded, so decoding here into utf-16. */ CustomExternalStringResource::CustomExternalStringResource(MDB_val *val) { // appending '\0' to input to feed into String::New char *tmp = new char[val->mv_size + 1]; memcpy(tmp, val->mv_data, val->mv_size); tmp[val->mv_size] = 0; // convert utf8 -> utf16 Local<String> jsString = String::New(tmp); delete [] tmp; // write into output buffer int len = jsString->Length(); uint16_t *d = new uint16_t[len + 1]; jsString->Write(d); this->d = d; this->l = len; } CustomExternalStringResource::~CustomExternalStringResource() { // TODO: alter this if zero-copy semantics is reintroduced above delete [] d; } void CustomExternalStringResource::Dispose() { // No need to do anything, the data is owned by LMDB, not us // But actually need to delete the string resource itself: // the docs say that "The default implementation will use the delete operator." // while initially I thought this means using delete on the string, // apparently they meant just calling the destructor of this class. delete this; } const uint16_t *CustomExternalStringResource::data() const { return this->d; } size_t CustomExternalStringResource::length() const { return this->l; } <|endoftext|>
<commit_before>/* * Copyright 2013 Matthew Harvey * * 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. */ // TODO HIGH PRIORITY Under KDE (at least on Mageia) the way I have set // up the widths of wxComboBox and wxTextCtrl and wxButton (in various // controls in which these feature), where they are // supposed to be the same height, they actually turn out to be slightly // different heights. However even if I manually set them all to the same // hard-coded height number, they still seem to come out different heights // on KDE. It doesn't make a lot of sense. // TODO MEDIUM PRIORITY Tooltips aren't showing on Windows. /// TODO MEDIUM PRIORITY The database file should perhaps have a checksum to // guard against its contents changing other than via the application. // TODO HIGH PRIORITY Facilitate automatic checking for updates from user's // machine, or at least provide an easy process for installing updates // via NSIS. It appears that the default configuration of CPack/NSIS is // such that updates will not overwrite existing files. Some manual NSIS // scripting may be required to enable this. Also take into account that // the user may have to restart their computer in the event that they have // files open while the installer (or "updater") is running (although I // \e think that the default configuration under CPack does this // automatically). // TODO HIGH PRIORITY Create a decent icon for the application. We want this // in both .ico form (for Windows executable icon) and .xpm // form (for icon for Frame). Note, when I exported my // "token icon" using GIMP to .ico format, and later used this // to create a double-clickable icon in Windows, only the text // on the icon appeared, and the background image became // transparent for some reason. Furthermore, when set as the // large in-windows icon in the CPack/NSIS installer, the icon // wasn't showing at all. Once decent icon is created, also make sure it is // pulled into the wxBitmap in SetupWizard. // TODO HIGH PRIORITY Create a better name for the application. // TODO HIGH PRIORITY Make the GUI display acceptably on smaller screen // i.e. laptop. // TODO MEDIUM PRIORITY Startup time under Windows is really slow, even when // compiled in Release mode. // TODO MEDIUM PRIORITY Give user the option to export to CSV. // TODO LOW PRIORITY Allow export/import to/from .qif (?) format. // TODO MEDIUM PRIORITY Allow window borders to be dragged around, especially // for DraftJournalListCtrl. This make it easier for users on laptops. // TODO HIGH PRIORITY User guide. // TODO MEDIUM PRIORITY When the user creates a new file, ask if they want to // create a shortcut to the file on their Desktop (assuming they didn't // actually create the file in their desktop). #include "app.hpp" #include <wx/app.h> wxIMPLEMENT_APP(dcm::App); <commit_msg>Deleted an obsolete TODO.<commit_after>/* * Copyright 2013 Matthew Harvey * * 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. */ // TODO HIGH PRIORITY Under KDE (at least on Mageia) the way I have set // up the widths of wxComboBox and wxTextCtrl and wxButton (in various // controls in which these feature), where they are // supposed to be the same height, they actually turn out to be slightly // different heights. However even if I manually set them all to the same // hard-coded height number, they still seem to come out different heights // on KDE. It doesn't make a lot of sense. // TODO MEDIUM PRIORITY Tooltips aren't showing on Windows. /// TODO MEDIUM PRIORITY The database file should perhaps have a checksum to // guard against its contents changing other than via the application. // TODO HIGH PRIORITY Facilitate automatic checking for updates from user's // machine, or at least provide an easy process for installing updates // via NSIS. It appears that the default configuration of CPack/NSIS is // such that updates will not overwrite existing files. Some manual NSIS // scripting may be required to enable this. Also take into account that // the user may have to restart their computer in the event that they have // files open while the installer (or "updater") is running (although I // \e think that the default configuration under CPack does this // automatically). // TODO HIGH PRIORITY Create a decent icon for the application. We want this // in both .ico form (for Windows executable icon) and .xpm // form (for icon for Frame). Note, when I exported my // "token icon" using GIMP to .ico format, and later used this // to create a double-clickable icon in Windows, only the text // on the icon appeared, and the background image became // transparent for some reason. Furthermore, when set as the // large in-windows icon in the CPack/NSIS installer, the icon // wasn't showing at all. Once decent icon is created, also make sure it is // pulled into the wxBitmap in SetupWizard. // TODO HIGH PRIORITY Make the GUI display acceptably on smaller screen // i.e. laptop. // TODO MEDIUM PRIORITY Startup time under Windows is really slow, even when // compiled in Release mode. // TODO MEDIUM PRIORITY Give user the option to export to CSV. // TODO LOW PRIORITY Allow export/import to/from .qif (?) format. // TODO MEDIUM PRIORITY Allow window borders to be dragged around, especially // for DraftJournalListCtrl. This make it easier for users on laptops. // TODO HIGH PRIORITY User guide. // TODO MEDIUM PRIORITY When the user creates a new file, ask if they want to // create a shortcut to the file on their Desktop (assuming they didn't // actually create the file in their desktop). #include "app.hpp" #include <wx/app.h> wxIMPLEMENT_APP(dcm::App); <|endoftext|>
<commit_before>#include <iostream> #include <string> #include <string.h> #include <typeinfo> #include <boost/tokenizer.hpp> #include <unistd.h> #include <sys/wait.h> #include <sys/types.h> #include <stdio.h> #include <stdlib.h> #include <cmath> using namespace std; using namespace boost; int Test(char** args, bool &previous, bool &previous_prev, int con, int prev_con){ // fails cases such as ls || ls || ls || ls || ls && stuff && ls //pass in the command and previous if (strcmp(args[0], "exit") == 0){ //if exit is the command exit(0); //then exit } if((previous == false) && (con != 2) && (prev_con != 2)){ //check if the last one was false return EXIT_FAILURE; //will/should only work for && } if((previous == true) && (prev_con == 2)){ return 0;//EXIT_FAILURE; } pid_t pid = fork(); //start forking if (pid == -1){ //fail to fork error perror("failed to fork"); return EXIT_FAILURE; } else if(pid == 0){ //start the process if(execvp(args[0], args) == -1){ //checks to see if it failed perror("execvp"); //if so output error and exit exit(1); return EXIT_FAILURE; } } int status; if ( waitpid(pid, &status, 0) == -1 ) { //waitpid waits(not sure what it does) perror("waitpid failed"); exit(1); return EXIT_FAILURE; //exit(1); } if(WIFEXITED(status)){ //always goes into here(I think so) const int es = WEXITSTATUS(status); // checks what the exit was //cout << "ES " << es << endl; if(es == 1){ //if exit was 1 then it failed(IMPORTANT) return EXIT_FAILURE; } //return EXIT_SUCCESS; } return EXIT_SUCCESS; //else return 0 for true } void string_check(string &s, bool &Is_Comment){//helper function for the comment delete for(unsigned i = 0; i < s.size(); ++i){ char temp = s.at(i); //takes in a string if(temp == '#'){ //compares it to the # Is_Comment = false; //if true then set flag/boolean } } } void Delete_Comment(vector<string> &CC){ //takes in our full vector vector<string>::iterator it; //iterates through the vector bool Comment_Checker = true; int i = 0; for(it = CC.begin(); it != CC.end(); ++it){ string test = ""; test = *it; ++i; string str(test); //passes each individual string string_check(test, Comment_Checker);//to our helper function if(Comment_Checker == false){ //deletes everything past the # CC.erase(CC.begin() + i - 1, CC.end()); return; } } } void Print(vector<string> pts){ //function that prints string vector vector<string>::iterator it; //helped when doing the first steps for(it = pts.begin(); it != pts.end(); ++it){ cout << *it << " "; //not really needed(the print function) } } void Parse(vector<string> &ParseString, int size, bool P_previous, bool P_previous_prev, int P_conn, int P_conn_prev){ if(size < 1){ //passing in nothing = return return; } int ParseSize; // will need variables for later string connector; //will hold the ;/&&/|| int P_con_prev = P_conn; int P_con; unsigned i = 0; //basic counter vector<string> S_T_E; //empty vector to be filled in while((i < ParseString.size()) && (ParseString.at(i) != ";") //creates the string && (ParseString.at(i) != "||") //that will execute && (ParseString.at(i) != "&&")){ //stops when connector/empty S_T_E.push_back(ParseString.at(i)); ++i; ParseSize = i; } string SP = ParseString.at(0); //if input is ;/&&/|| then error if((SP == ";") || (SP == "||") || (SP == "&&")){ ParseString.erase(ParseString.begin(), ParseString.end()); //delete full string cout << "bash: syntax error near unexpected token '" << SP << "'" << endl; return; } if(i == ((ParseString.size()))){ //checks the last character connector = "0"; P_con = 0; // 0 connector //cout << " in 0" << endl; } //sets connnector else if(ParseString.at(i) == "&&"){ //&& connector connector = "&&"; P_con = 1; //cout << " in &&" << endl; } else if(ParseString.at(i) == "||"){ //|| connector connector = "||"; P_con = 2; //cout << " in ||" << endl; } else if(ParseString.at(i) == ";"){ // ; connector connector = ";"; P_con = 3; //cout << " in ;" << endl; } char** args = new char*[128]; //creates new array to store the characters for(int i = 0; i < ParseSize; i++){ char * temp = strdup(S_T_E.at(i).c_str()); args[i] = temp; } if(ParseSize > 126){ // limit of 127 strings as one command cout << "INPUT TOO LARGE" << endl; return; } args[ParseSize] = '\0'; // null terminating character at the end int temp = Test(args, P_previous, P_previous_prev, P_con, P_con_prev); //checks whether it executed or not P_previous_prev = P_previous; if(temp == 0){ // sets out boolean P_previous P_previous = true; } else{ P_previous = false; } if(connector == "0"){ //should be empty but parse will handle it ParseString.erase(ParseString.begin(), ParseString.begin() + i); P_previous = true; Parse(ParseString, ParseString.size(), P_previous, P_previous_prev, P_con, P_con_prev); } if(connector == "&&"){ //&& case(only one not set to true*******) ParseString.erase(ParseString.begin(), ParseString.begin() + i + 1); Parse(ParseString, ParseString.size(), P_previous, P_previous_prev, P_con, P_con_prev); } if(connector == "||"){ //|| case ParseString.erase(ParseString.begin(), ParseString.begin() + i + 1); if((P_previous_prev == true) && (P_con_prev == 2)){ P_previous = true; } Parse(ParseString, ParseString.size(), P_previous, P_previous_prev, P_con, P_con_prev); } if(connector == ";"){ //; case ParseString.erase(ParseString.begin(), ParseString.begin() + i + 1); P_previous = true; Parse(ParseString, ParseString.size(), P_previous, P_previous_prev, P_con, P_con_prev); } return; } int main(){ bool MainPrevious = true; //allows us to run our first command bool MainPrevious_prev = false; vector<string> cmd; //vector to hold our string string str; //will simply be our input string while(1){ cout << "$ "; //outputs the $ every iteration cmd.erase(cmd.begin(), cmd.end()); getline(cin, str); //gets input from user char_separator<char> delim(" ", ";" "#"); // parameters for our input tokenizer< char_separator<char> > mytok(str, delim); for(tokenizer<char_separator<char> >::iterator it = mytok.begin(); it != mytok.end(); ++it){ cmd.push_back(*it); //push to our cmd vector } Delete_Comment(cmd); // checks for # int size = cmd.size(); //gets updated size(if changed) Parse(cmd, size, MainPrevious, MainPrevious_prev, 0, 0); //starts parsing commands } return 0; } <commit_msg>Rshell is functional for part 1, going to start the second part after this<commit_after>#include <iostream> #include <string> #include <string.h> #include <typeinfo> #include <boost/tokenizer.hpp> #include <unistd.h> #include <sys/wait.h> #include <sys/types.h> #include <stdio.h> #include <stdlib.h> #include <cmath> #include <stack> using namespace std; using namespace boost; int execute(char** args, bool &prev, bool &prev_prev, int con, int prev_con){ //pass in the command and previous if((prev == false) && (con != 2) && (prev_con != 2)){ //check if the last one was false return EXIT_FAILURE; //will/should only work for && } if((prev == true) && (prev_con == 2)){ return 0;//EXIT_FAILURE; } if (strcmp(args[0], "exit") == 0){ //if exit is the command exit(0); //then exit } pid_t pid = fork(); //start forking if (pid == -1){ //fail to fork error perror("failed to fork"); return EXIT_FAILURE; } else if(pid == 0){ //start the process if(execvp(args[0], args) == -1){ //checks to see if it failed perror("execvp"); //if so output error and exit exit(1); return EXIT_FAILURE; } } int status; if ( waitpid(pid, &status, 0) == -1 ) { //waitpid waits(not sure what it does) perror("waitpid failed"); exit(1); return EXIT_FAILURE; } if(WIFEXITED(status)){ //always goes into here(I think so) const int es = WEXITSTATUS(status); // checks what the exit was //cout << "ES " << es << endl; if(es != 0){ //if exit was 1 then it failed(IMPORTANT) return EXIT_FAILURE; } } return EXIT_SUCCESS; //else return 0 for true } void Parse(vector<string> &ParseString, int size, bool P_previous, bool P_previous_prev, int P_conn, int P_conn_prev){ if(size < 1){ //passing in nothing = return return; } if(ParseString.at(0).at(0) == '('){ cout << "paranthesis: " << endl; } int ParseSize; // will need variables for later string connector; //will hold the ;/&&/|| int P_con_prev = P_conn; int P_con; unsigned i = 0; //basic counter vector<string> S_T_E; //empty vector to be filled in while((i < ParseString.size()) && (ParseString.at(i) != ";") //creates the string && (ParseString.at(i) != "||") //that will execute && (ParseString.at(i) != "&&")){ //stops when connector/empty S_T_E.push_back(ParseString.at(i)); ++i; ParseSize = i; } string SP = ParseString.at(0); //if input is ;/&&/|| then error if((SP == ";") || (SP == "||") || (SP == "&&")){ ParseString.erase(ParseString.begin(), ParseString.end()); //delete full string cout << "bash: syntax error near unexpected token '" << SP << "'" << endl; return; } if(i == ((ParseString.size()))){ //checks the last character connector = "0"; P_con = 0; // 0 connector //cout << " in 0" << endl; } //sets connnector else if(ParseString.at(i) == "&&"){ //&& connector connector = "&&"; P_con = 1; //cout << " in &&" << endl; } else if(ParseString.at(i) == "||"){ //|| connector connector = "||"; P_con = 2; //cout << " in ||" << endl; } else if(ParseString.at(i) == ";"){ // ; connector connector = ";"; P_con = 3; //cout << " in ;" << endl; } char** args = new char*[128]; //creates new array to store the characters for(int i = 0; i < ParseSize; i++){ char * temp = strdup(S_T_E.at(i).c_str()); args[i] = temp; } if(ParseSize > 126){ // limit of 127 strings as one command cout << "INPUT TOO LARGE" << endl; return; } args[ParseSize] = '\0'; // null terminating character at the end int temp = execute(args, P_previous, P_previous_prev, P_con, P_con_prev); //checks whether it executed or not P_previous_prev = P_previous; if(temp == 0){ // sets out boolean P_previous P_previous = true; } else{ P_previous = false; } if(connector == "0"){ //should be empty but parse will handle it ParseString.erase(ParseString.begin(), ParseString.begin() + i); P_previous = true; Parse(ParseString, ParseString.size(), P_previous, P_previous_prev, P_con, P_con_prev); } if(connector == "&&"){ //&& case(only one not set to true*******) ParseString.erase(ParseString.begin(), ParseString.begin() + i + 1); Parse(ParseString, ParseString.size(), P_previous, P_previous_prev, P_con, P_con_prev); } if(connector == "||"){ //|| case ParseString.erase(ParseString.begin(), ParseString.begin() + i + 1); if((P_previous_prev == true) && (P_con_prev == 2)){ P_previous = true; } Parse(ParseString, ParseString.size(), P_previous, P_previous_prev, P_con, P_con_prev); } if(connector == ";"){ //; case ParseString.erase(ParseString.begin(), ParseString.begin() + i + 1); P_previous = true; Parse(ParseString, ParseString.size(), P_previous, P_previous_prev, P_con, P_con_prev); } return; } //////////////////////IGNORE THIS CODE, JUST DELETES THE COMMENT AND PRINTS//////////////////////////////////// void string_check(string &s, bool &Is_Comment){//helper function for the comment delete for(unsigned i = 0; i < s.size(); ++i){ char temp = s.at(i); //takes in a string if(temp == '#'){ //compares it to the # Is_Comment = false; //if true then set flag/boolean } } } void Delete_Comment(vector<string> &CC){ //takes in our full vector vector<string>::iterator it; //iterates through the vector bool Comment_Checker = true; int i = 0; for(it = CC.begin(); it != CC.end(); ++it){ string test = ""; test = *it; ++i; string str(test); //passes each individual string string_check(test, Comment_Checker);//to our helper function if(Comment_Checker == false){ //deletes everything past the # CC.erase(CC.begin() + i - 1, CC.end()); return; } } } void Print(vector<string> pts){ //function that prints string vector vector<string>::iterator it; //helped when doing the first steps for(it = pts.begin(); it != pts.end(); ++it){ cout << *it << " "; //not really needed(the print function) } } bool Prec_checker(vector<string> prec){ stack<char> S; for(int j = 0; j < prec.size(); ++j){ for(int i = 0; i < prec.at(j).size(); ++i){ if(prec.at(j).at(i) == '(') S.push(prec.at(j).at(i)); else if(prec.at(j).at(i) == ')'){ if(S.empty()) return false; else S.pop(); } } } return S.empty() ? true:false; } //////////////////////IGNORE THIS CODE, JUST DELETES THE COMMENT AND PRINTS//////////////////////////////////// int main(){ bool MainPrevious = true; //allows us to run our first command bool MainPrevious_prev = false; vector<string> cmd; //vector to hold our string string str; //will simply be our input string while(1){ cout << "$ "; //outputs the $ every iteration cmd.erase(cmd.begin(), cmd.end()); getline(cin, str); //gets input from user char_separator<char> delim(" ", ";" "#"); // parameters for our input tokenizer< char_separator<char> > mytok(str, delim); for(tokenizer<char_separator<char> >::iterator it = mytok.begin(); it != mytok.end(); ++it){ cmd.push_back(*it); //push to our cmd vector } Delete_Comment(cmd); // checks for # bool done = Prec_checker(cmd); //makes sure even number of precedence if(done == false){ cout << "unmatched paranthesis: " << endl; cmd.erase(cmd.begin(), cmd.end()); } int size = cmd.size(); //gets updated size(if changed) Parse(cmd, size, MainPrevious, MainPrevious_prev, 0, 0); //starts parsing commands } return 0; } <|endoftext|>
<commit_before>#include <cstdlib> #include <cmath> #include <fstream> #include <sstream> #include <iostream> #include <iomanip> #include <string> #include <vector> #include <algorithm> #include <exception> #include <sys/time.h> #include "modules/htmTree.h" #include "modules/kdTree.h" #include "misc.h" #include "feat.h" #include "structs.h" #include "collision.h" #include "global.h" //reduce redistributes, updates 07/02/15 rnc int main(int argc, char **argv) { //// Initializations --------------------------------------------- srand48(1234); // Make sure we have reproducability check_args(argc); Time t, time; // t for global, time for local init_time(t); Feat F; // Read parameters file // F.readInputFile(argv[1]); printFile(argv[1]); // Read galaxies Gals G; if(F.Ascii){ G=read_galaxies_ascii(F);} else{ G = read_galaxies(F); } F.Ngal = G.size(); printf("# Read %s galaxies from %s \n",f(F.Ngal).c_str(),F.galFile.c_str()); std::vector<int> count; count=count_galaxies(G); for(int i=0;i<8;i++){printf (" %d \n",count[i]);} // make MTL MTL M=make_MTL(G,F); for(int i=0;i<M.priority_list.size();++i){ printf(" priority %d",M.priority_list[i]); } printf(" \n"); assign_priority_class(M); //find available SS and SF galaxies on each petal std::vector <int> count_class(M.priority_list.size(),0); for(int i;i<M.size();++i){ count_class[M[i].priority_class]+=1; } for(int i;i<M.priority_list.size();++i){ printf(" class %d number %d\n",i,count_class[i]); } printf(" number of MTL galaxies %d\n",M.size()); printf("Read fiber center positions and compute related things\n"); PP pp; pp.read_fiber_positions(F); F.Nfiber = pp.fp.size()/2; F.Npetal = max(pp.spectrom)+1; printf("spectrometer has to be identified from 0 to F.Npetal-1\n"); F.Nfbp = (int) (F.Nfiber/F.Npetal);// fibers per petal = 500 pp.get_neighbors(F); pp.compute_fibsofsp(F); printf("get neighbors of each fiber;\n"); //for each spectrometer, get list of fibers printf("Read plates in order they are to be observed\n "); Plates P_original = read_plate_centers(F); F.Nplate=P_original.size(); printf("This takes the place of Opsim or NextFieldSelector; will be replaced by appropriate code\n"); Plates P; P.resize(F.Nplate); List permut = random_permut(F.Nplate); for (int jj=0; jj<F.Nplate; jj++){ P[jj]=P_original[permut[jj]]; } printf("# Read %s plate centers from %s and %d fibers from %s\n",f(F.Nplate).c_str(),F.tileFile.c_str(),F.Nfiber,F.fibFile.c_str()); // Computes geometries of cb and fh: pieces of positioner - used to determine possible collisions F.cb = create_cb(); // cb=central body F.fh = create_fh(); // fh=fiber holder //// Collect available galaxies <-> tilefibers -------------------- // HTM Tree of galaxies const double MinTreeSize = 0.01; init_time_at(time,"# Start building HTM tree",t); htmTree<struct target> T(M,MinTreeSize); print_time(time,"# ... took :");//T.stats(); // For plates/fibers, collect available galaxies; done in parallel P[plate j].av_gal[k]=[g1,g2,..] collect_galaxies_for_all(M,T,P,pp,F); // For each galaxy, computes available tilefibers G[i].av_tfs = [(j1,k1),(j2,k2),..] collect_available_tilefibers(M,P,F); //results_on_inputs("doc/figs/",G,P,F,true); //// Assignment ||||||||||||||||||||||||||||||||||||||||||||||||||| printf("before assignment\n"); Assignment A(M,F); print_time(t,"# Start assignment at : "); // Make a plan ---------------------------------------------------- //new_assign_fibers(G,P,pp,F,A); // Plans whole survey without sky fibers, standard stars // assumes maximum number of observations needed for QSOs, LRGs printf(" Nplate %d Ngal %d Nfiber %d \n", F.Nplate, F.Ngal, F.Nfiber); simple_assign(M,P,pp,F,A); diagnostic(M,G,F,A); print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false); // Hist of unused fibs // Want to have even distribution of unused fibers // so we can put in sky fibers and standard stars // Smooth out distribution of free fibers, and increase the number of assignments for (int i=0; i<1; i++) redistribute_tf(M,P,pp,F,A);// more iterations will improve performance slightly for (int i=0; i<1; i++) { // more iterations will improve performance slightly improve(M,P,pp,F,A); redistribute_tf(M,P,pp,F,A); redistribute_tf(M,P,pp,F,A); } for (int i=0; i<1; i++) redistribute_tf(M,P,pp,F,A); print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false); // Still not updated, so all QSO targets have multiple observations etc // Apply and update the plan -------------------------------------- init_time_at(time,"# Begin real time assignment",t); for (int jj=0; jj<F.Nplate; jj++) { int j = A.next_plate; printf(" j == %d \n",j); //assign_sf_ss(j,M,P,pp,F,A); // Assign SS and SF just before an observation //assign_unused(j,M,P,pp,F,A); //if (j%2000==0) pyplotTile(j,"doc/figs",G,P,pp,F,A); // Picture of positioners, galaxies //printf(" %s not as - ",format(5,f(A.unused_f(j,F))).c_str()); fl(); // Update corrects all future occurrences of wrong QSOs etc and tries to observe something else if (0<=j-F.Analysis) update_plan_from_one_obs(G,M,P,pp,F,A,F.Nplate-1); else printf("\n"); A.next_plate++; // Redistribute and improve on various occasions add more times if desired if ( j==2000 || j==4000) { redistribute_tf(M,P,pp,F,A); redistribute_tf(M,P,pp,F,A); improve(M,P,pp,F,A); redistribute_tf(M,P,pp,F,A); diagnostic(M,G,F,A); } } print_time(time,"# ... took :"); // Results ------------------------------------------------------- if (F.Output) for (int j=0; j<F.Nplate; j++) write_FAtile_ascii(j,F.outDir,M,P,pp,F,A); // Write output display_results("doc/figs/",M,P,pp,F,A,true); if (F.Verif) A.verif(P,M,pp,F); // Verification that the assignment is sane print_time(t,"# Finished !... in"); return(0); } <commit_msg>look at 1000 instead of 2000<commit_after>#include <cstdlib> #include <cmath> #include <fstream> #include <sstream> #include <iostream> #include <iomanip> #include <string> #include <vector> #include <algorithm> #include <exception> #include <sys/time.h> #include "modules/htmTree.h" #include "modules/kdTree.h" #include "misc.h" #include "feat.h" #include "structs.h" #include "collision.h" #include "global.h" //reduce redistributes, updates 07/02/15 rnc int main(int argc, char **argv) { //// Initializations --------------------------------------------- srand48(1234); // Make sure we have reproducability check_args(argc); Time t, time; // t for global, time for local init_time(t); Feat F; // Read parameters file // F.readInputFile(argv[1]); printFile(argv[1]); // Read galaxies Gals G; if(F.Ascii){ G=read_galaxies_ascii(F);} else{ G = read_galaxies(F); } F.Ngal = G.size(); printf("# Read %s galaxies from %s \n",f(F.Ngal).c_str(),F.galFile.c_str()); std::vector<int> count; count=count_galaxies(G); for(int i=0;i<8;i++){printf (" %d \n",count[i]);} // make MTL MTL M=make_MTL(G,F); for(int i=0;i<M.priority_list.size();++i){ printf(" priority %d",M.priority_list[i]); } printf(" \n"); assign_priority_class(M); //find available SS and SF galaxies on each petal std::vector <int> count_class(M.priority_list.size(),0); for(int i;i<M.size();++i){ count_class[M[i].priority_class]+=1; } for(int i;i<M.priority_list.size();++i){ printf(" class %d number %d\n",i,count_class[i]); } printf(" number of MTL galaxies %d\n",M.size()); printf("Read fiber center positions and compute related things\n"); PP pp; pp.read_fiber_positions(F); F.Nfiber = pp.fp.size()/2; F.Npetal = max(pp.spectrom)+1; printf("spectrometer has to be identified from 0 to F.Npetal-1\n"); F.Nfbp = (int) (F.Nfiber/F.Npetal);// fibers per petal = 500 pp.get_neighbors(F); pp.compute_fibsofsp(F); printf("get neighbors of each fiber;\n"); //for each spectrometer, get list of fibers printf("Read plates in order they are to be observed\n "); Plates P_original = read_plate_centers(F); F.Nplate=P_original.size(); printf("This takes the place of Opsim or NextFieldSelector; will be replaced by appropriate code\n"); Plates P; P.resize(F.Nplate); List permut = random_permut(F.Nplate); for (int jj=0; jj<F.Nplate; jj++){ P[jj]=P_original[permut[jj]]; } printf("# Read %s plate centers from %s and %d fibers from %s\n",f(F.Nplate).c_str(),F.tileFile.c_str(),F.Nfiber,F.fibFile.c_str()); // Computes geometries of cb and fh: pieces of positioner - used to determine possible collisions F.cb = create_cb(); // cb=central body F.fh = create_fh(); // fh=fiber holder //// Collect available galaxies <-> tilefibers -------------------- // HTM Tree of galaxies const double MinTreeSize = 0.01; init_time_at(time,"# Start building HTM tree",t); htmTree<struct target> T(M,MinTreeSize); print_time(time,"# ... took :");//T.stats(); // For plates/fibers, collect available galaxies; done in parallel P[plate j].av_gal[k]=[g1,g2,..] collect_galaxies_for_all(M,T,P,pp,F); // For each galaxy, computes available tilefibers G[i].av_tfs = [(j1,k1),(j2,k2),..] collect_available_tilefibers(M,P,F); //results_on_inputs("doc/figs/",G,P,F,true); //// Assignment ||||||||||||||||||||||||||||||||||||||||||||||||||| printf("before assignment\n"); Assignment A(M,F); print_time(t,"# Start assignment at : "); // Make a plan ---------------------------------------------------- //new_assign_fibers(G,P,pp,F,A); // Plans whole survey without sky fibers, standard stars // assumes maximum number of observations needed for QSOs, LRGs printf(" Nplate %d Ngal %d Nfiber %d \n", F.Nplate, F.Ngal, F.Nfiber); simple_assign(M,P,pp,F,A); diagnostic(M,G,F,A); print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false); // Hist of unused fibs // Want to have even distribution of unused fibers // so we can put in sky fibers and standard stars // Smooth out distribution of free fibers, and increase the number of assignments for (int i=0; i<1; i++) redistribute_tf(M,P,pp,F,A);// more iterations will improve performance slightly for (int i=0; i<1; i++) { // more iterations will improve performance slightly improve(M,P,pp,F,A); redistribute_tf(M,P,pp,F,A); redistribute_tf(M,P,pp,F,A); } for (int i=0; i<1; i++) redistribute_tf(M,P,pp,F,A); print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false); // Still not updated, so all QSO targets have multiple observations etc // Apply and update the plan -------------------------------------- init_time_at(time,"# Begin real time assignment",t); for (int jj=0; jj<F.Nplate; jj++) { int j = A.next_plate; printf(" j == %d \n",j); //assign_sf_ss(j,M,P,pp,F,A); // Assign SS and SF just before an observation //assign_unused(j,M,P,pp,F,A); //if (j%2000==0) pyplotTile(j,"doc/figs",G,P,pp,F,A); // Picture of positioners, galaxies //printf(" %s not as - ",format(5,f(A.unused_f(j,F))).c_str()); fl(); // Update corrects all future occurrences of wrong QSOs etc and tries to observe something else if (0<=j-F.Analysis) update_plan_from_one_obs(G,M,P,pp,F,A,F.Nplate-1); else printf("\n"); A.next_plate++; // Redistribute and improve on various occasions add more times if desired if ( j==1000 || j==4000) { redistribute_tf(M,P,pp,F,A); redistribute_tf(M,P,pp,F,A); improve(M,P,pp,F,A); redistribute_tf(M,P,pp,F,A); diagnostic(M,G,F,A); } } print_time(time,"# ... took :"); // Results ------------------------------------------------------- if (F.Output) for (int j=0; j<F.Nplate; j++) write_FAtile_ascii(j,F.outDir,M,P,pp,F,A); // Write output display_results("doc/figs/",M,P,pp,F,A,true); if (F.Verif) A.verif(P,M,pp,F); // Verification that the assignment is sane print_time(t,"# Finished !... in"); return(0); } <|endoftext|>
<commit_before>#include "config.h" #include "dbmanager.h" #include "iconmanager.h" #include "mainwindow.h" #include "plugins/pluginmanager.h" #include "sqlhighlighter.h" #include "tabwidget/abstracttabwidget.h" #include "tools/logger.h" #include "widgets/querytextedit.h" #include <QtWidgets/QApplication> #include <QtWidgets/QSplashScreen> int main(int argc, char *argv[]) { QApplication::setApplicationName("dbmaster"); QApplication::setApplicationVersion("0.9.0"); QApplication::setOrganizationDomain("dbmaster.org"); QApplication a(argc, argv); a.setWindowIcon(QIcon(":/img/dbmaster.png")); QSplashScreen splash(QPixmap(":/img/splash.png")); splash.show(); Logger *logger = new Logger; // Loading translations splash.showMessage(QObject::tr("Loading translations..."), Qt::AlignBottom); QTranslator translator; // getting the current locale QString lang = QLocale::system().name().left(2); QString transdir = "."; #if defined(Q_WS_X11) // for *nix transdir = QString(PREFIX).append("/share/dbmaster/tr"); #endif #if defined(Q_OS_MAC) transdir = "DbMaster.app/Contents/MacOS"; #endif QString path; /* on teste d'abord si le .qm est dans le dossier courant -> alors on est en * dev, on le charge, sinon il est dans le répertoire d'installation. */ path = QString("../../dbmaster/tr/%1.qm").arg(lang); if (!QFile::exists(path)) path = transdir.append("/%1.qm").arg(lang); qDebug() << QString("Loaded %1 translation file").arg(path); translator.load(path); a.installTranslator(&translator); path = QLibraryInfo::location(QLibraryInfo::TranslationsPath); #if defined (Q_WS_WIN) path = QDir::currentPath(); #endif QTranslator qtTranslator; qtTranslator.load("qt_" + lang, path); a.installTranslator(&qtTranslator); // Ajout des plugins splash.showMessage(QObject::tr("Loading plugins..."), Qt::AlignBottom); PluginManager::init(); splash.showMessage(QObject::tr("Initialization..."), Qt::AlignBottom); IconManager::init(); DbManager::init(); Config::init(); QueryTextEdit::reloadCompleter(); MainWindow *w = new MainWindow(); w->show(); splash.finish(w); if (a.arguments().size() >= 2) { for (int i=1; i<a.arguments().size(); i++) { w->openQuery(a.arguments()[i]); } } return a.exec(); } <commit_msg>Version number<commit_after>#include "config.h" #include "dbmanager.h" #include "iconmanager.h" #include "mainwindow.h" #include "plugins/pluginmanager.h" #include "sqlhighlighter.h" #include "tabwidget/abstracttabwidget.h" #include "tools/logger.h" #include "widgets/querytextedit.h" #include <QtWidgets/QApplication> #include <QtWidgets/QSplashScreen> int main(int argc, char *argv[]) { QApplication::setApplicationName("dbmaster"); QApplication::setApplicationVersion("0.10.0"); QApplication::setOrganizationDomain("dbmaster.org"); QApplication a(argc, argv); a.setWindowIcon(QIcon(":/img/dbmaster.png")); QSplashScreen splash(QPixmap(":/img/splash.png")); splash.show(); Logger *logger = new Logger; // Loading translations splash.showMessage(QObject::tr("Loading translations..."), Qt::AlignBottom); QTranslator translator; // getting the current locale QString lang = QLocale::system().name().left(2); QString transdir = "."; #if defined(Q_WS_X11) // for *nix transdir = QString(PREFIX).append("/share/dbmaster/tr"); #endif #if defined(Q_OS_MAC) transdir = "DbMaster.app/Contents/MacOS"; #endif QString path; /* on teste d'abord si le .qm est dans le dossier courant -> alors on est en * dev, on le charge, sinon il est dans le répertoire d'installation. */ path = QString("../../dbmaster/tr/%1.qm").arg(lang); if (!QFile::exists(path)) path = transdir.append("/%1.qm").arg(lang); qDebug() << QString("Loaded %1 translation file").arg(path); translator.load(path); a.installTranslator(&translator); path = QLibraryInfo::location(QLibraryInfo::TranslationsPath); #if defined (Q_WS_WIN) path = QDir::currentPath(); #endif QTranslator qtTranslator; qtTranslator.load("qt_" + lang, path); a.installTranslator(&qtTranslator); // Ajout des plugins splash.showMessage(QObject::tr("Loading plugins..."), Qt::AlignBottom); PluginManager::init(); splash.showMessage(QObject::tr("Initialization..."), Qt::AlignBottom); IconManager::init(); DbManager::init(); Config::init(); QueryTextEdit::reloadCompleter(); MainWindow *w = new MainWindow(); w->show(); splash.finish(w); if (a.arguments().size() >= 2) { for (int i=1; i<a.arguments().size(); i++) { w->openQuery(a.arguments()[i]); } } return a.exec(); } <|endoftext|>
<commit_before>/* * Copyright (C) 2010 O01eg <o01eg@yandex.ru> * * This file is part of Genetic Function Programming. * * Genetic Function Programming 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. * * Genetic Function Programming 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 Genetic Function Programming. If not, see <http://www.gnu.org/licenses/>. */ #include <iostream> #include <glibmm/thread.h> #include <csignal> #include <string> #include "ga.h" #include "current_state.h" /// \brief Maximum step for persistent best individuals. const size_t MAX_STEP_UNCHANGED = 4000; bool app_is_run = true; ///< Application's state variable. /// Handler of Ctrl+D event. void close_handler() { while(! std::cin.eof()) { char c; std::cin >> c; } app_is_run = false; } /// \brief Handler of Ctrl+C event. /// \param signum Number of signal. void interrupt_handler(int signum) { CurrentState::Dump(); app_is_run = false; } /// \brief Main Function. /// \param argc Number of arguments. /// \param argv Array of arguments. /// \return Exit code. int main(int argc, char **argv) { #if 1 signal(SIGINT, interrupt_handler); #endif Glib::thread_init(); #if 0 Glib::Thread::create(sigc::ptr_fun(close_handler), false); #endif time_t seed = time(NULL); std::cout << "seed = " << seed << std::endl; srand(seed); char *filename = NULL; if(argc == 2) { filename = argv[1]; } // Start application. std::clog << "Start application" << std::endl; try { #if 0 VM::Environment env; env.LoadFunctions(DATA_DIR "functions.txt"); try { VM::Program prog(env, DATA_DIR "2.lsp"); env.program = &prog; const size_t MAX_CIRCLES = 1000; VM::Object a(env); std::cin >> a; env.circle_count = MAX_CIRCLES; std::cout << "result = " << env.Run(a) << std::endl; std::cout << "use " << (MAX_CIRCLES - env.circle_count) << " circles" << std::endl; } catch(Glib::Error &e) { std::clog << "Catch Glib::Error in environment: " << e.what() << std::endl; } #endif // Genetic programming GA ga(20); if(filename) { try { ga.Load(filename); } catch(std::exception &e) { std::clog << "Catch std::exception: " << e.what() << std::endl; } catch(Glib::Error &e) { std::clog << "Catch Glib::Error: " << e.what() << std::endl; } } std::cout << "Start evolution" << std::endl; size_t remain_steps = MAX_STEP_UNCHANGED; size_t generation = 0; std::vector<GA::Operation> operations; operations.push_back(GA::Mutation(0)); operations.push_back(GA::Mutation(1)); operations.push_back(GA::Mutation(2)); operations.push_back(GA::Mutation(3)); operations.push_back(GA::Mutation(4)); operations.push_back(GA::Mutation(5)); operations.push_back(GA::Crossover(0, 1)); operations.push_back(GA::Crossover(0, 1)); operations.push_back(GA::Crossover(0, 2)); operations.push_back(GA::Crossover(0, 3)); operations.push_back(GA::Crossover(0, 4)); operations.push_back(GA::Crossover(1, 2)); operations.push_back(GA::Crossover(1, 3)); operations.push_back(GA::Crossover(2, 3)); while((remain_steps > 0) && app_is_run) { CurrentState::s_Generation = generation; if(ga.Step(operations)) { std::clog << "Better." << std::endl; remain_steps = MAX_STEP_UNCHANGED; std::clog << "best = " << ga.GetBest().GetText() << std::endl; std::clog << "result = " << ga.GetBest().GetResult().m_Result; std::clog << "result[MOVE_CHANGES] = " << ga.GetBest().GetResult().m_Quality[Individual::Result::ST_MOVE_CHANGES] << std::endl; std::clog << "result[STATIC_CHECK] = " << ga.GetBest().GetResult().m_Quality[Individual::Result::ST_STATIC_CHECK] << std::endl; std::clog << "result[GOOD_MOVES] = " << ga.GetBest().GetResult().m_Quality[Individual::Result::ST_GOOD_MOVES] << std::endl; std::clog << "result[BAD_MOVES] = " << ga.GetBest().GetResult().m_Quality[Individual::Result::ST_BAD_MOVES] << std::endl; std::clog << "result[ANSWER_QUALITY] = " << ga.GetBest().GetResult().m_Quality[Individual::Result::ST_ANSWER_QUALITY] << std::endl; std::clog << "result[ANSWER_CHANGES] = " << ga.GetBest().GetResult().m_Quality[Individual::Result::ST_ANSWER_CHANGES] << std::endl; std::clog << "result[MOVE_DIFF] = " << ga.GetBest().GetResult().m_Quality[Individual::Result::ST_MOVE_DIFF] << std::endl; std::clog << "result[DIR_DIFF] = " << ga.GetBest().GetResult().m_Quality[Individual::Result::ST_DIR_DIFF] << std::endl; std::clog << "result[STATE_CHANGES] = " << ga.GetBest().GetResult().m_Quality[Individual::Result::ST_STATE_CHANGES] << std::endl; std::clog << "result[NEG_CIRCLES] = " << ga.GetBest().GetResult().m_Quality[Individual::Result::ST_NEG_CIRCLES] << std::endl; } else { remain_steps --; //std::cout << "steps: " << remain_steps << std::endl; } generation ++; if(generation % 100 == 0) { std::cout << "generation = " << generation << std::endl; } } std::clog << "best = " << ga.GetBest().GetText() << std::endl; if(filename) { ga.Save(filename); } } catch(std::exception &e) { std::clog << "Catch std::exception: " << e.what() << std::endl; } catch(Glib::Error &e) { std::clog << "Catch Glib::Error: " << e.what() << std::endl; } // Finish application. std::clog << "Finish application" << std::endl; return 0; } <commit_msg>More individuals.<commit_after>/* * Copyright (C) 2010 O01eg <o01eg@yandex.ru> * * This file is part of Genetic Function Programming. * * Genetic Function Programming 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. * * Genetic Function Programming 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 Genetic Function Programming. If not, see <http://www.gnu.org/licenses/>. */ #include <iostream> #include <glibmm/thread.h> #include <csignal> #include <string> #include "ga.h" #include "current_state.h" /// \brief Maximum step for persistent best individuals. const size_t MAX_STEP_UNCHANGED = 10000; bool app_is_run = true; ///< Application's state variable. /// Handler of Ctrl+D event. void close_handler() { while(! std::cin.eof()) { char c; std::cin >> c; } app_is_run = false; } /// \brief Handler of Ctrl+C event. /// \param signum Number of signal. void interrupt_handler(int signum) { CurrentState::Dump(); app_is_run = false; } /// \brief Main Function. /// \param argc Number of arguments. /// \param argv Array of arguments. /// \return Exit code. int main(int argc, char **argv) { #if 1 signal(SIGINT, interrupt_handler); #endif Glib::thread_init(); #if 0 Glib::Thread::create(sigc::ptr_fun(close_handler), false); #endif time_t seed = time(NULL); std::cout << "seed = " << seed << std::endl; srand(seed); char *filename = NULL; if(argc == 2) { filename = argv[1]; } // Start application. std::clog << "Start application" << std::endl; try { #if 0 VM::Environment env; env.LoadFunctions(DATA_DIR "functions.txt"); try { VM::Program prog(env, DATA_DIR "2.lsp"); env.program = &prog; const size_t MAX_CIRCLES = 1000; VM::Object a(env); std::cin >> a; env.circle_count = MAX_CIRCLES; std::cout << "result = " << env.Run(a) << std::endl; std::cout << "use " << (MAX_CIRCLES - env.circle_count) << " circles" << std::endl; } catch(Glib::Error &e) { std::clog << "Catch Glib::Error in environment: " << e.what() << std::endl; } #endif // Genetic programming GA ga(24); if(filename) { try { ga.Load(filename); } catch(std::exception &e) { std::clog << "Catch std::exception: " << e.what() << std::endl; } catch(Glib::Error &e) { std::clog << "Catch Glib::Error: " << e.what() << std::endl; } } std::cout << "Start evolution" << std::endl; size_t remain_steps = MAX_STEP_UNCHANGED; size_t generation = 0; std::vector<GA::Operation> operations; operations.push_back(GA::Mutation(0)); operations.push_back(GA::Mutation(0)); operations.push_back(GA::Mutation(0)); operations.push_back(GA::Mutation(1)); operations.push_back(GA::Mutation(1)); operations.push_back(GA::Mutation(2)); operations.push_back(GA::Mutation(3)); operations.push_back(GA::Mutation(4)); operations.push_back(GA::Mutation(5)); operations.push_back(GA::Crossover(0, 1)); operations.push_back(GA::Crossover(0, 1)); operations.push_back(GA::Crossover(0, 2)); operations.push_back(GA::Crossover(0, 3)); operations.push_back(GA::Crossover(0, 4)); operations.push_back(GA::Crossover(1, 2)); operations.push_back(GA::Crossover(1, 3)); operations.push_back(GA::Crossover(2, 3)); while((remain_steps > 0) && app_is_run) { CurrentState::s_Generation = generation; if(ga.Step(operations)) { std::clog << "Better." << std::endl; remain_steps = MAX_STEP_UNCHANGED; std::clog << "best = " << ga.GetBest().GetText() << std::endl; std::clog << "result = " << ga.GetBest().GetResult().m_Result; std::clog << "result[MOVE_CHANGES] = " << ga.GetBest().GetResult().m_Quality[Individual::Result::ST_MOVE_CHANGES] << std::endl; std::clog << "result[STATIC_CHECK] = " << ga.GetBest().GetResult().m_Quality[Individual::Result::ST_STATIC_CHECK] << std::endl; std::clog << "result[GOOD_MOVES] = " << ga.GetBest().GetResult().m_Quality[Individual::Result::ST_GOOD_MOVES] << std::endl; std::clog << "result[BAD_MOVES] = " << ga.GetBest().GetResult().m_Quality[Individual::Result::ST_BAD_MOVES] << std::endl; std::clog << "result[ANSWER_QUALITY] = " << ga.GetBest().GetResult().m_Quality[Individual::Result::ST_ANSWER_QUALITY] << std::endl; std::clog << "result[ANSWER_CHANGES] = " << ga.GetBest().GetResult().m_Quality[Individual::Result::ST_ANSWER_CHANGES] << std::endl; std::clog << "result[MOVE_DIFF] = " << ga.GetBest().GetResult().m_Quality[Individual::Result::ST_MOVE_DIFF] << std::endl; std::clog << "result[DIR_DIFF] = " << ga.GetBest().GetResult().m_Quality[Individual::Result::ST_DIR_DIFF] << std::endl; std::clog << "result[STATE_CHANGES] = " << ga.GetBest().GetResult().m_Quality[Individual::Result::ST_STATE_CHANGES] << std::endl; std::clog << "result[NEG_CIRCLES] = " << ga.GetBest().GetResult().m_Quality[Individual::Result::ST_NEG_CIRCLES] << std::endl; } else { remain_steps --; //std::cout << "steps: " << remain_steps << std::endl; } generation ++; if(generation % 100 == 0) { std::cout << "generation = " << generation << std::endl; } } std::clog << "best = " << ga.GetBest().GetText() << std::endl; if(filename) { ga.Save(filename); } } catch(std::exception &e) { std::clog << "Catch std::exception: " << e.what() << std::endl; } catch(Glib::Error &e) { std::clog << "Catch Glib::Error: " << e.what() << std::endl; } // Finish application. std::clog << "Finish application" << std::endl; return 0; } <|endoftext|>
<commit_before>/** Copyright (C) 2013 David Braam - Released under terms of the AGPLv3 License */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/time.h> #include <signal.h> #if defined(__linux__) || (defined(__APPLE__) && defined(__MACH__)) #include <execinfo.h> #include <sys/resource.h> #endif #include <stddef.h> #include <vector> #include "utils/gettime.h" #include "utils/logoutput.h" #include "sliceDataStorage.h" #include "modelFile/modelFile.h" #include "settings.h" #include "optimizedModel.h" #include "multiVolumes.h" #include "polygonOptimizer.h" #include "slicer.h" #include "layerPart.h" #include "inset.h" #include "skin.h" #include "infill.h" #include "bridge.h" #include "support.h" #include "pathOrderOptimizer.h" #include "skirt.h" #include "raft.h" #include "comb.h" #include "gcodeExport.h" #include "fffProcessor.h" void print_usage() { cura::logError("usage: CuraEngine [-h] [-v] [-m 3x3matrix] [-c <config file>] [-s <settingkey>=<value>] -o <output.gcode> <model.stl>\n"); } //Signal handler for a "floating point exception", which can also be integer division by zero errors. void signal_FPE(int n) { (void)n; cura::logError("Arithmetic exception.\n"); exit(1); } using namespace cura; int main(int argc, char **argv) { #if defined(__linux__) || (defined(__APPLE__) && defined(__MACH__)) //Lower the process priority on linux and mac. On windows this is done on process creation from the GUI. setpriority(PRIO_PROCESS, 0, 10); #endif //Register the exception handling for arithmic exceptions, this prevents the "something went wrong" dialog on windows to pop up on a division by zero. signal(SIGFPE, signal_FPE); ConfigSettings config; fffProcessor processor(config); std::vector<std::string> files; cura::logError("Cura_SteamEngine version %s\n", VERSION); cura::logError("Copyright (C) 2014 David Braam\n"); cura::logError("\n"); cura::logError("This program is free software: you can redistribute it and/or modify\n"); cura::logError("it under the terms of the GNU Affero General Public License as published by\n"); cura::logError("the Free Software Foundation, either version 3 of the License, or\n"); cura::logError("(at your option) any later version.\n"); cura::logError("\n"); cura::logError("This program is distributed in the hope that it will be useful,\n"); cura::logError("but WITHOUT ANY WARRANTY; without even the implied warranty of\n"); cura::logError("MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n"); cura::logError("GNU Affero General Public License for more details.\n"); cura::logError("\n"); cura::logError("You should have received a copy of the GNU Affero General Public License\n"); cura::logError("along with this program. If not, see <http://www.gnu.org/licenses/>.\n"); if(!config.readSettings()) { cura::logError("Default config '%s' not used\n", DEFAULT_CONFIG_PATH); } for(int argn = 1; argn < argc; argn++) cura::log("Arg: %s\n", argv[argn]); for(int argn = 1; argn < argc; argn++) { char* str = argv[argn]; if (str[0] == '-') { for(str++; *str; str++) { switch(*str) { case 'h': print_usage(); exit(1); case 'v': cura::increaseVerboseLevel(); break; case 'p': cura::enableProgressLogging(); break; case 'g': argn++; //Connect the GUI socket to the given port number. processor.guiConnect(atoi(argv[argn])); break; case 'b': argn++; //The binaryMeshBlob is depricated and will be removed in the future. binaryMeshBlob = fopen(argv[argn], "rb"); break; case 'o': argn++; if (!processor.setTargetFile(argv[argn])) { cura::logError("Failed to open %s for output.\n", argv[argn]); exit(1); } break; case 'c': { // Read a config file from the given path argn++; if(!config.readSettings(argv[argn])) { cura::logError("Failed to read config '%s'\n", argv[argn]); } } break; case 's': { //Parse the given setting and store it. argn++; char* valuePtr = strchr(argv[argn], '='); if (valuePtr) { *valuePtr++ = '\0'; if (!config.setSetting(argv[argn], valuePtr)) cura::logError("Setting not found: %s %s\n", argv[argn], valuePtr); } } break; case 'm': //Read the given rotation/scale matrix argn++; sscanf(argv[argn], "%lf,%lf,%lf,%lf,%lf,%lf,%lf,%lf,%lf", &config.matrix.m[0][0], &config.matrix.m[0][1], &config.matrix.m[0][2], &config.matrix.m[1][0], &config.matrix.m[1][1], &config.matrix.m[1][2], &config.matrix.m[2][0], &config.matrix.m[2][1], &config.matrix.m[2][2]); break; default: cura::logError("Unknown option: %c\n", *str); break; } } }else{ if (argv[argn][0] == '$') { try { //Catch all exceptions, this prevents the "something went wrong" dialog on windows to pop up on a thrown exception. // Only ClipperLib currently throws exceptions. And only in case that it makes an internal error. std::vector<std::string> tmp; tmp.push_back(argv[argn]); processor.processFile(tmp); }catch(...){ cura::logError("Unknown exception\n"); exit(1); } }else{ files.push_back(argv[argn]); } } } try { //Catch all exceptions, this prevents the "something went wrong" dialog on windows to pop up on a thrown exception. // Only ClipperLib currently throws exceptions. And only in case that it makes an internal error. if (files.size() > 0) processor.processFile(files); }catch(...){ cura::logError("Unknown exception\n"); exit(1); } //Finalize the processor, this adds the end.gcode. And reports statistics. processor.finalize(); return 0; } <commit_msg>On -- process the current file, which allows for one-at-a-time printing from the commandline.<commit_after>/** Copyright (C) 2013 David Braam - Released under terms of the AGPLv3 License */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/time.h> #include <signal.h> #if defined(__linux__) || (defined(__APPLE__) && defined(__MACH__)) #include <execinfo.h> #include <sys/resource.h> #endif #include <stddef.h> #include <vector> #include "utils/gettime.h" #include "utils/logoutput.h" #include "sliceDataStorage.h" #include "modelFile/modelFile.h" #include "settings.h" #include "optimizedModel.h" #include "multiVolumes.h" #include "polygonOptimizer.h" #include "slicer.h" #include "layerPart.h" #include "inset.h" #include "skin.h" #include "infill.h" #include "bridge.h" #include "support.h" #include "pathOrderOptimizer.h" #include "skirt.h" #include "raft.h" #include "comb.h" #include "gcodeExport.h" #include "fffProcessor.h" void print_usage() { cura::logError("usage: CuraEngine [-h] [-v] [-m 3x3matrix] [-c <config file>] [-s <settingkey>=<value>] -o <output.gcode> <model.stl>\n"); } //Signal handler for a "floating point exception", which can also be integer division by zero errors. void signal_FPE(int n) { (void)n; cura::logError("Arithmetic exception.\n"); exit(1); } using namespace cura; int main(int argc, char **argv) { #if defined(__linux__) || (defined(__APPLE__) && defined(__MACH__)) //Lower the process priority on linux and mac. On windows this is done on process creation from the GUI. setpriority(PRIO_PROCESS, 0, 10); #endif //Register the exception handling for arithmic exceptions, this prevents the "something went wrong" dialog on windows to pop up on a division by zero. signal(SIGFPE, signal_FPE); ConfigSettings config; fffProcessor processor(config); std::vector<std::string> files; cura::logError("Cura_SteamEngine version %s\n", VERSION); cura::logError("Copyright (C) 2014 David Braam\n"); cura::logError("\n"); cura::logError("This program is free software: you can redistribute it and/or modify\n"); cura::logError("it under the terms of the GNU Affero General Public License as published by\n"); cura::logError("the Free Software Foundation, either version 3 of the License, or\n"); cura::logError("(at your option) any later version.\n"); cura::logError("\n"); cura::logError("This program is distributed in the hope that it will be useful,\n"); cura::logError("but WITHOUT ANY WARRANTY; without even the implied warranty of\n"); cura::logError("MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n"); cura::logError("GNU Affero General Public License for more details.\n"); cura::logError("\n"); cura::logError("You should have received a copy of the GNU Affero General Public License\n"); cura::logError("along with this program. If not, see <http://www.gnu.org/licenses/>.\n"); if(!config.readSettings()) { cura::logError("Default config '%s' not used\n", DEFAULT_CONFIG_PATH); } for(int argn = 1; argn < argc; argn++) cura::log("Arg: %s\n", argv[argn]); for(int argn = 1; argn < argc; argn++) { char* str = argv[argn]; if (str[0] == '-') { for(str++; *str; str++) { switch(*str) { case 'h': print_usage(); exit(1); case 'v': cura::increaseVerboseLevel(); break; case 'p': cura::enableProgressLogging(); break; case 'g': argn++; //Connect the GUI socket to the given port number. processor.guiConnect(atoi(argv[argn])); break; case 'b': argn++; //The binaryMeshBlob is depricated and will be removed in the future. binaryMeshBlob = fopen(argv[argn], "rb"); break; case 'o': argn++; if (!processor.setTargetFile(argv[argn])) { cura::logError("Failed to open %s for output.\n", argv[argn]); exit(1); } break; case 'c': { // Read a config file from the given path argn++; if(!config.readSettings(argv[argn])) { cura::logError("Failed to read config '%s'\n", argv[argn]); } } break; case 's': { //Parse the given setting and store it. argn++; char* valuePtr = strchr(argv[argn], '='); if (valuePtr) { *valuePtr++ = '\0'; if (!config.setSetting(argv[argn], valuePtr)) cura::logError("Setting not found: %s %s\n", argv[argn], valuePtr); } } break; case 'm': //Read the given rotation/scale matrix argn++; sscanf(argv[argn], "%lf,%lf,%lf,%lf,%lf,%lf,%lf,%lf,%lf", &config.matrix.m[0][0], &config.matrix.m[0][1], &config.matrix.m[0][2], &config.matrix.m[1][0], &config.matrix.m[1][1], &config.matrix.m[1][2], &config.matrix.m[2][0], &config.matrix.m[2][1], &config.matrix.m[2][2]); break; case '-': try { //Catch all exceptions, this prevents the "something went wrong" dialog on windows to pop up on a thrown exception. // Only ClipperLib currently throws exceptions. And only in case that it makes an internal error. if (files.size() > 0) processor.processFile(files); files.clear(); }catch(...){ cura::logError("Unknown exception\n"); exit(1); } break; default: cura::logError("Unknown option: %c\n", *str); break; } } }else{ if (argv[argn][0] == '$') { try { //Catch all exceptions, this prevents the "something went wrong" dialog on windows to pop up on a thrown exception. // Only ClipperLib currently throws exceptions. And only in case that it makes an internal error. std::vector<std::string> tmp; tmp.push_back(argv[argn]); processor.processFile(tmp); }catch(...){ cura::logError("Unknown exception\n"); exit(1); } }else{ files.push_back(argv[argn]); } } } try { //Catch all exceptions, this prevents the "something went wrong" dialog on windows to pop up on a thrown exception. // Only ClipperLib currently throws exceptions. And only in case that it makes an internal error. if (files.size() > 0) processor.processFile(files); }catch(...){ cura::logError("Unknown exception\n"); exit(1); } //Finalize the processor, this adds the end.gcode. And reports statistics. processor.finalize(); return 0; } <|endoftext|>
<commit_before>#include <cstdlib> #include <cmath> #include <fstream> #include <sstream> #include <iostream> #include <iomanip> #include <string> #include <vector> #include <algorithm> #include <exception> #include <sys/time.h> #include "modules/htmTree.h" #include "modules/kdTree.h" #include "misc.h" #include "feat.h" #include "structs.h" #include "collision.h" #include "global.h" //reduce redistributes, updates 07/02/15 rnc int main(int argc, char **argv) { //// Initializations --------------------------------------------- srand48(1234); // Make sure we have reproducability check_args(argc); Time t, time; // t for global, time for local init_time(t); Feat F; // Read parameters file // F.readInputFile(argv[1]); printFile(argv[1]); // Read galaxies Gals G; if(F.Ascii){ G=read_galaxies_ascii(F);} else{ G = read_galaxies(F); } F.Ngal = G.size(); printf("# Read %s galaxies from %s \n",f(F.Ngal).c_str(),F.galFile.c_str()); std::vector<int> count; count=count_galaxies(G); for(int i=0;i<8;i++){printf (" %d \n",count[i]);} // make MTL MTL M=make_MTL(G,F); for(int i=0;i<M.priority_list.size();++i){ printf(" priority %d",M.priority_list[i]); } printf(" \n"); assign_priority_class(M); //find available SS and SF galaxies on each petal std::vector <int> count_class(M.priority_list.size(),0); for(int i;i<M.size();++i){ count_class[M[i].priority_class]+=1; } for(int i;i<M.priority_list.size();++i){ printf(" class %d number %d\n",i,count_class[i]); } printf(" number of MTL galaxies %d\n",M.size()); printf("Read fiber center positions and compute related things\n"); PP pp; pp.read_fiber_positions(F); F.Nfiber = pp.fp.size()/2; F.Npetal = max(pp.spectrom)+1; printf("spectrometer has to be identified from 0 to F.Npetal-1\n"); F.Nfbp = (int) (F.Nfiber/F.Npetal);// fibers per petal = 500 pp.get_neighbors(F); pp.compute_fibsofsp(F); printf("get neighbors of each fiber;\n"); //for each spectrometer, get list of fibers printf("Read plates in order they are to be observed\n "); Plates P_original = read_plate_centers(F); F.Nplate=P_original.size(); printf("This takes the place of Opsim or NextFieldSelector; will be replaced by appropriate code\n"); Plates P; P.resize(F.Nplate); List permut = random_permut(F.Nplate); for (int jj=0; jj<F.Nplate; jj++){ P[jj]=P_original[permut[jj]]; } printf("# Read %s plate centers from %s and %d fibers from %s\n",f(F.Nplate).c_str(),F.tileFile.c_str(),F.Nfiber,F.fibFile.c_str()); // Computes geometries of cb and fh: pieces of positioner - used to determine possible collisions F.cb = create_cb(); // cb=central body F.fh = create_fh(); // fh=fiber holder //// Collect available galaxies <-> tilefibers -------------------- // HTM Tree of galaxies const double MinTreeSize = 0.01; init_time_at(time,"# Start building HTM tree",t); htmTree<struct target> T(M,MinTreeSize); print_time(time,"# ... took :");//T.stats(); // For plates/fibers, collect available galaxies; done in parallel P[plate j].av_gal[k]=[g1,g2,..] collect_galaxies_for_all(M,T,P,pp,F); // For each galaxy, computes available tilefibers G[i].av_tfs = [(j1,k1),(j2,k2),..] collect_available_tilefibers(M,P,F); //results_on_inputs("doc/figs/",G,P,F,true); //// Assignment ||||||||||||||||||||||||||||||||||||||||||||||||||| printf("before assignment\n"); Assignment A(M,F); print_time(t,"# Start assignment at : "); // Make a plan ---------------------------------------------------- //new_assign_fibers(G,P,pp,F,A); // Plans whole survey without sky fibers, standard stars // assumes maximum number of observations needed for QSOs, LRGs printf(" Nplate %d Ngal %d Nfiber %d \n", F.Nplate, F.Ngal, F.Nfiber); simple_assign(M,P,pp,F,A); diagnostic(M,G,F,A); print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false); // Hist of unused fibs // Want to have even distribution of unused fibers // so we can put in sky fibers and standard stars // Smooth out distribution of free fibers, and increase the number of assignments for (int i=0; i<1; i++) redistribute_tf(M,P,pp,F,A);// more iterations will improve performance slightly for (int i=0; i<1; i++) { // more iterations will improve performance slightly improve(M,P,pp,F,A); redistribute_tf(M,P,pp,F,A); redistribute_tf(M,P,pp,F,A); } for (int i=0; i<1; i++) redistribute_tf(M,P,pp,F,A); print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false); // Still not updated, so all QSO targets have multiple observations etc // Apply and update the plan -------------------------------------- init_time_at(time,"# Begin real time assignment",t); for (int jj=0; jj<F.Nplate; jj++) { int j = A.next_plate; printf(" j == %d \n",j); //assign_sf_ss(j,M,P,pp,F,A); // Assign SS and SF just before an observation //assign_unused(j,M,P,pp,F,A); //if (j%2000==0) pyplotTile(j,"doc/figs",G,P,pp,F,A); // Picture of positioners, galaxies //printf(" %s not as - ",format(5,f(A.unused_f(j,F))).c_str()); fl(); // Update corrects all future occurrences of wrong QSOs etc and tries to observe something else if (0<=j-F.Analysis) update_plan_from_one_obs(G,M,P,pp,F,A,F.Nplate-1); else printf("\n"); A.next_plate++; // Redistribute and improve on various occasions add more times if desired if ( j==1000 || j==4000) { redistribute_tf(M,P,pp,F,A); redistribute_tf(M,P,pp,F,A); improve(M,P,pp,F,A); redistribute_tf(M,P,pp,F,A); diagnostic(M,G,F,A); } } print_time(time,"# ... took :"); // Results ------------------------------------------------------- if (F.Output) for (int j=0; j<F.Nplate; j++) write_FAtile_ascii(j,F.outDir,M,P,pp,F,A); // Write output display_results("doc/figs/",M,P,pp,F,A,true); if (F.Verif) A.verif(P,M,pp,F); // Verification that the assignment is sane print_time(t,"# Finished !... in"); return(0); } <commit_msg>remove diagnostic<commit_after>#include <cstdlib> #include <cmath> #include <fstream> #include <sstream> #include <iostream> #include <iomanip> #include <string> #include <vector> #include <algorithm> #include <exception> #include <sys/time.h> #include "modules/htmTree.h" #include "modules/kdTree.h" #include "misc.h" #include "feat.h" #include "structs.h" #include "collision.h" #include "global.h" //reduce redistributes, updates 07/02/15 rnc int main(int argc, char **argv) { //// Initializations --------------------------------------------- srand48(1234); // Make sure we have reproducability check_args(argc); Time t, time; // t for global, time for local init_time(t); Feat F; // Read parameters file // F.readInputFile(argv[1]); printFile(argv[1]); // Read galaxies Gals G; if(F.Ascii){ G=read_galaxies_ascii(F);} else{ G = read_galaxies(F); } F.Ngal = G.size(); printf("# Read %s galaxies from %s \n",f(F.Ngal).c_str(),F.galFile.c_str()); std::vector<int> count; count=count_galaxies(G); for(int i=0;i<8;i++){printf (" %d \n",count[i]);} // make MTL MTL M=make_MTL(G,F); for(int i=0;i<M.priority_list.size();++i){ printf(" priority %d",M.priority_list[i]); } printf(" \n"); assign_priority_class(M); //find available SS and SF galaxies on each petal std::vector <int> count_class(M.priority_list.size(),0); for(int i;i<M.size();++i){ count_class[M[i].priority_class]+=1; } for(int i;i<M.priority_list.size();++i){ printf(" class %d number %d\n",i,count_class[i]); } printf(" number of MTL galaxies %d\n",M.size()); printf("Read fiber center positions and compute related things\n"); PP pp; pp.read_fiber_positions(F); F.Nfiber = pp.fp.size()/2; F.Npetal = max(pp.spectrom)+1; printf("spectrometer has to be identified from 0 to F.Npetal-1\n"); F.Nfbp = (int) (F.Nfiber/F.Npetal);// fibers per petal = 500 pp.get_neighbors(F); pp.compute_fibsofsp(F); printf("get neighbors of each fiber;\n"); //for each spectrometer, get list of fibers printf("Read plates in order they are to be observed\n "); Plates P_original = read_plate_centers(F); F.Nplate=P_original.size(); printf("This takes the place of Opsim or NextFieldSelector; will be replaced by appropriate code\n"); Plates P; P.resize(F.Nplate); List permut = random_permut(F.Nplate); for (int jj=0; jj<F.Nplate; jj++){ P[jj]=P_original[permut[jj]]; } printf("# Read %s plate centers from %s and %d fibers from %s\n",f(F.Nplate).c_str(),F.tileFile.c_str(),F.Nfiber,F.fibFile.c_str()); // Computes geometries of cb and fh: pieces of positioner - used to determine possible collisions F.cb = create_cb(); // cb=central body F.fh = create_fh(); // fh=fiber holder //// Collect available galaxies <-> tilefibers -------------------- // HTM Tree of galaxies const double MinTreeSize = 0.01; init_time_at(time,"# Start building HTM tree",t); htmTree<struct target> T(M,MinTreeSize); print_time(time,"# ... took :");//T.stats(); // For plates/fibers, collect available galaxies; done in parallel P[plate j].av_gal[k]=[g1,g2,..] collect_galaxies_for_all(M,T,P,pp,F); // For each galaxy, computes available tilefibers G[i].av_tfs = [(j1,k1),(j2,k2),..] collect_available_tilefibers(M,P,F); //results_on_inputs("doc/figs/",G,P,F,true); //// Assignment ||||||||||||||||||||||||||||||||||||||||||||||||||| printf("before assignment\n"); Assignment A(M,F); print_time(t,"# Start assignment at : "); // Make a plan ---------------------------------------------------- //new_assign_fibers(G,P,pp,F,A); // Plans whole survey without sky fibers, standard stars // assumes maximum number of observations needed for QSOs, LRGs printf(" Nplate %d Ngal %d Nfiber %d \n", F.Nplate, F.Ngal, F.Nfiber); simple_assign(M,P,pp,F,A); diagnostic(M,G,F,A); print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false); // Hist of unused fibs // Want to have even distribution of unused fibers // so we can put in sky fibers and standard stars // Smooth out distribution of free fibers, and increase the number of assignments for (int i=0; i<1; i++) redistribute_tf(M,P,pp,F,A);// more iterations will improve performance slightly for (int i=0; i<1; i++) { // more iterations will improve performance slightly improve(M,P,pp,F,A); redistribute_tf(M,P,pp,F,A); redistribute_tf(M,P,pp,F,A); } for (int i=0; i<1; i++) redistribute_tf(M,P,pp,F,A); print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false); // Still not updated, so all QSO targets have multiple observations etc // Apply and update the plan -------------------------------------- init_time_at(time,"# Begin real time assignment",t); for (int jj=0; jj<F.Nplate; jj++) { int j = A.next_plate; printf(" j == %d \n",j); //assign_sf_ss(j,M,P,pp,F,A); // Assign SS and SF just before an observation //assign_unused(j,M,P,pp,F,A); //if (j%2000==0) pyplotTile(j,"doc/figs",G,P,pp,F,A); // Picture of positioners, galaxies //printf(" %s not as - ",format(5,f(A.unused_f(j,F))).c_str()); fl(); // Update corrects all future occurrences of wrong QSOs etc and tries to observe something else if (0<=j-F.Analysis) update_plan_from_one_obs(G,M,P,pp,F,A,F.Nplate-1); else printf("\n"); A.next_plate++; // Redistribute and improve on various occasions add more times if desired if ( j==1000 || j==4000) { redistribute_tf(M,P,pp,F,A); redistribute_tf(M,P,pp,F,A); improve(M,P,pp,F,A); redistribute_tf(M,P,pp,F,A); //diagnostic(M,G,F,A); } } print_time(time,"# ... took :"); // Results ------------------------------------------------------- if (F.Output) for (int j=0; j<F.Nplate; j++) write_FAtile_ascii(j,F.outDir,M,P,pp,F,A); // Write output display_results("doc/figs/",M,P,pp,F,A,true); if (F.Verif) A.verif(P,M,pp,F); // Verification that the assignment is sane print_time(t,"# Finished !... in"); return(0); } <|endoftext|>
<commit_before>#ifndef _NODE_H #define _NODE_H class Node{ private: union Content{ double idX; //var double value; //const int function; //func1 ou func2 }; //não sei se enum e union deveriam ser globais ou declaradas dentro //do node. A principio, acho que não é de interesse de nenhuma outra //função acessar estas informação, mas pode ser que eu esteja enganado. Content C; int tipo; Node *left; Node *right; public: Node(); ~Node(); //double eval(vector<double> input); void print_node_d(); Node *get_copy(); }; #endif<commit_msg>1.2 Adicionado função eval<commit_after>#ifndef _NODE_H #define _NODE_H #include <vector> class Node{ private: union Content{ double idX; //var double value; //const int function; //func1 ou func2 }; //não sei se enum e union deveriam ser globais ou declaradas dentro //do node. A principio, acho que não é de interesse de nenhuma outra //função acessar estas informação, mas pode ser que eu esteja enganado. Content C; int tipo; //recebe o índice do content Node *left; Node *right; public: Node(); ~Node(); double eval(std::vector<double> x); void print_node_d(); Node *get_copy(); }; #endif <|endoftext|>
<commit_before>#include "Variant.h" #include "split.h" #include "cdflib.hpp" #include "pdflib.hpp" #include <string> #include <iostream> #include <math.h> #include <cmath> #include <stdlib.h> #include <time.h> #include <stdio.h> #include <getopt.h> using namespace std; using namespace vcf; struct pop{ double nalt ; double nref ; double af ; double nhomr; double nhoma; double nhet ; double ngeno; double fis ; vector<int> geno_index ; vector< vector< double > > unphred_p; }; struct popPool : pop{ double nalt ; double nref ; double af ; double npop ; double ntot ; vector<double> nalts; vector<double> nrefs; }; double unphred(string phred){ double unphred = atof(phred.c_str()); unphred = unphred / -10; return unphred; } void initPop(pop & population){ population.nalt = 0; population.nref = 0; population.af = 0; population.nhomr = 0; population.nhoma = 0; population.nhet = 0; population.ngeno = 0; population.fis = 0; } void initPop(popPool & population){ population.nalt = 0; population.nref = 0; population.npop = 0; population.ntot = 0; } void loadPop( vector< map< string, vector<string> > >& group, pop & population){ vector< map< string, vector<string> > >::iterator targ_it = group.begin(); for(; targ_it != group.end(); targ_it++){ string genotype = (*targ_it)["GT"].front(); if(genotype != "./."){ vector<double> phreds; phreds.push_back( unphred((*targ_it)["PL"][0])); phreds.push_back( unphred((*targ_it)["PL"][1])); phreds.push_back( unphred((*targ_it)["PL"][2])); population.unphred_p.push_back(phreds); } while(1){ if(genotype == "0/0"){ population.ngeno += 1; population.nhomr += 1; population.nref += 2; population.geno_index.push_back(0); break; } if(genotype == "0/1"){ population.ngeno += 1; population.nhet += 1; population.nref += 1; population.nalt += 1; population.geno_index.push_back(1); break; } if(genotype == "1/1"){ population.ngeno += 1; population.nhoma += 1; population.nalt += 2; population.geno_index.push_back(2); break; } if(genotype == "0|0"){ population.ngeno += 1; population.nhomr += 1; population.nref += 2; population.geno_index.push_back(0); break; } if(genotype == "0|1"){ population.ngeno += 1; population.nhet += 1; population.nref += 1; population.nalt += 1; population.geno_index.push_back(1); break; } if(genotype == "1|1"){ population.ngeno += 1; population.nhoma += 1; population.nalt += 2; population.geno_index.push_back(2); break; } cerr << "FATAL: unknown genotype" << endl; exit(1); } } if(population.nalt == 0 && population.nref == 0){ population.af = -1; } else{ population.af = (population.nalt / (population.nref + population.nalt)); if(population.nhet > 0){ population.fis = ( 1 - ((population.nhet/population.ngeno) / (2*population.af*(1 - population.af)))); } else{ population.fis = 1; } if(population.fis < 0){ population.fis = 0.00001; } } } void loadPop( vector< map< string, vector<string> > >& group, popPool & population){ vector< map< string, vector<string> > >::iterator targ_it = group.begin(); for(; targ_it != group.end(); targ_it++){ string allelecounts = (*targ_it)["AD"].front(); vector<string> ac = split(allelecounts, ','); population.npop += 1; population.nrefs.push_back(atof(ac[0].c_str())); population.nalts.push_back(atof(ac[1].c_str())); population.nref += atof(ac[0].c_str()); population.ntot += atof(ac[0].c_str()); population.nalt += atof(ac[1].c_str()); population.ntot += atof(ac[1].c_str()); } if(population.npop < 1){ population.af = -1; } else{ population.af = population.nalt / population.ntot; } } double bound(double v){ if(v <= 0.00001){ return 0.00001; } if(v >= 0.99999){ return 0.99999; } return v; } void loadIndices(map<int, int> & index, string set){ vector<string> indviduals = split(set, ","); vector<string>::iterator it = indviduals.begin(); for(; it != indviduals.end(); it++){ index[ atoi( (*it).c_str() ) ] = 1; } } void getPosterior(pop & population, double *alpha, double *beta){ int ng = population.geno_index.size(); for(int i = 0 ; i < ng; i++){ double aa = population.unphred_p[i][0] ; double ab = population.unphred_p[i][1] ; double bb = population.unphred_p[i][2] ; double norm = log(exp(aa) + exp(ab) + exp(bb)); int gi = population.geno_index[i]; (*alpha) += exp(ab - norm); (*beta ) += exp(ab - norm); (*alpha) += 2 * exp(aa - norm); (*beta ) += 2 * exp(bb - norm); } } void getPosterior(popPool & population, double *alpha, double *beta){ } int main(int argc, char** argv) { // pooled or genotyped int pool = 0; // the filename string filename = "NA"; // set region to scaffold string region = "NA"; // using vcflib; thanks to Erik Garrison VariantCallFile variantFile; // zero based index for the target and background indivudals map<int, int> it, ib; // deltaaf is the difference of allele frequency we bother to look at string deltaaf ; double daf = 0; // int counts = 0; const struct option longopts[] = { {"version" , 0, 0, 'v'}, {"help" , 0, 0, 'h'}, {"counts" , 0, 0, 'c'}, {"file" , 1, 0, 'f'}, {"target" , 1, 0, 't'}, {"background", 1, 0, 'b'}, {"deltaaf" , 1, 0, 'd'}, {"region" , 1, 0, 'r'}, {0,0,0,0} }; int index; int iarg=0; while(iarg != -1) { iarg = getopt_long(argc, argv, "r:d:t:b:f:chv", longopts, &index); switch (iarg) { case 'h': cerr << endl << endl; cerr << "INFO: help" << endl; cerr << "INFO: description:" << endl; cerr << " pFst is a probabilistic approach for detecting differences in allele frequencies between two populations, " << endl; cerr << " a target and background. pFst uses the conjugated form of the beta-binomial distributions to estimate " << endl; cerr << " the posterior distribution for the background's allele frequency. pFst calculates the probability of observing " << endl; cerr << " the target's allele frequency given the posterior distribution of the background. By default " << endl; cerr << " pFst uses the genotype likelihoods to estimate alpha, beta and the allele frequency of the target group. If you would like to assume " << endl; cerr << " all genotypes are correct set the count flag equal to one. " << endl << endl; cerr << "Output : 3 columns : " << endl; cerr << " 1. seqid " << endl; cerr << " 2. position " << endl; cerr << " 3. pFst probability " << endl << endl; cerr << "INFO: usage: pFst --target 0,1,2,3,4,5,6,7 --background 11,12,13,16,17,19,22 --file my.vcf --deltaaf 0.1" << endl; cerr << endl; cerr << "INFO: required: t,target -- a zero bases comma seperated list of target individuals corrisponding to VCF columns" << endl; cerr << "INFO: required: b,background -- a zero bases comma seperated list of background individuals corrisponding to VCF columns" << endl; cerr << "INFO: required: f,file a -- proper formatted VCF. the FORMAT field MUST contain \"PL\"" << endl; cerr << "INFO: optional: d,deltaaf -- skip sites where the difference in allele frequencies is less than deltaaf, default is zero" << endl; cerr << "INFO: optional: c,counts -- use genotype counts rather than genotype likelihoods to estimate parameters, default false" << endl; cerr << endl; cerr << "INFO: version 1.0.0 ; date: April 2014 ; author: Zev Kronenberg; email : zev.kronenberg@utah.edu " << endl; cerr << endl << endl; return 0; case 'v': cerr << endl << endl; cerr << "INFO: version 1.0.0 ; date: April 2014 ; author: Zev Kronenberg; email : zev.kronenberg@utah.edu " << endl; return 0; case 'c': cerr << "INFO: using genotype counts rather than genotype likelihoods" << endl; counts = 1; break; case 't': loadIndices(ib, optarg); cerr << "INFO: There are " << ib.size() << " individuals in the target" << endl; cerr << "INFO: target ids: " << optarg << endl; break; case 'b': loadIndices(it, optarg); cerr << "INFO: There are " << it.size() << " individuals in the background" << endl; cerr << "INFO: background ids: " << optarg << endl; break; case 'f': cerr << "INFO: File: " << optarg << endl; filename = optarg; break; case 'd': cerr << "INFO: only scoring sites where the allele frequency difference is greater than: " << optarg << endl; deltaaf = optarg; daf = atof(deltaaf.c_str()); break; case 'r': cerr << "INFO: set seqid region to : " << optarg << endl; region = optarg; break; default: break; } } variantFile.open(filename); if(region != "NA"){ variantFile.setRegion(region); } if (!variantFile.is_open()) { return 1; } Variant var(variantFile); while (variantFile.getNextVariant(var)) { if(var.alt.size() > 1){ continue; } map<string, map<string, vector<string> > >::iterator s = var.samples.begin(); map<string, map<string, vector<string> > >::iterator sEnd = var.samples.end(); vector < map< string, vector<string> > > target, background; int index = 0; for (; s != sEnd; ++s) { map<string, vector<string> >& sample = s->second; if(sample["GT"].front() != "./."){ if(it.find(index) != it.end() ){ target.push_back(sample); } if(ib.find(index) != ib.end()){ background.push_back(sample); } } index += 1; } pop * popt; pop * popb; if(pool == 1){ popt = new popPool; popb = new popPool; } initPop(*popt); initPop(*popb); loadPop(target, *popt); loadPop(background, *popb); if((*popt).af == -1 || (*popb).af == -1){ continue; } if((*popt).af == 1 && (*popb).af == 1){ continue; } if((*popt).af == 0 && (*popb).af == 0){ continue; } double afdiff = abs((*popt).af - (*popb).af); if(afdiff < daf){ continue; } double alphaT = 0.01; double alphaB = 0.01; double betaT = 0.01; double betaB = 0.01; if(counts == 1){ alphaT += (*popt).nref ; alphaB += (*popb).nref ; betaT += (*popt).nalt ; betaB += (*popb).nalt ; } else{ getPosterior(*popt, &alphaT, &betaT); getPosterior(*popb, &alphaB, &betaB); } double targm = alphaT / ( alphaT + betaT ); double backm = alphaB / ( alphaB + betaB ); double xa = targm - 0.001; double xb = targm + 0.001; if(xa <= 0){ xa = 0; xb = 0.002; } if(xb >= 1){ xa = 0.998; xb = 1; } double dph = r8_beta_pdf(alphaB, betaB, xa); double dpl = r8_beta_pdf(alphaB, betaB, xb); double p = ((dph + dpl)/2) * 0.01; cout << var.sequenceName << "\t" << var.position << "\t" << p << endl ; delete popt; delete popb; popt = NULL; popb = NULL; } return 0; } <commit_msg>pooled vs unpooled caused failture<commit_after>#include "Variant.h" #include "split.h" #include "cdflib.hpp" #include "pdflib.hpp" #include <string> #include <iostream> #include <math.h> #include <cmath> #include <stdlib.h> #include <time.h> #include <stdio.h> #include <getopt.h> using namespace std; using namespace vcf; struct pop{ double nalt ; double nref ; double af ; double nhomr; double nhoma; double nhet ; double ngeno; double fis ; vector<int> geno_index ; vector< vector< double > > unphred_p; }; struct popPool : pop{ double nalt ; double nref ; double af ; double npop ; double ntot ; vector<double> nalts; vector<double> nrefs; }; double unphred(string phred){ double unphred = atof(phred.c_str()); unphred = unphred / -10; return unphred; } void initPop(pop & population){ population.nalt = 0; population.nref = 0; population.af = 0; population.nhomr = 0; population.nhoma = 0; population.nhet = 0; population.ngeno = 0; population.fis = 0; } void initPop(popPool & population){ population.nalt = 0; population.nref = 0; population.npop = 0; population.ntot = 0; } void loadPop( vector< map< string, vector<string> > >& group, pop & population){ vector< map< string, vector<string> > >::iterator targ_it = group.begin(); for(; targ_it != group.end(); targ_it++){ string genotype = (*targ_it)["GT"].front(); vector<double> phreds; phreds.push_back( unphred((*targ_it)["PL"][0])); phreds.push_back( unphred((*targ_it)["PL"][1])); phreds.push_back( unphred((*targ_it)["PL"][2])); population.unphred_p.push_back(phreds); while(1){ if(genotype == "0/0"){ population.ngeno += 1; population.nhomr += 1; population.nref += 2; population.geno_index.push_back(0); break; } if(genotype == "0/1"){ population.ngeno += 1; population.nhet += 1; population.nref += 1; population.nalt += 1; population.geno_index.push_back(1); break; } if(genotype == "1/1"){ population.ngeno += 1; population.nhoma += 1; population.nalt += 2; population.geno_index.push_back(2); break; } if(genotype == "0|0"){ population.ngeno += 1; population.nhomr += 1; population.nref += 2; population.geno_index.push_back(0); break; } if(genotype == "0|1"){ population.ngeno += 1; population.nhet += 1; population.nref += 1; population.nalt += 1; population.geno_index.push_back(1); break; } if(genotype == "1|1"){ population.ngeno += 1; population.nhoma += 1; population.nalt += 2; population.geno_index.push_back(2); break; } cerr << "FATAL: unknown genotype" << endl; exit(1); } } if(population.nalt == 0 && population.nref == 0){ population.af = -1; } else{ population.af = (population.nalt / (population.nref + population.nalt)); if(population.nhet > 0){ population.fis = ( 1 - ((population.nhet/population.ngeno) / (2*population.af*(1 - population.af)))); } else{ population.fis = 1; } if(population.fis < 0){ population.fis = 0.00001; } } } void loadPop( vector< map< string, vector<string> > >& group, popPool & population){ vector< map< string, vector<string> > >::iterator targ_it = group.begin(); for(; targ_it != group.end(); targ_it++){ string allelecounts = (*targ_it)["AD"].front(); vector<string> ac = split(allelecounts, ','); population.npop += 1; population.nrefs.push_back(atof(ac[0].c_str())); population.nalts.push_back(atof(ac[1].c_str())); population.nref += atof(ac[0].c_str()); population.ntot += atof(ac[0].c_str()); population.nalt += atof(ac[1].c_str()); population.ntot += atof(ac[1].c_str()); } if(population.npop < 1){ population.af = -1; } else{ population.af = population.nalt / population.ntot; } } double bound(double v){ if(v <= 0.00001){ return 0.00001; } if(v >= 0.99999){ return 0.99999; } return v; } void loadIndices(map<int, int> & index, string set){ vector<string> indviduals = split(set, ","); vector<string>::iterator it = indviduals.begin(); for(; it != indviduals.end(); it++){ index[ atoi( (*it).c_str() ) ] = 1; } } void getPosterior(pop & population, double *alpha, double *beta){ int ng = population.geno_index.size(); for(int i = 0 ; i < ng; i++){ double aa = population.unphred_p[i][0] ; double ab = population.unphred_p[i][1] ; double bb = population.unphred_p[i][2] ; double norm = log(exp(aa) + exp(ab) + exp(bb)); int gi = population.geno_index[i]; (*alpha) += exp(ab - norm); (*beta ) += exp(ab - norm); (*alpha) += 2 * exp(aa - norm); (*beta ) += 2 * exp(bb - norm); } } void getPosterior(popPool & population, double *alpha, double *beta){ } int main(int argc, char** argv) { // pooled or genotyped int pool = 0; // the filename string filename = "NA"; // set region to scaffold string region = "NA"; // using vcflib; thanks to Erik Garrison VariantCallFile variantFile; // zero based index for the target and background indivudals map<int, int> it, ib; // deltaaf is the difference of allele frequency we bother to look at string deltaaf ; double daf = 0; // int counts = 0; const struct option longopts[] = { {"version" , 0, 0, 'v'}, {"help" , 0, 0, 'h'}, {"counts" , 0, 0, 'c'}, {"file" , 1, 0, 'f'}, {"target" , 1, 0, 't'}, {"background", 1, 0, 'b'}, {"deltaaf" , 1, 0, 'd'}, {"region" , 1, 0, 'r'}, {0,0,0,0} }; int index; int iarg=0; while(iarg != -1) { iarg = getopt_long(argc, argv, "r:d:t:b:f:chv", longopts, &index); switch (iarg) { case 'h': cerr << endl << endl; cerr << "INFO: help" << endl; cerr << "INFO: description:" << endl; cerr << " pFst is a probabilistic approach for detecting differences in allele frequencies between two populations, " << endl; cerr << " a target and background. pFst uses the conjugated form of the beta-binomial distributions to estimate " << endl; cerr << " the posterior distribution for the background's allele frequency. pFst calculates the probability of observing " << endl; cerr << " the target's allele frequency given the posterior distribution of the background. By default " << endl; cerr << " pFst uses the genotype likelihoods to estimate alpha, beta and the allele frequency of the target group. If you would like to assume " << endl; cerr << " all genotypes are correct set the count flag equal to one. " << endl << endl; cerr << "Output : 3 columns : " << endl; cerr << " 1. seqid " << endl; cerr << " 2. position " << endl; cerr << " 3. pFst probability " << endl << endl; cerr << "INFO: usage: pFst --target 0,1,2,3,4,5,6,7 --background 11,12,13,16,17,19,22 --file my.vcf --deltaaf 0.1" << endl; cerr << endl; cerr << "INFO: required: t,target -- a zero bases comma seperated list of target individuals corrisponding to VCF columns" << endl; cerr << "INFO: required: b,background -- a zero bases comma seperated list of background individuals corrisponding to VCF columns" << endl; cerr << "INFO: required: f,file a -- proper formatted VCF. the FORMAT field MUST contain \"PL\"" << endl; cerr << "INFO: optional: d,deltaaf -- skip sites where the difference in allele frequencies is less than deltaaf, default is zero" << endl; cerr << "INFO: optional: c,counts -- use genotype counts rather than genotype likelihoods to estimate parameters, default false" << endl; cerr << endl; cerr << "INFO: version 1.0.0 ; date: April 2014 ; author: Zev Kronenberg; email : zev.kronenberg@utah.edu " << endl; cerr << endl << endl; return 0; case 'v': cerr << endl << endl; cerr << "INFO: version 1.0.0 ; date: April 2014 ; author: Zev Kronenberg; email : zev.kronenberg@utah.edu " << endl; return 0; case 'c': cerr << "INFO: using genotype counts rather than genotype likelihoods" << endl; counts = 1; break; case 't': loadIndices(ib, optarg); cerr << "INFO: There are " << ib.size() << " individuals in the target" << endl; cerr << "INFO: target ids: " << optarg << endl; break; case 'b': loadIndices(it, optarg); cerr << "INFO: There are " << it.size() << " individuals in the background" << endl; cerr << "INFO: background ids: " << optarg << endl; break; case 'f': cerr << "INFO: File: " << optarg << endl; filename = optarg; break; case 'd': cerr << "INFO: only scoring sites where the allele frequency difference is greater than: " << optarg << endl; deltaaf = optarg; daf = atof(deltaaf.c_str()); break; case 'r': cerr << "INFO: set seqid region to : " << optarg << endl; region = optarg; break; default: break; } } variantFile.open(filename); if(region != "NA"){ variantFile.setRegion(region); } if (!variantFile.is_open()) { return 1; } Variant var(variantFile); while (variantFile.getNextVariant(var)) { if(var.alt.size() > 1){ continue; } map<string, map<string, vector<string> > >::iterator s = var.samples.begin(); map<string, map<string, vector<string> > >::iterator sEnd = var.samples.end(); vector < map< string, vector<string> > > target, background; int index = 0; for (; s != sEnd; ++s) { map<string, vector<string> >& sample = s->second; if(sample["GT"].front() != "./."){ if(it.find(index) != it.end() ){ target.push_back(sample); } if(ib.find(index) != ib.end()){ background.push_back(sample); } } index += 1; } pop * popt = new pop; pop * popb = new pop; initPop(*popt); initPop(*popb); loadPop(target, *popt); loadPop(background, *popb); if((*popt).af == -1 || (*popb).af == -1){ continue; } if((*popt).af == 1 && (*popb).af == 1){ continue; } if((*popt).af == 0 && (*popb).af == 0){ continue; } double afdiff = abs((*popt).af - (*popb).af); if(afdiff < daf){ continue; } double alphaT = 0.01; double alphaB = 0.01; double betaT = 0.01; double betaB = 0.01; if(counts == 1){ alphaT += (*popt).nref ; alphaB += (*popb).nref ; betaT += (*popt).nalt ; betaB += (*popb).nalt ; } else{ getPosterior(*popt, &alphaT, &betaT); getPosterior(*popb, &alphaB, &betaB); } double targm = alphaT / ( alphaT + betaT ); double backm = alphaB / ( alphaB + betaB ); double xa = targm - 0.001; double xb = targm + 0.001; if(xa <= 0){ xa = 0; xb = 0.002; } if(xb >= 1){ xa = 0.998; xb = 1; } double dph = r8_beta_pdf(alphaB, betaB, xa); double dpl = r8_beta_pdf(alphaB, betaB, xb); double p = ((dph + dpl)/2) * 0.01; cout << var.sequenceName << "\t" << var.position << "\t" << p << endl ; delete popt; delete popb; popt = NULL; popb = NULL; } return 0; } <|endoftext|>
<commit_before>// // PUSHY - standalone push server // godexsoft 2014 // #include <boost/program_options.hpp> #include <boost/asio.hpp> #include <push_service.hpp> #include <vector> #include "logging.hpp" #include "api_service.hpp" #include "pushy_service.hpp" #include "database.hpp" namespace po = boost::program_options; using namespace boost::asio; using namespace push; using namespace pushy; using namespace pushy::database; int main(int ac, char **av) try { // global options std::string config_path; std::string logfile; severity_t loglevel; // db options std::string redis_host; int redis_port; // automation options bool auto_redeliver; int auto_redeliver_attempts; bool auto_deregister; // api options std::string api_base_uri; std::string api_addr; std::string api_port; int api_workers; // apns options std::string apns_key; // pem std::string apns_cert; // pem std::string apns_password; // p12 password std::string apns_p12_cert_key; // p12 file with both cert and key std::string apns_mode; int apns_poolsize; std::string apns_logfile; // gcm options std::string gcm_project_id; std::string gcm_api_key; int gcm_poolsize; std::string gcm_logfile; // a banner just for fun static char banner[] = "\n" " ██████╗ ██╗ ██╗███████╗██╗ ██╗██╗ ██╗\n" " ██╔══██╗██║ ██║██╔════╝██║ ██║╚██╗ ██╔╝\n" " ██████╔╝██║ ██║███████╗███████║ ╚████╔╝ \n" " ██╔═══╝ ██║ ██║╚════██║██╔══██║ ╚██╔╝ \n" " ██║ ╚██████╔╝███████║██║ ██║ ██║ \n" " ╚═╝ ╚═════╝ ╚══════╝╚═╝ ╚═╝ ╚═╝ \n"; // option parsing po::options_description generic_config("Generic"); generic_config.add_options() ("help,h", "produce help message") ("config,c", po::value<std::string>(&config_path), "config file to read") ("loglevel,L", po::value<severity_t>(&loglevel)->default_value(severity_t("info")), "log level (trace, debug, info, warning, error)") ("logfile,l", po::value<std::string>(&logfile), "logfile to use instead of standard output; see docs for format options") ; po::options_description redis_config("Redis"); redis_config.add_options() ("redis.host", po::value<std::string>(&redis_host)->default_value("127.0.0.1"), "redis host") ("redis.port", po::value<int>(&redis_port)->default_value(6379), "redis port") ; po::options_description auto_config("Automation"); auto_config.add_options() ("auto.redeliver,r", po::value<bool>(&auto_redeliver)->default_value(true), "automatically redeliver undelivered messages") ("auto.attempts,t", po::value<int>(&auto_redeliver_attempts)->default_value(3), "times to try deliver a message before giving up (only if auto.redeliver is on)") ("auto.deregister,d", po::value<bool>(&auto_deregister)->default_value(true), "automatically deregister devices which reported as unreachable") ; po::options_description api_config("JSON API"); api_config.add_options() ("api.base,b", po::value<std::string>(&api_base_uri)->default_value("/api"), "base uri") ("api.address,a", po::value<std::string>(&api_addr)->default_value("0.0.0.0"), "address") ("api.port,p", po::value<std::string>(&api_port)->default_value("7446"), "port") ("api.workers,w", po::value<int>(&api_workers)->default_value(1), "workers to spawn (threads)") ; po::options_description apns_config("APNS"); apns_config.add_options() ("apns.p12", po::value<std::string>(&apns_p12_cert_key), "cert and key p12 file path") ("apns.password", po::value<std::string>(&apns_password), "password for the key if needed") ("apns.mode", po::value<std::string>(&apns_mode)->default_value("sandbox"), "mode ('production' or 'sandbox')") ("apns.pool", po::value<int>(&apns_poolsize)->default_value(1), "pool size (connections count)") ("apns.logfile", po::value<std::string>(&apns_logfile), "logstash JSON format logfile for APNS stats") ; po::options_description gcm_config("GCM"); gcm_config.add_options() ("gcm.project", po::value<std::string>(&gcm_project_id), "project id") ("gcm.key", po::value<std::string>(&gcm_api_key), "api key") ("gcm.pool", po::value<int>(&gcm_poolsize)->default_value(1), "pool size (connections count)") ("gcm.logfile", po::value<std::string>(&gcm_logfile), "logstash JSON format logfile for GCM stats") ; po::options_description desc("Pushy server options"); desc.add(generic_config).add(redis_config).add(auto_config) .add(api_config).add(apns_config).add(gcm_config); // initialize logger's basic properties logging::init_basics(); po::variables_map vm; po::store(po::parse_command_line(ac, av, desc), vm); po::notify(vm); std::cout << banner << "\n"; if(vm.count("help")) { std::cout << desc << "\n"; return 1; } if(vm.count("config")) { po::store(po::parse_config_file<char>(config_path.c_str(), desc), vm); po::notify(vm); } // initialize logger to files etc. logging::init(logfile, loglevel.level, apns_logfile, gcm_logfile); // initialize redis database connection pool dba::instance().init_pool(redis_host, redis_port); // the push service pushy_service service(auto_redeliver, auto_redeliver_attempts, auto_deregister); // now check if apns, gcm, etc. are enabled if(vm.count("apns.p12")) { if(apns_mode != "sandbox" && apns_mode != "production") { throw std::runtime_error("apns.mode must be either 'sandbox' or 'production'"); } service.setup_apns(apns_mode, apns_p12_cert_key, apns_password, apns_poolsize); LOG_DEBUG << "configure apns with " << apns_mode << " p12=" << apns_p12_cert_key; } // gcm if(vm.count("gcm.project") || vm.count("gcm.key")) { if(!vm.count("gcm.project") || !vm.count("gcm.key")) { throw std::runtime_error("both gcm.project and gcm.key must be defined in order to use GCM"); } LOG_DEBUG << "configure gcm with project_id=" << gcm_project_id << ", key=" << gcm_api_key; service.setup_gcm(gcm_project_id, gcm_api_key, gcm_poolsize); LOG_DEBUG << "configuration of gcm done"; } LOG_INFO << "running json api service."; // create the api service. it runs on background thread automatically api_service api(service, api_addr, api_port, api_base_uri, api_workers); LOG_INFO << "running pushy service."; // run pushy service service.run(); } catch(push::exception::push_exception& e) { LOG_ERROR << "push_service error: " << e.what(); } catch(std::exception& e) { LOG_ERROR << "fatal: " << e.what(); } <commit_msg>fixed config parsing and added error handling<commit_after>// // PUSHY - standalone push server // godexsoft 2014 // #include <boost/program_options.hpp> #include <boost/asio.hpp> #include <push_service.hpp> #include <vector> #include <fstream> #include "logging.hpp" #include "api_service.hpp" #include "pushy_service.hpp" #include "database.hpp" namespace po = boost::program_options; using namespace boost::asio; using namespace push; using namespace pushy; using namespace pushy::database; int main(int ac, char **av) try { // global options std::string config_path; std::string logfile; severity_t loglevel; // db options std::string redis_host; int redis_port; // automation options bool auto_redeliver; int auto_redeliver_attempts; bool auto_deregister; // api options std::string api_base_uri; std::string api_addr; std::string api_port; int api_workers; // apns options std::string apns_key; // pem std::string apns_cert; // pem std::string apns_password; // p12 password std::string apns_p12_cert_key; // p12 file with both cert and key std::string apns_mode; int apns_poolsize; std::string apns_logfile; // gcm options std::string gcm_project_id; std::string gcm_api_key; int gcm_poolsize; std::string gcm_logfile; // a banner just for fun static char banner[] = "\n" " ██████╗ ██╗ ██╗███████╗██╗ ██╗██╗ ██╗\n" " ██╔══██╗██║ ██║██╔════╝██║ ██║╚██╗ ██╔╝\n" " ██████╔╝██║ ██║███████╗███████║ ╚████╔╝ \n" " ██╔═══╝ ██║ ██║╚════██║██╔══██║ ╚██╔╝ \n" " ██║ ╚██████╔╝███████║██║ ██║ ██║ \n" " ╚═╝ ╚═════╝ ╚══════╝╚═╝ ╚═╝ ╚═╝ \n"; // option parsing po::options_description generic_config("Generic"); generic_config.add_options() ("help,h", "produce help message") ("config,c", po::value<std::string>(&config_path), "config file to read") ("loglevel,L", po::value<severity_t>(&loglevel)->default_value(severity_t("info")), "log level (trace, debug, info, warning, error)") ("logfile,l", po::value<std::string>(&logfile), "logfile to use instead of standard output; see docs for format options") ; po::options_description redis_config("Redis"); redis_config.add_options() ("redis.host", po::value<std::string>(&redis_host)->default_value("127.0.0.1"), "redis host") ("redis.port", po::value<int>(&redis_port)->default_value(6379), "redis port") ; po::options_description auto_config("Automation"); auto_config.add_options() ("auto.redeliver,r", po::value<bool>(&auto_redeliver)->default_value(true), "automatically redeliver undelivered messages") ("auto.attempts,t", po::value<int>(&auto_redeliver_attempts)->default_value(3), "times to try deliver a message before giving up (only if auto.redeliver is on)") ("auto.deregister,d", po::value<bool>(&auto_deregister)->default_value(true), "automatically deregister devices which reported as unreachable") ; po::options_description api_config("JSON API"); api_config.add_options() ("api.base,b", po::value<std::string>(&api_base_uri)->default_value("/api"), "base uri") ("api.address,a", po::value<std::string>(&api_addr)->default_value("0.0.0.0"), "address") ("api.port,p", po::value<std::string>(&api_port)->default_value("7446"), "port") ("api.workers,w", po::value<int>(&api_workers)->default_value(1), "workers to spawn (threads)") ; po::options_description apns_config("APNS"); apns_config.add_options() ("apns.p12", po::value<std::string>(&apns_p12_cert_key), "cert and key p12 file path") ("apns.password", po::value<std::string>(&apns_password), "password for the key if needed") ("apns.mode", po::value<std::string>(&apns_mode)->default_value("sandbox"), "mode ('production' or 'sandbox')") ("apns.pool", po::value<int>(&apns_poolsize)->default_value(1), "pool size (connections count)") ("apns.logfile", po::value<std::string>(&apns_logfile), "logstash JSON format logfile for APNS stats") ; po::options_description gcm_config("GCM"); gcm_config.add_options() ("gcm.project", po::value<std::string>(&gcm_project_id), "project id") ("gcm.key", po::value<std::string>(&gcm_api_key), "api key") ("gcm.pool", po::value<int>(&gcm_poolsize)->default_value(1), "pool size (connections count)") ("gcm.logfile", po::value<std::string>(&gcm_logfile), "logstash JSON format logfile for GCM stats") ; po::options_description desc("Pushy server options"); desc.add(generic_config).add(redis_config).add(auto_config) .add(api_config).add(apns_config).add(gcm_config); // initialize logger's basic properties logging::init_basics(); po::variables_map vm; po::store(po::parse_command_line(ac, av, desc), vm); po::notify(vm); std::cout << banner << "\n"; if(vm.count("help")) { std::cout << desc << "\n"; return 1; } if(vm.count("config")) { std::ifstream f(config_path.c_str()); if(f.good()) { po::store(po::parse_config_file(f, desc, true), vm); po::notify(vm); } else { throw std::runtime_error("specified configuration file does not exist or is not accessible."); } } // initialize logger to files etc. logging::init(logfile, loglevel.level, apns_logfile, gcm_logfile); // initialize redis database connection pool dba::instance().init_pool(redis_host, redis_port); // the push service pushy_service service(auto_redeliver, auto_redeliver_attempts, auto_deregister); // now check if apns, gcm, etc. are enabled if(vm.count("apns.p12")) { if(apns_mode != "sandbox" && apns_mode != "production") { throw std::runtime_error("apns.mode must be either 'sandbox' or 'production'"); } LOG_DEBUG << "configuring apns with " << apns_mode << " p12=" << apns_p12_cert_key; service.setup_apns(apns_mode, apns_p12_cert_key, apns_password, apns_poolsize); LOG_DEBUG << "configuration of apns done"; } // gcm if(vm.count("gcm.project") || vm.count("gcm.key")) { if(!vm.count("gcm.project") || !vm.count("gcm.key")) { throw std::runtime_error("both gcm.project and gcm.key must be defined in order to use GCM"); } LOG_DEBUG << "configure gcm with project_id=" << gcm_project_id << ", key=" << gcm_api_key; service.setup_gcm(gcm_project_id, gcm_api_key, gcm_poolsize); LOG_DEBUG << "configuration of gcm done"; } LOG_INFO << "running json api service."; // create the api service. it runs on background thread automatically api_service api(service, api_addr, api_port, api_base_uri, api_workers); LOG_INFO << "running pushy service."; // run pushy service service.run(); } catch(push::exception::push_exception& e) { LOG_ERROR << "push_service error: " << e.what(); } catch(std::exception& e) { LOG_ERROR << "fatal: " << e.what(); } <|endoftext|>
<commit_before>#include <QApplication> #include <QDir> #include <QCommandLineParser> #include <QMessageBox> #include "version.hpp" #include "dvwindow.hpp" void registerFileTypes(); int main(int argc, char *argv[]) { QApplication app(argc, argv); app.setOrganizationName("chipgw"); app.setApplicationName("DepthView2"); app.setApplicationVersion(version::number.toString()); /* QML needs a stencil buffer. */ QSurfaceFormat fmt; fmt.setDepthBufferSize(24); fmt.setStencilBufferSize(8); QSurfaceFormat::setDefaultFormat(fmt); QCommandLineParser parser; /* TODO - More arguments. */ parser.addOptions({ {"register", QCoreApplication::translate("main", "")}, { {"f", "fullscreen"}, QCoreApplication::translate("main", "")}, { {"d", "startdir"}, QCoreApplication::translate("main", ""), QCoreApplication::translate("main", "directory")}, { {"r", "renderer"}, QCoreApplication::translate("main", ""), QCoreApplication::translate("main", "renderer")}, }); parser.parse(app.arguments()); if(parser.isSet("register")){ registerFileTypes(); return 0; } /* If not started in a specific directory default to the user's home path. */ if(QDir::currentPath() == app.applicationDirPath()) QDir::setCurrent(QDir::homePath()); DVWindow window; window.show(); window.doCommandLine(parser); return app.exec(); } /* File association code. */ #if defined(Q_OS_WIN32) /* Windows-specific code used for file association. */ #include <Windows.h> #pragma comment(lib, "advapi32") void addRegistryEntry(const QString& path, const QString& value, QString& error) { HKEY key; LSTATUS result = RegCreateKeyExA(HKEY_CURRENT_USER, LPCSTR(path.toLocal8Bit().constData()), 0, nullptr, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, nullptr, &key, nullptr); if (result != ERROR_SUCCESS) { error += "<p>Error creating key \"" + path + "\"!</p>"; return; } result = RegSetValueExA(key, nullptr, 0, REG_SZ, LPBYTE(value.toLocal8Bit().constData()), DWORD(value.size())); if (result != ERROR_SUCCESS) error += "<p>Error setting value for \"" + path + "\"!</p>"; RegCloseKey(key); } #endif void registerFileTypes() { QString error; #if defined(Q_OS_WIN32) QString progID = "chipgw.DepthView." + version::number.toString(); addRegistryEntry("Software\\Classes\\.jps", progID, error); addRegistryEntry("Software\\Classes\\.pns", progID, error); /* TODO - Add video formats. */ addRegistryEntry("Software\\Classes\\" + progID, "Stereo 3D Image", error); QString command = "\"" + QDir::toNativeSeparators(QApplication::applicationFilePath()) + "\" \"%1\""; addRegistryEntry("Software\\Classes\\" + progID + "\\shell\\open\\command", command, error); #else /* TODO - make other platforms work. */ error = QObject::tr("File association is currently unsupported on your platform!"); #endif if (error.isNull()) QMessageBox::information(nullptr, QObject::tr("Success!"), QObject::tr("Successfully associated .jps and .pns files with DepthView.")); else QMessageBox::warning(nullptr, QObject::tr("Error setting file association!"), error); } <commit_msg>Added help and version command line arguments. Made the --register argument only exist on Windows, as that was the only place it was implemented anyway.<commit_after>#include <QApplication> #include <QDir> #include <QCommandLineParser> #include <QMessageBox> #include "version.hpp" #include "dvwindow.hpp" void registerFileTypes(); int main(int argc, char *argv[]) { QApplication app(argc, argv); app.setOrganizationName("chipgw"); app.setApplicationName("DepthView2"); app.setApplicationVersion(version::number.toString()); /* QML needs a stencil buffer. */ QSurfaceFormat fmt; fmt.setDepthBufferSize(24); fmt.setStencilBufferSize(8); QSurfaceFormat::setDefaultFormat(fmt); QCommandLineParser parser; /* TODO - More arguments. */ parser.addOptions({ #ifdef Q_OS_WIN32 {"register", QCoreApplication::translate("main", "")}, #endif { {"f", "fullscreen"}, QCoreApplication::translate("main", "Open the window in fullscreen mode.")}, { {"d", "startdir"}, QCoreApplication::translate("main", "Start the application in the specified directory. (Ignored if a file is opened)"), QCoreApplication::translate("main", "directory")}, { {"r", "renderer"}, /* TODO - List valid modes in help string. */ QCoreApplication::translate("main", "Set the render mode."), QCoreApplication::translate("main", "renderer")}, }); parser.addHelpOption(); parser.addVersionOption(); parser.addPositionalArgument("file", "A file to open."); parser.process(app.arguments()); #ifdef Q_OS_WIN32 if(parser.isSet("register")){ registerFileTypes(); return 0; } #endif /* If not started in a specific directory default to the user's home path. */ if(QDir::currentPath() == app.applicationDirPath()) QDir::setCurrent(QDir::homePath()); DVWindow window; window.show(); window.doCommandLine(parser); return app.exec(); } /* Windows file association code. */ #ifdef Q_OS_WIN32 /* Windows-specific code used for file association. */ #include <Windows.h> #pragma comment(lib, "advapi32") void addRegistryEntry(const QString& path, const QString& value, QString& error) { HKEY key; LSTATUS result = RegCreateKeyExA(HKEY_CURRENT_USER, LPCSTR(path.toLocal8Bit().constData()), 0, nullptr, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, nullptr, &key, nullptr); if (result != ERROR_SUCCESS) { error += "<p>Error creating key \"" + path + "\"!</p>"; return; } result = RegSetValueExA(key, nullptr, 0, REG_SZ, LPBYTE(value.toLocal8Bit().constData()), DWORD(value.size())); if (result != ERROR_SUCCESS) error += "<p>Error setting value for \"" + path + "\"!</p>"; RegCloseKey(key); } void registerFileTypes() { QString error; QString progID = "chipgw.DepthView." + version::number.toString(); addRegistryEntry("Software\\Classes\\.jps", progID, error); addRegistryEntry("Software\\Classes\\.pns", progID, error); /* TODO - Add video formats. */ addRegistryEntry("Software\\Classes\\" + progID, "Stereo 3D Image", error); QString command = "\"" + QDir::toNativeSeparators(QApplication::applicationFilePath()) + "\" \"%1\""; addRegistryEntry("Software\\Classes\\" + progID + "\\shell\\open\\command", command, error); if (error.isNull()) QMessageBox::information(nullptr, QObject::tr("Success!"), QObject::tr("Successfully associated .jps and .pns files with DepthView.")); else QMessageBox::warning(nullptr, QObject::tr("Error setting file association!"), error); } #endif <|endoftext|>
<commit_before>#include "mario.h" #include "producer.h" #include "consumer.h" #include "version.h" #include "mutexlock.h" #include "port.h" #include "filename.h" #include "signal.h" #include <iostream> #include <string> #include <stdint.h> #define __STDC_FORMAT_MACROS #include <inttypes.h> namespace mario { struct Mario::Writer { Status status; bool done; port::CondVar cv; explicit Writer(port::Mutex* mu) : cv(mu) { } }; Mario::Mario(uint32_t consumer_num, Consumer::Handler *h, int32_t retry) : consumer_num_(consumer_num), h_(h), item_num_(0), env_(Env::Default()), readfile_(NULL), writefile_(NULL), versionfile_(NULL), version_(NULL), bg_cv_(&mutex_), pronum_(0), connum_(0), retry_(retry), pool_(NULL), exit_all_consume_(false), mario_path_("./log") { env_->set_thread_num(consumer_num_); #if defined(MARIO_MEMORY) pool_ = (char *)malloc(sizeof(char) * kPoolSize); if (pool_ == NULL) { log_err("malloc error"); exit(-1); } producer_ = new Producer(pool_, kPoolSize); consumer_ = new Consumer(0, h, pool_, kPoolSize); #endif #if defined(MARIO_MMAP) filename_ = mario_path_ + kWrite2file; const std::string manifest = mario_path_ + kManifest; std::string profile; std::string confile; env_->CreateDir(mario_path_); Status s; if (!env_->FileExists(manifest)) { log_info("Manifest file not exist"); profile = NewFileName(filename_, pronum_); confile = NewFileName(filename_, connum_); env_->NewWritableFile(profile, &writefile_); env_->NewSequentialFile(confile, &readfile_); env_->NewRWFile(manifest, &versionfile_); if (versionfile_ == NULL) { log_warn("new versionfile error"); } version_ = new Version(versionfile_); version_->StableSave(); } else { log_info("Find the exist file "); s = env_->NewRWFile(manifest, &versionfile_); if (s.ok()) { version_ = new Version(versionfile_); version_->InitSelf(); pronum_ = version_->pronum(); connum_ = version_->connum(); version_->debug(); } else { log_warn("new REFile error"); } profile = NewFileName(filename_, pronum_); confile = NewFileName(filename_, connum_); log_info("profile %s confile %s", profile.c_str(), confile.c_str()); env_->AppendWritableFile(profile, &writefile_, version_->pro_offset()); uint64_t filesize = writefile_->Filesize(); log_info("filesize %" PRIu64 "", filesize); env_->AppendSequentialFile(confile, &readfile_); } producer_ = new Producer(writefile_, version_); consumer_ = new Consumer(readfile_, h_, version_, connum_); env_->StartThread(&Mario::SplitLogWork, this); #endif for (uint32_t i = 0; i < consumer_num_; i++) { env_->StartThread(&Mario::BGWork, this); } // env_->Schedule(&Mario::BGWork, this); } Mario::~Mario() { mutex_.Lock(); exit_all_consume_ = true; bg_cv_.SignalAll(); while (consumer_num_ > 0) { bg_cv_.Wait(); } mutex_.Unlock(); delete consumer_; delete producer_; #if defined(MARIO_MMAP) delete version_; delete versionfile_; #endif delete writefile_; delete readfile_; #if defined(MARIO_MEMORY) free(pool_); #endif // delete env_; } #if defined(MARIO_MMAP) void Mario::SplitLogWork(void *m) { reinterpret_cast<Mario*>(m)->SplitLogCall(); } void Mario::SplitLogCall() { Status s; std::string profile; while (1) { uint64_t filesize = writefile_->Filesize(); // log_info("filesize %llu kMmapSize %llu", filesize, kMmapSize); if (filesize > kMmapSize) { { MutexLock l(&mutex_); delete producer_; delete writefile_; pronum_++; profile = NewFileName(filename_, pronum_); env_->NewWritableFile(profile, &writefile_); version_->set_pro_offset(0); version_->set_pronum(pronum_); version_->StableSave(); version_->debug(); producer_ = new Producer(writefile_, version_); } } sleep(1); } } #endif void Mario::BGWork(void *m) { reinterpret_cast<Mario*>(m)->BackgroundCall(); } void Mario::BackgroundCall() { std::string scratch(""); Status s; while (1) { { mutex_.Lock(); #if defined(MARIO_MMAP) while (version_->item_num() <= 0) { #endif #if defined(MARIO_MEMORY) while (item_num_ <= 0) { #endif if (exit_all_consume_) { consumer_num_--; mutex_.Unlock(); bg_cv_.Signal(); pthread_exit(NULL); } bg_cv_.Wait(); } scratch = ""; #if defined(MARIO_MMAP) s = consumer_->Consume(scratch); while (!s.ok()) { // log_info("consumer_ consume %s", s.ToString().c_str()); // log_info("connum_ %d", connum_); std::string confile = NewFileName(filename_, connum_ + 1); // log_info("confile %s connum_ %d", confile.c_str(), connum_); // log_info("isendfile %d fileexist %d item_num %d", s.IsEndFile(), env_->FileExists(confile), version_->item_num()); if (s.IsEndFile() && env_->FileExists(confile)) { // log_info("Rotate file "); delete readfile_; env_->AppendSequentialFile(confile, &readfile_); connum_++; delete consumer_; version_->set_con_offset(0); version_->set_connum(connum_); version_->StableSave(); consumer_ = new Consumer(readfile_, h_, version_, connum_); s = consumer_->Consume(scratch); // log_info("consumer_ consume %s", s.ToString().c_str()); break; } else { mutex_.Unlock(); sleep(1); mutex_.Lock(); } s = consumer_->Consume(scratch); } version_->minus_item_num(); version_->StableSave(); #endif #if defined(MARIO_MEMORY) s = consumer_->Consume(scratch); item_num_--; #endif mutex_.Unlock(); if (retry_ == -1) { while (h_->processMsg(scratch)) { } } else { int retry = retry_ - 1; while (!h_->processMsg(scratch) && retry--) { } if (retry <= 0) { log_warn("message retry %d time still error %s", retry_, scratch.c_str()); } } } } return ; } Status Mario::Put(const std::string &item) { Status s; { MutexLock l(&mutex_); s = producer_->Produce(Slice(item.data(), item.size())); if (s.ok()) { #if defined(MARIO_MMAP) version_->plus_item_num(); version_->StableSave(); #endif #if defined(MARIO_MEMORY) item_num_++; #endif } } bg_cv_.Signal(); return s; } Status Mario::Put(const char* item, int len) { Status s; { MutexLock l(&mutex_); s = producer_->Produce(Slice(item, len)); if (s.ok()) { #if defined(MARIO_MMAP) version_->plus_item_num(); version_->StableSave(); #endif #if defined(MARIO_MEMORY) item_num_++; #endif } } bg_cv_.Signal(); return s; } Status Mario::Get() { Status s; std::string scratch; MutexLock l(&mutex_); s = consumer_->Consume(scratch); return s; } } // namespace mario <commit_msg>add feature:delete consumed file & file missing tolerence<commit_after>#include "mario.h" #include "producer.h" #include "consumer.h" #include "version.h" #include "mutexlock.h" #include "port.h" #include "filename.h" #include "signal.h" #include <iostream> #include <string> #include <stdint.h> #define __STDC_FORMAT_MACROS #include <inttypes.h> namespace mario { struct Mario::Writer { Status status; bool done; port::CondVar cv; explicit Writer(port::Mutex* mu) : cv(mu) { } }; Mario::Mario(uint32_t consumer_num, Consumer::Handler *h, int32_t retry) : consumer_num_(consumer_num), h_(h), item_num_(0), env_(Env::Default()), readfile_(NULL), writefile_(NULL), versionfile_(NULL), version_(NULL), bg_cv_(&mutex_), pronum_(0), connum_(0), retry_(retry), pool_(NULL), exit_all_consume_(false), mario_path_("./log") { env_->set_thread_num(consumer_num_); #if defined(MARIO_MEMORY) pool_ = (char *)malloc(sizeof(char) * kPoolSize); if (pool_ == NULL) { log_err("malloc error"); exit(-1); } producer_ = new Producer(pool_, kPoolSize); consumer_ = new Consumer(0, h, pool_, kPoolSize); #endif #if defined(MARIO_MMAP) filename_ = mario_path_ + kWrite2file; const std::string manifest = mario_path_ + kManifest; std::string profile; std::string confile; env_->CreateDir(mario_path_); Status s; if (!env_->FileExists(manifest)) { log_info("Manifest file not exist"); profile = NewFileName(filename_, pronum_); confile = NewFileName(filename_, connum_); env_->NewWritableFile(profile, &writefile_); env_->NewSequentialFile(confile, &readfile_); env_->NewRWFile(manifest, &versionfile_); if (versionfile_ == NULL) { log_warn("new versionfile error"); } version_ = new Version(versionfile_); version_->StableSave(); } else { log_info("Find the manifest file "); s = env_->NewRWFile(manifest, &versionfile_); if (s.ok()) { version_ = new Version(versionfile_); version_->InitSelf(); pronum_ = version_->pronum(); connum_ = version_->connum(); version_->debug(); } else { log_warn("new REFile error"); } profile = NewFileName(filename_, pronum_); confile = NewFileName(filename_, connum_); if(!env_->FileExists(profile)){ pronum_ = pronum_ + 1; profile = NewFileName(filename_, pronum_); env_->NewWritableFile(profile, &writefile_); version_->set_pro_offset(0); version_->set_pronum(pronum_); version_->StableSave(); } else{ env_->AppendWritableFile(profile, &writefile_, version_->pro_offset()); uint64_t filesize = writefile_->Filesize(); log_info("filesize %" PRIu64 "", filesize); } if(!env_->FileExists(confile)){ while(!env_->FileExists(confile) && connum_ < pronum_){ connum_ = connum_ + 1; confile = NewFileName(filename_, connum_); } version_->set_connum(connum_); version_->set_con_offset(0); version_->StableSave(); env_->NewSequentialFile(confile, &readfile_); } else env_->AppendSequentialFile(confile, &readfile_); } log_info("profile %s confile %s", profile.c_str(), confile.c_str()); producer_ = new Producer(writefile_, version_); consumer_ = new Consumer(readfile_, h_, version_, connum_); env_->StartThread(&Mario::SplitLogWork, this); #endif for (uint32_t i = 0; i < consumer_num_; i++) { env_->StartThread(&Mario::BGWork, this); } // env_->Schedule(&Mario::BGWork, this); } Mario::~Mario() { mutex_.Lock(); exit_all_consume_ = true; bg_cv_.SignalAll(); while (consumer_num_ > 0) { bg_cv_.Wait(); } mutex_.Unlock(); delete consumer_; delete producer_; #if defined(MARIO_MMAP) delete version_; delete versionfile_; #endif delete writefile_; delete readfile_; #if defined(MARIO_MEMORY) free(pool_); #endif // delete env_; } #if defined(MARIO_MMAP) void Mario::SplitLogWork(void *m) { reinterpret_cast<Mario*>(m)->SplitLogCall(); } void Mario::SplitLogCall() { Status s; std::string profile; while (1) { uint64_t filesize = writefile_->Filesize(); // log_info("filesize %llu kMmapSize %llu", filesize, kMmapSize); if (filesize > kMmapSize) { { MutexLock l(&mutex_); delete producer_; delete writefile_; pronum_++; profile = NewFileName(filename_, pronum_); env_->NewWritableFile(profile, &writefile_); version_->set_pro_offset(0); version_->set_pronum(pronum_); version_->StableSave(); version_->debug(); producer_ = new Producer(writefile_, version_); } } sleep(1); } } #endif void Mario::BGWork(void *m) { reinterpret_cast<Mario*>(m)->BackgroundCall(); } void Mario::BackgroundCall() { std::string scratch(""); Status s; while (1) { { mutex_.Lock(); #if defined(MARIO_MMAP) while (version_->item_num() <= 0) { #endif #if defined(MARIO_MEMORY) while (item_num_ <= 0) { #endif if (exit_all_consume_) { consumer_num_--; mutex_.Unlock(); bg_cv_.Signal(); pthread_exit(NULL); } bg_cv_.Wait(); } scratch = ""; #if defined(MARIO_MMAP) s = consumer_->Consume(scratch); while (!s.ok()) { // log_info("consumer_ consume %s", s.ToString().c_str()); // log_info("connum_ %d", connum_); std::string confile = NewFileName(filename_, connum_ + 1); // log_info("confile %s connum_ %d", confile.c_str(), connum_); // log_info("isendfile %d fileexist %d item_num %d", s.IsEndFile(), env_->FileExists(confile), version_->item_num()); if (s.IsEndFile() && env_->FileExists(confile)) { // log_info("Rotate file "); delete readfile_; std::string previousFile = NewFileName(filename_, connum_ ); env_->DeleteFile(previousFile); env_->AppendSequentialFile(confile, &readfile_); connum_++; delete consumer_; version_->set_con_offset(0); version_->set_connum(connum_); version_->StableSave(); consumer_ = new Consumer(readfile_, h_, version_, connum_); s = consumer_->Consume(scratch); // log_info("consumer_ consume %s", s.ToString().c_str()); break; } else { mutex_.Unlock(); sleep(1); mutex_.Lock(); } s = consumer_->Consume(scratch); } version_->minus_item_num(); version_->StableSave(); #endif #if defined(MARIO_MEMORY) s = consumer_->Consume(scratch); item_num_--; #endif mutex_.Unlock(); if (retry_ == -1) { while (h_->processMsg(scratch)) { } } else { int retry = retry_ - 1; while (!h_->processMsg(scratch) && retry--) { } if (retry <= 0) { log_warn("message retry %d time still error %s", retry_, scratch.c_str()); } } } } return ; } Status Mario::Put(const std::string &item) { Status s; { MutexLock l(&mutex_); s = producer_->Produce(Slice(item.data(), item.size())); if (s.ok()) { #if defined(MARIO_MMAP) version_->plus_item_num(); version_->StableSave(); #endif #if defined(MARIO_MEMORY) item_num_++; #endif } } bg_cv_.Signal(); return s; } Status Mario::Put(const char* item, int len) { Status s; { MutexLock l(&mutex_); s = producer_->Produce(Slice(item, len)); if (s.ok()) { #if defined(MARIO_MMAP) version_->plus_item_num(); version_->StableSave(); #endif #if defined(MARIO_MEMORY) item_num_++; #endif } } bg_cv_.Signal(); return s; } Status Mario::Get() { Status s; std::string scratch; MutexLock l(&mutex_); s = consumer_->Consume(scratch); return s; } } // namespace mario <|endoftext|>
<commit_before>/* main.cpp - CS 472 Project #2: Genetic Programming * Copyright 2014 Andrew Schwartzmeyer */ #include <algorithm> #include <cassert> #include <chrono> #include <ctime> #include <future> #include <iostream> #include <thread> #include "algorithm/algorithm.hpp" #include "individual/individual.hpp" #include "options/options.hpp" #include "random_generator/random_generator.hpp" int main() { using individual::Individual; using namespace options; const Options options{get_data(), 64, 128, 3, 3}; const int trials = 4; int trial = 0; const unsigned long hardware_threads = std::thread::hardware_concurrency(); const unsigned long blocks = hardware_threads != 0 ? hardware_threads : 2; assert(trials % blocks == 0); std::vector<Individual> candidates; std::chrono::time_point<std::chrono::system_clock> start, end; // begin timing trials std::time_t time = std::time(nullptr); start = std::chrono::system_clock::now(); // spawn trials number of threads in blocks for (unsigned long t = 0; t < trials / blocks; ++t) { std::vector<std::future<const Individual>> results; for (unsigned long i = 0; i < blocks; ++i) results.emplace_back(std::async(std::launch::async, algorithm::genetic, options, time, ++trial)); // gather results for (std::future<const Individual> & result : results) candidates.emplace_back(result.get()); } // end timing trials end = std::chrono::system_clock::now(); std::chrono::duration<double> elapsed_seconds = end - start; std::vector<Individual>::iterator best = std::min_element(candidates.begin(), candidates.end(), algorithm::compare_fitness); std::cout << "Total elapsed time: " << elapsed_seconds.count() << "s\n" << "Average time: " << elapsed_seconds.count() / trials << "s\n" << "Best trial: " << time << "_" << std::distance(candidates.begin(), best) + 1 << "\n" << best->print(); } <commit_msg>Refactoring trials into own namespace<commit_after>/* main.cpp - CS 472 Project #2: Genetic Programming * Copyright 2014 Andrew Schwartzmeyer */ #include <algorithm> #include <cassert> #include <chrono> #include <ctime> #include <future> #include <iostream> #include <thread> #include <tuple> #include "algorithm/algorithm.hpp" #include "individual/individual.hpp" #include "options/options.hpp" #include "random_generator/random_generator.hpp" namespace trials { std::tuple<int, individual::Individual> run(options::Options options, int trials, std::time_t time) { // spawn trials number of threads in blocks using individual::Individual; int trial = 0; const unsigned long hardware_threads = std::thread::hardware_concurrency(); const unsigned long blocks = hardware_threads != 0 ? hardware_threads : 2; assert(trials % blocks == 0); std::vector<Individual> candidates; for (unsigned long t = 0; t < trials / blocks; ++t) { std::vector<std::future<const Individual>> results; for (unsigned long i = 0; i < blocks; ++i) results.emplace_back(std::async(std::launch::async, algorithm::genetic, options, time, ++trial)); // gather results for (std::future<const Individual> & result : results) candidates.emplace_back(result.get()); } auto best = std::min_element(candidates.begin(), candidates.end(), algorithm::compare_fitness); int distance = std::distance(candidates.begin(), best) + 1; // filenames are not zero-indexed return std::make_tuple(distance, *best); } } int main() { using namespace options; const Options options{get_data(), 64, 128, 3, 3}; const int trials = 4; std::chrono::time_point<std::chrono::system_clock> start, end; std::time_t time = std::time(nullptr); // begin timing trials start = std::chrono::system_clock::now(); auto best = trials::run(options, trials, time); // end timing trials end = std::chrono::system_clock::now(); std::chrono::duration<double> elapsed_seconds = end - start; std::cout << "Total elapsed time: " << elapsed_seconds.count() << "s\n" << "Average time: " << elapsed_seconds.count() / trials << "s\n" << "Best trial: " << time << "_" << std::get<0>(best) << "\n" << std::get<1>(best).print(); } <|endoftext|>
<commit_before>/* Copyright (c) 2020 ANON authors, see AUTHORS file. 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 <stdlib.h> #include <aws/core/Aws.h> #include <aws/core/client/ClientConfiguration.h> #include <aws/core/auth/AWSCredentialsProvider.h> #include <aws/core/auth/AWSCredentialsProviderChain.h> #include <aws/core/config/AWSProfileConfigLoader.h> #include <aws/core/client/DefaultRetryStrategy.h> #include "nlohmann/json.hpp" #include <fstream> #include "log.h" #include "resin.h" using namespace nlohmann; ec2_info::ec2_info(const char *filename) { Aws::Client::ClientConfiguration config; config.connectTimeoutMs = 100; config.httpRequestTimeoutMs = 100; config.retryStrategy = std::make_shared<Aws::Client::DefaultRetryStrategy>(2, 10); Aws::Internal::EC2MetadataClient client(config); Aws::String region; auto rgn = getenv("AWS_DEFAULT_REGION"); if (rgn) region = rgn; else { region = client.GetCurrentRegion(); if (region.size() == 0) region = "us-east-1"; } default_region = region; ami_id = client.GetResource("/latest/meta-data/ami-id").c_str(); if (ami_id.size() != 0) { instance_id = client.GetResource("/latest/meta-data/instance-id").c_str(); host_name = client.GetResource("/latest/meta-data/local-hostname").c_str(); private_ipv4 = client.GetResource("/latest/meta-data/local-ipv4").c_str(); public_ipv4 = client.GetResource("/latest/meta-data/public-ipv4").c_str(); } else { ami_id = "ami_id"; instance_id = "instance_id"; host_name = "host_name"; private_ipv4 = "private_ipv4"; public_ipv4 = "public_ipv4"; } if (filename != 0) { json js = json::parse(std::ifstream(filename)); user_data = user_data_js.dump(); } else user_data = client.GetResource("/latest/user-data/").c_str(); if (user_data.size() != 0) user_data_js = json::parse(user_data); auto cwd = getcwd(0, 0); root_dir = cwd; root_dir += "/resin_root"; free(cwd); } namespace { Aws::SDKOptions options; bool in_ec2(ec2_info &r) { return r.ami_id.size() != 0 && r.instance_id.size() != 0 && r.host_name.size() != 0 && r.private_ipv4.size() != 0; } bool has_user_data(ec2_info &r) { return r.user_data.size() != 0; } } // namespace extern "C" int main(int argc, char **argv) { anon_log("resin starting"); int ret = 0; Aws::InitAPI(options); try { const char* filename = argc >= 2 ? argv[1] : (const char*)0; ec2_info ec2i(filename); if (!in_ec2(ec2i)) anon_log("resin run outside of ec2, stopping now"); else if (!has_user_data(ec2i)) anon_log("resin run without supplying user data, stopping now"); else { // we always access ec2 at the endpoint that matches the region we are in Aws::Client::ClientConfiguration ec2_config; ec2_config.region = ec2i.default_region; ec2i.ec2_client = std::make_shared<Aws::EC2::EC2Client>(ec2_config); std::string server_type = ec2i.user_data_js["server_type"]; if (server_type == "bash_worker") run_worker(ec2i); else if (server_type == "teflon_server") run_server(ec2i); else { ret = 1; anon_log("unknown server_type: \"" << server_type << "\", stopping now"); } } } catch (const std::exception &exc) { anon_log("resin threw uncaught exception, aborting now, what(): " << exc.what()); ret = 1; } catch (...) { anon_log("resin threw uncaught, unknown exception, aborting now"); ret = 1; } Aws::ShutdownAPI(options); return ret; } <commit_msg>bug fix<commit_after>/* Copyright (c) 2020 ANON authors, see AUTHORS file. 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 <stdlib.h> #include <aws/core/Aws.h> #include <aws/core/client/ClientConfiguration.h> #include <aws/core/auth/AWSCredentialsProvider.h> #include <aws/core/auth/AWSCredentialsProviderChain.h> #include <aws/core/config/AWSProfileConfigLoader.h> #include <aws/core/client/DefaultRetryStrategy.h> #include "nlohmann/json.hpp" #include <fstream> #include "log.h" #include "resin.h" using namespace nlohmann; ec2_info::ec2_info(const char *filename) { Aws::Client::ClientConfiguration config; config.connectTimeoutMs = 100; config.httpRequestTimeoutMs = 100; config.retryStrategy = std::make_shared<Aws::Client::DefaultRetryStrategy>(2, 10); Aws::Internal::EC2MetadataClient client(config); Aws::String region; auto rgn = getenv("AWS_DEFAULT_REGION"); if (rgn) region = rgn; else { region = client.GetCurrentRegion(); if (region.size() == 0) region = "us-east-1"; } default_region = region; ami_id = client.GetResource("/latest/meta-data/ami-id").c_str(); if (ami_id.size() != 0) { instance_id = client.GetResource("/latest/meta-data/instance-id").c_str(); host_name = client.GetResource("/latest/meta-data/local-hostname").c_str(); private_ipv4 = client.GetResource("/latest/meta-data/local-ipv4").c_str(); public_ipv4 = client.GetResource("/latest/meta-data/public-ipv4").c_str(); } else { ami_id = "ami_id"; instance_id = "instance_id"; host_name = "host_name"; private_ipv4 = "private_ipv4"; public_ipv4 = "public_ipv4"; } if (filename != 0) { json js = json::parse(std::ifstream(filename)); user_data = js.dump(); } else user_data = client.GetResource("/latest/user-data/").c_str(); if (user_data.size() != 0) user_data_js = json::parse(user_data); auto cwd = getcwd(0, 0); root_dir = cwd; root_dir += "/resin_root"; free(cwd); } namespace { Aws::SDKOptions options; bool in_ec2(ec2_info &r) { return r.ami_id.size() != 0 && r.instance_id.size() != 0 && r.host_name.size() != 0 && r.private_ipv4.size() != 0; } bool has_user_data(ec2_info &r) { return r.user_data.size() != 0; } } // namespace extern "C" int main(int argc, char **argv) { anon_log("resin starting"); int ret = 0; Aws::InitAPI(options); try { const char* filename = argc >= 2 ? argv[1] : (const char*)0; ec2_info ec2i(filename); if (!in_ec2(ec2i)) anon_log("resin run outside of ec2, stopping now"); else if (!has_user_data(ec2i)) anon_log("resin run without supplying user data, stopping now"); else { // we always access ec2 at the endpoint that matches the region we are in Aws::Client::ClientConfiguration ec2_config; ec2_config.region = ec2i.default_region; ec2i.ec2_client = std::make_shared<Aws::EC2::EC2Client>(ec2_config); std::string server_type = ec2i.user_data_js["server_type"]; if (server_type == "bash_worker") run_worker(ec2i); else if (server_type == "teflon_server") run_server(ec2i); else { ret = 1; anon_log("unknown server_type: \"" << server_type << "\", stopping now"); } } } catch (const std::exception &exc) { anon_log("resin threw uncaught exception, aborting now, what(): " << exc.what()); ret = 1; } catch (...) { anon_log("resin threw uncaught, unknown exception, aborting now"); ret = 1; } Aws::ShutdownAPI(options); return ret; } <|endoftext|>
<commit_before>#include <iostream> #include <string.h> #include <sys/types.h> #include <unistd.h> #include <stdio.h> using namespace std; /* // Deprecated function call. int sizefunc(char* commandstream, const char* delim){ int i; char* p = strtok(commandstream, delim); for (i = 0; p!= NULL; p = strtok(NULL, delim) ){ ++i; } return (i+1); } */ bool checkforexit(char ** &commandList, char* commands, const char* pk){ int c = 0; bool exiting = false; char* par = strtok(commands, pk); const char* exitword = "exit"; for (c = 0; par != NULL; ++c, par = strtok(NULL, pk)){ if (strcmp(exitword, commandList[c])){ exiting = true; } commandList[c] = par; } return exiting; //cout << "CommandList@" << it << ": " << commandList[it] << endl; } } void changeToArray(char ** &commandList, char* commands, const char* parser){ int it = 0; char* pkey = strtok(commands, parser); for (it = 0; pkey != NULL; ++it, pkey = strtok(NULL, parser)){ //cout << "CommandList@" << it << ": " << commandList[it] << endl; } //cout << "it is @ " << it << endl; commandList[it] = NULL; } int main() { string user_stream; char * parsedString = NULL; //char * iterate = NULL; char * username = getlogin(); const char * parr = " "; //const char * andL = "&&"; //const char * orL = "||"; //const char * semiL = ";"; char host[100]; gethostname(host, 100); //Introductory Message to make sure shell is running. cout << "Hello, and welcome to Kevin's shell." << endl; while(1){ // Prints out the username and hostname if it exists. if (username){ cout << username << "@" << host; } cout << "$ "; //Gets line for user stream. getline(cin, user_stream); int strlength = user_stream.length(); int hashpos = user_stream.find("#"); //Parsing the string using strdup to change from const char* to char* strcpy(parsedString, user_stream.c_str()); parsedString[hashpos] = '\0'; char ** commandstream = new char*[sizeof(parsedString)+1]; changeToArray(commandstream, parsedString, parr); int pid = fork(); if (pid == -1){ cout << "You have taken up all the processes available.\n Please kill some processes before continuing.\n "; } else if (pid == 0){ if(execvp((const char*)commandstream[0], (char* const*) commandstream) == -1){ cout << "Unable to perform request." << endl; } } else{ wait(NULL); /* if (checkforexit(commandstream, parsedString, parr)){ cout << "Thank you for using rshell. Goodbye.\n"; exit(1); } */ } } return 0; } <commit_msg>Added sys/wait.h<commit_after>#include <iostream> #include <string.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> #include <stdio.h> using namespace std; /* // Deprecated function call. int sizefunc(char* commandstream, const char* delim){ int i; char* p = strtok(commandstream, delim); for (i = 0; p!= NULL; p = strtok(NULL, delim) ){ ++i; } return (i+1); } */ bool checkforexit(char ** &commandList, char* commands, const char* pk){ int c = 0; bool exiting = false; char* par = strtok(commands, pk); const char* exitword = "exit"; for (c = 0; par != NULL; ++c, par = strtok(NULL, pk)){ if (strcmp(exitword, commandList[c])){ exiting = true; } commandList[c] = par; } return exiting; //cout << "CommandList@" << it << ": " << commandList[it] << endl; } } void changeToArray(char ** &commandList, char* commands, const char* parser){ int it = 0; char* pkey = strtok(commands, parser); for (it = 0; pkey != NULL; ++it, pkey = strtok(NULL, parser)){ //cout << "CommandList@" << it << ": " << commandList[it] << endl; } //cout << "it is @ " << it << endl; commandList[it] = NULL; } int main() { string user_stream; char * parsedString = NULL; //char * iterate = NULL; char * username = getlogin(); const char * parr = " "; //const char * andL = "&&"; //const char * orL = "||"; //const char * semiL = ";"; char host[100]; gethostname(host, 100); //Introductory Message to make sure shell is running. cout << "Hello, and welcome to Kevin's shell." << endl; while(1){ // Prints out the username and hostname if it exists. if (username){ cout << username << "@" << host; } cout << "$ "; //Gets line for user stream. getline(cin, user_stream); //int strlength = user_stream.length(); int hashpos = user_stream.find("#"); //Parsing the string using strdup to change from const char* to char* strcpy(parsedString, user_stream.c_str()); parsedString[hashpos] = '\0'; char ** commandstream = new char*[sizeof(parsedString)+1]; changeToArray(commandstream, parsedString, parr); int pid = fork(); if (pid == -1){ cout << "You have taken up all the processes available.\n Please kill some processes before continuing.\n "; } else if (pid == 0){ if(execvp((const char*)commandstream[0], (char* const*) commandstream) == -1){ cout << "Unable to perform request." << endl; } } else{ wait(NULL); /* if (checkforexit(commandstream, parsedString, parr)){ cout << "Thank you for using rshell. Goodbye.\n"; exit(1); } */ } } return 0; } <|endoftext|>
<commit_before>#include <iostream> #include <armadillo> using namespace arma; constexpr int training_size = 4000; constexpr int input_layer_size = 784; constexpr int hidden_layer_size = 25; constexpr int num_labels = 10; constexpr double lambda = 0.1; constexpr int max_iterations = 100; int main () { std::cout << "Starting program..." << std::endl; mat x_train(training_size,input_layer_size); x_train.load("train_x_4000.csv"); mat initial_theta1(input_layer_size,hidden_layer_size,fill::randu); mat initial_theta2(hidden_layer_size,num_labels,fill::randu); initial_theta1.reshape(1,input_layer_size*hidden_layer_size); initial_theta2.reshape(1,hidden_layer_size*num_labels); mat combined_theta = join_rows(initial_theta1,initial_theta2); //vec initial_nn_params = vectorise(combined_theta); mat m3(training_size,hidden_layer_size,fill::zeros); mat y_train(1,training_size); y_train.load("train_y_4000.csv"); //m3=x_train*initial_theta1; //std::cout << m3.row(0) << std::endl; return 0; } <commit_msg>split thetas<commit_after>#include <iostream> #include <armadillo> using namespace arma; constexpr int training_size = 4000; constexpr int input_layer_size = 784; constexpr int hidden_layer_size = 25; constexpr int num_labels = 10; constexpr double lambda = 0.1; constexpr int max_iterations = 100; int main () { std::cout << "Starting program..." << std::endl; mat x_train(training_size,input_layer_size); x_train.load("train_x_4000.csv"); mat initial_theta1(input_layer_size,hidden_layer_size,fill::randu); mat initial_theta2(hidden_layer_size,num_labels,fill::randu); initial_theta1.reshape(1,input_layer_size*hidden_layer_size); initial_theta2.reshape(1,hidden_layer_size*num_labels); mat combined_theta = join_rows(initial_theta1,initial_theta2); //vec initial_nn_params = vectorise(combined_theta); std::cout << "combined_theta rows: " << combined_theta.n_rows << ", cols: " << combined_theta.n_cols << endl; initial_theta1 = combined_theta.submat(0, 0, 0, initial_theta1.n_cols-1); std::cout << "initial_theta1 rows: " << initial_theta1.n_rows << ", cols: " << initial_theta1.n_cols << endl; initial_theta2 = combined_theta.submat(0, initial_theta1.n_cols-1, 0,initial_theta1.n_cols-1+initial_theta2.n_cols-1); std::cout << "initial_theta2rows: " << initial_theta2.n_rows << ", cols: " << initial_theta2.n_cols << endl; mat m3(training_size,hidden_layer_size,fill::zeros); mat y_train(1,training_size); y_train.load("train_y_4000.csv"); //m3=x_train*initial_theta1; //std::cout << m3.row(0) << std::endl; return 0; } <|endoftext|>
<commit_before>/* Copyright (c) 2013, Taiga Nomi 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 <organization> 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 <iostream> #include <boost/timer.hpp> #include <boost/progress.hpp> #include "tiny_cnn.h" //#define NOMINMAX //#include "imdebug.h" void sample1_convnet(); void sample2_mlp(); void sample3_dae(); void sample4_dropout(); using namespace tiny_cnn; int main(void) { sample1_convnet(); } /////////////////////////////////////////////////////////////////////////////// // learning convolutional neural networks (LeNet-5 like architecture) void sample1_convnet(void) { // construct LeNet-5 architecture typedef network<mse, gradient_descent_levenberg_marquardt> CNN; CNN nn; convolutional_layer<CNN, tanh_activation> C1(32, 32, 5, 1, 6); average_pooling_layer<CNN, tanh_activation> S2(28, 28, 6, 2); // connection table [Y.Lecun, 1998 Table.1] #define O true #define X false static const bool connection[] = { O, X, X, X, O, O, O, X, X, O, O, O, O, X, O, O, O, O, X, X, X, O, O, O, X, X, O, O, O, O, X, O, O, O, O, X, X, X, O, O, O, X, X, O, X, O, O, O, X, O, O, O, X, X, O, O, O, O, X, X, O, X, O, O, X, X, O, O, O, X, X, O, O, O, O, X, O, O, X, O, X, X, X, O, O, O, X, X, O, O, O, O, X, O, O, O }; #undef O #undef X convolutional_layer<CNN, tanh_activation> C3(14, 14, 5, 6, 16, connection_table(connection, 6, 16)); average_pooling_layer<CNN, tanh_activation> S4(10, 10, 16, 2); convolutional_layer<CNN, tanh_activation> C5(5, 5, 5, 16, 120); fully_connected_layer<CNN, tanh_activation> F6(120, 10); assert(C1.param_size() == 156 && C1.connection_size() == 122304); assert(S2.param_size() == 12 && S2.connection_size() == 5880); assert(C3.param_size() == 1516 && C3.connection_size() == 151600); assert(S4.param_size() == 32 && S4.connection_size() == 2000); assert(C5.param_size() == 48120 && C5.connection_size() == 48120); nn.add(&C1); nn.add(&S2); nn.add(&C3); nn.add(&S4); nn.add(&C5); nn.add(&F6); std::cout << "load models..." << std::endl; // load MNIST dataset std::vector<label_t> train_labels, test_labels; std::vector<vec_t> train_images, test_images; parse_mnist_labels("train-labels.idx1-ubyte", &train_labels); parse_mnist_images("train-images.idx3-ubyte", &train_images); parse_mnist_labels("t10k-labels.idx1-ubyte", &test_labels); parse_mnist_images("t10k-images.idx3-ubyte", &test_images); std::cout << "start learning" << std::endl; boost::progress_display disp(train_images.size()); boost::timer t; int minibatch_size = 10; nn.optimizer().alpha *= std::sqrt(minibatch_size); // create callback auto on_enumerate_epoch = [&](){ std::cout << t.elapsed() << "s elapsed." << std::endl; tiny_cnn::result res = nn.test(test_images, test_labels); std::cout << nn.optimizer().alpha << "," << res.num_success << "/" << res.num_total << std::endl; nn.optimizer().alpha *= 0.85; // decay learning rate nn.optimizer().alpha = std::max(0.00001, nn.optimizer().alpha); disp.restart(train_images.size()); t.restart(); }; auto on_enumerate_minibatch = [&](){ disp += minibatch_size; // weight visualization in imdebug /*static int n = 0; n+=minibatch_size; if (n >= 1000) { image img; C3.weight_to_image(img); imdebug("lum b=8 w=%d h=%d %p", img.width(), img.height(), &img.data()[0]); n = 0; }*/ }; // training nn.train(train_images, train_labels, minibatch_size, 20, on_enumerate_minibatch, on_enumerate_epoch); std::cout << "end training." << std::endl; // test and show results nn.test(test_images, test_labels).print_detail(std::cout); // save networks std::ofstream ofs("LeNet-weights"); ofs << C1 << S2 << C3 << S4 << C5 << F6; } /////////////////////////////////////////////////////////////////////////////// // learning 3-Layer Networks void sample2_mlp() { const int num_hidden_units = 500; #if defined(_MSC_VER) && _MSC_VER < 1800 // initializer-list is not supported int num_units[] = { 28 * 28, num_hidden_units, 10 }; auto nn = make_mlp<mse, gradient_descent, tanh_activation>(num_units, num_units + 3); #else auto nn = make_mlp<mse, gradient_descent, tanh_activation>({ 28 * 28, num_hidden_units, 10 }); #endif // load MNIST dataset std::vector<label_t> train_labels, test_labels; std::vector<vec_t> train_images, test_images; parse_mnist_labels("train-labels.idx1-ubyte", &train_labels); parse_mnist_images("train-images.idx3-ubyte", &train_images, -1.0, 1.0, 0, 0); parse_mnist_labels("t10k-labels.idx1-ubyte", &test_labels); parse_mnist_images("t10k-images.idx3-ubyte", &test_images, -1.0, 1.0, 0, 0); nn.optimizer().alpha = 0.001; boost::progress_display disp(train_images.size()); boost::timer t; // create callback auto on_enumerate_epoch = [&](){ std::cout << t.elapsed() << "s elapsed." << std::endl; tiny_cnn::result res = nn.test(test_images, test_labels); std::cout << nn.optimizer().alpha << "," << res.num_success << "/" << res.num_total << std::endl; nn.optimizer().alpha *= 0.85; // decay learning rate nn.optimizer().alpha = std::max(0.00001, nn.optimizer().alpha); disp.restart(train_images.size()); t.restart(); }; auto on_enumerate_data = [&](){ ++disp; }; nn.train(train_images, train_labels, 1, 20, on_enumerate_data, on_enumerate_epoch); } /////////////////////////////////////////////////////////////////////////////// // denoising auto-encoder void sample3_dae() { #if defined(_MSC_VER) && _MSC_VER < 1800 // initializer-list is not supported int num_units[] = { 100, 400, 100 }; auto nn = make_mlp<mse, gradient_descent, tanh_activation>(num_units, num_units + 3); #else auto nn = make_mlp<mse, gradient_descent, tanh_activation>({ 100, 400, 100 }); #endif std::vector<vec_t> train_data_original; // load train-data std::vector<vec_t> train_data_corrupted(train_data_original); for (auto& d : train_data_corrupted) { corrupt(d, 0.1, 0.0, &d); // corrupt 10% data } // learning 100-400-100 denoising auto-encoder nn.train(train_data_corrupted, train_data_original); } /////////////////////////////////////////////////////////////////////////////// // dropout-learning void sample4_dropout() { typedef network<mse, gradient_descent> Network; Network nn; int input_dim = 10; int hidden_units = 100; int output_dim = 10; fully_connected_dropout_layer<Network, tanh_activation> f1(input_dim, hidden_units, dropout::per_data); fully_connected_layer<Network, tanh_activation> f2(hidden_units, output_dim); nn.add(&f1); nn.add(&f2); std::vector<vec_t> train_data, test_data; std::vector<label_t> train_label, test_label; // load train-data, label_data // learning nn.train(train_data, train_label); // change context to enable all hidden-units f1.set_context(dropout::test_phase); tiny_cnn::result res = nn.test(test_data, test_label); std::cout << res.num_success << "/" << res.num_total << std::endl; } <commit_msg>implement dropout sample code<commit_after>/* Copyright (c) 2013, Taiga Nomi 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 <organization> 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 <iostream> #include <boost/timer.hpp> #include <boost/progress.hpp> #include "tiny_cnn.h" //#define NOMINMAX //#include "imdebug.h" void sample1_convnet(); void sample2_mlp(); void sample3_dae(); void sample4_dropout(); using namespace tiny_cnn; int main(void) { sample1_convnet(); } /////////////////////////////////////////////////////////////////////////////// // learning convolutional neural networks (LeNet-5 like architecture) void sample1_convnet(void) { // construct LeNet-5 architecture typedef network<mse, gradient_descent_levenberg_marquardt> CNN; CNN nn; convolutional_layer<CNN, tanh_activation> C1(32, 32, 5, 1, 6); average_pooling_layer<CNN, tanh_activation> S2(28, 28, 6, 2); // connection table [Y.Lecun, 1998 Table.1] #define O true #define X false static const bool connection[] = { O, X, X, X, O, O, O, X, X, O, O, O, O, X, O, O, O, O, X, X, X, O, O, O, X, X, O, O, O, O, X, O, O, O, O, X, X, X, O, O, O, X, X, O, X, O, O, O, X, O, O, O, X, X, O, O, O, O, X, X, O, X, O, O, X, X, O, O, O, X, X, O, O, O, O, X, O, O, X, O, X, X, X, O, O, O, X, X, O, O, O, O, X, O, O, O }; #undef O #undef X convolutional_layer<CNN, tanh_activation> C3(14, 14, 5, 6, 16, connection_table(connection, 6, 16)); average_pooling_layer<CNN, tanh_activation> S4(10, 10, 16, 2); convolutional_layer<CNN, tanh_activation> C5(5, 5, 5, 16, 120); fully_connected_layer<CNN, tanh_activation> F6(120, 10); assert(C1.param_size() == 156 && C1.connection_size() == 122304); assert(S2.param_size() == 12 && S2.connection_size() == 5880); assert(C3.param_size() == 1516 && C3.connection_size() == 151600); assert(S4.param_size() == 32 && S4.connection_size() == 2000); assert(C5.param_size() == 48120 && C5.connection_size() == 48120); nn.add(&C1); nn.add(&S2); nn.add(&C3); nn.add(&S4); nn.add(&C5); nn.add(&F6); std::cout << "load models..." << std::endl; // load MNIST dataset std::vector<label_t> train_labels, test_labels; std::vector<vec_t> train_images, test_images; parse_mnist_labels("train-labels.idx1-ubyte", &train_labels); parse_mnist_images("train-images.idx3-ubyte", &train_images); parse_mnist_labels("t10k-labels.idx1-ubyte", &test_labels); parse_mnist_images("t10k-images.idx3-ubyte", &test_images); std::cout << "start learning" << std::endl; boost::progress_display disp(train_images.size()); boost::timer t; int minibatch_size = 10; nn.optimizer().alpha *= std::sqrt(minibatch_size); // create callback auto on_enumerate_epoch = [&](){ std::cout << t.elapsed() << "s elapsed." << std::endl; tiny_cnn::result res = nn.test(test_images, test_labels); std::cout << nn.optimizer().alpha << "," << res.num_success << "/" << res.num_total << std::endl; nn.optimizer().alpha *= 0.85; // decay learning rate nn.optimizer().alpha = std::max(0.00001, nn.optimizer().alpha); disp.restart(train_images.size()); t.restart(); }; auto on_enumerate_minibatch = [&](){ disp += minibatch_size; // weight visualization in imdebug /*static int n = 0; n+=minibatch_size; if (n >= 1000) { image img; C3.weight_to_image(img); imdebug("lum b=8 w=%d h=%d %p", img.width(), img.height(), &img.data()[0]); n = 0; }*/ }; // training nn.train(train_images, train_labels, minibatch_size, 20, on_enumerate_minibatch, on_enumerate_epoch); std::cout << "end training." << std::endl; // test and show results nn.test(test_images, test_labels).print_detail(std::cout); // save networks std::ofstream ofs("LeNet-weights"); ofs << C1 << S2 << C3 << S4 << C5 << F6; } /////////////////////////////////////////////////////////////////////////////// // learning 3-Layer Networks void sample2_mlp() { const int num_hidden_units = 500; #if defined(_MSC_VER) && _MSC_VER < 1800 // initializer-list is not supported int num_units[] = { 28 * 28, num_hidden_units, 10 }; auto nn = make_mlp<mse, gradient_descent, tanh_activation>(num_units, num_units + 3); #else auto nn = make_mlp<mse, gradient_descent, tanh_activation>({ 28 * 28, num_hidden_units, 10 }); #endif // load MNIST dataset std::vector<label_t> train_labels, test_labels; std::vector<vec_t> train_images, test_images; parse_mnist_labels("train-labels.idx1-ubyte", &train_labels); parse_mnist_images("train-images.idx3-ubyte", &train_images, -1.0, 1.0, 0, 0); parse_mnist_labels("t10k-labels.idx1-ubyte", &test_labels); parse_mnist_images("t10k-images.idx3-ubyte", &test_images, -1.0, 1.0, 0, 0); nn.optimizer().alpha = 0.001; boost::progress_display disp(train_images.size()); boost::timer t; // create callback auto on_enumerate_epoch = [&](){ std::cout << t.elapsed() << "s elapsed." << std::endl; tiny_cnn::result res = nn.test(test_images, test_labels); std::cout << nn.optimizer().alpha << "," << res.num_success << "/" << res.num_total << std::endl; nn.optimizer().alpha *= 0.85; // decay learning rate nn.optimizer().alpha = std::max(0.00001, nn.optimizer().alpha); disp.restart(train_images.size()); t.restart(); }; auto on_enumerate_data = [&](){ ++disp; }; nn.train(train_images, train_labels, 1, 20, on_enumerate_data, on_enumerate_epoch); } /////////////////////////////////////////////////////////////////////////////// // denoising auto-encoder void sample3_dae() { #if defined(_MSC_VER) && _MSC_VER < 1800 // initializer-list is not supported int num_units[] = { 100, 400, 100 }; auto nn = make_mlp<mse, gradient_descent, tanh_activation>(num_units, num_units + 3); #else auto nn = make_mlp<mse, gradient_descent, tanh_activation>({ 100, 400, 100 }); #endif std::vector<vec_t> train_data_original; // load train-data std::vector<vec_t> train_data_corrupted(train_data_original); for (auto& d : train_data_corrupted) { corrupt(d, 0.1, 0.0, &d); // corrupt 10% data } // learning 100-400-100 denoising auto-encoder nn.train(train_data_corrupted, train_data_original); } /////////////////////////////////////////////////////////////////////////////// // dropout-learning void sample4_dropout() { typedef network<mse, gradient_descent> Network; Network nn; int input_dim = 28*28; int hidden_units = 800; int output_dim = 10; fully_connected_dropout_layer<Network, tanh_activation> f1(input_dim, hidden_units, dropout::per_data); fully_connected_layer<Network, tanh_activation> f2(hidden_units, output_dim); nn.add(&f1); nn.add(&f2); nn.optimizer().alpha = 0.003; // TODO: not optimized nn.optimizer().lambda = 0.0; // load MNIST dataset std::vector<label_t> train_labels, test_labels; std::vector<vec_t> train_images, test_images; parse_mnist_labels("train-labels.idx1-ubyte", &train_labels); parse_mnist_images("train-images.idx3-ubyte", &train_images, -1.0, 1.0, 0, 0); parse_mnist_labels("t10k-labels.idx1-ubyte", &test_labels); parse_mnist_images("t10k-images.idx3-ubyte", &test_images, -1.0, 1.0, 0, 0); // load train-data, label_data boost::progress_display disp(train_images.size()); boost::timer t; // create callback auto on_enumerate_epoch = [&](){ std::cout << t.elapsed() << "s elapsed." << std::endl; f1.set_context(dropout::test_phase); tiny_cnn::result res = nn.test(test_images, test_labels); f1.set_context(dropout::train_phase); std::cout << nn.optimizer().alpha << "," << res.num_success << "/" << res.num_total << std::endl; nn.optimizer().alpha *= 0.99; // decay learning rate nn.optimizer().alpha = std::max(0.00001, nn.optimizer().alpha); disp.restart(train_images.size()); t.restart(); }; auto on_enumerate_data = [&](){ ++disp; }; nn.train(train_images, train_labels, 1, 100, on_enumerate_data, on_enumerate_epoch); // change context to enable all hidden-units //f1.set_context(dropout::test_phase); //std::cout << res.num_success << "/" << res.num_total << std::endl; } <|endoftext|>
<commit_before>/** * Copyright : falcon build system (c) 2014. * LICENSE : see accompanying LICENSE file for details. */ #include <iostream> #include <cstdlib> #include "daemon_instance.h" #include "exceptions.h" #include "graph.h" #include "graph_consistency_checker.h" #include "graph_dependency_scan.h" #include "logging.h" #include "options.h" #include "stream_consumer.h" static void setOptions(falcon::Options& opt) { /* get the default working directory path from then environment variable */ char const* pwd = NULL; pwd = getenv("PWD"); /* No need to free this string */ if (!pwd) { LOG(ERROR) << "enable to get the PWD"; return; } std::string pwdString(pwd); /* *********************************************************************** */ /* add command line options */ opt.addCLIOption("daemon,d", "daemonize the build system"); opt.addCLIOption("build,b", "launch a sequential build"); opt.addCLIOption("module,M", po::value<std::string>(), "use -M help for more info"); opt.addCLIOption("config,f", /* TODO */ po::value<std::string>(), "falcon configuration file"); /* *********************************************************************** */ /* add command line option and configuration file option (this options can be * setted on both configuration file or from the CLI) */ opt.addCFileOption("working-directory", po::value<std::string>()->default_value(pwdString), "falcon working directory path"); opt.addCFileOption("graph", po::value<std::string>()->default_value("makefile.json"), "falcon graph file"); opt.addCFileOption("api-port", po::value<int>()->default_value(4242), "the API listening port"); opt.addCFileOption("stream-port", po::value<int>()->default_value(4343), "stream port"); opt.addCFileOption("log-level", po::value<google::LogSeverity>()->default_value(google::GLOG_WARNING), "define the log level"); opt.addCFileOption("log-dir", po::value<std::string>(), "write log files in the given directory"); } static int loadModule(falcon::Graph& g, std::string const& s) { LOG(INFO) << "load module '" << s << "'"; if (0 == s.compare("dot")) { printGraphGraphiz(g, std::cout); } else if (0 == s.compare("make")) { printGraphMakefile(g, std::cout); } else if (0 == s.compare("help")) { std::cout << "list of available modules: " << std::endl << " dot show the graph in DOT format" << std::endl << " loop check is there is a loop in the graph" << std::endl << " make show the graph in Makefile format" << std::endl; } else { LOG(ERROR) << "module '" << s << "' not supported"; return 1; } return 0; } /** * Daemonize the current process. */ static void daemonize(std::unique_ptr<falcon::GlobalConfig> config, std::unique_ptr<falcon::Graph> graph) { /** the double-fork-and-setsid trick establishes a child process that runs in * its own process group with its own session and that won't get killed off * when your shell exits (for example). */ if (fork()) { return; } setsid(); if (fork()) { _exit(0); } falcon::DaemonInstance daemon(std::move(config)); daemon.loadConf(std::move(graph)); daemon.start(); } /** Start a build. */ static int build(const std::unique_ptr<falcon::GlobalConfig>& config, const std::unique_ptr<falcon::Graph>& graph) { falcon::StdoutStreamConsumer consumer; std::mutex mutex; falcon::GraphSequentialBuilder builder(*graph, mutex, nullptr /* watchmanClient */, config->getWorkingDirectoryPath(), &consumer); builder.startBuild(graph->getRoots(), false /* No callback. */); builder.wait(); FALCON_CHECK_GRAPH_CONSISTENCY(graph.get(), mutex); return builder.getResult() == falcon::BuildResult::SUCCEEDED ? 0 : 1; } int main (int const argc, char const* const* argv) { falcon::Options opt; setOptions(opt); /* parse the command line options */ try { opt.parseOptions(argc, argv); } catch (falcon::Exception& e) { if (e.getCode () != 0) { // the help throw a SUCCESS code, no error to show std::cerr << e.getErrorMessage() << std::endl; } return e.getCode(); } std::unique_ptr<falcon::GlobalConfig> config(new falcon::GlobalConfig(opt)); /* Analyze the graph given in the configuration file */ falcon::GraphParser graphParser; try { graphParser.processFile(config->getJsonGraphFile()); } catch (falcon::Exception& e) { LOG(ERROR) << e.getErrorMessage (); return e.getCode(); } std::unique_ptr<falcon::Graph> graphPtr = std::move(graphParser.getGraph()); /* Check the graph for cycles. */ try { checkGraphLoop(*graphPtr); } catch (falcon::Exception& e) { LOG(ERROR) << e.getErrorMessage(); return e.getCode(); } /* Scan the graph to discover what needs to be rebuilt, and compute the * hashes of all nodes. */ falcon::GraphDependencyScan scanner(*graphPtr); scanner.scan(); /* if a module has been requested to execute then load it and return */ if (opt.isOptionSetted("module")) { return loadModule(*graphPtr, opt.vm_["module"].as<std::string>()); } /* User explicitly requires a build. Do not daemonize.*/ if (config->runSequentialBuild()) { return build(config, graphPtr); } /* Start the daemon. */ daemonize(std::move(config), std::move(graphPtr)); return 0; } <commit_msg>Fix useless help line<commit_after>/** * Copyright : falcon build system (c) 2014. * LICENSE : see accompanying LICENSE file for details. */ #include <iostream> #include <cstdlib> #include "daemon_instance.h" #include "exceptions.h" #include "graph.h" #include "graph_consistency_checker.h" #include "graph_dependency_scan.h" #include "logging.h" #include "options.h" #include "stream_consumer.h" static void setOptions(falcon::Options& opt) { /* get the default working directory path from then environment variable */ char const* pwd = NULL; pwd = getenv("PWD"); /* No need to free this string */ if (!pwd) { LOG(ERROR) << "enable to get the PWD"; return; } std::string pwdString(pwd); /* *********************************************************************** */ /* add command line options */ opt.addCLIOption("daemon,d", "daemonize the build system"); opt.addCLIOption("build,b", "launch a sequential build"); opt.addCLIOption("module,M", po::value<std::string>(), "use -M help for more info"); opt.addCLIOption("config,f", /* TODO */ po::value<std::string>(), "falcon configuration file"); /* *********************************************************************** */ /* add command line option and configuration file option (this options can be * setted on both configuration file or from the CLI) */ opt.addCFileOption("working-directory", po::value<std::string>()->default_value(pwdString), "falcon working directory path"); opt.addCFileOption("graph", po::value<std::string>()->default_value("makefile.json"), "falcon graph file"); opt.addCFileOption("api-port", po::value<int>()->default_value(4242), "the API listening port"); opt.addCFileOption("stream-port", po::value<int>()->default_value(4343), "stream port"); opt.addCFileOption("log-level", po::value<google::LogSeverity>()->default_value(google::GLOG_WARNING), "define the log level"); opt.addCFileOption("log-dir", po::value<std::string>(), "write log files in the given directory"); } static int loadModule(falcon::Graph& g, std::string const& s) { LOG(INFO) << "load module '" << s << "'"; if (0 == s.compare("dot")) { printGraphGraphiz(g, std::cout); } else if (0 == s.compare("make")) { printGraphMakefile(g, std::cout); } else if (0 == s.compare("help")) { std::cout << "list of available modules: " << std::endl << " dot show the graph in DOT format" << std::endl << " make show the graph in Makefile format" << std::endl; } else { LOG(ERROR) << "module '" << s << "' not supported"; return 1; } return 0; } /** * Daemonize the current process. */ static void daemonize(std::unique_ptr<falcon::GlobalConfig> config, std::unique_ptr<falcon::Graph> graph) { /** the double-fork-and-setsid trick establishes a child process that runs in * its own process group with its own session and that won't get killed off * when your shell exits (for example). */ if (fork()) { return; } setsid(); if (fork()) { _exit(0); } falcon::DaemonInstance daemon(std::move(config)); daemon.loadConf(std::move(graph)); daemon.start(); } /** Start a build. */ static int build(const std::unique_ptr<falcon::GlobalConfig>& config, const std::unique_ptr<falcon::Graph>& graph) { falcon::StdoutStreamConsumer consumer; std::mutex mutex; falcon::GraphSequentialBuilder builder(*graph, mutex, nullptr /* watchmanClient */, config->getWorkingDirectoryPath(), &consumer); builder.startBuild(graph->getRoots(), false /* No callback. */); builder.wait(); FALCON_CHECK_GRAPH_CONSISTENCY(graph.get(), mutex); return builder.getResult() == falcon::BuildResult::SUCCEEDED ? 0 : 1; } int main (int const argc, char const* const* argv) { falcon::Options opt; setOptions(opt); /* parse the command line options */ try { opt.parseOptions(argc, argv); } catch (falcon::Exception& e) { if (e.getCode () != 0) { // the help throw a SUCCESS code, no error to show std::cerr << e.getErrorMessage() << std::endl; } return e.getCode(); } std::unique_ptr<falcon::GlobalConfig> config(new falcon::GlobalConfig(opt)); /* Analyze the graph given in the configuration file */ falcon::GraphParser graphParser; try { graphParser.processFile(config->getJsonGraphFile()); } catch (falcon::Exception& e) { LOG(ERROR) << e.getErrorMessage (); return e.getCode(); } std::unique_ptr<falcon::Graph> graphPtr = std::move(graphParser.getGraph()); /* Check the graph for cycles. */ try { checkGraphLoop(*graphPtr); } catch (falcon::Exception& e) { LOG(ERROR) << e.getErrorMessage(); return e.getCode(); } /* Scan the graph to discover what needs to be rebuilt, and compute the * hashes of all nodes. */ falcon::GraphDependencyScan scanner(*graphPtr); scanner.scan(); /* if a module has been requested to execute then load it and return */ if (opt.isOptionSetted("module")) { return loadModule(*graphPtr, opt.vm_["module"].as<std::string>()); } /* User explicitly requires a build. Do not daemonize.*/ if (config->runSequentialBuild()) { return build(config, graphPtr); } /* Start the daemon. */ daemonize(std::move(config), std::move(graphPtr)); return 0; } <|endoftext|>
<commit_before>/* * Copyright 2014, 2017 Matthew Harvey * * 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 "application.hpp" #include "info.hpp" #include "stream_utilities.hpp" #include <cassert> #include <cstdlib> #include <iostream> #include <stdexcept> #include <string> #include <vector> using std::cerr; using std::cout; using std::endl; using std::runtime_error; using std::string; using std::vector; using swx::enable_exceptions; using swx::Info; using swx::Application; int main(int argc, char** argv) { try { enable_exceptions(cout); if (argc < 2) { cerr << "Command not provided.\n" << Application::directions_to_get_help() << endl; return EXIT_FAILURE; } assert (argc >= 2); vector<string> const args(argv + 2, argv + argc); auto const config_path = Info::home_dir() + "/.swxrc"; // non-portable Application const manager(config_path); return manager.process_command(argv[1], args); } catch (runtime_error& e) { cerr << "Error: " << e.what() << endl; return EXIT_FAILURE; } catch (...) { // Ensure stack is fully unwound. throw; } } <commit_msg>Minor variable name change<commit_after>/* * Copyright 2014, 2017 Matthew Harvey * * 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 "application.hpp" #include "info.hpp" #include "stream_utilities.hpp" #include <cassert> #include <cstdlib> #include <iostream> #include <stdexcept> #include <string> #include <vector> using std::cerr; using std::cout; using std::endl; using std::runtime_error; using std::string; using std::vector; using swx::enable_exceptions; using swx::Info; using swx::Application; int main(int argc, char** argv) { try { enable_exceptions(cout); if (argc < 2) { cerr << "Command not provided.\n" << Application::directions_to_get_help() << endl; return EXIT_FAILURE; } assert (argc >= 2); vector<string> const args(argv + 2, argv + argc); auto const config_path = Info::home_dir() + "/.swxrc"; // non-portable Application const application(config_path); return application.process_command(argv[1], args); } catch (runtime_error& e) { cerr << "Error: " << e.what() << endl; return EXIT_FAILURE; } catch (...) { // Ensure stack is fully unwound. throw; } } <|endoftext|>
<commit_before>#include "main.h" int main(int argc, char* argv[]) { //Init Logger FLAGS_logtostderr = 1; google::InitGoogleLogging("OpenKAI"); printEnvironment(); //Load config LOG(INFO)<<"Kiss file:"<<argv[1]; string kissFile(argv[1]); if(!g_file.open(&kissFile)) { LOG(ERROR)<<"Kiss file not found"; return 1; } string* pKiss = g_file.readAll(); if(pKiss==NULL) { LOG(ERROR)<<"Cannot open Kiss file"; return 1; } if(pKiss->empty()) { LOG(ERROR)<<"Cannot open Kiss file"; return 1; } g_pKiss = new Kiss(); if(!g_pKiss->parse(pKiss)) { LOG(ERROR)<<"Kiss file parsing failed"; return 1; } g_file.close(); //Start Application g_pStart = new Startup(); g_pStart->start(g_pKiss); return 0; } void printEnvironment(void) { #ifndef USE_OPENCV4TEGRA LOG(INFO)<<"OpenCV optimized code:"<<useOptimized(); LOG(INFO)<<"CUDA devices:"<<cuda::getCudaEnabledDeviceCount(); LOG(INFO)<<"Using CUDA device:"<<cuda::getDevice(); if (ocl::haveOpenCL()) { LOG(INFO)<<"OpenCL is found"; ocl::setUseOpenCL(true); if (ocl::useOpenCL()) { LOG(INFO)<<"Using OpenCL"; } } else { LOG(INFO)<<"OpenCL not found"; } #endif } <commit_msg>Added argc check<commit_after>#include "main.h" int main(int argc, char* argv[]) { //Init Logger FLAGS_logtostderr = 1; google::InitGoogleLogging("OpenKAI"); printEnvironment(); //Check arg if(argc < 2) { LOG(INFO)<<"Usage: ./OpenKAI [kiss file]"; return 1; } //Load config LOG(INFO)<<"Kiss file:"<<argv[1]; string kissFile(argv[1]); if(!g_file.open(&kissFile)) { LOG(ERROR)<<"Kiss file not found"; return 1; } string* pKiss = g_file.readAll(); if(pKiss==NULL) { LOG(ERROR)<<"Cannot open Kiss file"; return 1; } if(pKiss->empty()) { LOG(ERROR)<<"Cannot open Kiss file"; return 1; } g_pKiss = new Kiss(); if(!g_pKiss->parse(pKiss)) { LOG(ERROR)<<"Kiss file parsing failed"; return 1; } g_file.close(); //Start Application g_pStart = new Startup(); g_pStart->start(g_pKiss); return 0; } void printEnvironment(void) { #ifndef USE_OPENCV4TEGRA LOG(INFO)<<"OpenCV optimized code:"<<useOptimized(); LOG(INFO)<<"CUDA devices:"<<cuda::getCudaEnabledDeviceCount(); LOG(INFO)<<"Using CUDA device:"<<cuda::getDevice(); if (ocl::haveOpenCL()) { LOG(INFO)<<"OpenCL is found"; ocl::setUseOpenCL(true); if (ocl::useOpenCL()) { LOG(INFO)<<"Using OpenCL"; } } else { LOG(INFO)<<"OpenCL not found"; } #endif } <|endoftext|>
<commit_before>#include <cstdlib> #include <cstdio> #include "SDL.h" #include "SDL_opengles.h" #include "canvas/CanvasContext.h" #include "script/Script.h" #include "AmityContext.h" #include "log.h" #include "assets.h" #define FPS_INTERVAL (5000) static SDL_Window* window; static AmityContext amityCtx; Uint32 delayFrame () { static Uint32 nextTick = 0; Uint32 currentTick = SDL_GetTicks(); Uint32 delay = 0; if (currentTick < nextTick) { delay = nextTick - currentTick; SDL_Delay(delay); } nextTick = currentTick + (1000/60); return delay; } void loadScript (Script* script, const char *filename) { // TODO: C++ stream IO char buffer[500 * 1024]; SDL_RWops* asset = loadAsset(filename); if (asset == NULL) { exit(1); } int r = SDL_RWread(asset, buffer, sizeof(char), sizeof(buffer)); buffer[r] = '\0'; script->parse(filename, buffer); } void mainLoop () { SDL_Event event; int x = 0, y = 0; Uint32 fpsFrames = 0; Uint32 fpsTime = 0; Uint32 lastTime = SDL_GetTicks(); loadScript(&amityCtx.script, "app.js"); for (;;) { Uint32 startTime = SDL_GetTicks(); while (SDL_PollEvent(&event)) { amityCtx.script.onEvent(&event); if (event.type == SDL_QUIT) { return; } } glClearColor(0.1, 0.1, 0.1, 1.0); glClear(GL_COLOR_BUFFER_BIT); Uint32 nowTime = SDL_GetTicks(); Uint32 elapsed = nowTime - lastTime; lastTime = nowTime; ++fpsFrames; fpsTime += elapsed; if (fpsTime > FPS_INTERVAL) { float fps = 1000 * (float)fpsFrames / fpsTime; LOGI("FPS: %.2f (%i frames in %.2fs)", fps, fpsFrames, (float)fpsTime/1000); fpsTime = 0; fpsFrames = 0; } amityCtx.script.onEnterFrame(elapsed); SDL_GL_SwapWindow(window); delayFrame(); } } int main (int argc, char* argv[]) { LOGI("Main screen turn on, compiled " __DATE__ " at " __TIME__); if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO) < 0) { LOGE("Unable to init SDL: %s", SDL_GetError()); return 1; } atexit(SDL_Quit); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 0); SDL_GL_SetAttribute(SDL_GL_RETAINED_BACKING, 0); SDL_GL_SetAttribute(SDL_GL_ACCELERATED_VISUAL, 1); window = SDL_CreateWindow(NULL, 0, 0, 0, 0, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN | SDL_WINDOW_BORDERLESS); if (window == NULL) { LOGE("Unable to create window: %s", SDL_GetError()); return 1; } amityCtx.window = window; int width, height; SDL_GetWindowSize(window, &width, &height); LOGI("Created window [width=%i, height=%i]", width, height); SDL_GL_CreateContext(window); SDL_GL_SetSwapInterval(1); glViewport(0, 0, width, height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrthof(0, width, height, 0, 0, 1); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); mainLoop(); LOGI("Quitting normally"); return 0; } <commit_msg>Helpful comment for a cryptic function call.<commit_after>#include <cstdlib> #include <cstdio> #include "SDL.h" #include "SDL_opengles.h" #include "canvas/CanvasContext.h" #include "script/Script.h" #include "AmityContext.h" #include "log.h" #include "assets.h" #define FPS_INTERVAL (5000) static SDL_Window* window; static AmityContext amityCtx; Uint32 delayFrame () { static Uint32 nextTick = 0; Uint32 currentTick = SDL_GetTicks(); Uint32 delay = 0; if (currentTick < nextTick) { delay = nextTick - currentTick; SDL_Delay(delay); } nextTick = currentTick + (1000/60); return delay; } void loadScript (Script* script, const char *filename) { // TODO: C++ stream IO char buffer[500 * 1024]; SDL_RWops* asset = loadAsset(filename); if (asset == NULL) { exit(1); } int r = SDL_RWread(asset, buffer, sizeof(char), sizeof(buffer)); buffer[r] = '\0'; script->parse(filename, buffer); } void mainLoop () { SDL_Event event; int x = 0, y = 0; Uint32 fpsFrames = 0; Uint32 fpsTime = 0; Uint32 lastTime = SDL_GetTicks(); loadScript(&amityCtx.script, "app.js"); for (;;) { Uint32 startTime = SDL_GetTicks(); while (SDL_PollEvent(&event)) { amityCtx.script.onEvent(&event); if (event.type == SDL_QUIT) { return; } } glClearColor(0.1, 0.1, 0.1, 1.0); glClear(GL_COLOR_BUFFER_BIT); Uint32 nowTime = SDL_GetTicks(); Uint32 elapsed = nowTime - lastTime; lastTime = nowTime; ++fpsFrames; fpsTime += elapsed; if (fpsTime > FPS_INTERVAL) { float fps = 1000 * (float)fpsFrames / fpsTime; LOGI("FPS: %.2f (%i frames in %.2fs)", fps, fpsFrames, (float)fpsTime/1000); fpsTime = 0; fpsFrames = 0; } amityCtx.script.onEnterFrame(elapsed); SDL_GL_SwapWindow(window); delayFrame(); } } int main (int argc, char* argv[]) { LOGI("Main screen turn on, compiled " __DATE__ " at " __TIME__); if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO) < 0) { LOGE("Unable to init SDL: %s", SDL_GetError()); return 1; } atexit(SDL_Quit); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 0); SDL_GL_SetAttribute(SDL_GL_RETAINED_BACKING, 0); SDL_GL_SetAttribute(SDL_GL_ACCELERATED_VISUAL, 1); window = SDL_CreateWindow(NULL, 0, 0, 0, 0, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN | SDL_WINDOW_BORDERLESS); if (window == NULL) { LOGE("Unable to create window: %s", SDL_GetError()); return 1; } amityCtx.window = window; int width, height; SDL_GetWindowSize(window, &width, &height); LOGI("Created window [width=%i, height=%i]", width, height); SDL_GL_CreateContext(window); SDL_GL_SetSwapInterval(1); // Enable vsync glViewport(0, 0, width, height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrthof(0, width, height, 0, 0, 1); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); mainLoop(); LOGI("Quitting normally"); return 0; } <|endoftext|>
<commit_before>#include "common.hpp" #include "graph.hpp" #include "aco_parameters.hpp" #include "aco_parallel_strategy.hpp" #include "aco_sequential_strategy.hpp" #include "metaheuristic.hpp" #include "aco.hpp" #include "INI.hpp" Metaheuristic *metaheuristic = NULL; int debug = 0; void terminte_work(int sig) { if (metaheuristic) { metaheuristic->terminate(); } } int main(int argc, char* argv[]) { signal(SIGINT, terminte_work); string instance_file; string config_file; if(argc == 2) { //default config config_file = "config.ini"; } else if (argc == 3) { //given config config_file = argv[2]; cout << "Config from " << config_file << endl; } else { cout << "Usage: \n\tsequencing-ants <input file> <config file>(optional)\n"; return 0; } instance_file = argv[1]; unsigned max_solution_length; { unsigned pos = instance_file.find("."); if (pos == string::npos) { cerr << "Bad filename format, use: *.<n>*" << endl; return 1; } sscanf(instance_file.substr(pos + 1).c_str(), "%u", &max_solution_length); if (max_solution_length == 0) { cerr << "n == 0, bad filename format, use: *.<n>*" << endl; return 1; } } ini_t ini(config_file, true); ini.select("global"); bool parallel = ini.get<bool>("parallel", 0); debug = ini.get<int>("debug", 0); Graph *graph = new Graph(instance_file); if(graph->get_size() == 0) { cout << "Graph initialization failed\n"; return 0; } max_solution_length += graph->get_node_size() - 1; if (debug >= 2) { cout << "n = " << max_solution_length << endl; } ini.select("ACOParameters"); ACOParameters params( ini.get<double>("alpha", ALPHA), ini.get<double>("beta", BETA), ini.get<double>("gamma", GAMMA), ini.get<unsigned>("number_of_ants", NUMBER_OF_ANTS), max_solution_length, ini.get<double>("q_param", Q_PARAM), ini.get<double>("r_param", R_PARAM), ini.get<double>("ro", RO), ini.get<double>("max_pheromones_multiplier", MAX_PHEROMONES_MULTIPLIER), ini.get<double>("amplify_best", AMPLIFY_BEST) ); if(debug) cout << params << endl; if(debug >= 4) cout << *graph << endl; ACOStrategy *strategy; if (parallel) { strategy = new ACOParallelStrategy(&params); } else { strategy = new ACOSequentialStrategy(&params); } metaheuristic = new ACO(graph, strategy, &params); metaheuristic->optimize(); delete strategy; delete metaheuristic; delete graph; return 0; } <commit_msg>Segfault<commit_after>#include "common.hpp" #include "graph.hpp" #include "aco_parameters.hpp" #include "aco_parallel_strategy.hpp" #include "aco_sequential_strategy.hpp" #include "metaheuristic.hpp" #include "aco.hpp" #include "INI.hpp" Metaheuristic *metaheuristic = NULL; int debug = 0; void terminte_work(int sig) { if (metaheuristic) { metaheuristic->terminate(); } } int main(int argc, char* argv[]) { signal(SIGINT, terminte_work); string instance_file; string config_file; if(argc == 2) { //default config config_file = "config.ini"; } else if (argc == 3) { //given config config_file = argv[2]; cout << "Config from " << config_file << endl; } else { cout << "Usage: \n\tsequencing-ants <input file> <config file>(optional)\n"; return 0; } instance_file = argv[1]; unsigned max_solution_length; { unsigned pos = instance_file.find("."); if (pos == string::npos) { cerr << "Bad filename format, use: *.<n>*" << endl; return 1; } sscanf(instance_file.substr(pos + 1).c_str(), "%u", &max_solution_length); if (max_solution_length == 0) { cerr << "n == 0, bad filename format, use: *.<n>*" << endl; return 1; } } ini_t ini(config_file, true); ini.select("global"); bool parallel = ini.get<bool>("parallel", 0); debug = ini.get<int>("debug", 0); Graph *graph = new Graph(instance_file); if(graph->get_size() == 0) { cout << "Graph initialization failed\n"; return 0; } max_solution_length += graph->get_node_size() - 1; if (debug >= 2) { cout << "n = " << max_solution_length << endl; } ini.select("ACOParameters"); ACOParameters params( ini.get<double>("alpha", ALPHA), ini.get<double>("beta", BETA), ini.get<double>("gamma", GAMMA), ini.get<unsigned>("number_of_ants", NUMBER_OF_ANTS), max_solution_length, ini.get<double>("q_param", Q_PARAM), ini.get<double>("r_param", R_PARAM), ini.get<double>("ro", RO), ini.get<double>("max_pheromones_multiplier", MAX_PHEROMONES_MULTIPLIER), ini.get<double>("amplify_best", AMPLIFY_BEST) ); if(debug) cout << params << endl; if(debug >= 4) cout << *graph << endl; ACOStrategy *strategy; if (parallel) { strategy = new ACOParallelStrategy(&params); } else { strategy = new ACOSequentialStrategy(&params); } metaheuristic = new ACO(graph, strategy, &params); metaheuristic->optimize(); delete metaheuristic; delete graph; return 0; } <|endoftext|>
<commit_before>#include <stdlib.h> #include <algorithm> #include <iostream> #include <vector> #include <unistd.h> #include <dirent.h> #include <fstream> #include <queue> #include "omp.h" struct Settings { Settings(): extract(), compress(), verbose() {} bool extract; bool compress; bool verbose; }; void helpCheck(char *argv[]) { if (argv[1] == std::string("-h") || argv[1] == std::string("--help")) { std::cout << "\nptxv - Parallel Tar XZ by Ryan Chui (2017)\n" << std::endl; exit(0); } } void getSettings(int argc, char *argv[], Settings *instance) { std::queue<std::string> settings; for (int i = 0; i < argc; ++i) { settings.push(argv[i]); } while (!settings.empty()) { std::cout << settings.pop() << std::endl; } } void findAll(int *numFiles, const char *cwd) { DIR *dir; struct dirent *ent; // Check if cwd is a directory if ((dir = opendir(cwd)) != NULL) { // Get all file paths within directory. while ((ent = readdir (dir)) != NULL) { std::string fileBuff = std::string(ent -> d_name); if (fileBuff != "." && fileBuff != "..") { DIR *dir2; std::string filePath = std::string(cwd) + "/" + fileBuff; // Check if file path is a directory. if ((dir2 = opendir(filePath.c_str())) != NULL) { closedir(dir2); findAll(numFiles, filePath.c_str()); } else { *numFiles += 1; } } } closedir(dir); } } void getPaths(std::vector<std::string> *filePaths, const char *cwd, std::string rootPath) { DIR *dir; struct dirent *ent; // Check if cwd is a directory if ((dir = opendir(cwd)) != NULL) { // Get all file paths within directory. while ((ent = readdir (dir)) != NULL) { std::string fileBuff = std::string(ent -> d_name); if (fileBuff != "." && fileBuff != "..") { DIR *dir2; std::string filePath = std::string(cwd) + "/" + fileBuff; // Check if file path is a directory. if ((dir2 = opendir(filePath.c_str())) != NULL) { closedir(dir2); getPaths(filePaths, filePath.c_str(), rootPath + fileBuff + "/"); } else { filePaths->push_back(rootPath + fileBuff); } } } closedir(dir); } } void compression(std::vector<std::string> *filePaths) { unsigned long long int filePathSize = filePaths->size(); unsigned long long int blockSize = (filePathSize / (omp_get_max_threads() * 10)) + 1; std::vector<std::string> *tarNames = new std::vector<std::string>(); #pragma omp parallel for schedule(dynamic) for (int i = 0; i < omp_get_max_threads() * 10; ++i) { unsigned long long int start = blockSize * i; if (start < filePathSize) { std::string xzCommand = "XZ_OPT=-1 tar cJf test." + std::to_string(i) + ".tar.xz"; for (unsigned long long int j = start; j < std::min(start + blockSize, filePathSize); ++j) { xzCommand += " " + filePaths->at(j); } system(xzCommand.c_str()); #pragma omp crtical { tarNames->push_back("test." + std::to_string(i) + ".tar.xz"); } } } std::string tarCommand = "tar cf ptxz.output.tar"; for (int i = 0; i < tarNames->size(); ++i) { tarCommand += " " + tarNames->at(i); } system(tarCommand.c_str()); std::string rmCommand = "rm"; for (int i = 0; i < tarNames->size(); ++i) { rmCommand += " " + tarNames->at(i); } system(rmCommand.c_str()); delete(tarNames); } char cwd [PATH_MAX]; int main(int argc, char *argv[]) { Settings *instance = new Settings; int *numFiles = new int(0); helpCheck(argv); getSettings(argc, argv, instance); getcwd(cwd, PATH_MAX); findAll(numFiles, cwd); // std::cout << *numFiles << std::endl; std::vector<std::string> *filePaths = new std::vector<std::string>(); getPaths(filePaths, cwd, ""); compression(filePaths); delete(numFiles); delete(filePaths); return 0; } <commit_msg>using front instead of pop<commit_after>#include <stdlib.h> #include <algorithm> #include <iostream> #include <vector> #include <unistd.h> #include <dirent.h> #include <fstream> #include <queue> #include "omp.h" struct Settings { Settings(): extract(), compress(), verbose() {} bool extract; bool compress; bool verbose; }; void helpCheck(char *argv[]) { if (argv[1] == std::string("-h") || argv[1] == std::string("--help")) { std::cout << "\nptxv - Parallel Tar XZ by Ryan Chui (2017)\n" << std::endl; exit(0); } } void getSettings(int argc, char *argv[], Settings *instance) { std::queue<std::string> settings; for (int i = 0; i < argc; ++i) { settings.push(argv[i]); } while (!settings.empty()) { std::cout << settings.front() << std::endl; } } void findAll(int *numFiles, const char *cwd) { DIR *dir; struct dirent *ent; // Check if cwd is a directory if ((dir = opendir(cwd)) != NULL) { // Get all file paths within directory. while ((ent = readdir (dir)) != NULL) { std::string fileBuff = std::string(ent -> d_name); if (fileBuff != "." && fileBuff != "..") { DIR *dir2; std::string filePath = std::string(cwd) + "/" + fileBuff; // Check if file path is a directory. if ((dir2 = opendir(filePath.c_str())) != NULL) { closedir(dir2); findAll(numFiles, filePath.c_str()); } else { *numFiles += 1; } } } closedir(dir); } } void getPaths(std::vector<std::string> *filePaths, const char *cwd, std::string rootPath) { DIR *dir; struct dirent *ent; // Check if cwd is a directory if ((dir = opendir(cwd)) != NULL) { // Get all file paths within directory. while ((ent = readdir (dir)) != NULL) { std::string fileBuff = std::string(ent -> d_name); if (fileBuff != "." && fileBuff != "..") { DIR *dir2; std::string filePath = std::string(cwd) + "/" + fileBuff; // Check if file path is a directory. if ((dir2 = opendir(filePath.c_str())) != NULL) { closedir(dir2); getPaths(filePaths, filePath.c_str(), rootPath + fileBuff + "/"); } else { filePaths->push_back(rootPath + fileBuff); } } } closedir(dir); } } void compression(std::vector<std::string> *filePaths) { unsigned long long int filePathSize = filePaths->size(); unsigned long long int blockSize = (filePathSize / (omp_get_max_threads() * 10)) + 1; std::vector<std::string> *tarNames = new std::vector<std::string>(); #pragma omp parallel for schedule(dynamic) for (int i = 0; i < omp_get_max_threads() * 10; ++i) { unsigned long long int start = blockSize * i; if (start < filePathSize) { std::string xzCommand = "XZ_OPT=-1 tar cJf test." + std::to_string(i) + ".tar.xz"; for (unsigned long long int j = start; j < std::min(start + blockSize, filePathSize); ++j) { xzCommand += " " + filePaths->at(j); } system(xzCommand.c_str()); #pragma omp crtical { tarNames->push_back("test." + std::to_string(i) + ".tar.xz"); } } } std::string tarCommand = "tar cf ptxz.output.tar"; for (int i = 0; i < tarNames->size(); ++i) { tarCommand += " " + tarNames->at(i); } system(tarCommand.c_str()); std::string rmCommand = "rm"; for (int i = 0; i < tarNames->size(); ++i) { rmCommand += " " + tarNames->at(i); } system(rmCommand.c_str()); delete(tarNames); } char cwd [PATH_MAX]; int main(int argc, char *argv[]) { Settings *instance = new Settings; int *numFiles = new int(0); helpCheck(argv); getSettings(argc, argv, instance); getcwd(cwd, PATH_MAX); findAll(numFiles, cwd); // std::cout << *numFiles << std::endl; std::vector<std::string> *filePaths = new std::vector<std::string>(); getPaths(filePaths, cwd, ""); compression(filePaths); delete(numFiles); delete(filePaths); return 0; } <|endoftext|>
<commit_before>#include <unistd.h> #include "glload/gl_3_2.h" #include "glload/gll.hpp" #include <GL/glfw.h> #include <cassert> #include "render/shaderpipeline.hpp" #include "heightmap/heightmapgenerator.hpp" int main(int argc, char** argv) { glfwInit(); glfwOpenWindowHint(GLFW_FSAA_SAMPLES, 8); glfwOpenWindowHint(GLFW_OPENGL_VERSION_MAJOR, 3); glfwOpenWindowHint(GLFW_OPENGL_VERSION_MINOR, 2); glfwOpenWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwOpenWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwOpenWindow(1024, 768, 8, 8, 8, 8, 24, 24, GLFW_WINDOW); glfwSetWindowTitle("OpenGL 3.2 Core profile test"); //Load OpenGL functions if(glload::LoadFunctions() == glload::LS_LOAD_FAILED) { return 1; } glViewport(0, 0, 1024, 768); //Set clear colour to black glClearColor(0.0f, 0.0f, 0.0f, 1.0f); GLuint vaos[1]; glGenVertexArrays(1, vaos); glBindVertexArray(vaos[0]); GLuint vbos[1]; glGenBuffers(1, vbos); glBindBuffer(GL_ARRAY_BUFFER, vbos[0]); HeightmapGenerator* hmgen = new HeightmapGenerator(1025, 0, 512); hmgen->fillMap(); hmgen->convertMap(); unsigned int vertexCount = hmgen->getVertexCount(); glBufferData(GL_ARRAY_BUFFER, vertexCount * sizeof(HMVertex), hmgen->getVertices(), GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_INT, GL_TRUE, 0, 0); render::ShaderPipeLine shaderpipe("Vertex-Pass Y", "Fragment-Colour Height"); shaderpipe.addShaderAttribute("vertex"); shaderpipe.linkPipeLine(); GLuint shaderProgram = shaderpipe.getShaderProgram(); glUseProgram(shaderProgram); while(true) { usleep(500000); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); glDrawArrays(GL_TRIANGLE_STRIP, 0, 9); glfwSwapBuffers(); } glfwTerminate(); } <commit_msg>Make main render heightmap-model theoretically<commit_after>#include <unistd.h> #include "glload/gl_3_2.h" #include "glload/gll.hpp" #include <GL/glfw.h> #include <cassert> #include "render/shaderpipeline.hpp" #include "heightmap/heightmapgenerator.hpp" int main(int argc, char** argv) { glfwInit(); glfwOpenWindowHint(GLFW_FSAA_SAMPLES, 8); glfwOpenWindowHint(GLFW_OPENGL_VERSION_MAJOR, 3); glfwOpenWindowHint(GLFW_OPENGL_VERSION_MINOR, 2); glfwOpenWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwOpenWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwOpenWindow(1024, 768, 8, 8, 8, 8, 24, 24, GLFW_WINDOW); glfwSetWindowTitle("OpenGL 3.2 Core profile test"); //Load OpenGL functions if(glload::LoadFunctions() == glload::LS_LOAD_FAILED) { return 1; } glViewport(0, 0, 1024, 768); //Set clear colour to black glClearColor(0.0f, 0.0f, 0.0f, 1.0f); GLuint vaos[1]; glGenVertexArrays(1, vaos); glBindVertexArray(vaos[0]); GLuint vbos[1]; glGenBuffers(1, vbos); glBindBuffer(GL_ARRAY_BUFFER, vbos[0]); HeightmapGenerator* hmgen = new HeightmapGenerator(1025, 0, 512); hmgen->fillMap(); hmgen->convertMap(); unsigned int vertexCount = hmgen->getVertexCount(); glBufferData(GL_ARRAY_BUFFER, vertexCount * sizeof(HMVertex), hmgen->getVertices(), GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, GL_TRUE, 0, 0); render::ShaderPipeLine shaderpipe("Vertex-Pass Y", "Fragment-Colour Height"); shaderpipe.addShaderAttribute("vertex"); shaderpipe.linkPipeLine(); GLuint shaderProgram = shaderpipe.getShaderProgram(); glUseProgram(shaderProgram); while(true) { usleep(500000); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); glDrawArrays(GL_TRIANGLE_STRIP, 0, vertexCount); glfwSwapBuffers(); } glfwTerminate(); } <|endoftext|>
<commit_before>/* Michael Chen mchen046 SID: 861108671 CS100 Spring 2015: hw0-rshell https://www.github.com/mchen046/rshell/src/main.cpp */ /* Worklist: bug when running: ls -a; echo hello; mkdir test; the command exits when mkdir test finishes. problem when running ls -a multiple times ls -a breaks on the second execution "error in execvp: Bad address */ #include <iostream> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> #include <string.h> #include <string> #include <vector> #include <cstdlib> #include <stdio.h> #include <boost/tokenizer.hpp> #include <boost/token_iterator.hpp> using namespace std; using namespace boost; char** parseString(string cmd); void checkExitCmd(char* cmdText){ //exit command char exitText[] = {'e','x', 'i', 't'}; bool same = true; for(int i = 0; cmdText[i]!='\0' && same; i++){ if(cmdText[i]!=exitText[i]) same = false; } if(same) exit(1); } int main(){ while(1){ string cmd; cout << "$ "; getline(cin, cmd); //convert string to char[] char *cmdArray = new char[cmd.size()]; for(int i=0; i<static_cast<int>(cmd.size()); i++){ cmdArray[i] = cmd.at(i); } //cout << "cmdArray: " << cmdArray << endl; bool cmdLineDone = false; char *cmdLine = strtok(cmdArray, ";"); //parsing ";" while(!cmdLineDone){ //cout << "cmdLine: " << cmdLine << endl; //parsing " " string str = static_cast<string>(cmdLine); char_separator<char> delim(" "); tokenizer< char_separator<char> > mytok(str, delim); //creating cmdLinePart char **cmdLinePart = new char*[cmd.size()]; int i = 0; for(tokenizer <char_separator<char> >::iterator it = mytok.begin(); it!=mytok.end(); it++){ char *token = new char[cmd.size()]; string cmdString = static_cast<string>(*it); for(unsigned int j = 0; j!=cmdString.size(); j++){ token[j] = cmdString[j]; } cmdLinePart[i] = token; i++; } cmdLine = strtok(NULL, ";"); //parse ";" if(cmdLine==NULL){ cmdLineDone = true; } checkExitCmd(cmdLinePart[0]); //check for exit command //process spawning int pid = fork(); //cout << "pid: " << pid << endl; if(pid == -1){ //error perror("fork() error"); exit(1); } else if(pid == 0){ //child process cout << "in child process\n"; if(execvp(cmdLinePart[0], cmdLinePart) == -1){ perror("error in execvp"); } exit(1); } else if(pid > 0){ //parent process cout << "in parent process\n"; if(wait(0) == -1){ perror("error in wait()"); } } //delete[] *cmdLinePart; } //delete[] cmdLine; //delete[] cmdArray; } cout << "reached end of program\n"; return 0; } <commit_msg>added defined size for each command line<commit_after>/* Michael Chen mchen046 SID: 861108671 CS100 Spring 2015: hw0-rshell https://www.github.com/mchen046/rshell/src/main.cpp */ /* Worklist: bug when running: ls -a; echo hello; mkdir test; the command exits when mkdir test finishes. problem when running ls -a multiple times ls -a breaks on the second execution "error in execvp: Bad address */ #include <iostream> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> #include <string.h> #include <string> #include <vector> #include <cstdlib> #include <stdio.h> #include <boost/tokenizer.hpp> #include <boost/token_iterator.hpp> using namespace std; using namespace boost; char** parseString(string cmd); void checkExitCmd(char* cmdText){ //exit command char exitText[] = {'e','x', 'i', 't'}; bool same = true; for(int i = 0; cmdText[i]!='\0' && same; i++){ if(cmdText[i]!=exitText[i]) same = false; } if(same) exit(1); } int main(){ while(1){ string cmd; cout << "$ "; getline(cin, cmd); //convert string to char[] char *cmdArray = new char[cmd.size()]; for(int i=0; i<static_cast<int>(cmd.size()); i++){ cmdArray[i] = cmd.at(i); } //cout << "cmdArray: " << cmdArray << endl; bool cmdLineDone = false; char *cmdLine = strtok(cmdArray, ";"); //parsing ";" while(!cmdLineDone){ //cout << "cmdLine: " << cmdLine << endl; //parsing " " string str = static_cast<string>(cmdLine); char_separator<char> delim(" "); tokenizer< char_separator<char> > mytok(str, delim); //creating cmdLinePart char **cmdLinePart = new char*[cmd.size()]; //finding size of cmdLinePart int cmdLinePartSize = 0; for(tokenizer<char_separator<char> >::iterator it = mytok.begin(); it!=mytok.end(); it++){ cmdLinePartSize++; } int i = 0; for(tokenizer<char_separator<char> >::iterator it = mytok.begin(); it!=mytok.end(); it++){ char *token = new char[cmdLinePartSize+1]; string cmdString = static_cast<string>(*it); for(unsigned int j = 0; j!=cmdString.size(); j++){ token[j] = cmdString[j]; } cmdLinePart[i] = token; i++; tokenizer<char_separator<char> >::iterator itA = it; if(++itA==mytok.end()){ //cout << "adding NULL to end of cmdLinePart\n"; cmdLinePart[i+1] = NULL; } } cmdLine = strtok(NULL, ";"); //parse ";" if(cmdLine==NULL){ cmdLineDone = true; } checkExitCmd(cmdLinePart[0]); //check for exit command //process spawning int pid = fork(); //cout << "pid: " << pid << endl; if(pid == -1){ //error perror("fork() error"); cout << "exiting pid error msg\n"; exit(1); } else if(pid == 0){ //child process cout << "in child process\n"; if(execvp(cmdLinePart[0], cmdLinePart) == -1){ perror("error in execvp"); } cout << "exiting child process\n"; exit(1); } else if(pid > 0){ //parent process cout << "in parent process\n"; if(wait(0) == -1){ perror("error in wait()"); } } //delete[] *cmdLinePart; } //delete[] cmdLine; //delete[] cmdArray; } cout << "reached end of program\n"; return 0; } <|endoftext|>
<commit_before>#include "precompiled.h" #include "engine/math/random.h" #include "engine/actor/AISystem.h" #include "engine/EngineSystem.h" #include "engine/render/RenderSystem.h" #include "engine/UI/UISystem.h" #include "engine/UI/Window.h" #include "engine/UI/containers/TextContainer.h" #include "engine/UI/containers/SelectContainer.h" #include "engine/scene/SceneSystem.h" #include "engine/console/ConsoleSystem.h" #include "engine/actor/ActorManager.h" #include "engine/console/Cvar.h" #include "game/actor/player/PlayerActor.h" #include "game/item/PotionItem.h" #include "game/actor/npc/DummyActor.h" #include "game/UI/containers/StatsContainer.h" #include <cstring> //#include <boost/filesystem.hpp> #ifdef TERMRENDER #include "engine/render/term/TermRender.h" #endif #ifdef NULLRENDER #include "engine/render/null/NullRender.h" #endif namespace cvar { CVAR(int,developer,0); } void handleArgs(int argc,char *argv[]); int main(int argc, char *argv[]){ randomInit(); if(argc == 2){ handleArgs(argc,argv); } LOG_INFO("Engine starting"); #ifdef DEBUG //If this is debug build, enable developer by default *cvar::developer = 1; #endif if(*cvar::developer){ LOG_INFO("Developer mode enabled!"); printf("Developer mode is enabled!\n"); } engine::console::ConsoleSystem *consoleSystem = new engine::console::ConsoleSystem(); consoleSystem->init(); //Config loader planner: First try to read from the same directory, after that try to read from cfg location (~/. or %appdata%) if(!consoleSystem->loadConfig("config.cfg")){ //cfg loading from the run directory failed. Testing out the platform depended default directory #ifdef WINDOWS char* cfgDirectory = getenv("APPDATA"); const String cfgFolder = "\\ProjectIce\\"; const String cfgFilename = "ProjectIce.cfg"; #endif #ifdef LINUX char* cfgDirectory = "~/"; const String cfgFolder = ".projectice/"; const String cfgFilename = "ProjectIce.cfg"; #endif if(!consoleSystem->loadConfig(cfgDirectory + cfgFolder + cfgFilename) ){ LOG_INFO("No config files found, creating one to default directory."); //TODO: Create the folder here! Make sure it works on all platforms. //if(boost::filesystem::create_directory(cfgDirectory + cfgFolder)){ consoleSystem->saveConfig(cfgDirectory + cfgFolder + cfgFilename); // }else{ // LOG_ERROR("Could not create the directory! Your system permissions are fucked up."); // } } } game::actor::player::PlayerActor * playerActor = new game::actor::player::PlayerActor(); playerActor->setName("Player"); playerActor->setPosition(vec2(10,10)); playerActor->setLocation(vec3(0,0,0)); engine::world::WorldSystem * worldSystem = new engine::world::WorldSystem(); worldSystem->init(); worldSystem->generate(); playerActor->setWorld(worldSystem); engine::actor::ActorManager * actorManager = new engine::actor::ActorManager(); engine::scene::SceneSystem *scene = new engine::scene::SceneSystem(worldSystem,actorManager,playerActor); game::item::PotionItem * pi = new game::item::PotionItem(); scene->addItem(pi); engine::UI::UISystem *ui = new engine::UI::UISystem(); engine::actor::AISystem *ai = new engine::actor::AISystem(actorManager,worldSystem); #ifdef TERMRENDER engine::render::RenderSystem *render = new engine::render::term::TermRender(scene,ui); #endif #ifdef NULLRENDER engine::render::RenderSystem *render = new engine::render::null::NullRender(scene,ui); #endif render->init(); ui->init(); ai->init(); engine::UI::Window welcomeWindow; welcomeWindow.setPos(vec2(4,3)); welcomeWindow.setSize(vec2(35,15)); welcomeWindow.setName("Welcome to ProjectIce"); engine::UI::containers::TextContainer *textCont = new engine::UI::containers::TextContainer(); textCont->init(); textCont->setText("ProjectIce is an experimental roguelike project developed in C++. This is a early development build. And this string is useless and long to test the word wrapping feature on the textContainer. -- press anykey to continue --"); welcomeWindow.setContainer(textCont); // ui->addWindow(welcomeWindow); /* engine::UI::Window blob; blob.setPos(vec2(84,3)); blob.setSize(vec2(15,15)); blob.setName("blob"); engine::UI::containers::SelectContainer *selectCont = new engine::UI::containers::SelectContainer(); selectCont->insertItem("0 zero"); selectCont->insertItem("& second"); selectCont->insertItem("# so on"); blob.setContainer(selectCont); ui->addWindow(blob); */ engine::UI::Window statsWindow; statsWindow.setPos(vec2(84,3)); statsWindow.setSize(vec2(15,15)); statsWindow.setName("Stats"); game::UI::containers::StatsContainer *statsUI = new game::UI::containers::StatsContainer(); statsUI->setPlayerActor(playerActor); statsWindow.setContainer(statsUI); ui->addWindow(statsWindow); /* * Testing area for the NPCs */ engine::world::Tile voidTile; //force it to dungeon also LOG_INFO("Building testing area"); worldSystem->getRoom( vec3(0,0,0) )->roomType = engine::world::ROOM_TYPE_DUNGEON; worldSystem->getRoom( vec3(0,0,0) )->generate(); voidTile.setType(engine::world::TILE_TREE); for(int x = 7;x < 20;++x){ for(int y = 7;y < 20;++y){ worldSystem->getRoom( vec3(0,0,0) )->setTile(x,y,voidTile); } } voidTile.setType(engine::world::TILE_VOID); for(int x = 8;x < 19;++x){ for(int y = 8;y < 19;++y){ worldSystem->getRoom( vec3(0,0,0) )->setTile(x,y,voidTile); } } //Add some Dummy Ai for testing. for(int i = 0;i < 5;++i){ game::actor::npc::DummyActor * dummy = new game::actor::npc::DummyActor(); dummy->setWorld( worldSystem ); dummy->setPosition( vec2(10+i,15) ); dummy->setLocation( vec3(0,0,0) ); scene->getActorManager()->insertActorToRoom(dummy); } game::actor::npc::DummyActor * dummy = new game::actor::npc::DummyActor(); dummy->setWorld( worldSystem ); dummy->setPosition( vec2(11,11) ); dummy->setLocation( vec3(0,0,0) ); dummy->setAIState(engine::actor::AISTATE_SLEEP); scene->getActorManager()->insertActorToRoom(dummy); worldSystem->getRoom( vec3(0,0,0) )->printLayout(); //printf("CvarCount: %lu\n",engine::console::ConsoleSystem::getCVarList().size()); // consoleSystem->saveConfig("config.cfg"); bool quitStatus = false; while(quitStatus == false){ scene->update(); ai->update(); render->update(); ui->update(); } ai->uninit(); render->uninit(); scene->uninit(); consoleSystem->uninit(); return 0; } void handleArgs(int argc, char *argv[]){ if(std::strcmp(argv[1],"-createconfig") == 0){ //Create console system just to save default cvar settings engine::console::ConsoleSystem *consoleSystem = new engine::console::ConsoleSystem(); consoleSystem->saveConfig("./config.cfg"); printf("Default config created into ./config.cfg\n"); printf("Exitting...\n"); exit(0); } if(std::strcmp(argv[1],"-help") == 0){ printf("/-(ProjectIce special commands)--------------\\\n"); printf("| -| create default configs |\n"); printf("| -help | show this help |\n"); printf("| -version | shows version information |\n"); printf("\\--------------------------------------------/"); exit(0); } if(std::strcmp(argv[1],"-version") == 0){ #ifdef DEBUG printf("Development build"); #else printf("Release build"); #endif exit(0); } printf("Invalid command.\n"); exit(1); } <commit_msg>Fixed build. and cfgDirectory.<commit_after>#include "precompiled.h" #include "engine/math/random.h" #include "engine/actor/AISystem.h" #include "engine/EngineSystem.h" #include "engine/render/RenderSystem.h" #include "engine/UI/UISystem.h" #include "engine/UI/Window.h" #include "engine/UI/containers/TextContainer.h" #include "engine/UI/containers/SelectContainer.h" #include "engine/scene/SceneSystem.h" #include "engine/console/ConsoleSystem.h" #include "engine/actor/ActorManager.h" #include "engine/console/Cvar.h" #include "game/actor/player/PlayerActor.h" #include "game/item/PotionItem.h" #include "game/actor/npc/DummyActor.h" #include "game/UI/containers/StatsContainer.h" #include <cstring> //#include <boost/filesystem.hpp> #ifdef TERMRENDER #include "engine/render/term/TermRender.h" #endif #ifdef NULLRENDER #include "engine/render/null/NullRender.h" #endif namespace cvar { CVAR(int,developer,0); } void handleArgs(int argc,char *argv[]); int main(int argc, char *argv[]){ randomInit(); if(argc == 2){ handleArgs(argc,argv); } LOG_INFO("Engine starting"); #ifdef DEBUG //If this is debug build, enable developer by default *cvar::developer = 1; #endif if(*cvar::developer){ LOG_INFO("Developer mode enabled!"); printf("Developer mode is enabled!\n"); } engine::console::ConsoleSystem *consoleSystem = new engine::console::ConsoleSystem(); consoleSystem->init(); //Config loader planner: First try to read from the same directory, after that try to read from cfg location (~/. or %appdata%) if(!consoleSystem->loadConfig("config.cfg")){ //cfg loading from the run directory failed. Testing out the platform depended default directory String cfgDirectory; #ifdef WINDOWS cfgDirectory = getenv("APPDATA"); const String cfgFolder = "\\ProjectIce\\"; const String cfgFilename = "ProjectIce.cfg"; #endif #ifdef LINUX cfgDirectory = "~/"; const String cfgFolder = ".projectice/"; const String cfgFilename = "ProjectIce.cfg"; #endif if(!consoleSystem->loadConfig(cfgDirectory + cfgFolder + cfgFilename) ){ LOG_INFO("No config files found, creating one to default directory."); //TODO: Create the folder here! Make sure it works on all platforms. //if(boost::filesystem::create_directory(cfgDirectory + cfgFolder)){ consoleSystem->saveConfig(cfgDirectory + cfgFolder + cfgFilename); // }else{ // LOG_ERROR("Could not create the directory! Your system permissions are fucked up."); // } } } game::actor::player::PlayerActor * playerActor = new game::actor::player::PlayerActor(); playerActor->setName("Player"); playerActor->setPosition(vec2(10,10)); playerActor->setLocation(vec3(0,0,0)); engine::world::WorldSystem * worldSystem = new engine::world::WorldSystem(); worldSystem->init(); worldSystem->generate(); playerActor->setWorld(worldSystem); engine::actor::ActorManager * actorManager = new engine::actor::ActorManager(); engine::scene::SceneSystem *scene = new engine::scene::SceneSystem(worldSystem,actorManager,playerActor); game::item::PotionItem * pi = new game::item::PotionItem(); scene->addItem(pi); engine::UI::UISystem *ui = new engine::UI::UISystem(); engine::actor::AISystem *ai = new engine::actor::AISystem(actorManager,worldSystem); #ifdef TERMRENDER engine::render::RenderSystem *render = new engine::render::term::TermRender(scene,ui); #endif #ifdef NULLRENDER engine::render::RenderSystem *render = new engine::render::null::NullRender(scene,ui); #endif render->init(); ui->init(); ai->init(); engine::UI::Window welcomeWindow; welcomeWindow.setPos(vec2(4,3)); welcomeWindow.setSize(vec2(35,15)); welcomeWindow.setName("Welcome to ProjectIce"); engine::UI::containers::TextContainer *textCont = new engine::UI::containers::TextContainer(); textCont->init(); textCont->setText("ProjectIce is an experimental roguelike project developed in C++. This is a early development build. And this string is useless and long to test the word wrapping feature on the textContainer. -- press anykey to continue --"); welcomeWindow.setContainer(textCont); // ui->addWindow(welcomeWindow); /* engine::UI::Window blob; blob.setPos(vec2(84,3)); blob.setSize(vec2(15,15)); blob.setName("blob"); engine::UI::containers::SelectContainer *selectCont = new engine::UI::containers::SelectContainer(); selectCont->insertItem("0 zero"); selectCont->insertItem("& second"); selectCont->insertItem("# so on"); blob.setContainer(selectCont); ui->addWindow(blob); */ engine::UI::Window statsWindow; statsWindow.setPos(vec2(84,3)); statsWindow.setSize(vec2(15,15)); statsWindow.setName("Stats"); game::UI::containers::StatsContainer *statsUI = new game::UI::containers::StatsContainer(); statsUI->setPlayerActor(playerActor); statsWindow.setContainer(statsUI); ui->addWindow(statsWindow); /* * Testing area for the NPCs */ engine::world::Tile voidTile; //force it to dungeon also LOG_INFO("Building testing area"); worldSystem->getRoom( vec3(0,0,0) )->roomType = engine::world::ROOM_TYPE_DUNGEON; worldSystem->getRoom( vec3(0,0,0) )->generate(); voidTile.setType(engine::world::TILE_TREE); for(int x = 7;x < 20;++x){ for(int y = 7;y < 20;++y){ worldSystem->getRoom( vec3(0,0,0) )->setTile(x,y,voidTile); } } voidTile.setType(engine::world::TILE_VOID); for(int x = 8;x < 19;++x){ for(int y = 8;y < 19;++y){ worldSystem->getRoom( vec3(0,0,0) )->setTile(x,y,voidTile); } } //Add some Dummy Ai for testing. for(int i = 0;i < 5;++i){ game::actor::npc::DummyActor * dummy = new game::actor::npc::DummyActor(); dummy->setWorld( worldSystem ); dummy->setPosition( vec2(10+i,15) ); dummy->setLocation( vec3(0,0,0) ); scene->getActorManager()->insertActorToRoom(dummy); } game::actor::npc::DummyActor * dummy = new game::actor::npc::DummyActor(); dummy->setWorld( worldSystem ); dummy->setPosition( vec2(11,11) ); dummy->setLocation( vec3(0,0,0) ); dummy->setAIState(engine::actor::AISTATE_SLEEP); scene->getActorManager()->insertActorToRoom(dummy); worldSystem->getRoom( vec3(0,0,0) )->printLayout(); //printf("CvarCount: %lu\n",engine::console::ConsoleSystem::getCVarList().size()); // consoleSystem->saveConfig("config.cfg"); bool quitStatus = false; while(quitStatus == false){ scene->update(); ai->update(); render->update(); ui->update(); } ai->uninit(); render->uninit(); scene->uninit(); consoleSystem->uninit(); return 0; } void handleArgs(int argc, char *argv[]){ if(std::strcmp(argv[1],"-createconfig") == 0){ //Create console system just to save default cvar settings engine::console::ConsoleSystem *consoleSystem = new engine::console::ConsoleSystem(); consoleSystem->saveConfig("./config.cfg"); printf("Default config created into ./config.cfg\n"); printf("Exitting...\n"); exit(0); } if(std::strcmp(argv[1],"-help") == 0){ printf("/-(ProjectIce special commands)--------------\\\n"); printf("| -| create default configs |\n"); printf("| -help | show this help |\n"); printf("| -version | shows version information |\n"); printf("\\--------------------------------------------/"); exit(0); } if(std::strcmp(argv[1],"-version") == 0){ #ifdef DEBUG printf("Development build"); #else printf("Release build"); #endif exit(0); } printf("Invalid command.\n"); exit(1); } <|endoftext|>
<commit_before>/* * boostMPI template, boost+boostMPI, include boost include/lib MS-MPI include, and MS-MPI library, which is msmpi.lib * Author: Shirong Bai * Email: bunnysirah@hotmail.com or shirong.bai@colorado.edu * Date: 10/08/2015 */ #include "../include/drivers/drivers.h" #include "../include/tools/my_debug/my_debug.h" int main(int argc, char **argv) { /*************************************************************************************************/ /* * 0. Parse parameters * Default, has to run */ /*************************************************************************************************/ po::variables_map vm; // current working directory std::string main_cwd; // boost property tree boost::property_tree::ptree pt; driver::parse_parameters(argc, argv, vm, main_cwd, pt); #if defined(__NO_USE_MPI_) if (pt.get<std::string>("job.job_type") == std::string("generate_pathway_running_Monte_carlo_trajectory")) driver::generate_pathway_running_Monte_carlo_trajectory(main_cwd, pt); #endif // __NO_USE_MPI_ #if defined(__MPI_AVALABLE_) boost::mpi::environment env(argc, argv); boost::mpi::communicator world; MyClock_us timer; if (world.rank() == 0) timer.begin(); /*************************************************************************************************/ /* * 1. Solve for concentration of Lokta-Voltera system or Dimerization or MichaelisMenten, using LSODE */ /*************************************************************************************************/ if (pt.get<std::string>("job.job_type") == std::string("solve_ODEs_for_concentration_using_LSODE")) driver::solve_ODEs_for_concentration_using_LSODE(world, main_cwd, pt); else if (pt.get<std::string>("job.job_type") == std::string("solve_ODEs_for_concentration_using_SSA")) driver::solve_ODEs_for_concentration_using_SSA(world, main_cwd, pt); else if (pt.get<std::string>("job.job_type") == std::string("write_concentration_at_time_to_file")) driver::write_concentration_at_time_to_file(world, main_cwd, pt); /*************************************************************************************************/ /* * 2. Generate pathway first, it might take some time, depends on what kinds of pathway you want */ /*************************************************************************************************/ else if (pt.get<std::string>("job.job_type") == std::string("generate_pathway_running_Monte_carlo_trajectory")) driver::generate_pathway_running_Monte_carlo_trajectory(world, main_cwd, pt); /*************************************************************************************************/ /* * 3. Evaluate pathway integral using Importance based Monte Carlo simulation */ /*************************************************************************************************/ else if (pt.get<std::string>("job.job_type") == std::string("evaluate_path_integral_over_time")) driver::evaluate_path_integral_over_time(world, main_cwd, pt); /*************************************************************************************************/ /* * 4. For speciation, print out concentration at for different sets of rate constant */ /*************************************************************************************************/ else if (pt.get<std::string>("job.job_type") == std::string("speciation_evaluate_concentrations_for_different_sets_rate_coefficients")) driver::speciation_evaluate_concentrations_for_different_sets_rate_coefficients(world, main_cwd, pt); /*************************************************************************************************/ /* * 5. Pathway based equation solver, solve differential equations derived from chemical mechanisms * version 2 * Monte Carlo simulation * not parallel code */ /*************************************************************************************************/ else if (pt.get<std::string>("job.job_type") == std::string("ODE_solver_MC_trajectory_single_core")) driver::ODE_solver_MC_trajectory_single_core(world, main_cwd, pt); /*************************************************************************************************/ /* * 6. Pathway based equation solver, solve differential equations derived from chemical mechanisms * version 4 * constant temperature, surface reactions, independent of pressure * Monte Carlo Simulation * Parallel version */ /*************************************************************************************************/ else if (pt.get<std::string>("job.job_type") == std::string("ODE_solver_MC_trajectory_s_ct_np_parallel")) driver::ODE_solver_MC_trajectory_s_ct_np_parallel(world, main_cwd, pt); /*************************************************************************************************/ /* * 7. Pathway based equation solver, solve differential equations derived from chemical mechanisms * version 5 * varing temperature, varing pressure, constant volume, H2-O2 system, not working because the initiation * is actually a rare event, stochastic trajectory converge too slow * Monte Carlo Simulation * Parallel version */ /*************************************************************************************************/ else if (pt.get<std::string>("job.job_type") == std::string("ODE_solver_MC_trajectory_cv_parallel")) driver::ODE_solver_MC_trajectory_cv_parallel(world, main_cwd, pt); /*************************************************************************************************/ /* * 8. Pathway based equation solver, solve differential equations derived from chemical mechanisms * version 3 * surface reaction, independent of pressure, constant temperature, or independent or temperature * directly evaluate the pathway probability */ /*************************************************************************************************/ else if (pt.get<std::string>("job.job_type") == std::string("ODE_solver_path_integral_parallel_s_ct_np_v1")) driver::ODE_solver_path_integral_parallel_s_ct_np_v1(world, main_cwd, pt); else if (pt.get<std::string>("job.job_type") == std::string("ODE_solver_path_integral_parallel_s_ct_np_v2")) driver::ODE_solver_path_integral_parallel_s_ct_np_v2(world, main_cwd, pt); else if (pt.get<std::string>("job.job_type") == std::string("ODE_solver_path_integral_parallel_s_ct_np_v3")) driver::ODE_solver_path_integral_parallel_s_ct_np_v3(world, main_cwd, pt); /*************************************************************************************************/ /* * 9. Pathway based equation solver, solve differential equations derived from chemical mechanisms * surface reaction, independent of pressure, constant temperature, or independent or temperature * directly evaluate the pathway probability * hold concentration of some species to be constant */ /*************************************************************************************************/ else if (pt.get<std::string>("job.job_type") == std::string("ODE_solver_path_integral_parallel_s_ct_np_cc1_v1")) driver::ODE_solver_path_integral_parallel_s_ct_np_cc1_v1(world, main_cwd, pt); /*************************************************************************************************/ /* * 10. Pathway based equation solver, solve differential equations derived from chemical mechanisms * version 3 * constant volume, varying temperature, varying pressure * directly evaluate the pathway probability */ /*************************************************************************************************/ else if (pt.get<std::string>("job.job_type") == std::string("ODE_solver_path_integral_parallel_cv_v9")) driver::ODE_solver_path_integral_parallel_cv_v9(world, main_cwd, pt); else if (pt.get<std::string>("job.job_type") == std::string("ODE_solver_path_integral_parallel_cv_v10")) driver::ODE_solver_path_integral_parallel_cv_v10(world, main_cwd, pt); else if (pt.get<std::string>("job.job_type") == std::string("ODE_solver_path_integral_parallel_cv_v11")) driver::ODE_solver_path_integral_parallel_cv_v11(world, main_cwd, pt); /* * 11. constant volume, constant temperature */ else if (pt.get<std::string>("job.job_type") == std::string("ODE_solver_path_integral_parallel_cv_ct_v1")) driver::ODE_solver_path_integral_parallel_cv_ct_v1(world, main_cwd, pt); else if (pt.get<std::string>("job.job_type") == std::string("ODE_solver_path_integral_parallel_cv_ct_v2")) driver::ODE_solver_path_integral_parallel_cv_ct_v2(world, main_cwd, pt); else if (pt.get<std::string>("job.job_type") == std::string("ODE_solver_path_integral_parallel_cv_ct_v3")) driver::ODE_solver_path_integral_parallel_cv_ct_v3(world, main_cwd, pt); else if (pt.get<std::string>("job.job_type") == std::string("ODE_solver_path_integral_parallel_cv_ct_v4")) driver::ODE_solver_path_integral_parallel_cv_ct_v4(world, main_cwd, pt); /*************************************************************************************************/ /* * 12. Dijkstra based algorithm, actually it is eppstein's k-shortest path algorightm */ /*************************************************************************************************/ else if (pt.get<std::string>("job.job_type") == std::string("k_shortest_path_algorithms")) driver::k_shortest_path_algorithms(world, main_cwd); /*************************************************************************************************/ /* * 13. M-matrix test */ /*************************************************************************************************/ else if (pt.get<std::string>("job.job_type") == std::string("M_matrix_R_matrix")) driver::M_matrix_R_matrix(world, main_cwd); /*************************************************************************************************/ /* * MISC */ /*************************************************************************************************/ else if (pt.get<std::string>("job.job_type") == std::string("MISC")) driver::MISC(world, main_cwd); #endif // __MPI_AVALABLE_ return EXIT_SUCCESS; } <commit_msg>minor<commit_after>/* * boostMPI template, boost+boostMPI, include boost include/lib MS-MPI include, and MS-MPI library, which is msmpi.lib * Author: Shirong Bai * Email: bunnysirah@hotmail.com or shirong.bai@colorado.edu * Date: 10/08/2015 */ #include "../include/drivers/drivers.h" #include "../include/tools/my_debug/my_debug.h" int main(int argc, char **argv) { /*************************************************************************************************/ /* * 0. Parse parameters * Default, has to run */ /*************************************************************************************************/ po::variables_map vm; // current working directory std::string main_cwd; // boost property tree boost::property_tree::ptree pt; driver::parse_parameters(argc, argv, vm, main_cwd, pt); #if defined(__NO_USE_MPI_) if (pt.get<std::string>("job.job_type") == std::string("generate_pathway_running_Monte_carlo_trajectory")) driver::generate_pathway_running_Monte_carlo_trajectory(main_cwd, pt); #endif // __NO_USE_MPI_ #if defined(__USE_MPI_) boost::mpi::environment env(argc, argv); boost::mpi::communicator world; MyClock_us timer; if (world.rank() == 0) timer.begin(); /*************************************************************************************************/ /* * 1. Solve for concentration of Lokta-Voltera system or Dimerization or MichaelisMenten, using LSODE */ /*************************************************************************************************/ if (pt.get<std::string>("job.job_type") == std::string("solve_ODEs_for_concentration_using_LSODE")) driver::solve_ODEs_for_concentration_using_LSODE(world, main_cwd, pt); else if (pt.get<std::string>("job.job_type") == std::string("solve_ODEs_for_concentration_using_SSA")) driver::solve_ODEs_for_concentration_using_SSA(world, main_cwd, pt); else if (pt.get<std::string>("job.job_type") == std::string("write_concentration_at_time_to_file")) driver::write_concentration_at_time_to_file(world, main_cwd, pt); /*************************************************************************************************/ /* * 2. Generate pathway first, it might take some time, depends on what kinds of pathway you want */ /*************************************************************************************************/ else if (pt.get<std::string>("job.job_type") == std::string("generate_pathway_running_Monte_carlo_trajectory")) driver::generate_pathway_running_Monte_carlo_trajectory(world, main_cwd, pt); /*************************************************************************************************/ /* * 3. Evaluate pathway integral using Importance based Monte Carlo simulation */ /*************************************************************************************************/ else if (pt.get<std::string>("job.job_type") == std::string("evaluate_path_integral_over_time")) driver::evaluate_path_integral_over_time(world, main_cwd, pt); /*************************************************************************************************/ /* * 4. For speciation, print out concentration at for different sets of rate constant */ /*************************************************************************************************/ else if (pt.get<std::string>("job.job_type") == std::string("speciation_evaluate_concentrations_for_different_sets_rate_coefficients")) driver::speciation_evaluate_concentrations_for_different_sets_rate_coefficients(world, main_cwd, pt); /*************************************************************************************************/ /* * 5. Pathway based equation solver, solve differential equations derived from chemical mechanisms * version 2 * Monte Carlo simulation * not parallel code */ /*************************************************************************************************/ else if (pt.get<std::string>("job.job_type") == std::string("ODE_solver_MC_trajectory_single_core")) driver::ODE_solver_MC_trajectory_single_core(world, main_cwd, pt); /*************************************************************************************************/ /* * 6. Pathway based equation solver, solve differential equations derived from chemical mechanisms * version 4 * constant temperature, surface reactions, independent of pressure * Monte Carlo Simulation * Parallel version */ /*************************************************************************************************/ else if (pt.get<std::string>("job.job_type") == std::string("ODE_solver_MC_trajectory_s_ct_np_parallel")) driver::ODE_solver_MC_trajectory_s_ct_np_parallel(world, main_cwd, pt); /*************************************************************************************************/ /* * 7. Pathway based equation solver, solve differential equations derived from chemical mechanisms * version 5 * varing temperature, varing pressure, constant volume, H2-O2 system, not working because the initiation * is actually a rare event, stochastic trajectory converge too slow * Monte Carlo Simulation * Parallel version */ /*************************************************************************************************/ else if (pt.get<std::string>("job.job_type") == std::string("ODE_solver_MC_trajectory_cv_parallel")) driver::ODE_solver_MC_trajectory_cv_parallel(world, main_cwd, pt); /*************************************************************************************************/ /* * 8. Pathway based equation solver, solve differential equations derived from chemical mechanisms * version 3 * surface reaction, independent of pressure, constant temperature, or independent or temperature * directly evaluate the pathway probability */ /*************************************************************************************************/ else if (pt.get<std::string>("job.job_type") == std::string("ODE_solver_path_integral_parallel_s_ct_np_v1")) driver::ODE_solver_path_integral_parallel_s_ct_np_v1(world, main_cwd, pt); else if (pt.get<std::string>("job.job_type") == std::string("ODE_solver_path_integral_parallel_s_ct_np_v2")) driver::ODE_solver_path_integral_parallel_s_ct_np_v2(world, main_cwd, pt); else if (pt.get<std::string>("job.job_type") == std::string("ODE_solver_path_integral_parallel_s_ct_np_v3")) driver::ODE_solver_path_integral_parallel_s_ct_np_v3(world, main_cwd, pt); /*************************************************************************************************/ /* * 9. Pathway based equation solver, solve differential equations derived from chemical mechanisms * surface reaction, independent of pressure, constant temperature, or independent or temperature * directly evaluate the pathway probability * hold concentration of some species to be constant */ /*************************************************************************************************/ else if (pt.get<std::string>("job.job_type") == std::string("ODE_solver_path_integral_parallel_s_ct_np_cc1_v1")) driver::ODE_solver_path_integral_parallel_s_ct_np_cc1_v1(world, main_cwd, pt); /*************************************************************************************************/ /* * 10. Pathway based equation solver, solve differential equations derived from chemical mechanisms * version 3 * constant volume, varying temperature, varying pressure * directly evaluate the pathway probability */ /*************************************************************************************************/ else if (pt.get<std::string>("job.job_type") == std::string("ODE_solver_path_integral_parallel_cv_v9")) driver::ODE_solver_path_integral_parallel_cv_v9(world, main_cwd, pt); else if (pt.get<std::string>("job.job_type") == std::string("ODE_solver_path_integral_parallel_cv_v10")) driver::ODE_solver_path_integral_parallel_cv_v10(world, main_cwd, pt); else if (pt.get<std::string>("job.job_type") == std::string("ODE_solver_path_integral_parallel_cv_v11")) driver::ODE_solver_path_integral_parallel_cv_v11(world, main_cwd, pt); /* * 11. constant volume, constant temperature */ else if (pt.get<std::string>("job.job_type") == std::string("ODE_solver_path_integral_parallel_cv_ct_v1")) driver::ODE_solver_path_integral_parallel_cv_ct_v1(world, main_cwd, pt); else if (pt.get<std::string>("job.job_type") == std::string("ODE_solver_path_integral_parallel_cv_ct_v2")) driver::ODE_solver_path_integral_parallel_cv_ct_v2(world, main_cwd, pt); else if (pt.get<std::string>("job.job_type") == std::string("ODE_solver_path_integral_parallel_cv_ct_v3")) driver::ODE_solver_path_integral_parallel_cv_ct_v3(world, main_cwd, pt); else if (pt.get<std::string>("job.job_type") == std::string("ODE_solver_path_integral_parallel_cv_ct_v4")) driver::ODE_solver_path_integral_parallel_cv_ct_v4(world, main_cwd, pt); /*************************************************************************************************/ /* * 12. Dijkstra based algorithm, actually it is eppstein's k-shortest path algorightm */ /*************************************************************************************************/ else if (pt.get<std::string>("job.job_type") == std::string("k_shortest_path_algorithms")) driver::k_shortest_path_algorithms(world, main_cwd); /*************************************************************************************************/ /* * 13. M-matrix test */ /*************************************************************************************************/ else if (pt.get<std::string>("job.job_type") == std::string("M_matrix_R_matrix")) driver::M_matrix_R_matrix(world, main_cwd); /*************************************************************************************************/ /* * MISC */ /*************************************************************************************************/ else if (pt.get<std::string>("job.job_type") == std::string("MISC")) driver::MISC(world, main_cwd); #endif // __MPI_AVALABLE_ return EXIT_SUCCESS; } <|endoftext|>
<commit_before>#include "read.h" #include <sstream> Read::Read(string name, string seq, string strand, string quality){ mName = name; mSeq = Sequence(seq); mStrand = strand; mQuality = quality; mHasQuality = true; } Read::Read(string name, string seq, string strand){ mName = name; mSeq = Sequence(seq); mStrand = strand; mHasQuality = false; } Read::Read(string name, Sequence seq, string strand, string quality){ mName = name; mSeq = seq; mStrand = strand; mQuality = quality; mHasQuality = true; } Read::Read(string name, Sequence seq, string strand){ mName = name; mSeq = seq; mStrand = strand; mHasQuality = false; } Read::Read(Read &r) { mName = r.mName; mSeq = r.mSeq; mStrand = r.mStrand; mQuality = r.mQuality; mHasQuality = r.mHasQuality; } void Read::print(){ std::cout << mName << endl; std::cout << mSeq.mStr << endl; std::cout << mStrand << endl; if(mHasQuality) std::cout << mQuality << endl; } void Read::printFile(ofstream& file){ file << mName << endl; file << mSeq.mStr << endl; file << mStrand << endl; if(mHasQuality) file << mQuality << endl; } void Read::printWithBreaks(vector<int>& breaks){ std::cout << mName << endl; std::cout << makeStringWithBreaks(mSeq.mStr, breaks)<< endl; std::cout << mStrand << endl; if(mHasQuality) std::cout << makeStringWithBreaks(mQuality, breaks) << endl; } string Read::makeStringWithBreaks(const string origin, vector<int>& breaks) { string ret = origin.substr(0, breaks[0]); for(int i=0;i<breaks.size()-1;i++){ ret += " " + origin.substr(breaks[i], breaks[i+1]-breaks[i]); } if(breaks[breaks.size()-1]>0) ret += " " + origin.substr(breaks[breaks.size()-1], origin.length() - breaks[breaks.size()-1]); return ret; } void Read::printHtmlTDWithBreaks(ofstream& file, vector<int>& breaks, int mutid, int matchid) { file << "<td id='b-"<<mutid<<"-"<<matchid<<"-"<<"0' class='alignright'>" << makeHtmlSeqWithQual(0, breaks[0]) << "</td>"; for(int i=0;i<breaks.size()-1;i++){ file << "<td id='b-"<<mutid<<"-"<<matchid<<"-"<<i+1<<"' "; if(i==0) file << " class='alignright'"; file << ">" << makeHtmlSeqWithQual(breaks[i], breaks[i+1]-breaks[i]) << "</td>"; } if(breaks[breaks.size()-1]>0) file << "<td id='b-"<<mutid<<"-"<<matchid<<"-"<<breaks.size()<<"' "; file << "class='alignleft'>" << makeHtmlSeqWithQual(breaks[breaks.size()-1], mSeq.mStr.length() - breaks[breaks.size()-1]) << "</td>"; } string Read::makeHtmlSeqWithQual(int start, int length) { //new HTML report is dynamically created by JavaScript //so, just return return ""; stringstream ss; for(int i=start;i<start+length && i<mSeq.length(); i++) { ss << "<a title='" << mQuality[i] << "'><font color='" << qualityColor(mQuality[i]) << "'>"<< mSeq.mStr[i] << "</font></a>"; } return ss.str(); } void Read::printJSWithBreaks(ofstream& file, vector<int>& breaks) { if(breaks.size()>0){ file << "\n["; file << "'" << mSeq.mStr.substr(0, breaks[0]) << "'"; file << ", " ; file << "'" << mQuality.substr(0, breaks[0]) << "'"; file << "],"; } for(int i=0;i<breaks.size()-1;i++){ file << "\n["; file << "'" << mSeq.mStr.substr(breaks[i], breaks[i+1]-breaks[i]) << "'"; file << ", " ; file << "'" << mQuality.substr(breaks[i], breaks[i+1]-breaks[i]) << "'"; file << "],"; } if(breaks[breaks.size()-1]>0){ file << "\n["; file << "'" << mSeq.mStr.substr(breaks[breaks.size()-1], mSeq.mStr.length() - breaks[breaks.size()-1]) << "'"; file << ", " ; file << "'" << mQuality.substr(breaks[breaks.size()-1], mSeq.mStr.length() - breaks[breaks.size()-1]) << "'"; file << "],"; } } string Read::qualityColor(char qual) { if(qual >= 'I') // >= Q40, extremely high quality return "#78C6B9"; if(qual >= '?') // Q30 ~ Q39, high quality return "#33BBE2"; if(qual >= '5') // Q20 ~ Q29, moderate quality return "#666666"; if(qual >= '0') // Q15 ~ Q19, low quality return "#E99E5B"; else // <= Q14, extremely low quality return "#FF0000"; } Read* Read::reverseComplement(){ Sequence seq = ~mSeq; string qual; qual.assign(mQuality.rbegin(), mQuality.rend()); string strand = (mStrand=="+") ? "-" : "+"; return new Read(mName, seq, strand, qual); } string Read::lastIndex(){ int len = mName.length(); if(len<5) return ""; for(int i=len-5;i>=0;i--){ if(mName[i]==':' or mName[i]=='+'){ return mName.substr(i+1, len-i); } } } int Read::lowQualCount(int qual){ int count = 0; for(int q=0;q<mQuality.size();q++){ if(mQuality[q] < qual + 33) count++; } return count; } int Read::length(){ return mSeq.length(); } bool Read::test(){ Read r("@NS500713:64:HFKJJBGXY:1:11101:20469:1097 1:N:0:TATAGCCT+GGTCCCGA", "CTCTTGGACTCTAACACTGTTTTTTCTTATGAAAACACAGGAGTGATGACTAGTTGAGTGCATTCTTATGAGACTCATAGTCATTCTATGATGTAGTTTTCCTTAGGAGGACATTTTTTACATGAAATTATTAACCTAAATAGAGTTGATC", "+", "AAAAA6EEEEEEEEEEEEEEEEE#EEEEEEEEEEEEEEEEE/EEEEEEEEEEEEEEEEAEEEAEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE<EEEEAEEEEEEEEEEEEEEEAEEE/EEEEEEEEEEAAEAEAAEEEAEEAA"); string idx = r.lastIndex(); return idx == "GGTCCCGA"; } ReadPair::ReadPair(Read* left, Read* right){ mLeft = left; mRight = right; } ReadPair::~ReadPair(){ if(mLeft){ delete mLeft; mLeft = NULL; } if(mRight){ delete mRight; mRight = NULL; } } Read* ReadPair::fastMerge(){ Read* rcRight = mRight->reverseComplement(); int len1 = mLeft->length(); int len2 = rcRight->length(); // use the pointer directly for speed const char* str1 = mLeft->mSeq.mStr.c_str(); const char* str2 = rcRight->mSeq.mStr.c_str(); const char* qual1 = mLeft->mQuality.c_str(); const char* qual2 = rcRight->mQuality.c_str(); // we require at least 30 bp overlapping to merge a pair const int MIN_OVERLAP = 30; bool overlapped = false; int olen = MIN_OVERLAP; int diff = 0; // the diff count for 1 high qual + 1 low qual int lowQualDiff = 0; while(olen <= min(len1, len2)){ diff = 0; lowQualDiff = 0; bool ok = true; int offset = len1 - olen; for(int i=0;i<olen;i++){ if(str1[offset+i] != str2[i]){ diff++; // one is >= Q30 and the other is <= Q15 if((qual1[offset+i]>='?' && qual2[i]<='0') || (qual1[offset+i]<='0' && qual2[i]>='?')){ lowQualDiff++; } // we disallow high quality diff, and only allow up to 3 low qual diff if(diff>lowQualDiff || lowQualDiff>=3){ ok = false; break; } } } if(ok){ overlapped = true; break; } olen++; } if(overlapped){ int offset = len1 - olen; int mergedLen = offset + len2; stringstream ss; ss << mLeft->mName << " merged offset:" << offset << " overlap:" << olen << " diff:" << diff; string mergedName = ss.str(); string mergedSeq = mLeft->mSeq.mStr.substr(0, offset) + rcRight->mSeq.mStr; string mergedQual = mLeft->mQuality.substr(0, offset) + rcRight->mQuality; // quality adjuction and correction for low qual diff for(int i=0;i<olen;i++){ if(str1[offset+i] != str2[i]){ if(qual1[offset+i]>='?' && qual2[i]<='0'){ mergedSeq[offset+i] = str1[offset+i]; mergedQual[offset+i] = qual1[offset+i]; } else { mergedSeq[offset+i] = str2[i]; mergedQual[offset+i] = qual2[i]; } } else { // add the quality of the pair to make a high qual mergedQual[offset+i] = qual1[offset+i] + qual2[i] - 33; } } return new Read(mergedName, mergedSeq, "+", mergedQual); } return NULL; } bool ReadPair::test(){ Read* left = new Read("@NS500713:64:HFKJJBGXY:1:11101:20469:1097 1:N:0:TATAGCCT+GGTCCCGA", "TTTTTTCTCTTGGACTCTAACACTGTTTTTTCTTATGAAAACACAGGAGTGATGACTAGTTGAGTGCATTCTTATGAGACTCATAGTCATTCTATGATGTAG", "+", "AAAAA6EEEEEEEEEEEEEEEEE#EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEAEEEAEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE"); Read* right = new Read("@NS500713:64:HFKJJBGXY:1:11101:20469:1097 1:N:0:TATAGCCT+GGTCCCGA", "AAAAAACTACACCATAGAATGACTATGAGTCTCATAAGAATGCACTCAACTAGTCATCACTCCTGTGTTTTCATAAGAAAAAACAGTGTTAGAGTCCAAGAG", "+", "AAAAA6EEEEE/EEEEEEEEEEE#EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEAEEEAEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE"); ReadPair pair(left, right); Read* merged = pair.fastMerge(); if(merged == NULL) return false; if(merged->mSeq.mStr != "TTTTTTCTCTTGGACTCTAACACTGTTTTTTCTTATGAAAACACAGGAGTGATGACTAGTTGAGTGCATTCTTATGAGACTCATAGTCATTCTATGATGTAGTTTTTT") return false; //merged->print(); return true; } <commit_msg>avoid slash since it will affect HTML output<commit_after>#include "read.h" #include <sstream> Read::Read(string name, string seq, string strand, string quality){ mName = name; mSeq = Sequence(seq); mStrand = strand; mQuality = quality; mHasQuality = true; } Read::Read(string name, string seq, string strand){ mName = name; mSeq = Sequence(seq); mStrand = strand; mHasQuality = false; } Read::Read(string name, Sequence seq, string strand, string quality){ mName = name; mSeq = seq; mStrand = strand; mQuality = quality; mHasQuality = true; } Read::Read(string name, Sequence seq, string strand){ mName = name; mSeq = seq; mStrand = strand; mHasQuality = false; } Read::Read(Read &r) { mName = r.mName; mSeq = r.mSeq; mStrand = r.mStrand; mQuality = r.mQuality; mHasQuality = r.mHasQuality; } void Read::print(){ std::cout << mName << endl; std::cout << mSeq.mStr << endl; std::cout << mStrand << endl; if(mHasQuality) std::cout << mQuality << endl; } void Read::printFile(ofstream& file){ file << mName << endl; file << mSeq.mStr << endl; file << mStrand << endl; if(mHasQuality) file << mQuality << endl; } void Read::printWithBreaks(vector<int>& breaks){ std::cout << mName << endl; std::cout << makeStringWithBreaks(mSeq.mStr, breaks)<< endl; std::cout << mStrand << endl; if(mHasQuality) std::cout << makeStringWithBreaks(mQuality, breaks) << endl; } string Read::makeStringWithBreaks(const string origin, vector<int>& breaks) { string ret = origin.substr(0, breaks[0]); for(int i=0;i<breaks.size()-1;i++){ ret += " " + origin.substr(breaks[i], breaks[i+1]-breaks[i]); } if(breaks[breaks.size()-1]>0) ret += " " + origin.substr(breaks[breaks.size()-1], origin.length() - breaks[breaks.size()-1]); return ret; } void Read::printHtmlTDWithBreaks(ofstream& file, vector<int>& breaks, int mutid, int matchid) { file << "<td id='b-"<<mutid<<"-"<<matchid<<"-"<<"0' class='alignright'>" << makeHtmlSeqWithQual(0, breaks[0]) << "</td>"; for(int i=0;i<breaks.size()-1;i++){ file << "<td id='b-"<<mutid<<"-"<<matchid<<"-"<<i+1<<"' "; if(i==0) file << " class='alignright'"; file << ">" << makeHtmlSeqWithQual(breaks[i], breaks[i+1]-breaks[i]) << "</td>"; } if(breaks[breaks.size()-1]>0) file << "<td id='b-"<<mutid<<"-"<<matchid<<"-"<<breaks.size()<<"' "; file << "class='alignleft'>" << makeHtmlSeqWithQual(breaks[breaks.size()-1], mSeq.mStr.length() - breaks[breaks.size()-1]) << "</td>"; } string Read::makeHtmlSeqWithQual(int start, int length) { //new HTML report is dynamically created by JavaScript //so, just return return ""; stringstream ss; for(int i=start;i<start+length && i<mSeq.length(); i++) { ss << "<a title='" << mQuality[i] << "'><font color='" << qualityColor(mQuality[i]) << "'>"<< mSeq.mStr[i] << "</font></a>"; } return ss.str(); } void Read::printJSWithBreaks(ofstream& file, vector<int>& breaks) { if(breaks.size()>0){ file << "\n["; file << "'" << mSeq.mStr.substr(0, breaks[0]) << "'"; file << ", " ; file << "'" << mQuality.substr(0, breaks[0]) << "'"; file << "],"; } for(int i=0;i<breaks.size()-1;i++){ file << "\n["; file << "'" << mSeq.mStr.substr(breaks[i], breaks[i+1]-breaks[i]) << "'"; file << ", " ; file << "'" << mQuality.substr(breaks[i], breaks[i+1]-breaks[i]) << "'"; file << "],"; } if(breaks[breaks.size()-1]>0){ file << "\n["; file << "'" << mSeq.mStr.substr(breaks[breaks.size()-1], mSeq.mStr.length() - breaks[breaks.size()-1]) << "'"; file << ", " ; file << "'" << mQuality.substr(breaks[breaks.size()-1], mSeq.mStr.length() - breaks[breaks.size()-1]) << "'"; file << "],"; } } string Read::qualityColor(char qual) { if(qual >= 'I') // >= Q40, extremely high quality return "#78C6B9"; if(qual >= '?') // Q30 ~ Q39, high quality return "#33BBE2"; if(qual >= '5') // Q20 ~ Q29, moderate quality return "#666666"; if(qual >= '0') // Q15 ~ Q19, low quality return "#E99E5B"; else // <= Q14, extremely low quality return "#FF0000"; } Read* Read::reverseComplement(){ Sequence seq = ~mSeq; string qual; qual.assign(mQuality.rbegin(), mQuality.rend()); string strand = (mStrand=="+") ? "-" : "+"; return new Read(mName, seq, strand, qual); } string Read::lastIndex(){ int len = mName.length(); if(len<5) return ""; for(int i=len-5;i>=0;i--){ if(mName[i]==':' or mName[i]=='+'){ return mName.substr(i+1, len-i); } } } int Read::lowQualCount(int qual){ int count = 0; for(int q=0;q<mQuality.size();q++){ if(mQuality[q] < qual + 33) count++; } return count; } int Read::length(){ return mSeq.length(); } bool Read::test(){ Read r("@NS500713:64:HFKJJBGXY:1:11101:20469:1097 1:N:0:TATAGCCT+GGTCCCGA", "CTCTTGGACTCTAACACTGTTTTTTCTTATGAAAACACAGGAGTGATGACTAGTTGAGTGCATTCTTATGAGACTCATAGTCATTCTATGATGTAGTTTTCCTTAGGAGGACATTTTTTACATGAAATTATTAACCTAAATAGAGTTGATC", "+", "AAAAA6EEEEEEEEEEEEEEEEE#EEEEEEEEEEEEEEEEE/EEEEEEEEEEEEEEEEAEEEAEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE<EEEEAEEEEEEEEEEEEEEEAEEE/EEEEEEEEEEAAEAEAAEEEAEEAA"); string idx = r.lastIndex(); return idx == "GGTCCCGA"; } ReadPair::ReadPair(Read* left, Read* right){ mLeft = left; mRight = right; } ReadPair::~ReadPair(){ if(mLeft){ delete mLeft; mLeft = NULL; } if(mRight){ delete mRight; mRight = NULL; } } Read* ReadPair::fastMerge(){ Read* rcRight = mRight->reverseComplement(); int len1 = mLeft->length(); int len2 = rcRight->length(); // use the pointer directly for speed const char* str1 = mLeft->mSeq.mStr.c_str(); const char* str2 = rcRight->mSeq.mStr.c_str(); const char* qual1 = mLeft->mQuality.c_str(); const char* qual2 = rcRight->mQuality.c_str(); // we require at least 30 bp overlapping to merge a pair const int MIN_OVERLAP = 30; bool overlapped = false; int olen = MIN_OVERLAP; int diff = 0; // the diff count for 1 high qual + 1 low qual int lowQualDiff = 0; while(olen <= min(len1, len2)){ diff = 0; lowQualDiff = 0; bool ok = true; int offset = len1 - olen; for(int i=0;i<olen;i++){ if(str1[offset+i] != str2[i]){ diff++; // one is >= Q30 and the other is <= Q15 if((qual1[offset+i]>='?' && qual2[i]<='0') || (qual1[offset+i]<='0' && qual2[i]>='?')){ lowQualDiff++; } // we disallow high quality diff, and only allow up to 3 low qual diff if(diff>lowQualDiff || lowQualDiff>=3){ ok = false; break; } } } if(ok){ overlapped = true; break; } olen++; } if(overlapped){ int offset = len1 - olen; int mergedLen = offset + len2; stringstream ss; ss << mLeft->mName << " merged offset:" << offset << " overlap:" << olen << " diff:" << diff; string mergedName = ss.str(); string mergedSeq = mLeft->mSeq.mStr.substr(0, offset) + rcRight->mSeq.mStr; string mergedQual = mLeft->mQuality.substr(0, offset) + rcRight->mQuality; // quality adjuction and correction for low qual diff for(int i=0;i<olen;i++){ if(str1[offset+i] != str2[i]){ if(qual1[offset+i]>='?' && qual2[i]<='0'){ mergedSeq[offset+i] = str1[offset+i]; mergedQual[offset+i] = qual1[offset+i]; } else { mergedSeq[offset+i] = str2[i]; mergedQual[offset+i] = qual2[i]; } } else { // add the quality of the pair to make a high qual mergedQual[offset+i] = qual1[offset+i] + qual2[i] - 33; // avoid slash since it will affect HTML output if(mergedQual[offset+i] == '\\') mergedQual[offset+i] = '\\' - 1; } } return new Read(mergedName, mergedSeq, "+", mergedQual); } return NULL; } bool ReadPair::test(){ Read* left = new Read("@NS500713:64:HFKJJBGXY:1:11101:20469:1097 1:N:0:TATAGCCT+GGTCCCGA", "TTTTTTCTCTTGGACTCTAACACTGTTTTTTCTTATGAAAACACAGGAGTGATGACTAGTTGAGTGCATTCTTATGAGACTCATAGTCATTCTATGATGTAG", "+", "AAAAA6EEEEEEEEEEEEEEEEE#EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEAEEEAEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE"); Read* right = new Read("@NS500713:64:HFKJJBGXY:1:11101:20469:1097 1:N:0:TATAGCCT+GGTCCCGA", "AAAAAACTACACCATAGAATGACTATGAGTCTCATAAGAATGCACTCAACTAGTCATCACTCCTGTGTTTTCATAAGAAAAAACAGTGTTAGAGTCCAAGAG", "+", "AAAAA6EEEEE/EEEEEEEEEEE#EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEAEEEAEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE"); ReadPair pair(left, right); Read* merged = pair.fastMerge(); if(merged == NULL) return false; if(merged->mSeq.mStr != "TTTTTTCTCTTGGACTCTAACACTGTTTTTTCTTATGAAAACACAGGAGTGATGACTAGTTGAGTGCATTCTTATGAGACTCATAGTCATTCTATGATGTAGTTTTTT") return false; //merged->print(); return true; } <|endoftext|>
<commit_before>#include "node.hpp" #include "helpers.hpp" #include "core/Log.h" #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> Node::Node() : _vao(0u), _vertices_nb(0u), _indices_nb(0u), _drawing_mode(GL_TRIANGLES), _has_indices(true), _program(nullptr), _textures(), _scaling(1.0f), _rotation(), _translation(), _children() { } void Node::render(glm::mat4 const& WVP, glm::mat4 const& world) const { if (_program != nullptr) render(WVP, world, *_program, _set_uniforms); } void Node::render(glm::mat4 const& WVP, glm::mat4 const& world, GLuint program, std::function<void (GLuint)> const& set_uniforms) const { if (_vao == 0u || program == 0u) return; glUseProgram(program); auto const normal_model_to_world = glm::transpose(glm::inverse(world)); set_uniforms(program); glUniformMatrix4fv(glGetUniformLocation(program, "vertex_model_to_world"), 1, GL_FALSE, glm::value_ptr(world)); glUniformMatrix4fv(glGetUniformLocation(program, "normal_model_to_world"), 1, GL_FALSE, glm::value_ptr(normal_model_to_world)); glUniformMatrix4fv(glGetUniformLocation(program, "vertex_world_to_clip"), 1, GL_FALSE, glm::value_ptr(WVP)); for (size_t i = 0u; i < _textures.size(); ++i) { auto const texture = _textures[i]; glActiveTexture(GL_TEXTURE0 + static_cast<GLenum>(i)); glBindTexture(std::get<2>(texture), std::get<1>(texture)); glUniform1i(glGetUniformLocation(program, std::get<0>(texture).c_str()), static_cast<GLint>(i)); std::string texture_presence_var_name = "has_" + std::get<0>(texture); glUniform1i(glGetUniformLocation(program, texture_presence_var_name.c_str()), 1); } glBindVertexArray(_vao); if (_has_indices) glDrawElements(_drawing_mode, _indices_nb, GL_UNSIGNED_INT, reinterpret_cast<GLvoid const*>(0x0)); else glDrawArrays(_drawing_mode, 0, _vertices_nb); glBindVertexArray(0u); glUseProgram(0u); } void Node::set_geometry(bonobo::mesh_data const& shape) { _vao = shape.vao; _vertices_nb = static_cast<GLsizei>(shape.vertices_nb); _indices_nb = static_cast<GLsizei>(shape.indices_nb); _drawing_mode = shape.drawing_mode; _has_indices = shape.ibo != 0u; if (!shape.bindings.empty()) { for (auto const& binding : shape.bindings) add_texture(binding.first, binding.second, GL_TEXTURE_2D); } } void Node::set_program(GLuint const* const program, std::function<void (GLuint)> const& set_uniforms) { if (program == nullptr) throw std::runtime_error("Node::set_program: program can not be null."); _program = program; _set_uniforms = set_uniforms; } size_t Node::get_indices_nb() const { return static_cast<size_t>(_indices_nb); } void Node::set_indices_nb(size_t const& indices_nb) { _indices_nb = static_cast<GLsizei>(indices_nb); } void Node::add_texture(std::string const& name, GLuint tex_id, GLenum type) { if (tex_id != 0u) _textures.emplace_back(name, tex_id, type); } void Node::add_child(Node const* child) { if (child == nullptr) LogError("Trying to add a nullptr as child!"); _children.emplace_back(child); } size_t Node::get_children_nb() const { return _children.size(); } Node const* Node::get_child(size_t index) const { assert(index < _children.size()); return _children[index]; } void Node::set_translation(glm::vec3 const& translation) { _translation = translation; } void Node::translate(glm::vec3 const& v) { _translation += v; } void Node::set_scaling(glm::vec3 const& scaling) { _scaling = scaling; } void Node::scale(glm::vec3 const& s) { _scaling *= s; } glm::mat4x4 Node::get_transform() const { auto const scaling = glm::scale(glm::mat4(1.0f), _scaling); auto const translating = glm::translate(glm::mat4(1.0f), _translation); auto const rotation_x = glm::rotate(glm::mat4(1.0f), _rotation.x, glm::vec3(1.0, 0.0, 0.0)); auto const rotation_y = glm::rotate(glm::mat4(1.0f), _rotation.y, glm::vec3(0.0, 1.0, 0.0)); auto const rotation_z = glm::rotate(glm::mat4(1.0f), _rotation.z, glm::vec3(0.0, 0.0, 1.0)); auto const rotating = rotation_z * rotation_y * rotation_x; return translating * rotating * scaling; } <commit_msg>core: Reset has_${texture_name} after the rendering<commit_after>#include "node.hpp" #include "helpers.hpp" #include "core/Log.h" #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> Node::Node() : _vao(0u), _vertices_nb(0u), _indices_nb(0u), _drawing_mode(GL_TRIANGLES), _has_indices(true), _program(nullptr), _textures(), _scaling(1.0f), _rotation(), _translation(), _children() { } void Node::render(glm::mat4 const& WVP, glm::mat4 const& world) const { if (_program != nullptr) render(WVP, world, *_program, _set_uniforms); } void Node::render(glm::mat4 const& WVP, glm::mat4 const& world, GLuint program, std::function<void (GLuint)> const& set_uniforms) const { if (_vao == 0u || program == 0u) return; glUseProgram(program); auto const normal_model_to_world = glm::transpose(glm::inverse(world)); set_uniforms(program); glUniformMatrix4fv(glGetUniformLocation(program, "vertex_model_to_world"), 1, GL_FALSE, glm::value_ptr(world)); glUniformMatrix4fv(glGetUniformLocation(program, "normal_model_to_world"), 1, GL_FALSE, glm::value_ptr(normal_model_to_world)); glUniformMatrix4fv(glGetUniformLocation(program, "vertex_world_to_clip"), 1, GL_FALSE, glm::value_ptr(WVP)); for (size_t i = 0u; i < _textures.size(); ++i) { auto const texture = _textures[i]; glActiveTexture(GL_TEXTURE0 + static_cast<GLenum>(i)); glBindTexture(std::get<2>(texture), std::get<1>(texture)); glUniform1i(glGetUniformLocation(program, std::get<0>(texture).c_str()), static_cast<GLint>(i)); std::string texture_presence_var_name = "has_" + std::get<0>(texture); glUniform1i(glGetUniformLocation(program, texture_presence_var_name.c_str()), 1); } glBindVertexArray(_vao); if (_has_indices) glDrawElements(_drawing_mode, _indices_nb, GL_UNSIGNED_INT, reinterpret_cast<GLvoid const*>(0x0)); else glDrawArrays(_drawing_mode, 0, _vertices_nb); glBindVertexArray(0u); for (auto const& texture : _textures) { std::string texture_presence_var_name = "has_" + std::get<0>(texture); glUniform1i(glGetUniformLocation(program, texture_presence_var_name.c_str()), 0); } glUseProgram(0u); } void Node::set_geometry(bonobo::mesh_data const& shape) { _vao = shape.vao; _vertices_nb = static_cast<GLsizei>(shape.vertices_nb); _indices_nb = static_cast<GLsizei>(shape.indices_nb); _drawing_mode = shape.drawing_mode; _has_indices = shape.ibo != 0u; if (!shape.bindings.empty()) { for (auto const& binding : shape.bindings) add_texture(binding.first, binding.second, GL_TEXTURE_2D); } } void Node::set_program(GLuint const* const program, std::function<void (GLuint)> const& set_uniforms) { if (program == nullptr) throw std::runtime_error("Node::set_program: program can not be null."); _program = program; _set_uniforms = set_uniforms; } size_t Node::get_indices_nb() const { return static_cast<size_t>(_indices_nb); } void Node::set_indices_nb(size_t const& indices_nb) { _indices_nb = static_cast<GLsizei>(indices_nb); } void Node::add_texture(std::string const& name, GLuint tex_id, GLenum type) { if (tex_id != 0u) _textures.emplace_back(name, tex_id, type); } void Node::add_child(Node const* child) { if (child == nullptr) LogError("Trying to add a nullptr as child!"); _children.emplace_back(child); } size_t Node::get_children_nb() const { return _children.size(); } Node const* Node::get_child(size_t index) const { assert(index < _children.size()); return _children[index]; } void Node::set_translation(glm::vec3 const& translation) { _translation = translation; } void Node::translate(glm::vec3 const& v) { _translation += v; } void Node::set_scaling(glm::vec3 const& scaling) { _scaling = scaling; } void Node::scale(glm::vec3 const& s) { _scaling *= s; } glm::mat4x4 Node::get_transform() const { auto const scaling = glm::scale(glm::mat4(1.0f), _scaling); auto const translating = glm::translate(glm::mat4(1.0f), _translation); auto const rotation_x = glm::rotate(glm::mat4(1.0f), _rotation.x, glm::vec3(1.0, 0.0, 0.0)); auto const rotation_y = glm::rotate(glm::mat4(1.0f), _rotation.y, glm::vec3(0.0, 1.0, 0.0)); auto const rotation_z = glm::rotate(glm::mat4(1.0f), _rotation.z, glm::vec3(0.0, 0.0, 1.0)); auto const rotating = rotation_z * rotation_y * rotation_x; return translating * rotating * scaling; } <|endoftext|>
<commit_before>// Copyright (c) 2016 Kasper Kronborg Isager and Radoslaw Niemczyk. #pragma once #include <vector> #include <random> #include "vector.hpp" namespace lsh { /** * The mask class acts as sort of a bit mask that can reduce the dimensionality of * vectors by a projection. */ class mask { public: /** * Project a vector, reducing it to a dimensionality specified by this mask. * * @param vector The vector to project. * @return The projected vector. */ virtual vector project(const vector& vector) const; }; class random_mask: public mask { private: /** * The number of dimensions in vector projections. */ unsigned int width_; /** * The randomly chosen indices to pick for vector projections. */ std::vector<unsigned int> indices_; public: /** * Construct a new mask. * * @param dimensionality The dimensionality of vectors to mask. * @param width The number of dimensions in vector projections. */ random_mask(unsigned int dimensions, unsigned int width); /** * Project a vector, reducing it to a dimensionality specified by this mask. * * @param vector The vector to project. * @return The projected vector. */ vector project(const vector& vector) const; }; class covering_mask: public mask { public: /** * A random mapping of vectors. */ typedef std::vector<vector> mapping; private: /** * The random mapping to use for this mask. */ mapping mapping_; /** * Project a vector, reducing it to a dimensionality specified by this mask. * * @param vector The vector to project. * @return The projected vector. */ vector project(const vector& vector) const; /** * Create a random mapping. * * @param dimensions The number of vectors in the mapping. * @param radius The radius that the mapping should cover. * @return The random mapping. */ static mapping create_mapping(unsigned int dimensions, unsigned int radius); }; } <commit_msg>Add missing line<commit_after>// Copyright (c) 2016 Kasper Kronborg Isager and Radoslaw Niemczyk. #pragma once #include <vector> #include <random> #include "vector.hpp" namespace lsh { /** * The mask class acts as sort of a bit mask that can reduce the dimensionality of * vectors by a projection. */ class mask { public: /** * Project a vector, reducing it to a dimensionality specified by this mask. * * @param vector The vector to project. * @return The projected vector. */ virtual vector project(const vector& vector) const; }; class random_mask: public mask { private: /** * The number of dimensions in vector projections. */ unsigned int width_; /** * The randomly chosen indices to pick for vector projections. */ std::vector<unsigned int> indices_; public: /** * Construct a new mask. * * @param dimensionality The dimensionality of vectors to mask. * @param width The number of dimensions in vector projections. */ random_mask(unsigned int dimensions, unsigned int width); /** * Project a vector, reducing it to a dimensionality specified by this mask. * * @param vector The vector to project. * @return The projected vector. */ vector project(const vector& vector) const; }; class covering_mask: public mask { public: /** * A random mapping of vectors. */ typedef std::vector<vector> mapping; private: /** * The random mapping to use for this mask. */ mapping mapping_; public: /** * Project a vector, reducing it to a dimensionality specified by this mask. * * @param vector The vector to project. * @return The projected vector. */ vector project(const vector& vector) const; /** * Create a random mapping. * * @param dimensions The number of vectors in the mapping. * @param radius The radius that the mapping should cover. * @return The random mapping. */ static mapping create_mapping(unsigned int dimensions, unsigned int radius); }; } <|endoftext|>
<commit_before>#pragma once #include <cmath> // windows MinGW fix #ifdef __MINGW32__ #ifndef M_PI const double M_PI = 3.14159265358979323846264338327950288; const double M_2PI = M_PI * 2.0; #endif #endif inline float _fmod( float x, float y ) { return fmod( fmod( x, y ) + y, y ); } <commit_msg>[fix] M_2PI not defined in cmath<commit_after>#pragma once #include <cmath> // windows MinGW fix #ifdef __MINGW32__ #ifndef M_PI const double M_PI = 3.14159265358979323846264338327950288; #endif #endif const double M_2PI = M_PI * 2.0; inline float _fmod( float x, float y ) { return fmod( fmod( x, y ) + y, y ); } <|endoftext|>
<commit_before>/* This is free and unencumbered software released into the public domain. */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include "cpr/vector.h" #include <cerrno> /* for errno */ #include <cstdlib> /* for std::calloc(), std::free() */ #include <new> /* for std::bad_alloc */ #include <stdexcept> /* for std::out_of_range */ #include <system_error> /* for std::errc */ #include <vector> /* for std::vector */ struct cpr_vector : public std::vector<void*> {}; extern const size_t cpr_vector_sizeof = sizeof(cpr_vector); cpr_vector* cpr_vector_alloc(void) { return reinterpret_cast<cpr_vector*>(std::calloc(1, sizeof(cpr_vector))); } void cpr_vector_free(cpr_vector* const vector) { std::free(vector); } void cpr_vector_init(cpr_vector* const vector) { new(vector) cpr_vector(); // TODO: handle exceptions? } void cpr_vector_dispose(cpr_vector* const vector) { /* Guaranteed to never throw an exception: */ vector->~cpr_vector(); } bool cpr_vector_empty(const cpr_vector* const vector) { /* Guaranteed to never throw an exception: */ return vector->empty(); } size_t cpr_vector_size(const cpr_vector* const vector) { /* Guaranteed to never throw an exception: */ return vector->size(); } void* cpr_vector_data(const cpr_vector* const vector) { /* Guaranteed to never throw an exception: */ return const_cast<cpr_vector*>(vector)->data(); } void* cpr_vector_at(const cpr_vector* const vector, const size_t position) { try { return vector->at(position); } catch (const std::out_of_range& error) { errno = static_cast<int>(std::errc::argument_out_of_domain); /* EDOM */ return nullptr; } } void cpr_vector_clear(cpr_vector* const vector) { /* Guaranteed to never throw an exception: */ vector->clear(); } void cpr_vector_push_back(cpr_vector* const vector, const void* const element) { try { vector->push_back(const_cast<void*>(element)); } catch (const std::bad_alloc& error) { errno = static_cast<int>(std::errc::not_enough_memory); /* ENOMEM */ } } void cpr_vector_pop_back(cpr_vector* const vector) { if (vector->empty()) { /* Invoking #pop_back() on an empty vector is defined to result in * undefined behavior. We'd rather avoid undefined behavior, so we'll * just fail gracefully instead. */ errno = static_cast<int>(std::errc::bad_address); /* EFAULT */ return; } /* Guaranteed to never throw an exception: */ vector->pop_back(); } <commit_msg>Added static_assert(noexcept(...)) checks for no-throw guarantees.<commit_after>/* This is free and unencumbered software released into the public domain. */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include "cpr/vector.h" #include <cerrno> /* for errno */ #include <cstdlib> /* for std::calloc(), std::free() */ #include <new> /* for std::bad_alloc */ #include <stdexcept> /* for std::out_of_range */ #include <system_error> /* for std::errc */ #include <vector> /* for std::vector */ struct cpr_vector : public std::vector<void*> {}; extern const size_t cpr_vector_sizeof = sizeof(cpr_vector); cpr_vector* cpr_vector_alloc(void) { return reinterpret_cast<cpr_vector*>(std::calloc(1, sizeof(cpr_vector))); } void cpr_vector_free(cpr_vector* const vector) { std::free(vector); } void cpr_vector_init(cpr_vector* const vector) { new(vector) cpr_vector(); // TODO: handle exceptions? } void cpr_vector_dispose(cpr_vector* const vector) { /* Guaranteed to never throw an exception: */ vector->~cpr_vector(); } bool cpr_vector_empty(const cpr_vector* const vector) { /* Guaranteed to never throw an exception: */ return vector->empty(); #ifdef DEBUG static_assert(noexcept(vector->empty()), "std::vector::empty() declaration is missing the noexcept specifier"); #endif } size_t cpr_vector_size(const cpr_vector* const vector) { /* Guaranteed to never throw an exception: */ return vector->size(); #ifdef DEBUG static_assert(noexcept(vector->size()), "std::vector::size() declaration is missing the noexcept specifier"); #endif } void* cpr_vector_data(const cpr_vector* const vector) { /* Guaranteed to never throw an exception: */ return const_cast<cpr_vector*>(vector)->data(); #ifdef DEBUG static_assert(noexcept(vector->data()), "std::vector::data() declaration is missing the noexcept specifier"); #endif } void* cpr_vector_at(const cpr_vector* const vector, const size_t position) { try { return vector->at(position); } catch (const std::out_of_range& error) { errno = static_cast<int>(std::errc::argument_out_of_domain); /* EDOM */ return nullptr; } } void cpr_vector_clear(cpr_vector* const vector) { /* Guaranteed to never throw an exception: */ vector->clear(); #ifdef DEBUG static_assert(noexcept(vector->clear()), "std::vector::clear() declaration is missing the noexcept specifier"); #endif } void cpr_vector_push_back(cpr_vector* const vector, const void* const element) { try { vector->push_back(const_cast<void*>(element)); } catch (const std::bad_alloc& error) { errno = static_cast<int>(std::errc::not_enough_memory); /* ENOMEM */ } } void cpr_vector_pop_back(cpr_vector* const vector) { if (vector->empty()) { /* Invoking #pop_back() on an empty vector is defined to result in * undefined behavior. We'd rather avoid undefined behavior, so we'll * just fail gracefully instead. */ errno = static_cast<int>(std::errc::bad_address); /* EFAULT */ return; } /* Guaranteed to never throw an exception: */ vector->pop_back(); #if 0 static_assert(noexcept(vector->pop_back()), "std::vector::pop_back() declaration is missing the noexcept specifier"); #endif } <|endoftext|>
<commit_before>#include <room.hpp> #include <glm/gtc/noise.hpp> #include <mos/util.hpp> mos::Assets Room::assets_; Room::Room(const glm::mat4 &transform) { room_.transform = transform; size_.x = int(glm::abs(glm::simplex(room_.position()) * 5.0f)) + 2.0f; size_.y = int(glm::abs(glm::simplex(room_.position()) * 5.0f)) + 2.0f; //size_ = {3, 3}; const auto entry_pos = mos::position(transform); auto floor_model = assets_.model("room_floor.model"); std::vector<mos::Model> edge_models{assets_.model("room_edge.model"), assets_.model("room_edge1.model")}; auto corner_model = assets_.model("room_corner.model"); auto entry_model = assets_.model("room_entry.model"); //Entry door entry_model.transform = glm::rotate(glm::translate(glm::mat4(1.0f), {.5f, .0f, .0f}), 0.0f, {.0f, .0f, 1.f}); room_.models.push_back(entry_model); //Exit door entry_model.transform = glm::rotate(glm::translate(glm::mat4(1.0f), {size_.x - .5f, .0f, .0f}), 0.0f, {.0f, .0f, 1.f}); room_.models.push_back(entry_model); corner_model.transform = glm::rotate(glm::translate(glm::mat4(1.0f), {0.5f, size_.y - 1.0f, .0f}), 0.0f, {.0f, .0f, 1.f}); room_.models.push_back(corner_model); corner_model.transform = glm::rotate(glm::translate(glm::mat4(1.0f), {size_.x - 0.5f, size_.y - 1.0f, .0f}), -glm::half_pi<float>(), {.0f, .0f, 1.f}); room_.models.push_back(corner_model); for (float x = 1.0f; x < (size_.x - 1.0f); x++) { const auto t0 = glm::rotate(glm::translate(glm::mat4(1.0f), {x + .5f, .0f, .0f}), glm::half_pi<float>(), {.0f, .0f, 1.f}); const auto t1 = glm::rotate(glm::translate(glm::mat4(1.0f), {x + .5f, size_.y - 1.0f, .0f}), -glm::half_pi<float>(), {.0f, .0f, 1.f}); auto & edge_model = edge_models[int(glm::abs(glm::simplex(mos::position(t0)) * edge_models.size()))]; if (x != float(size_.x / 2)) { edge_model.transform = t0; room_.models.push_back(edge_model); edge_model = edge_models[int(glm::abs(glm::simplex(mos::position(t1)) * edge_models.size()))]; edge_model.transform = t1; room_.models.push_back(edge_model); } else { floor_model.transform = t0; room_.models.push_back(floor_model); floor_model.transform = t1; room_.models.push_back(floor_model); } for (float y = 1; y < (size_.y - 1.f); y++) { floor_model.position(glm::vec3(x + 0.5f, y, 0.0f)); room_.models.push_back(floor_model); const auto t0 = glm::rotate(glm::translate(glm::mat4(1.0f), {0.5f, y, .0f}), 0.0f, {.0f, .0f, 1.f}); edge_model = edge_models[int(glm::abs(glm::simplex(mos::position(t0)) * edge_models.size()))]; edge_model.transform = t0; room_.models.push_back(edge_model); const auto t1 = glm::rotate(glm::translate(glm::mat4(1.0f), {size_.x - 0.5f, y, .0f}), glm::pi<float>(), {.0f, .0f, 1.f}); edge_model = edge_models[int(glm::abs(glm::simplex(mos::position(t1)) * edge_models.size()))]; edge_model.transform = t1; room_.models.push_back(edge_model); } } box_ = mos::Box::create_from_model(room_); box_.extent -= 0.01; exits.push_back( Door(transform * glm::translate(glm::mat4(1.0f), glm::vec3(size_.x, 0.0f, 0.0f)))); //uint right = uint((glm::abs(glm::simplex(model_.position())) * length_)); exits.push_back( Door(transform * glm::translate(glm::mat4(1.0f), glm::vec3((size_.x / 2) + 0.5f, -0.5f, 0.0f)) * glm::rotate(glm::mat4(1.0f), -glm::half_pi<float>(), glm::vec3(0.0f, 0.0f, 1.0f)))); //uint left = uint((glm::abs(glm::simplex(model_.position())) * length_)); exits.push_back( Door(transform * glm::translate(glm::mat4(1.0f), glm::vec3((size_.x / 2) + 0.5f, float(size_.y) - 0.5f, 0.0f)) * glm::rotate(glm::mat4(1.0f), glm::half_pi<float>(), glm::vec3(0.0f, 0.0f, 1.0f)))); } mos::Model Room::model() { return room_; } std::ostream &operator<<(std::ostream &os, const Room &room) { os << " size: " << room.size_; return os; } <commit_msg>algorithm.h<commit_after>#include <room.hpp> #include <glm/gtc/noise.hpp> #include <mos/util.hpp> #include <algorithm.hpp> mos::Assets Room::assets_; Room::Room(const glm::mat4 &transform) { room_.transform = transform; size_.x = int(glm::abs(glm::simplex(room_.position()) * 5.0f)) + 2.0f; size_.y = int(glm::abs(glm::simplex(room_.position()) * 5.0f)) + 2.0f; //size_ = {3, 3}; const auto entry_pos = mos::position(transform); auto floor_model = assets_.model("room_floor.model"); std::vector<mos::Model> edge_models{assets_.model("room_edge.model"), assets_.model("room_edge1.model")}; auto corner_model = assets_.model("room_corner.model"); auto entry_model = assets_.model("room_entry.model"); //Entry door entry_model.transform = glm::rotate(glm::translate(glm::mat4(1.0f), {.5f, .0f, .0f}), 0.0f, {.0f, .0f, 1.f}); room_.models.push_back(entry_model); //Exit door entry_model.transform = glm::rotate(glm::translate(glm::mat4(1.0f), {size_.x - .5f, .0f, .0f}), 0.0f, {.0f, .0f, 1.f}); room_.models.push_back(entry_model); corner_model.transform = glm::rotate(glm::translate(glm::mat4(1.0f), {0.5f, size_.y - 1.0f, .0f}), 0.0f, {.0f, .0f, 1.f}); room_.models.push_back(corner_model); corner_model.transform = glm::rotate(glm::translate(glm::mat4(1.0f), {size_.x - 0.5f, size_.y - 1.0f, .0f}), -glm::half_pi<float>(), {.0f, .0f, 1.f}); room_.models.push_back(corner_model); for (float x = 1.0f; x < (size_.x - 1.0f); x++) { const auto t0 = glm::rotate(glm::translate(glm::mat4(1.0f), {x + .5f, .0f, .0f}), glm::half_pi<float>(), {.0f, .0f, 1.f}); const auto t1 = glm::rotate(glm::translate(glm::mat4(1.0f), {x + .5f, size_.y - 1.0f, .0f}), -glm::half_pi<float>(), {.0f, .0f, 1.f}); auto & edge_model = edge_models[simplex_index(mos::position(t1),edge_models.size())]; if (x != float(size_.x / 2)) { edge_model.transform = t0; room_.models.push_back(edge_model); edge_model = edge_models[simplex_index(mos::position(t1),edge_models.size())]; edge_model.transform = t1; room_.models.push_back(edge_model); } else { floor_model.transform = t0; room_.models.push_back(floor_model); floor_model.transform = t1; room_.models.push_back(floor_model); } for (float y = 1; y < (size_.y - 1.f); y++) { floor_model.position(glm::vec3(x + 0.5f, y, 0.0f)); room_.models.push_back(floor_model); const auto t0 = glm::rotate(glm::translate(glm::mat4(1.0f), {0.5f, y, .0f}), 0.0f, {.0f, .0f, 1.f}); edge_model = edge_models[simplex_index(mos::position(t1),edge_models.size())]; edge_model.transform = t0; room_.models.push_back(edge_model); const auto t1 = glm::rotate(glm::translate(glm::mat4(1.0f), {size_.x - 0.5f, y, .0f}), glm::pi<float>(), {.0f, .0f, 1.f}); edge_model = edge_models[simplex_index(mos::position(t1),edge_models.size())]; edge_model.transform = t1; room_.models.push_back(edge_model); } } box_ = mos::Box::create_from_model(room_); box_.extent -= 0.01; exits.push_back( Door(transform * glm::translate(glm::mat4(1.0f), glm::vec3(size_.x, 0.0f, 0.0f)))); //uint right = uint((glm::abs(glm::simplex(model_.position())) * length_)); exits.push_back( Door(transform * glm::translate(glm::mat4(1.0f), glm::vec3((size_.x / 2) + 0.5f, -0.5f, 0.0f)) * glm::rotate(glm::mat4(1.0f), -glm::half_pi<float>(), glm::vec3(0.0f, 0.0f, 1.0f)))); //uint left = uint((glm::abs(glm::simplex(model_.position())) * length_)); exits.push_back( Door(transform * glm::translate(glm::mat4(1.0f), glm::vec3((size_.x / 2) + 0.5f, float(size_.y) - 0.5f, 0.0f)) * glm::rotate(glm::mat4(1.0f), glm::half_pi<float>(), glm::vec3(0.0f, 0.0f, 1.0f)))); } mos::Model Room::model() { return room_; } std::ostream &operator<<(std::ostream &os, const Room &room) { os << " size: " << room.size_; return os; } <|endoftext|>
<commit_before>/* Copyright (C) 2016 Volker Krause <vkrause@kde.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "rule.h" #include <QDebug> #include <QString> #include <QXmlStreamReader> using namespace KateSyntax; Rule::Rule() : m_firstNonSpace(false) { } Rule::~Rule() { qDeleteAll(m_subRules); } QString Rule::attribute() const { return m_attribute; } QString Rule::context() const { return m_context; } bool Rule::load(QXmlStreamReader &reader) { m_attribute = reader.attributes().value(QStringLiteral("attribute")).toString(); m_context = reader.attributes().value(QStringLiteral("context")).toString(); if (m_context.isEmpty()) m_context = QStringLiteral("#stay"); m_firstNonSpace = reader.attributes().value(QStringLiteral("firstNonSpace")) == QLatin1String("true"); auto result = doLoad(reader); // TODO load sub-rules reader.readNextStartElement(); return result; } bool Rule::doLoad(QXmlStreamReader& reader) { Q_UNUSED(reader); return true; } int Rule::match(const QString &text, int offset) { Q_ASSERT(!text.isEmpty()); if (m_firstNonSpace && (offset > 0 || text.at(0).isSpace())) return false; auto result = doMatch(text, offset); // TODO match sub-rules return result; } Rule* Rule::create(const QStringRef& name) { qDebug() << name; Rule *rule = nullptr; if (name == QLatin1String("AnyChar")) rule = new AnyChar; else if (name == QLatin1String("DetectChar")) rule = new DetectChar; else if (name == QLatin1String("Detect2Chars")) rule = new Detect2Char; else if (name == QLatin1String("DetectIdentifier")) rule = new DetectIdentifier; else if (name == QLatin1String("DetectSpaces")) rule = new DetectSpaces; else if (name == QLatin1String("Int")) rule = new Int; else if (name == QLatin1String("HlCHex")) rule = new HlCHex; else if (name == QLatin1String("keyword")) rule = new KeywordListRule; else if (name == QLatin1String("RegExpr")) rule = new RegExpr; else if (name == QLatin1String("StringDetect")) rule = new StringDetect; else if (name == QLatin1String("WordDetect")) rule = new WordDetect; else qDebug() << name << "rule not yet implemented"; return rule; } bool Rule::isDelimiter(QChar c) const { // TODO: this is definition-global and configurable! static const QString delimiters = QStringLiteral(".():!+,-<=>%&*/;?[]^{|}~\\ \t"); return delimiters.contains(c); } bool AnyChar::doLoad(QXmlStreamReader& reader) { m_chars = reader.attributes().value(QStringLiteral("String")).toString(); if (m_chars.size() == 1) qDebug() << "AnyChar rule with just one char: use DetectChar instead."; return !m_chars.isEmpty(); } int AnyChar::doMatch(const QString& text, int offset) { if (m_chars.contains(text.at(offset))) return offset + 1; return offset; } bool DetectChar::doLoad(QXmlStreamReader& reader) { const auto s = reader.attributes().value(QStringLiteral("char")); if (s.isEmpty()) return false; m_char = s.at(0); return true; } int DetectChar::doMatch(const QString& text, int offset) { if (text.at(offset) == m_char) return offset + 1; return offset; } bool Detect2Char::doLoad(QXmlStreamReader& reader) { const auto s1 = reader.attributes().value(QStringLiteral("char")); const auto s2 = reader.attributes().value(QStringLiteral("char1")); if (s1.isEmpty() || s2.isEmpty()) return false; m_char1 = s1.at(0); m_char2 = s2.at(0); return true; } int Detect2Char::doMatch(const QString& text, int offset) { if (text.size() - offset < 2) return offset; if (text.at(offset) == m_char1 && text.at(offset + 1) == m_char2) return offset + 2; return offset; } int DetectIdentifier::doMatch(const QString& text, int offset) { if (!text.at(offset).isLetter() && text.at(offset) != QLatin1Char('_')) return offset; for (int i = offset + 1; i < text.size(); ++i) { const auto c = text.at(i); if (!c.isLetterOrNumber() && c != QLatin1Char('_')) return i; } return offset + 1; } int DetectSpaces::doMatch(const QString& text, int offset) { while(offset < text.size() && text.at(offset).isSpace()) ++offset; return offset; } int Int::doMatch(const QString& text, int offset) { while(offset < text.size() && text.at(offset).isDigit()) ++offset; return offset; } bool KateSyntax::HlCHex::isHexChar(QChar c) { return c.isNumber() || c == QLatin1Char('a') || c == QLatin1Char('A') || c == QLatin1Char('b') || c == QLatin1Char('B') || c == QLatin1Char('c') || c == QLatin1Char('C') || c == QLatin1Char('d') || c == QLatin1Char('D') || c == QLatin1Char('e') || c == QLatin1Char('E') || c == QLatin1Char('f') || c == QLatin1Char('F'); } int HlCHex::doMatch(const QString& text, int offset) { if (text.size() < offset + 3) return offset; if (text.at(offset) != QLatin1Char('0') || (text.at(offset + 1) != QLatin1Char('x') && text.at(offset + 1) != QLatin1Char('X'))) return offset; if (!isHexChar(text.at(offset + 2))) return offset; offset += 3; while (offset < text.size() && isHexChar(text.at(offset))) ++offset; // TODO Kate matches U/L suffix, QtC does not? return offset; } QString KeywordListRule::listName() const { return m_listName; } void KeywordListRule::setKeywordList(const KeywordList &keywordList) { m_keywordList = keywordList; } bool KeywordListRule::doLoad(QXmlStreamReader& reader) { m_listName = reader.attributes().value(QStringLiteral("String")).toString(); return !m_listName.isEmpty(); } int KeywordListRule::doMatch(const QString& text, int offset) { if (offset > 0 && !isDelimiter(text.at(offset - 1))) return offset; int offset2 = offset; int wordLen = 0; int len = text.size(); while ((len > offset2) && !isDelimiter(text[offset2])) { offset2++; wordLen++; } // TODO support case-insensitive keywords if (m_keywordList.keywords().contains(text.mid(offset, wordLen))) return offset2; return offset; } bool RegExpr::doLoad(QXmlStreamReader& reader) { m_regexp.setPattern(reader.attributes().value(QStringLiteral("String")).toString()); m_regexp.setMinimal(reader.attributes().value(QStringLiteral("minimal")) != QLatin1String("true")); m_regexp.setCaseSensitivity(reader.attributes().value(QStringLiteral("insensitive")) == QLatin1String("true") ? Qt::CaseInsensitive : Qt::CaseSensitive); return m_regexp.isValid(); } int RegExpr::doMatch(const QString& text, int offset) { Q_ASSERT(m_regexp.isValid()); auto idx = m_regexp.indexIn(text, offset, QRegExp::CaretAtOffset); if (idx == offset) return offset + m_regexp.matchedLength(); return offset; } bool StringDetect::doLoad(QXmlStreamReader& reader) { m_string = reader.attributes().value(QStringLiteral("String")).toString(); m_caseSensitivity = reader.attributes().value(QStringLiteral("insensitive")) != QLatin1String("true") ? Qt::CaseInsensitive : Qt::CaseSensitive; return m_string.isEmpty(); } int StringDetect::doMatch(const QString& text, int offset) { if (text.midRef(offset, m_string.size()).compare(m_string, m_caseSensitivity) == 0) return offset + m_string.size(); return offset; } bool WordDetect::doLoad(QXmlStreamReader& reader) { m_word = reader.attributes().value(QStringLiteral("String")).toString(); return !m_word.isEmpty(); } int WordDetect::doMatch(const QString& text, int offset) { if (text.size() - offset < m_word.size()) return offset; if (offset > 0 && !isDelimiter(text.at(offset - 1))) return offset; if (text.midRef(offset, m_word.size()) != m_word) return offset; if (text.size() == offset + m_word.size() || isDelimiter(text.at(offset + m_word.size()))) return offset + m_word.size(); return offset; } <commit_msg>Load sub-rules.<commit_after>/* Copyright (C) 2016 Volker Krause <vkrause@kde.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "rule.h" #include <QDebug> #include <QString> #include <QXmlStreamReader> using namespace KateSyntax; Rule::Rule() : m_firstNonSpace(false) { } Rule::~Rule() { qDeleteAll(m_subRules); } QString Rule::attribute() const { return m_attribute; } QString Rule::context() const { return m_context; } bool Rule::load(QXmlStreamReader &reader) { Q_ASSERT(reader.tokenType() == QXmlStreamReader::StartElement); m_attribute = reader.attributes().value(QStringLiteral("attribute")).toString(); m_context = reader.attributes().value(QStringLiteral("context")).toString(); if (m_context.isEmpty()) m_context = QStringLiteral("#stay"); m_firstNonSpace = reader.attributes().value(QStringLiteral("firstNonSpace")) == QLatin1String("true"); auto result = doLoad(reader); if (m_lookAhead && m_context == QLatin1String("#stay")) result = false; reader.readNext(); while (!reader.atEnd()) { switch (reader.tokenType()) { case QXmlStreamReader::StartElement: { qDebug() << reader.name() << "sub-rule"; auto rule = Rule::create(reader.name()); if (rule && rule->load(reader)) m_subRules.push_back(rule); reader.skipCurrentElement(); break; } case QXmlStreamReader::EndElement: qDebug() << reader.name() << "end element"; return result; default: reader.readNext(); break; } } return result; } bool Rule::doLoad(QXmlStreamReader& reader) { Q_UNUSED(reader); return true; } int Rule::match(const QString &text, int offset) { Q_ASSERT(!text.isEmpty()); if (m_firstNonSpace && (offset > 0 || text.at(0).isSpace())) return false; auto result = doMatch(text, offset); // TODO match sub-rules return result; } Rule* Rule::create(const QStringRef& name) { qDebug() << name; Rule *rule = nullptr; if (name == QLatin1String("AnyChar")) rule = new AnyChar; else if (name == QLatin1String("DetectChar")) rule = new DetectChar; else if (name == QLatin1String("Detect2Chars")) rule = new Detect2Char; else if (name == QLatin1String("DetectIdentifier")) rule = new DetectIdentifier; else if (name == QLatin1String("DetectSpaces")) rule = new DetectSpaces; else if (name == QLatin1String("Int")) rule = new Int; else if (name == QLatin1String("HlCHex")) rule = new HlCHex; else if (name == QLatin1String("keyword")) rule = new KeywordListRule; else if (name == QLatin1String("RegExpr")) rule = new RegExpr; else if (name == QLatin1String("StringDetect")) rule = new StringDetect; else if (name == QLatin1String("WordDetect")) rule = new WordDetect; else qDebug() << name << "rule not yet implemented"; return rule; } bool Rule::isDelimiter(QChar c) const { // TODO: this is definition-global and configurable! static const QString delimiters = QStringLiteral(".():!+,-<=>%&*/;?[]^{|}~\\ \t"); return delimiters.contains(c); } bool AnyChar::doLoad(QXmlStreamReader& reader) { m_chars = reader.attributes().value(QStringLiteral("String")).toString(); if (m_chars.size() == 1) qDebug() << "AnyChar rule with just one char: use DetectChar instead."; return !m_chars.isEmpty(); } int AnyChar::doMatch(const QString& text, int offset) { if (m_chars.contains(text.at(offset))) return offset + 1; return offset; } bool DetectChar::doLoad(QXmlStreamReader& reader) { const auto s = reader.attributes().value(QStringLiteral("char")); if (s.isEmpty()) return false; m_char = s.at(0); return true; } int DetectChar::doMatch(const QString& text, int offset) { if (text.at(offset) == m_char) return offset + 1; return offset; } bool Detect2Char::doLoad(QXmlStreamReader& reader) { const auto s1 = reader.attributes().value(QStringLiteral("char")); const auto s2 = reader.attributes().value(QStringLiteral("char1")); if (s1.isEmpty() || s2.isEmpty()) return false; m_char1 = s1.at(0); m_char2 = s2.at(0); return true; } int Detect2Char::doMatch(const QString& text, int offset) { if (text.size() - offset < 2) return offset; if (text.at(offset) == m_char1 && text.at(offset + 1) == m_char2) return offset + 2; return offset; } int DetectIdentifier::doMatch(const QString& text, int offset) { if (!text.at(offset).isLetter() && text.at(offset) != QLatin1Char('_')) return offset; for (int i = offset + 1; i < text.size(); ++i) { const auto c = text.at(i); if (!c.isLetterOrNumber() && c != QLatin1Char('_')) return i; } return offset + 1; } int DetectSpaces::doMatch(const QString& text, int offset) { while(offset < text.size() && text.at(offset).isSpace()) ++offset; return offset; } int Int::doMatch(const QString& text, int offset) { while(offset < text.size() && text.at(offset).isDigit()) ++offset; return offset; } bool KateSyntax::HlCHex::isHexChar(QChar c) { return c.isNumber() || c == QLatin1Char('a') || c == QLatin1Char('A') || c == QLatin1Char('b') || c == QLatin1Char('B') || c == QLatin1Char('c') || c == QLatin1Char('C') || c == QLatin1Char('d') || c == QLatin1Char('D') || c == QLatin1Char('e') || c == QLatin1Char('E') || c == QLatin1Char('f') || c == QLatin1Char('F'); } int HlCHex::doMatch(const QString& text, int offset) { if (text.size() < offset + 3) return offset; if (text.at(offset) != QLatin1Char('0') || (text.at(offset + 1) != QLatin1Char('x') && text.at(offset + 1) != QLatin1Char('X'))) return offset; if (!isHexChar(text.at(offset + 2))) return offset; offset += 3; while (offset < text.size() && isHexChar(text.at(offset))) ++offset; // TODO Kate matches U/L suffix, QtC does not? return offset; } QString KeywordListRule::listName() const { return m_listName; } void KeywordListRule::setKeywordList(const KeywordList &keywordList) { m_keywordList = keywordList; } bool KeywordListRule::doLoad(QXmlStreamReader& reader) { m_listName = reader.attributes().value(QStringLiteral("String")).toString(); return !m_listName.isEmpty(); } int KeywordListRule::doMatch(const QString& text, int offset) { if (offset > 0 && !isDelimiter(text.at(offset - 1))) return offset; int offset2 = offset; int wordLen = 0; int len = text.size(); while ((len > offset2) && !isDelimiter(text[offset2])) { offset2++; wordLen++; } // TODO support case-insensitive keywords if (m_keywordList.keywords().contains(text.mid(offset, wordLen))) return offset2; return offset; } bool RegExpr::doLoad(QXmlStreamReader& reader) { m_regexp.setPattern(reader.attributes().value(QStringLiteral("String")).toString()); m_regexp.setMinimal(reader.attributes().value(QStringLiteral("minimal")) != QLatin1String("true")); m_regexp.setCaseSensitivity(reader.attributes().value(QStringLiteral("insensitive")) == QLatin1String("true") ? Qt::CaseInsensitive : Qt::CaseSensitive); return m_regexp.isValid(); } int RegExpr::doMatch(const QString& text, int offset) { Q_ASSERT(m_regexp.isValid()); auto idx = m_regexp.indexIn(text, offset, QRegExp::CaretAtOffset); if (idx == offset) return offset + m_regexp.matchedLength(); return offset; } bool StringDetect::doLoad(QXmlStreamReader& reader) { m_string = reader.attributes().value(QStringLiteral("String")).toString(); m_caseSensitivity = reader.attributes().value(QStringLiteral("insensitive")) != QLatin1String("true") ? Qt::CaseInsensitive : Qt::CaseSensitive; return m_string.isEmpty(); } int StringDetect::doMatch(const QString& text, int offset) { if (text.midRef(offset, m_string.size()).compare(m_string, m_caseSensitivity) == 0) return offset + m_string.size(); return offset; } bool WordDetect::doLoad(QXmlStreamReader& reader) { m_word = reader.attributes().value(QStringLiteral("String")).toString(); return !m_word.isEmpty(); } int WordDetect::doMatch(const QString& text, int offset) { if (text.size() - offset < m_word.size()) return offset; if (offset > 0 && !isDelimiter(text.at(offset - 1))) return offset; if (text.midRef(offset, m_word.size()) != m_word) return offset; if (text.size() == offset + m_word.size() || isDelimiter(text.at(offset + m_word.size()))) return offset + m_word.size(); return offset; } <|endoftext|>
<commit_before>#include "cvm.h" #include "../cshared/disasm.h" void DabVM_debug::print_registers() { fprintf(stderr, "IP = %p (%d)\n", (void *)vm.ip(), (int)vm.ip()); } void DabVM_debug::print_ssa_registers() { auto err_stream = $VM->options.output; fprintf(err_stream, "Registers:\n"); size_t index = 0; for (const auto &reg : vm._registers) { fprintf(err_stream, "R%zu: ", index); reg.dump(err_stream); fprintf(err_stream, "\n"); } } void DabVM_debug::print_classes() { for (const auto &it : vm.classes) { fprintf(stderr, " - 0x%04x %s (super = 0x%04x)\n", it.first, it.second.name.c_str(), it.second.superclass_index); for (const auto &fin : it.second.static_functions) { fprintf(stderr, " ::%s [%s]\n", $VM->get_symbol(fin.first).c_str(), fin.second.regular ? "Dab" : "C"); } for (const auto &fin : it.second.functions) { fprintf(stderr, " .%s [%s]\n", $VM->get_symbol(fin.first).c_str(), fin.second.regular ? "Dab" : "C"); } } } void DabVM_debug::print_functions() { for (auto it : vm.functions) { auto &fun = it.second; fprintf(stderr, " - %s: %s at %p\n", fun.name.c_str(), fun.regular ? "Dab" : "C", (void *)fun.address); } } void DabVM_debug::print_constants() { auto output = $VM->options.output; fprintf(output, "symbols:\n"); size_t i = 0; for (const auto &symbol : $VM->symbols) { fprintf(output, "%d: %s\n", (int)i, symbol.c_str()); i++; } } void DabVM_debug::print_stack() { } void DabVM_debug::print_code(bool current_only) { prepare_disasm(); auto err_stream = $VM->options.output; auto ip = vm.ip(); fprintf(err_stream, "IP = %d\n", (int)ip); auto it = find_if(disasm.begin(), disasm.end(), [ip](const std::pair<size_t, std::string> &obj) { return obj.first == ip; }); if (it == disasm.end()) return; auto index = std::distance(disasm.begin(), it); long start = current_only ? (index - 2) : 0; long end = current_only ? (index + 3) : disasm.size(); for (long i = start; i < end; i++) { if (i < 0 || i >= (int)disasm.size()) continue; const auto &line = disasm[i]; fprintf(err_stream, "%c %8" PRIu64 ": %s\n", line.first == ip ? '>' : ' ', line.first, line.second.c_str()); } } struct InstructionsReader : public BaseReader { DabVM &vm; const byte *_data; uint64_t _length; uint64_t start_position = 0; InstructionsReader(DabVM &vm, uint64_t &position) : BaseReader(position), vm(vm) { _data = vm.instructions.raw_base_data(); _length = vm.instructions.raw_base_length(); BinSection code_section; bool has_code = false; for (auto &section : vm.sections) { if (std::string(section.name) == "code") { code_section = section; has_code = true; break; } } if (!has_code) throw "no code?"; start_position = code_section.pos; _data += start_position; _length = code_section.length; } virtual uint64_t raw_read(void *buffer, uint64_t size) override { auto data = _data; auto length = _length; auto offset = position(); auto max_length = std::min(size, length - offset); memcpy(buffer, data + offset, max_length); return max_length; } bool feof() { return false; } }; void DabVM_debug::prepare_disasm() { if (has_disasm) return; has_disasm = true; uint64_t position = 0; InstructionsReader reader(vm, position); DisasmProcessor<InstructionsReader> processor(reader); processor.go([this, reader](size_t pos, std::string info) { disasm.push_back(std::make_pair(pos + reader.start_position, info)); }); } void DabVM::execute_debug(Stream &input) { auto err_stream = options.output; DabVM_debug debug(*this); while (!input.eof()) { char rawcmd[2048]; fprintf(stderr, "> "); fgets(rawcmd, sizeof(rawcmd), stdin); std::string cmd = rawcmd; cmd = cmd.substr(0, cmd.length() - 1); if (cmd == "help") { fprintf(err_stream, "Help:\n"); fprintf(err_stream, "help - print this\n"); fprintf(err_stream, "[s]tep - run single instruction\n"); fprintf(err_stream, "[r]egisters - show registers\n"); fprintf(err_stream, "classes - print classes\n"); fprintf(err_stream, "functions - print functions\n"); fprintf(err_stream, "constants - dump constants\n"); fprintf(err_stream, "stack - dump stack\n"); fprintf(err_stream, "code - show current code\n"); fprintf(err_stream, "allcode - show all code\n"); fprintf(err_stream, "run - run remaining instructions\n"); fprintf(err_stream, "break [ip] - break at defined IP\n"); fprintf(err_stream, "quit - quit\n"); } else if (cmd == "step" || cmd == "s") { execute_single(input); } else if (cmd == "registers" || cmd == "r") { debug.print_registers(); } else if (cmd == "classes") { debug.print_classes(); } else if (cmd == "functions") { debug.print_functions(); } else if (cmd == "constants") { debug.print_constants(); } else if (cmd == "stack") { debug.print_stack(); } else if (cmd == "ip") { fprintf(err_stream, "IP = %" PRIu64 "\n", ip()); } else if (cmd == "code") { debug.print_code(true); } else if (cmd == "allcode") { debug.print_code(false); } else if (cmd == "quit") { exit(0); } else if (cmd == "run") { execute(input); } else if (cmd.substr(0, 6) == "break ") { int ip = 0; int ret = sscanf(cmd.c_str(), "break %d", &ip); assert(ret == 1); fprintf(err_stream, "debug: break at %d.\n", ip); breakpoints.insert(ip); } else if (cmd == "ssaregs") { debug.print_ssa_registers(); } else { fprintf(stderr, "Unknown command, type <help> to get available commands.\n"); } } } <commit_msg>vm: fix some size_t/uint64_t issues (15)<commit_after>#include "cvm.h" #include "../cshared/disasm.h" void DabVM_debug::print_registers() { fprintf(stderr, "IP = %p (%d)\n", (void *)vm.ip(), (int)vm.ip()); } void DabVM_debug::print_ssa_registers() { auto err_stream = $VM->options.output; fprintf(err_stream, "Registers:\n"); size_t index = 0; for (const auto &reg : vm._registers) { fprintf(err_stream, "R%zu: ", index); reg.dump(err_stream); fprintf(err_stream, "\n"); } } void DabVM_debug::print_classes() { for (const auto &it : vm.classes) { fprintf(stderr, " - 0x%04x %s (super = 0x%04x)\n", it.first, it.second.name.c_str(), it.second.superclass_index); for (const auto &fin : it.second.static_functions) { fprintf(stderr, " ::%s [%s]\n", $VM->get_symbol(fin.first).c_str(), fin.second.regular ? "Dab" : "C"); } for (const auto &fin : it.second.functions) { fprintf(stderr, " .%s [%s]\n", $VM->get_symbol(fin.first).c_str(), fin.second.regular ? "Dab" : "C"); } } } void DabVM_debug::print_functions() { for (auto it : vm.functions) { auto &fun = it.second; fprintf(stderr, " - %s: %s at %p\n", fun.name.c_str(), fun.regular ? "Dab" : "C", (void *)fun.address); } } void DabVM_debug::print_constants() { auto output = $VM->options.output; fprintf(output, "symbols:\n"); size_t i = 0; for (const auto &symbol : $VM->symbols) { fprintf(output, "%d: %s\n", (int)i, symbol.c_str()); i++; } } void DabVM_debug::print_stack() { } void DabVM_debug::print_code(bool current_only) { prepare_disasm(); auto err_stream = $VM->options.output; auto ip = vm.ip(); fprintf(err_stream, "IP = %d\n", (int)ip); auto it = find_if(disasm.begin(), disasm.end(), [ip](const std::pair<size_t, std::string> &obj) { return obj.first == ip; }); if (it == disasm.end()) return; auto index = std::distance(disasm.begin(), it); long start = current_only ? (index - 2) : 0; long end = current_only ? (index + 3) : disasm.size(); for (long i = start; i < end; i++) { if (i < 0 || i >= (int)disasm.size()) continue; const auto &line = disasm[i]; fprintf(err_stream, "%c %8" PRIu64 ": %s\n", line.first == ip ? '>' : ' ', line.first, line.second.c_str()); } } struct InstructionsReader : public BaseReader { DabVM &vm; const byte *_data; uint64_t _length; uint64_t start_position = 0; InstructionsReader(DabVM &vm, uint64_t &position) : BaseReader(position), vm(vm) { _data = vm.instructions.raw_base_data(); _length = vm.instructions.raw_base_length(); BinSection code_section; bool has_code = false; for (auto &section : vm.sections) { if (std::string(section.name) == "code") { code_section = section; has_code = true; break; } } if (!has_code) throw "no code?"; start_position = code_section.pos; _data += start_position; _length = code_section.length; } virtual uint64_t raw_read(void *buffer, uint64_t size) override { auto data = _data; auto length = _length; auto offset = position(); auto max_length = std::min(size, length - offset); memcpy(buffer, data + offset, (size_t)max_length); return max_length; } bool feof() { return false; } }; void DabVM_debug::prepare_disasm() { if (has_disasm) return; has_disasm = true; uint64_t position = 0; InstructionsReader reader(vm, position); DisasmProcessor<InstructionsReader> processor(reader); processor.go([this, reader](size_t pos, std::string info) { disasm.push_back(std::make_pair(pos + reader.start_position, info)); }); } void DabVM::execute_debug(Stream &input) { auto err_stream = options.output; DabVM_debug debug(*this); while (!input.eof()) { char rawcmd[2048]; fprintf(stderr, "> "); fgets(rawcmd, sizeof(rawcmd), stdin); std::string cmd = rawcmd; cmd = cmd.substr(0, cmd.length() - 1); if (cmd == "help") { fprintf(err_stream, "Help:\n"); fprintf(err_stream, "help - print this\n"); fprintf(err_stream, "[s]tep - run single instruction\n"); fprintf(err_stream, "[r]egisters - show registers\n"); fprintf(err_stream, "classes - print classes\n"); fprintf(err_stream, "functions - print functions\n"); fprintf(err_stream, "constants - dump constants\n"); fprintf(err_stream, "stack - dump stack\n"); fprintf(err_stream, "code - show current code\n"); fprintf(err_stream, "allcode - show all code\n"); fprintf(err_stream, "run - run remaining instructions\n"); fprintf(err_stream, "break [ip] - break at defined IP\n"); fprintf(err_stream, "quit - quit\n"); } else if (cmd == "step" || cmd == "s") { execute_single(input); } else if (cmd == "registers" || cmd == "r") { debug.print_registers(); } else if (cmd == "classes") { debug.print_classes(); } else if (cmd == "functions") { debug.print_functions(); } else if (cmd == "constants") { debug.print_constants(); } else if (cmd == "stack") { debug.print_stack(); } else if (cmd == "ip") { fprintf(err_stream, "IP = %" PRIu64 "\n", ip()); } else if (cmd == "code") { debug.print_code(true); } else if (cmd == "allcode") { debug.print_code(false); } else if (cmd == "quit") { exit(0); } else if (cmd == "run") { execute(input); } else if (cmd.substr(0, 6) == "break ") { int ip = 0; int ret = sscanf(cmd.c_str(), "break %d", &ip); assert(ret == 1); fprintf(err_stream, "debug: break at %d.\n", ip); breakpoints.insert(ip); } else if (cmd == "ssaregs") { debug.print_ssa_registers(); } else { fprintf(stderr, "Unknown command, type <help> to get available commands.\n"); } } } <|endoftext|>
<commit_before>/* * Memory pool. * * author: Max Kellermann <mk@cm4all.com> */ #ifndef BENG_PROXY_POOL_HXX #define BENG_PROXY_POOL_HXX #include "trace.h" #include <inline/compiler.h> #include <utility> #include <new> #ifndef NDEBUG #include <assert.h> #endif #include <stddef.h> #include <stdbool.h> struct pool; struct SlicePool; struct AllocatorStats; struct pool_mark_state { /** * The area that was current when the mark was set. */ struct linear_pool_area *area; /** * The area before #area. This is used to dispose areas that were * inserted before the current area due to a large allocation. */ struct linear_pool_area *prev; /** * The position within the current area when the mark was set. */ size_t position; #ifndef NDEBUG /** * Used in an assertion: if the pool was empty before pool_mark(), * it must be empty again after pool_rewind(). */ bool was_empty; #endif }; struct StringView; void pool_recycler_clear(); gcc_malloc struct pool * pool_new_libc(struct pool *parent, const char *name); gcc_malloc struct pool * pool_new_linear(struct pool *parent, const char *name, size_t initial_size); gcc_malloc struct pool * pool_new_slice(struct pool *parent, const char *name, struct SlicePool *slice_pool); #ifdef NDEBUG #define pool_set_major(pool) #define pool_set_persistent(pool) #else void pool_set_major(struct pool *pool); void pool_set_persistent(struct pool *pool); #endif void pool_ref_impl(struct pool *pool TRACE_ARGS_DECL); #define pool_ref(pool) pool_ref_impl(pool TRACE_ARGS) #define pool_ref_fwd(pool) pool_ref_impl(pool TRACE_ARGS_FWD) unsigned pool_unref_impl(struct pool *pool TRACE_ARGS_DECL); #define pool_unref(pool) pool_unref_impl(pool TRACE_ARGS) #define pool_unref_fwd(pool) pool_unref_impl(pool TRACE_ARGS_FWD) class LinearPool { struct pool &p; public: LinearPool(struct pool &parent, const char *name, size_t initial_size) :p(*pool_new_linear(&parent, name, initial_size)) {} ~LinearPool() { gcc_unused auto ref = pool_unref(&p); #ifndef NDEBUG assert(ref == 0); #endif } struct pool &get() { return p; } operator struct pool &() { return p; } operator struct pool *() { return &p; } }; /** * Returns the total size of all allocations in this pool. */ gcc_pure size_t pool_netto_size(const struct pool *pool); /** * Returns the total amount of memory allocated by this pool. */ gcc_pure size_t pool_brutto_size(const struct pool *pool); /** * Returns the total size of this pool and all of its descendants * (recursively). */ gcc_pure size_t pool_recursive_netto_size(const struct pool *pool); gcc_pure size_t pool_recursive_brutto_size(const struct pool *pool); /** * Returns the total size of all descendants of this pool (recursively). */ gcc_pure size_t pool_children_netto_size(const struct pool *pool); gcc_pure size_t pool_children_brutto_size(const struct pool *pool); AllocatorStats pool_children_stats(const struct pool &pool); void pool_dump_tree(const struct pool *pool); #ifndef NDEBUG #include <boost/intrusive/list.hpp> struct pool_notify_state final : public boost::intrusive::list_base_hook<boost::intrusive::link_mode<boost::intrusive::normal_link>> { struct pool *pool; const char *name; bool destroyed, registered; #ifdef TRACE const char *file; int line; const char *destroyed_file; int destroyed_line; #endif }; void pool_notify(struct pool *pool, struct pool_notify_state *notify); bool pool_denotify(struct pool_notify_state *notify); /** * Hands over control from an existing #pool_notify to a new one. The * old one is unregistered. */ void pool_notify_move(struct pool *pool, struct pool_notify_state *src, struct pool_notify_state *dest); class PoolNotify { struct pool_notify_state state; public: explicit PoolNotify(struct pool &pool) { pool_notify(&pool, &state); } PoolNotify(const PoolNotify &) = delete; #ifndef NDEBUG ~PoolNotify() { assert(!state.registered); } #endif bool Denotify() { return pool_denotify(&state); } }; #endif class ScopePoolRef { struct pool &pool; #ifndef NDEBUG PoolNotify notify; #endif #ifdef TRACE const char *const file; unsigned line; #endif public: explicit ScopePoolRef(struct pool &_pool TRACE_ARGS_DECL_) :pool(_pool) #ifndef NDEBUG , notify(_pool) #endif TRACE_ARGS_INIT { pool_ref_fwd(&_pool); } ScopePoolRef(const ScopePoolRef &) = delete; ~ScopePoolRef() { #ifndef NDEBUG notify.Denotify(); #endif pool_unref_fwd(&pool); } operator struct pool &() { return pool; } operator struct pool *() { return &pool; } }; #ifndef NDEBUG void pool_ref_notify_impl(struct pool *pool, struct pool_notify_state *notify TRACE_ARGS_DECL); void pool_unref_denotify_impl(struct pool *pool, struct pool_notify_state *notify TRACE_ARGS_DECL); /** * Do a "checked" pool reference. */ #define pool_ref_notify(pool, notify) \ pool_ref_notify_impl(pool, notify TRACE_ARGS) /** * Do a "checked" pool unreference. If the pool has been destroyed, * an assertion will fail. Double frees are also caught. */ #define pool_unref_denotify(pool, notify) \ pool_unref_denotify_impl(pool, notify TRACE_ARGS) #else #define pool_ref_notify(pool, notify) pool_ref(pool) #define pool_unref_denotify(pool, notify) pool_unref(pool) #endif #ifdef NDEBUG static inline void pool_trash(gcc_unused struct pool *pool) { } static inline void pool_commit() { } static inline void pool_attach(gcc_unused struct pool *pool, gcc_unused const void *p, gcc_unused const char *name) { } static inline void pool_attach_checked(gcc_unused struct pool *pool, gcc_unused const void *p, gcc_unused const char *name) { } static inline void pool_detach(gcc_unused struct pool *pool, gcc_unused const void *p) { } static inline void pool_detach_checked(gcc_unused struct pool *pool, gcc_unused const void *p) { } static inline const char * pool_attachment_name(gcc_unused struct pool *pool, gcc_unused const void *p) { return NULL; } #else void pool_trash(struct pool *pool); void pool_commit(); bool pool_contains(struct pool *pool, const void *ptr, size_t size); /** * Attach an opaque object to the pool. It must be detached before * the pool is destroyed. This is used in debugging mode to track * whether all external objects have been destroyed. */ void pool_attach(struct pool *pool, const void *p, const char *name); /** * Same as pool_attach(), but checks if the object is already * registered. */ void pool_attach_checked(struct pool *pool, const void *p, const char *name); void pool_detach(struct pool *pool, const void *p); void pool_detach_checked(struct pool *pool, const void *p); const char * pool_attachment_name(struct pool *pool, const void *p); #endif void pool_mark(struct pool *pool, struct pool_mark_state *mark); void pool_rewind(struct pool *pool, const struct pool_mark_state *mark); class AutoRewindPool { struct pool &pool; pool_mark_state mark; public: AutoRewindPool(struct pool &_pool):pool(_pool) { pool_mark(&pool, &mark); } AutoRewindPool(const AutoRewindPool &) = delete; ~AutoRewindPool() { pool_rewind(&pool, &mark); } }; gcc_malloc void * p_malloc_impl(struct pool *pool, size_t size TRACE_ARGS_DECL); #define p_malloc(pool, size) p_malloc_impl(pool, size TRACE_ARGS) #define p_malloc_fwd(pool, size) p_malloc_impl(pool, size TRACE_ARGS_FWD) void p_free(struct pool *pool, const void *ptr); gcc_malloc void * p_calloc_impl(struct pool *pool, size_t size TRACE_ARGS_DECL); #define p_calloc(pool, size) p_calloc_impl(pool, size TRACE_ARGS) gcc_malloc void * p_memdup_impl(struct pool *pool, const void *src, size_t length TRACE_ARGS_DECL); #define p_memdup(pool, src, length) p_memdup_impl(pool, src, length TRACE_ARGS) #define p_memdup_fwd(pool, src, length) p_memdup_impl(pool, src, length TRACE_ARGS_FWD) gcc_malloc char * p_strdup_impl(struct pool *pool, const char *src TRACE_ARGS_DECL); #define p_strdup(pool, src) p_strdup_impl(pool, src TRACE_ARGS) #define p_strdup_fwd(pool, src) p_strdup_impl(pool, src TRACE_ARGS_FWD) static inline const char * p_strdup_checked(struct pool *pool, const char *s) { return s == NULL ? NULL : p_strdup(pool, s); } gcc_malloc char * p_strdup_lower_impl(struct pool *pool, const char *src TRACE_ARGS_DECL); #define p_strdup_lower(pool, src) p_strdup_lower_impl(pool, src TRACE_ARGS) #define p_strdup_lower_fwd(pool, src) p_strdup_lower_impl(pool, src TRACE_ARGS_FWD) gcc_malloc char * p_strndup_impl(struct pool *pool, const char *src, size_t length TRACE_ARGS_DECL); #define p_strndup(pool, src, length) p_strndup_impl(pool, src, length TRACE_ARGS) #define p_strndup_fwd(pool, src, length) p_strndup_impl(pool, src, length TRACE_ARGS_FWD) gcc_malloc char * p_strndup_lower_impl(struct pool *pool, const char *src, size_t length TRACE_ARGS_DECL); #define p_strndup_lower(pool, src, length) p_strndup_lower_impl(pool, src, length TRACE_ARGS) #define p_strndup_lower_fwd(pool, src, length) p_strndup_lower_impl(pool, src, length TRACE_ARGS_FWD) gcc_malloc gcc_printf(2, 3) char * p_sprintf(struct pool *pool, const char *fmt, ...); gcc_malloc char * p_strcat(struct pool *pool, const char *s, ...); gcc_malloc char * p_strncat(struct pool *pool, const char *s, size_t length, ...); template<typename T> T * PoolAlloc(pool &p) { return (T *)p_malloc(&p, sizeof(T)); } template<typename T> T * PoolAlloc(pool &p, size_t n) { return (T *)p_malloc(&p, sizeof(T) * n); } template<> inline void * PoolAlloc<void>(pool &p, size_t n) { return p_malloc(&p, n); } template<typename T, typename... Args> T * NewFromPool(pool &p, Args&&... args) { void *t = PoolAlloc<T>(p); return ::new(t) T(std::forward<Args>(args)...); } template<typename T> void DeleteFromPool(struct pool &pool, T *t) { t->~T(); p_free(&pool, t); } /** * A disposer for boost::intrusive that invokes the DeleteFromPool() * on the given pointer. */ class PoolDisposer { struct pool &p; public: explicit PoolDisposer(struct pool &_p):p(_p) {} template<typename T> void operator()(T *t) { DeleteFromPool(p, t); } }; template<typename T> void DeleteUnrefPool(struct pool &pool, T *t) { DeleteFromPool(pool, t); pool_unref(&pool); } template<typename T> void DeleteUnrefTrashPool(struct pool &pool, T *t) { pool_trash(&pool); DeleteUnrefPool(pool, t); } class PoolAllocator { struct pool &pool; public: explicit constexpr PoolAllocator(struct pool &_pool):pool(_pool) {} void *Allocate(size_t size) { return p_malloc(&pool, size); } char *DupString(const char *p) { return p_strdup(&pool, p); } void Free(void *p) { p_free(&pool, p); } template<typename T, typename... Args> T *New(Args&&... args) { return NewFromPool<T>(pool, std::forward<Args>(args)...); } template<typename T> void Delete(T *t) { DeleteFromPool(pool, t); } }; gcc_malloc char * p_strdup_impl(struct pool &pool, StringView src TRACE_ARGS_DECL); gcc_malloc char * p_strdup_lower_impl(struct pool &pool, StringView src TRACE_ARGS_DECL); #endif <commit_msg>pool: add class PoolHolder<commit_after>/* * Memory pool. * * author: Max Kellermann <mk@cm4all.com> */ #ifndef BENG_PROXY_POOL_HXX #define BENG_PROXY_POOL_HXX #include "trace.h" #include <inline/compiler.h> #include <utility> #include <new> #ifndef NDEBUG #include <assert.h> #endif #include <stddef.h> #include <stdbool.h> struct pool; struct SlicePool; struct AllocatorStats; struct pool_mark_state { /** * The area that was current when the mark was set. */ struct linear_pool_area *area; /** * The area before #area. This is used to dispose areas that were * inserted before the current area due to a large allocation. */ struct linear_pool_area *prev; /** * The position within the current area when the mark was set. */ size_t position; #ifndef NDEBUG /** * Used in an assertion: if the pool was empty before pool_mark(), * it must be empty again after pool_rewind(). */ bool was_empty; #endif }; struct StringView; void pool_recycler_clear(); gcc_malloc struct pool * pool_new_libc(struct pool *parent, const char *name); gcc_malloc struct pool * pool_new_linear(struct pool *parent, const char *name, size_t initial_size); gcc_malloc struct pool * pool_new_slice(struct pool *parent, const char *name, struct SlicePool *slice_pool); #ifdef NDEBUG #define pool_set_major(pool) #define pool_set_persistent(pool) #else void pool_set_major(struct pool *pool); void pool_set_persistent(struct pool *pool); #endif void pool_ref_impl(struct pool *pool TRACE_ARGS_DECL); #define pool_ref(pool) pool_ref_impl(pool TRACE_ARGS) #define pool_ref_fwd(pool) pool_ref_impl(pool TRACE_ARGS_FWD) unsigned pool_unref_impl(struct pool *pool TRACE_ARGS_DECL); #define pool_unref(pool) pool_unref_impl(pool TRACE_ARGS) #define pool_unref_fwd(pool) pool_unref_impl(pool TRACE_ARGS_FWD) class LinearPool { struct pool &p; public: LinearPool(struct pool &parent, const char *name, size_t initial_size) :p(*pool_new_linear(&parent, name, initial_size)) {} ~LinearPool() { gcc_unused auto ref = pool_unref(&p); #ifndef NDEBUG assert(ref == 0); #endif } struct pool &get() { return p; } operator struct pool &() { return p; } operator struct pool *() { return &p; } }; /** * Returns the total size of all allocations in this pool. */ gcc_pure size_t pool_netto_size(const struct pool *pool); /** * Returns the total amount of memory allocated by this pool. */ gcc_pure size_t pool_brutto_size(const struct pool *pool); /** * Returns the total size of this pool and all of its descendants * (recursively). */ gcc_pure size_t pool_recursive_netto_size(const struct pool *pool); gcc_pure size_t pool_recursive_brutto_size(const struct pool *pool); /** * Returns the total size of all descendants of this pool (recursively). */ gcc_pure size_t pool_children_netto_size(const struct pool *pool); gcc_pure size_t pool_children_brutto_size(const struct pool *pool); AllocatorStats pool_children_stats(const struct pool &pool); void pool_dump_tree(const struct pool *pool); #ifndef NDEBUG #include <boost/intrusive/list.hpp> struct pool_notify_state final : public boost::intrusive::list_base_hook<boost::intrusive::link_mode<boost::intrusive::normal_link>> { struct pool *pool; const char *name; bool destroyed, registered; #ifdef TRACE const char *file; int line; const char *destroyed_file; int destroyed_line; #endif }; void pool_notify(struct pool *pool, struct pool_notify_state *notify); bool pool_denotify(struct pool_notify_state *notify); /** * Hands over control from an existing #pool_notify to a new one. The * old one is unregistered. */ void pool_notify_move(struct pool *pool, struct pool_notify_state *src, struct pool_notify_state *dest); class PoolNotify { struct pool_notify_state state; public: explicit PoolNotify(struct pool &pool) { pool_notify(&pool, &state); } PoolNotify(const PoolNotify &) = delete; #ifndef NDEBUG ~PoolNotify() { assert(!state.registered); } #endif bool Denotify() { return pool_denotify(&state); } }; #endif class ScopePoolRef { struct pool &pool; #ifndef NDEBUG PoolNotify notify; #endif #ifdef TRACE const char *const file; unsigned line; #endif public: explicit ScopePoolRef(struct pool &_pool TRACE_ARGS_DECL_) :pool(_pool) #ifndef NDEBUG , notify(_pool) #endif TRACE_ARGS_INIT { pool_ref_fwd(&_pool); } ScopePoolRef(const ScopePoolRef &) = delete; ~ScopePoolRef() { #ifndef NDEBUG notify.Denotify(); #endif pool_unref_fwd(&pool); } operator struct pool &() { return pool; } operator struct pool *() { return &pool; } }; /** * Base class for classes which hold a reference to a #pool. */ class PoolHolder { protected: struct pool &pool; explicit PoolHolder(struct pool &_pool) :pool(_pool) { pool_ref(&_pool); } PoolHolder(const PoolHolder &) = delete; PoolHolder &operator=(const PoolHolder &) = delete; ~PoolHolder() { pool_unref(&pool); } struct pool &GetPool() { return pool; } }; #ifndef NDEBUG void pool_ref_notify_impl(struct pool *pool, struct pool_notify_state *notify TRACE_ARGS_DECL); void pool_unref_denotify_impl(struct pool *pool, struct pool_notify_state *notify TRACE_ARGS_DECL); /** * Do a "checked" pool reference. */ #define pool_ref_notify(pool, notify) \ pool_ref_notify_impl(pool, notify TRACE_ARGS) /** * Do a "checked" pool unreference. If the pool has been destroyed, * an assertion will fail. Double frees are also caught. */ #define pool_unref_denotify(pool, notify) \ pool_unref_denotify_impl(pool, notify TRACE_ARGS) #else #define pool_ref_notify(pool, notify) pool_ref(pool) #define pool_unref_denotify(pool, notify) pool_unref(pool) #endif #ifdef NDEBUG static inline void pool_trash(gcc_unused struct pool *pool) { } static inline void pool_commit() { } static inline void pool_attach(gcc_unused struct pool *pool, gcc_unused const void *p, gcc_unused const char *name) { } static inline void pool_attach_checked(gcc_unused struct pool *pool, gcc_unused const void *p, gcc_unused const char *name) { } static inline void pool_detach(gcc_unused struct pool *pool, gcc_unused const void *p) { } static inline void pool_detach_checked(gcc_unused struct pool *pool, gcc_unused const void *p) { } static inline const char * pool_attachment_name(gcc_unused struct pool *pool, gcc_unused const void *p) { return NULL; } #else void pool_trash(struct pool *pool); void pool_commit(); bool pool_contains(struct pool *pool, const void *ptr, size_t size); /** * Attach an opaque object to the pool. It must be detached before * the pool is destroyed. This is used in debugging mode to track * whether all external objects have been destroyed. */ void pool_attach(struct pool *pool, const void *p, const char *name); /** * Same as pool_attach(), but checks if the object is already * registered. */ void pool_attach_checked(struct pool *pool, const void *p, const char *name); void pool_detach(struct pool *pool, const void *p); void pool_detach_checked(struct pool *pool, const void *p); const char * pool_attachment_name(struct pool *pool, const void *p); #endif void pool_mark(struct pool *pool, struct pool_mark_state *mark); void pool_rewind(struct pool *pool, const struct pool_mark_state *mark); class AutoRewindPool { struct pool &pool; pool_mark_state mark; public: AutoRewindPool(struct pool &_pool):pool(_pool) { pool_mark(&pool, &mark); } AutoRewindPool(const AutoRewindPool &) = delete; ~AutoRewindPool() { pool_rewind(&pool, &mark); } }; gcc_malloc void * p_malloc_impl(struct pool *pool, size_t size TRACE_ARGS_DECL); #define p_malloc(pool, size) p_malloc_impl(pool, size TRACE_ARGS) #define p_malloc_fwd(pool, size) p_malloc_impl(pool, size TRACE_ARGS_FWD) void p_free(struct pool *pool, const void *ptr); gcc_malloc void * p_calloc_impl(struct pool *pool, size_t size TRACE_ARGS_DECL); #define p_calloc(pool, size) p_calloc_impl(pool, size TRACE_ARGS) gcc_malloc void * p_memdup_impl(struct pool *pool, const void *src, size_t length TRACE_ARGS_DECL); #define p_memdup(pool, src, length) p_memdup_impl(pool, src, length TRACE_ARGS) #define p_memdup_fwd(pool, src, length) p_memdup_impl(pool, src, length TRACE_ARGS_FWD) gcc_malloc char * p_strdup_impl(struct pool *pool, const char *src TRACE_ARGS_DECL); #define p_strdup(pool, src) p_strdup_impl(pool, src TRACE_ARGS) #define p_strdup_fwd(pool, src) p_strdup_impl(pool, src TRACE_ARGS_FWD) static inline const char * p_strdup_checked(struct pool *pool, const char *s) { return s == NULL ? NULL : p_strdup(pool, s); } gcc_malloc char * p_strdup_lower_impl(struct pool *pool, const char *src TRACE_ARGS_DECL); #define p_strdup_lower(pool, src) p_strdup_lower_impl(pool, src TRACE_ARGS) #define p_strdup_lower_fwd(pool, src) p_strdup_lower_impl(pool, src TRACE_ARGS_FWD) gcc_malloc char * p_strndup_impl(struct pool *pool, const char *src, size_t length TRACE_ARGS_DECL); #define p_strndup(pool, src, length) p_strndup_impl(pool, src, length TRACE_ARGS) #define p_strndup_fwd(pool, src, length) p_strndup_impl(pool, src, length TRACE_ARGS_FWD) gcc_malloc char * p_strndup_lower_impl(struct pool *pool, const char *src, size_t length TRACE_ARGS_DECL); #define p_strndup_lower(pool, src, length) p_strndup_lower_impl(pool, src, length TRACE_ARGS) #define p_strndup_lower_fwd(pool, src, length) p_strndup_lower_impl(pool, src, length TRACE_ARGS_FWD) gcc_malloc gcc_printf(2, 3) char * p_sprintf(struct pool *pool, const char *fmt, ...); gcc_malloc char * p_strcat(struct pool *pool, const char *s, ...); gcc_malloc char * p_strncat(struct pool *pool, const char *s, size_t length, ...); template<typename T> T * PoolAlloc(pool &p) { return (T *)p_malloc(&p, sizeof(T)); } template<typename T> T * PoolAlloc(pool &p, size_t n) { return (T *)p_malloc(&p, sizeof(T) * n); } template<> inline void * PoolAlloc<void>(pool &p, size_t n) { return p_malloc(&p, n); } template<typename T, typename... Args> T * NewFromPool(pool &p, Args&&... args) { void *t = PoolAlloc<T>(p); return ::new(t) T(std::forward<Args>(args)...); } template<typename T> void DeleteFromPool(struct pool &pool, T *t) { t->~T(); p_free(&pool, t); } /** * A disposer for boost::intrusive that invokes the DeleteFromPool() * on the given pointer. */ class PoolDisposer { struct pool &p; public: explicit PoolDisposer(struct pool &_p):p(_p) {} template<typename T> void operator()(T *t) { DeleteFromPool(p, t); } }; template<typename T> void DeleteUnrefPool(struct pool &pool, T *t) { DeleteFromPool(pool, t); pool_unref(&pool); } template<typename T> void DeleteUnrefTrashPool(struct pool &pool, T *t) { pool_trash(&pool); DeleteUnrefPool(pool, t); } class PoolAllocator { struct pool &pool; public: explicit constexpr PoolAllocator(struct pool &_pool):pool(_pool) {} void *Allocate(size_t size) { return p_malloc(&pool, size); } char *DupString(const char *p) { return p_strdup(&pool, p); } void Free(void *p) { p_free(&pool, p); } template<typename T, typename... Args> T *New(Args&&... args) { return NewFromPool<T>(pool, std::forward<Args>(args)...); } template<typename T> void Delete(T *t) { DeleteFromPool(pool, t); } }; gcc_malloc char * p_strdup_impl(struct pool &pool, StringView src TRACE_ARGS_DECL); gcc_malloc char * p_strdup_lower_impl(struct pool &pool, StringView src TRACE_ARGS_DECL); #endif <|endoftext|>
<commit_before>#include <Windows.h> #include "dbg_thunk.h" namespace vscode { void* thunk_create_hook(intptr_t dbg, intptr_t hook) { // int __cedel thunk_hook(lua_State* L, lua_Debug* ar) // { // `hook`(`dbg`, L, ar); // return `undefinition`; // } static unsigned char sc[] = { #if defined(_M_X64) 0x57, // push rdi 0x50, // push rax 0x48, 0x83, 0xec, 0x28, // sub rsp, 40 0x4c, 0x8b, 0xc2, // mov r8, rdx 0x48, 0x8b, 0xd1, // mov rdx, rcx 0x48, 0xb9, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // mov rcx, dbg 0x48, 0xb8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // mov rax, hook 0xff, 0xd0, // call rax 0x48, 0x83, 0xc4, 0x28, // add rsp, 40 0x58, // pop rax 0x5f, // pop rdi 0xc3, // ret #else 0xff, 0x74, 0x24, 0x08, // push [esp+8] 0xff, 0x74, 0x24, 0x08, // push [esp+8] 0x68, 0x00, 0x00, 0x00, 0x00, // push dbg 0xe8, 0x00, 0x00, 0x00, 0x00, // call hook 0x83, 0xc4, 0x0c, // add esp, 12 0xc3, // ret #endif }; LPVOID shellcode = VirtualAllocEx(GetCurrentProcess(), NULL, sizeof(sc), MEM_COMMIT, PAGE_EXECUTE_READWRITE); if (!shellcode) { return 0; } #if defined(_M_X64) memcpy(sc + 14, &dbg, sizeof(dbg)); memcpy(sc + 24, &hook, sizeof(hook)); #else memcpy(sc + 9, &dbg, sizeof(dbg)); hook = hook - ((intptr_t)shellcode + 18); memcpy(sc + 14, &hook, sizeof(hook)); #endif SIZE_T written = 0; BOOL ok = WriteProcessMemory(GetCurrentProcess(), shellcode, &sc, sizeof(sc), &written); if (!ok || written != sizeof(sc)) { thunk_destory(shellcode); return 0; } return shellcode; } void* thunk_create_panic(intptr_t dbg, intptr_t panic, intptr_t old_panic) { // int __cedel thunk_panic(lua_State* L) // { // `panic`(`dbg`, L); // `old_panic`(L); // return `undefinition`; // } static unsigned char sc[] = { #if defined(_M_X64) 0x57, // push rdi 0x50, // push rax 0x51, // push rcx 0x48, 0x83, 0xec, 0x28, // sub rsp, 40 0x48, 0x8b, 0xd1, // mov rdx, rcx 0x48, 0xb9, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // mov rcx, dbg 0x48, 0xb8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // mov rax, panic 0xff, 0xd0, // call rax 0x48, 0x83, 0xc4, 0x28, // add rsp, 40 0x59, // pop rcx 0x48, 0x83, 0xec, 0x28, // sub rsp, 40 0x48, 0xb8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // mov rax, old_panic 0xff, 0xd0, // call rax 0x48, 0x83, 0xc4, 0x28, // add rsp, 40 0x58, // pop rax 0x5f, // pop rdi 0xc3, // ret #else 0xff, 0x74, 0x24, 0x04, // push [esp+4] 0x68, 0x00, 0x00, 0x00, 0x00, // push dbg 0xe8, 0x00, 0x00, 0x00, 0x00, // call panic 0x83, 0xc4, 0x08, // add esp, 8 0xff, 0x74, 0x24, 0x04, // push [esp+4] 0xe8, 0x00, 0x00, 0x00, 0x00, // call old_panic 0x83, 0xc4, 0x04, // add esp, 4 0xc3, // ret #endif }; LPVOID shellcode = VirtualAllocEx(GetCurrentProcess(), NULL, sizeof(sc), MEM_COMMIT, PAGE_EXECUTE_READWRITE); if (!shellcode) { return 0; } #if defined(_M_X64) memcpy(sc + 12, &dbg, sizeof(dbg)); memcpy(sc + 22, &panic, sizeof(panic)); memcpy(sc + 43, &old_panic, sizeof(old_panic)); #else memcpy(sc + 5, &dbg, sizeof(dbg)); panic = panic - ((intptr_t)shellcode + 14); memcpy(sc + 10, &panic, sizeof(panic)); old_panic = old_panic - ((intptr_t)shellcode + 26); memcpy(sc + 22, &old_panic, sizeof(old_panic)); #endif SIZE_T written = 0; BOOL ok = WriteProcessMemory(GetCurrentProcess(), shellcode, &sc, sizeof(sc), &written); if (!ok || written != sizeof(sc)) { thunk_destory(shellcode); return 0; } return shellcode; } void thunk_destory(void* shellcode) { if (shellcode) { VirtualFreeEx(GetCurrentProcess(), shellcode, 0, MEM_RELEASE); } } } <commit_msg>old_panic有可能不存在<commit_after>#include <Windows.h> #include "dbg_thunk.h" namespace vscode { void* thunk_create_hook(intptr_t dbg, intptr_t hook) { // int __cedel thunk_hook(lua_State* L, lua_Debug* ar) // { // `hook`(`dbg`, L, ar); // return `undefinition`; // } static unsigned char sc[] = { #if defined(_M_X64) 0x57, // push rdi 0x50, // push rax 0x48, 0x83, 0xec, 0x28, // sub rsp, 40 0x4c, 0x8b, 0xc2, // mov r8, rdx 0x48, 0x8b, 0xd1, // mov rdx, rcx 0x48, 0xb9, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // mov rcx, dbg 0x48, 0xb8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // mov rax, hook 0xff, 0xd0, // call rax 0x48, 0x83, 0xc4, 0x28, // add rsp, 40 0x58, // pop rax 0x5f, // pop rdi 0xc3, // ret #else 0xff, 0x74, 0x24, 0x08, // push [esp+8] 0xff, 0x74, 0x24, 0x08, // push [esp+8] 0x68, 0x00, 0x00, 0x00, 0x00, // push dbg 0xe8, 0x00, 0x00, 0x00, 0x00, // call hook 0x83, 0xc4, 0x0c, // add esp, 12 0xc3, // ret #endif }; LPVOID shellcode = VirtualAllocEx(GetCurrentProcess(), NULL, sizeof(sc), MEM_COMMIT, PAGE_EXECUTE_READWRITE); if (!shellcode) { return 0; } #if defined(_M_X64) memcpy(sc + 14, &dbg, sizeof(dbg)); memcpy(sc + 24, &hook, sizeof(hook)); #else memcpy(sc + 9, &dbg, sizeof(dbg)); hook = hook - ((intptr_t)shellcode + 18); memcpy(sc + 14, &hook, sizeof(hook)); #endif SIZE_T written = 0; BOOL ok = WriteProcessMemory(GetCurrentProcess(), shellcode, &sc, sizeof(sc), &written); if (!ok || written != sizeof(sc)) { thunk_destory(shellcode); return 0; } return shellcode; } void* thunk_create_panic(intptr_t dbg, intptr_t panic) { // int __cedel thunk_panic(lua_State* L) // { // `panic`(`dbg`, L); // return `undefinition`; // } static unsigned char sc[] = { #if defined(_M_X64) 0x57, // push rdi 0x50, // push rax 0x48, 0x83, 0xec, 0x28, // sub rsp, 40 0x48, 0x8b, 0xd1, // mov rdx, rcx 0x48, 0xb9, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // mov rcx, dbg 0x48, 0xb8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // mov rax, panic 0xff, 0xd0, // call rax 0x48, 0x83, 0xc4, 0x28, // add rsp, 40 0x58, // pop rax 0x5f, // pop rdi 0xc3, // ret #else 0xff, 0x74, 0x24, 0x04, // push [esp+4] 0x68, 0x00, 0x00, 0x00, 0x00, // push dbg 0xe8, 0x00, 0x00, 0x00, 0x00, // call panic 0x83, 0xc4, 0x08, // add esp, 8 0xc3, // ret #endif }; LPVOID shellcode = VirtualAllocEx(GetCurrentProcess(), NULL, sizeof(sc), MEM_COMMIT, PAGE_EXECUTE_READWRITE); if (!shellcode) { return 0; } #if defined(_M_X64) memcpy(sc + 11, &dbg, sizeof(dbg)); memcpy(sc + 21, &panic, sizeof(panic)); #else memcpy(sc + 5, &dbg, sizeof(dbg)); panic = panic - ((intptr_t)shellcode + 14); memcpy(sc + 10, &panic, sizeof(panic)); #endif SIZE_T written = 0; BOOL ok = WriteProcessMemory(GetCurrentProcess(), shellcode, &sc, sizeof(sc), &written); if (!ok || written != sizeof(sc)) { thunk_destory(shellcode); return 0; } return shellcode; } void* thunk_create_panic(intptr_t dbg, intptr_t panic, intptr_t old_panic) { if (!old_panic) { return thunk_create_panic(dbg, panic); } // int __cedel thunk_panic(lua_State* L) // { // `panic`(`dbg`, L); // `old_panic`(L); // return `undefinition`; // } static unsigned char sc[] = { #if defined(_M_X64) 0x57, // push rdi 0x50, // push rax 0x51, // push rcx 0x48, 0x83, 0xec, 0x28, // sub rsp, 40 0x48, 0x8b, 0xd1, // mov rdx, rcx 0x48, 0xb9, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // mov rcx, dbg 0x48, 0xb8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // mov rax, panic 0xff, 0xd0, // call rax 0x48, 0x83, 0xc4, 0x28, // add rsp, 40 0x59, // pop rcx 0x48, 0x83, 0xec, 0x28, // sub rsp, 40 0x48, 0xb8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // mov rax, old_panic 0xff, 0xd0, // call rax 0x48, 0x83, 0xc4, 0x28, // add rsp, 40 0x58, // pop rax 0x5f, // pop rdi 0xc3, // ret #else 0xff, 0x74, 0x24, 0x04, // push [esp+4] 0x68, 0x00, 0x00, 0x00, 0x00, // push dbg 0xe8, 0x00, 0x00, 0x00, 0x00, // call panic 0x83, 0xc4, 0x08, // add esp, 8 0xff, 0x74, 0x24, 0x04, // push [esp+4] 0xe8, 0x00, 0x00, 0x00, 0x00, // call old_panic 0x83, 0xc4, 0x04, // add esp, 4 0xc3, // ret #endif }; LPVOID shellcode = VirtualAllocEx(GetCurrentProcess(), NULL, sizeof(sc), MEM_COMMIT, PAGE_EXECUTE_READWRITE); if (!shellcode) { return 0; } #if defined(_M_X64) memcpy(sc + 12, &dbg, sizeof(dbg)); memcpy(sc + 22, &panic, sizeof(panic)); memcpy(sc + 43, &old_panic, sizeof(old_panic)); #else memcpy(sc + 5, &dbg, sizeof(dbg)); panic = panic - ((intptr_t)shellcode + 14); memcpy(sc + 10, &panic, sizeof(panic)); old_panic = old_panic - ((intptr_t)shellcode + 26); memcpy(sc + 22, &old_panic, sizeof(old_panic)); #endif SIZE_T written = 0; BOOL ok = WriteProcessMemory(GetCurrentProcess(), shellcode, &sc, sizeof(sc), &written); if (!ok || written != sizeof(sc)) { thunk_destory(shellcode); return 0; } return shellcode; } void thunk_destory(void* shellcode) { if (shellcode) { VirtualFreeEx(GetCurrentProcess(), shellcode, 0, MEM_RELEASE); } } } <|endoftext|>
<commit_before>/* * Copyright (c) 2004-2005 The Regents of The University of Michigan * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders 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. * * Authors: Ali Saidi * Andrew Schultz * Miguel Serrano */ /* @file * A single PCI device configuration space entry. */ #include <list> #include <string> #include <vector> #include "base/inifile.hh" #include "base/intmath.hh" // for isPowerOf2( #include "base/misc.hh" #include "base/str.hh" // for to_number #include "base/trace.hh" #include "dev/pciconfigall.hh" #include "dev/pcidev.hh" #include "dev/alpha/tsunamireg.h" #include "mem/packet.hh" #include "mem/packet_access.hh" #include "sim/byteswap.hh" #include "sim/core.hh" using namespace std; PciDev::PciConfigPort::PciConfigPort(PciDev *dev, int busid, int devid, int funcid, Platform *p) : SimpleTimingPort(dev->name() + "-pciconf", dev), device(dev), platform(p), busId(busid), deviceId(devid), functionId(funcid) { configAddr = platform->calcConfigAddr(busId, deviceId, functionId); } Tick PciDev::PciConfigPort::recvAtomic(PacketPtr pkt) { assert(pkt->getAddr() >= configAddr && pkt->getAddr() < configAddr + PCI_CONFIG_SIZE); return pkt->isRead() ? device->readConfig(pkt) : device->writeConfig(pkt); } void PciDev::PciConfigPort::getDeviceAddressRanges(AddrRangeList &resp, bool &snoop) { snoop = false;; resp.push_back(RangeSize(configAddr, PCI_CONFIG_SIZE+1)); } PciDev::PciDev(const Params *p) : DmaDevice(p), plat(p->platform), pioDelay(p->pio_latency), configDelay(p->config_latency), configPort(NULL) { config.vendor = htole(p->VendorID); config.device = htole(p->DeviceID); config.command = htole(p->Command); config.status = htole(p->Status); config.revision = htole(p->Revision); config.progIF = htole(p->ProgIF); config.subClassCode = htole(p->SubClassCode); config.classCode = htole(p->ClassCode); config.cacheLineSize = htole(p->CacheLineSize); config.latencyTimer = htole(p->LatencyTimer); config.headerType = htole(p->HeaderType); config.bist = htole(p->BIST); config.baseAddr[0] = htole(p->BAR0); config.baseAddr[1] = htole(p->BAR1); config.baseAddr[2] = htole(p->BAR2); config.baseAddr[3] = htole(p->BAR3); config.baseAddr[4] = htole(p->BAR4); config.baseAddr[5] = htole(p->BAR5); config.cardbusCIS = htole(p->CardbusCIS); config.subsystemVendorID = htole(p->SubsystemVendorID); config.subsystemID = htole(p->SubsystemID); config.expansionROM = htole(p->ExpansionROM); config.reserved0 = 0; config.reserved1 = 0; config.interruptLine = htole(p->InterruptLine); config.interruptPin = htole(p->InterruptPin); config.minimumGrant = htole(p->MinimumGrant); config.maximumLatency = htole(p->MaximumLatency); BARSize[0] = p->BAR0Size; BARSize[1] = p->BAR1Size; BARSize[2] = p->BAR2Size; BARSize[3] = p->BAR3Size; BARSize[4] = p->BAR4Size; BARSize[5] = p->BAR5Size; for (int i = 0; i < 6; ++i) { uint32_t barsize = BARSize[i]; if (barsize != 0 && !isPowerOf2(barsize)) { fatal("BAR %d size %d is not a power of 2\n", i, BARSize[i]); } } memset(BARAddrs, 0, sizeof(BARAddrs)); plat->registerPciDevice(0, p->pci_dev, p->pci_func, letoh(config.interruptLine)); } void PciDev::init() { if (!configPort) panic("pci config port not connected to anything!"); configPort->sendStatusChange(Port::RangeChange); PioDevice::init(); } unsigned int PciDev::drain(Event *de) { unsigned int count; count = pioPort->drain(de) + dmaPort->drain(de) + configPort->drain(de); if (count) changeState(Draining); else changeState(Drained); return count; } Tick PciDev::readConfig(PacketPtr pkt) { int offset = pkt->getAddr() & PCI_CONFIG_SIZE; if (offset >= PCI_DEVICE_SPECIFIC) panic("Device specific PCI config space not implemented!\n"); pkt->allocate(); switch (pkt->getSize()) { case sizeof(uint8_t): pkt->set<uint8_t>(config.data[offset]); DPRINTF(PCIDEV, "readConfig: dev %#x func %#x reg %#x 1 bytes: data = %#x\n", params()->pci_dev, params()->pci_func, offset, (uint32_t)pkt->get<uint8_t>()); break; case sizeof(uint16_t): pkt->set<uint16_t>(*(uint16_t*)&config.data[offset]); DPRINTF(PCIDEV, "readConfig: dev %#x func %#x reg %#x 2 bytes: data = %#x\n", params()->pci_dev, params()->pci_func, offset, (uint32_t)pkt->get<uint16_t>()); break; case sizeof(uint32_t): pkt->set<uint32_t>(*(uint32_t*)&config.data[offset]); DPRINTF(PCIDEV, "readConfig: dev %#x func %#x reg %#x 4 bytes: data = %#x\n", params()->pci_dev, params()->pci_func, offset, (uint32_t)pkt->get<uint32_t>()); break; default: panic("invalid access size(?) for PCI configspace!\n"); } pkt->makeAtomicResponse(); return configDelay; } void PciDev::addressRanges(AddrRangeList &range_list) { int x = 0; range_list.clear(); for (x = 0; x < 6; x++) if (BARAddrs[x] != 0) range_list.push_back(RangeSize(BARAddrs[x],BARSize[x])); } Tick PciDev::writeConfig(PacketPtr pkt) { int offset = pkt->getAddr() & PCI_CONFIG_SIZE; if (offset >= PCI_DEVICE_SPECIFIC) panic("Device specific PCI config space not implemented!\n"); switch (pkt->getSize()) { case sizeof(uint8_t): switch (offset) { case PCI0_INTERRUPT_LINE: config.interruptLine = pkt->get<uint8_t>(); case PCI_CACHE_LINE_SIZE: config.cacheLineSize = pkt->get<uint8_t>(); case PCI_LATENCY_TIMER: config.latencyTimer = pkt->get<uint8_t>(); break; /* Do nothing for these read-only registers */ case PCI0_INTERRUPT_PIN: case PCI0_MINIMUM_GRANT: case PCI0_MAXIMUM_LATENCY: case PCI_CLASS_CODE: case PCI_REVISION_ID: break; default: panic("writing to a read only register"); } DPRINTF(PCIDEV, "writeConfig: dev %#x func %#x reg %#x 1 bytes: data = %#x\n", params()->pci_dev, params()->pci_func, offset, (uint32_t)pkt->get<uint8_t>()); break; case sizeof(uint16_t): switch (offset) { case PCI_COMMAND: config.command = pkt->get<uint8_t>(); case PCI_STATUS: config.status = pkt->get<uint8_t>(); case PCI_CACHE_LINE_SIZE: config.cacheLineSize = pkt->get<uint8_t>(); break; default: panic("writing to a read only register"); } DPRINTF(PCIDEV, "writeConfig: dev %#x func %#x reg %#x 2 bytes: data = %#x\n", params()->pci_dev, params()->pci_func, offset, (uint32_t)pkt->get<uint16_t>()); break; case sizeof(uint32_t): switch (offset) { case PCI0_BASE_ADDR0: case PCI0_BASE_ADDR1: case PCI0_BASE_ADDR2: case PCI0_BASE_ADDR3: case PCI0_BASE_ADDR4: case PCI0_BASE_ADDR5: { int barnum = BAR_NUMBER(offset); // convert BAR values to host endianness uint32_t he_old_bar = letoh(config.baseAddr[barnum]); uint32_t he_new_bar = letoh(pkt->get<uint32_t>()); uint32_t bar_mask = BAR_IO_SPACE(he_old_bar) ? BAR_IO_MASK : BAR_MEM_MASK; // Writing 0xffffffff to a BAR tells the card to set the // value of the bar to a bitmask indicating the size of // memory it needs if (he_new_bar == 0xffffffff) { he_new_bar = ~(BARSize[barnum] - 1); } else { // does it mean something special to write 0 to a BAR? he_new_bar &= ~bar_mask; if (he_new_bar) { Addr space_base = BAR_IO_SPACE(he_old_bar) ? TSUNAMI_PCI0_IO : TSUNAMI_PCI0_MEMORY; BARAddrs[barnum] = he_new_bar + space_base; pioPort->sendStatusChange(Port::RangeChange); } } config.baseAddr[barnum] = htole((he_new_bar & ~bar_mask) | (he_old_bar & bar_mask)); } break; case PCI0_ROM_BASE_ADDR: if (letoh(pkt->get<uint32_t>()) == 0xfffffffe) config.expansionROM = htole((uint32_t)0xffffffff); else config.expansionROM = pkt->get<uint32_t>(); break; case PCI_COMMAND: // This could also clear some of the error bits in the Status // register. However they should never get set, so lets ignore // it for now config.command = pkt->get<uint32_t>(); break; default: DPRINTF(PCIDEV, "Writing to a read only register"); } DPRINTF(PCIDEV, "writeConfig: dev %#x func %#x reg %#x 4 bytes: data = %#x\n", params()->pci_dev, params()->pci_func, offset, (uint32_t)pkt->get<uint32_t>()); break; default: panic("invalid access size(?) for PCI configspace!\n"); } pkt->makeAtomicResponse(); return configDelay; } void PciDev::serialize(ostream &os) { SERIALIZE_ARRAY(BARSize, sizeof(BARSize) / sizeof(BARSize[0])); SERIALIZE_ARRAY(BARAddrs, sizeof(BARAddrs) / sizeof(BARAddrs[0])); SERIALIZE_ARRAY(config.data, sizeof(config.data) / sizeof(config.data[0])); } void PciDev::unserialize(Checkpoint *cp, const std::string &section) { UNSERIALIZE_ARRAY(BARSize, sizeof(BARSize) / sizeof(BARSize[0])); UNSERIALIZE_ARRAY(BARAddrs, sizeof(BARAddrs) / sizeof(BARAddrs[0])); UNSERIALIZE_ARRAY(config.data, sizeof(config.data) / sizeof(config.data[0])); pioPort->sendStatusChange(Port::RangeChange); } <commit_msg>PCI: Add some missing breaks to a couple case statements.<commit_after>/* * Copyright (c) 2004-2005 The Regents of The University of Michigan * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders 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. * * Authors: Ali Saidi * Andrew Schultz * Miguel Serrano */ /* @file * A single PCI device configuration space entry. */ #include <list> #include <string> #include <vector> #include "base/inifile.hh" #include "base/intmath.hh" // for isPowerOf2( #include "base/misc.hh" #include "base/str.hh" // for to_number #include "base/trace.hh" #include "dev/pciconfigall.hh" #include "dev/pcidev.hh" #include "dev/alpha/tsunamireg.h" #include "mem/packet.hh" #include "mem/packet_access.hh" #include "sim/byteswap.hh" #include "sim/core.hh" using namespace std; PciDev::PciConfigPort::PciConfigPort(PciDev *dev, int busid, int devid, int funcid, Platform *p) : SimpleTimingPort(dev->name() + "-pciconf", dev), device(dev), platform(p), busId(busid), deviceId(devid), functionId(funcid) { configAddr = platform->calcConfigAddr(busId, deviceId, functionId); } Tick PciDev::PciConfigPort::recvAtomic(PacketPtr pkt) { assert(pkt->getAddr() >= configAddr && pkt->getAddr() < configAddr + PCI_CONFIG_SIZE); return pkt->isRead() ? device->readConfig(pkt) : device->writeConfig(pkt); } void PciDev::PciConfigPort::getDeviceAddressRanges(AddrRangeList &resp, bool &snoop) { snoop = false;; resp.push_back(RangeSize(configAddr, PCI_CONFIG_SIZE+1)); } PciDev::PciDev(const Params *p) : DmaDevice(p), plat(p->platform), pioDelay(p->pio_latency), configDelay(p->config_latency), configPort(NULL) { config.vendor = htole(p->VendorID); config.device = htole(p->DeviceID); config.command = htole(p->Command); config.status = htole(p->Status); config.revision = htole(p->Revision); config.progIF = htole(p->ProgIF); config.subClassCode = htole(p->SubClassCode); config.classCode = htole(p->ClassCode); config.cacheLineSize = htole(p->CacheLineSize); config.latencyTimer = htole(p->LatencyTimer); config.headerType = htole(p->HeaderType); config.bist = htole(p->BIST); config.baseAddr[0] = htole(p->BAR0); config.baseAddr[1] = htole(p->BAR1); config.baseAddr[2] = htole(p->BAR2); config.baseAddr[3] = htole(p->BAR3); config.baseAddr[4] = htole(p->BAR4); config.baseAddr[5] = htole(p->BAR5); config.cardbusCIS = htole(p->CardbusCIS); config.subsystemVendorID = htole(p->SubsystemVendorID); config.subsystemID = htole(p->SubsystemID); config.expansionROM = htole(p->ExpansionROM); config.reserved0 = 0; config.reserved1 = 0; config.interruptLine = htole(p->InterruptLine); config.interruptPin = htole(p->InterruptPin); config.minimumGrant = htole(p->MinimumGrant); config.maximumLatency = htole(p->MaximumLatency); BARSize[0] = p->BAR0Size; BARSize[1] = p->BAR1Size; BARSize[2] = p->BAR2Size; BARSize[3] = p->BAR3Size; BARSize[4] = p->BAR4Size; BARSize[5] = p->BAR5Size; for (int i = 0; i < 6; ++i) { uint32_t barsize = BARSize[i]; if (barsize != 0 && !isPowerOf2(barsize)) { fatal("BAR %d size %d is not a power of 2\n", i, BARSize[i]); } } memset(BARAddrs, 0, sizeof(BARAddrs)); plat->registerPciDevice(0, p->pci_dev, p->pci_func, letoh(config.interruptLine)); } void PciDev::init() { if (!configPort) panic("pci config port not connected to anything!"); configPort->sendStatusChange(Port::RangeChange); PioDevice::init(); } unsigned int PciDev::drain(Event *de) { unsigned int count; count = pioPort->drain(de) + dmaPort->drain(de) + configPort->drain(de); if (count) changeState(Draining); else changeState(Drained); return count; } Tick PciDev::readConfig(PacketPtr pkt) { int offset = pkt->getAddr() & PCI_CONFIG_SIZE; if (offset >= PCI_DEVICE_SPECIFIC) panic("Device specific PCI config space not implemented!\n"); pkt->allocate(); switch (pkt->getSize()) { case sizeof(uint8_t): pkt->set<uint8_t>(config.data[offset]); DPRINTF(PCIDEV, "readConfig: dev %#x func %#x reg %#x 1 bytes: data = %#x\n", params()->pci_dev, params()->pci_func, offset, (uint32_t)pkt->get<uint8_t>()); break; case sizeof(uint16_t): pkt->set<uint16_t>(*(uint16_t*)&config.data[offset]); DPRINTF(PCIDEV, "readConfig: dev %#x func %#x reg %#x 2 bytes: data = %#x\n", params()->pci_dev, params()->pci_func, offset, (uint32_t)pkt->get<uint16_t>()); break; case sizeof(uint32_t): pkt->set<uint32_t>(*(uint32_t*)&config.data[offset]); DPRINTF(PCIDEV, "readConfig: dev %#x func %#x reg %#x 4 bytes: data = %#x\n", params()->pci_dev, params()->pci_func, offset, (uint32_t)pkt->get<uint32_t>()); break; default: panic("invalid access size(?) for PCI configspace!\n"); } pkt->makeAtomicResponse(); return configDelay; } void PciDev::addressRanges(AddrRangeList &range_list) { int x = 0; range_list.clear(); for (x = 0; x < 6; x++) if (BARAddrs[x] != 0) range_list.push_back(RangeSize(BARAddrs[x],BARSize[x])); } Tick PciDev::writeConfig(PacketPtr pkt) { int offset = pkt->getAddr() & PCI_CONFIG_SIZE; if (offset >= PCI_DEVICE_SPECIFIC) panic("Device specific PCI config space not implemented!\n"); switch (pkt->getSize()) { case sizeof(uint8_t): switch (offset) { case PCI0_INTERRUPT_LINE: config.interruptLine = pkt->get<uint8_t>(); break; case PCI_CACHE_LINE_SIZE: config.cacheLineSize = pkt->get<uint8_t>(); break; case PCI_LATENCY_TIMER: config.latencyTimer = pkt->get<uint8_t>(); break; /* Do nothing for these read-only registers */ case PCI0_INTERRUPT_PIN: case PCI0_MINIMUM_GRANT: case PCI0_MAXIMUM_LATENCY: case PCI_CLASS_CODE: case PCI_REVISION_ID: break; default: panic("writing to a read only register"); } DPRINTF(PCIDEV, "writeConfig: dev %#x func %#x reg %#x 1 bytes: data = %#x\n", params()->pci_dev, params()->pci_func, offset, (uint32_t)pkt->get<uint8_t>()); break; case sizeof(uint16_t): switch (offset) { case PCI_COMMAND: config.command = pkt->get<uint8_t>(); break; case PCI_STATUS: config.status = pkt->get<uint8_t>(); break; case PCI_CACHE_LINE_SIZE: config.cacheLineSize = pkt->get<uint8_t>(); break; default: panic("writing to a read only register"); } DPRINTF(PCIDEV, "writeConfig: dev %#x func %#x reg %#x 2 bytes: data = %#x\n", params()->pci_dev, params()->pci_func, offset, (uint32_t)pkt->get<uint16_t>()); break; case sizeof(uint32_t): switch (offset) { case PCI0_BASE_ADDR0: case PCI0_BASE_ADDR1: case PCI0_BASE_ADDR2: case PCI0_BASE_ADDR3: case PCI0_BASE_ADDR4: case PCI0_BASE_ADDR5: { int barnum = BAR_NUMBER(offset); // convert BAR values to host endianness uint32_t he_old_bar = letoh(config.baseAddr[barnum]); uint32_t he_new_bar = letoh(pkt->get<uint32_t>()); uint32_t bar_mask = BAR_IO_SPACE(he_old_bar) ? BAR_IO_MASK : BAR_MEM_MASK; // Writing 0xffffffff to a BAR tells the card to set the // value of the bar to a bitmask indicating the size of // memory it needs if (he_new_bar == 0xffffffff) { he_new_bar = ~(BARSize[barnum] - 1); } else { // does it mean something special to write 0 to a BAR? he_new_bar &= ~bar_mask; if (he_new_bar) { Addr space_base = BAR_IO_SPACE(he_old_bar) ? TSUNAMI_PCI0_IO : TSUNAMI_PCI0_MEMORY; BARAddrs[barnum] = he_new_bar + space_base; pioPort->sendStatusChange(Port::RangeChange); } } config.baseAddr[barnum] = htole((he_new_bar & ~bar_mask) | (he_old_bar & bar_mask)); } break; case PCI0_ROM_BASE_ADDR: if (letoh(pkt->get<uint32_t>()) == 0xfffffffe) config.expansionROM = htole((uint32_t)0xffffffff); else config.expansionROM = pkt->get<uint32_t>(); break; case PCI_COMMAND: // This could also clear some of the error bits in the Status // register. However they should never get set, so lets ignore // it for now config.command = pkt->get<uint32_t>(); break; default: DPRINTF(PCIDEV, "Writing to a read only register"); } DPRINTF(PCIDEV, "writeConfig: dev %#x func %#x reg %#x 4 bytes: data = %#x\n", params()->pci_dev, params()->pci_func, offset, (uint32_t)pkt->get<uint32_t>()); break; default: panic("invalid access size(?) for PCI configspace!\n"); } pkt->makeAtomicResponse(); return configDelay; } void PciDev::serialize(ostream &os) { SERIALIZE_ARRAY(BARSize, sizeof(BARSize) / sizeof(BARSize[0])); SERIALIZE_ARRAY(BARAddrs, sizeof(BARAddrs) / sizeof(BARAddrs[0])); SERIALIZE_ARRAY(config.data, sizeof(config.data) / sizeof(config.data[0])); } void PciDev::unserialize(Checkpoint *cp, const std::string &section) { UNSERIALIZE_ARRAY(BARSize, sizeof(BARSize) / sizeof(BARSize[0])); UNSERIALIZE_ARRAY(BARAddrs, sizeof(BARAddrs) / sizeof(BARAddrs[0])); UNSERIALIZE_ARRAY(config.data, sizeof(config.data) / sizeof(config.data[0])); pioPort->sendStatusChange(Port::RangeChange); } <|endoftext|>
<commit_before>#include <re2/re2.h> #include <iostream> #include <fstream> #include <errno.h> #include <getopt.h> int extract(const re2::StringPiece &text, const re2::RE2& pattern, const re2::StringPiece &rewrite, std::string *out, bool global) { return global ? RE2::GlobalExtract(text, pattern, rewrite, out) : RE2::Extract(text, pattern, rewrite, out) ? 1 : 0; } int replace(std::string *text, const re2::RE2& pattern, const re2::StringPiece &rewrite, bool global) { return global ? RE2::GlobalReplace(text, pattern, rewrite) : RE2::Replace(text, pattern, rewrite) ? 1 : 0; } bool match(const re2::StringPiece &text, const re2::RE2& pattern, bool whole_line) { return whole_line ? RE2::FullMatch(text, pattern) : RE2::PartialMatch(text, pattern); } int main(int argc, const char **argv) { const char *appname = argv[0]; const char *apn = argv[0]; while(*apn) { if(*apn++ == '/') { appname = apn; } } int o_global = 0, o_usage = 0, o_print_match = 0, o_also_print_unreplaced = 0, o_negate_match = 0, o_substitute = 0, o_print_fname = 0, o_no_print_fname = 0, o_count = 0, o_list = 0, o_neg_list = 0, o_literal = 0, o_case_insensitive = 0, o_full_line = 0; enum {SEARCH, REPLACE} mode; const struct option options[] = { {"help",no_argument,&o_usage,'?'}, {"global",no_argument,&o_global,'g'}, {"invert-match",no_argument,&o_negate_match,'v'}, {"only-matching",no_argument,&o_global,'o'}, {"subtitute",no_argument,&o_substitute,'s'}, {"print-all",no_argument,&o_also_print_unreplaced,'p'}, {"print-names",no_argument,&o_print_fname,'H'}, {"no-print-names",no_argument,&o_no_print_fname,'h'}, {"count",no_argument,&o_count,'c'}, {"files-with-matches",no_argument,&o_list,'l'}, {"files-without-match",no_argument,&o_neg_list,'L'}, {"ignore-case",no_argument,&o_case_insensitive,'i'}, {"fixed-strings",no_argument,&o_literal,'F'}, {"line-regexp",no_argument,&o_full_line,'x'}, { NULL, 0, NULL, 0 } }; std::string rep; char c; while((c = getopt_long(argc, (char *const *)argv, "?ogvgs:pHhclLiFx", (const struct option *)&options[0], NULL))!=-1){ switch(c) { case 'g': o_global = 1; break; case 'o': o_print_match = 1; break; case 'p': o_also_print_unreplaced = 1; break; case 'v': o_negate_match = 1; break; case 's': rep=std::string(optarg); o_substitute = 1; break; case 'H': o_print_fname = 1; break; case 'h': o_no_print_fname = 1; break; case 'c': o_count = 1; break; case 'l': o_list = 1; break; case 'L': o_neg_list = 1; break; case 'F': o_literal = 1; break; case 'i': case 'y': o_case_insensitive = 1; break; case 'x': o_full_line = 1; break; default: o_usage = 1; } } argc -= optind; argv += optind; if(o_neg_list){ o_list = 1; } /* for(const struct option *o=&options[0];o->name;o++){ std::cout << o->name << ':' << *(o->flag) << std::endl; } std::cout << "ARGC: " << argc << std::endl; for(int i=0;i<argc;i++){ std::cout << "ARGV[" << i << "]: " << argv[i] << std::endl; } std::cout << std::endl;*/ if(argc >= 1){ mode=o_substitute?REPLACE:SEARCH; } else { o_usage = 1; } if(o_usage) { std::cout << appname << " [-?ogvgpHhclLiFx][-s substitution] pattern file1..." << std::endl << std:: endl << "TEXT text to search" << std::endl << "PATTERN re2 expression to apply" << std::endl << "REPLACEMENT optional replacement string, supports \\0 .. \\9 references" << std::endl << "FLAGS modifiers to operation" << std::endl << std::endl << " -?, --help: display help" << std::endl << " -v, --invert-match: invert match" << std::endl << " -o, --only-matching: only print matching portion" << std::endl << " -s substitution, --sub=substitution do substitution" << std::endl << " -g, --global: global search/replace, default is one per line" << std::endl << " -p, --print-all: (when replacing) print lines where no replacement was made" << std::endl << " -H, --print-names: always print file name" << std::endl << " -h, --no-print-names: never print file name" << std::endl << " -c, --count: print match count instead of normal output" << std::endl << " -l, --files-with-matches: list matching files instead of normal output" << std::endl << " -L, --files-without-match: list nonmatching files instead of normal output" << std::endl << " -i, --ignore-case: ignore case when matching; same as (?i)" << std::endl << " -F, --fixed-strings: treat pattern argument as literal string" << std::endl << " -x, --line-regexp: match whole lines only" << std::endl << std::endl; return 0; } re2::RE2::Options opts(re2::RE2::DefaultOptions); if(o_case_insensitive) { opts.set_case_sensitive(false); } if(o_literal) { opts.set_literal(true); } RE2::RE2 pat(argv[0], opts); //rationalize flags if(o_negate_match && o_print_match) { o_print_match = 0; } if(mode == SEARCH && o_print_match) { //o_print_match for SEARCH uses REPLACE code with constant repstr rep = std::string("\\0"); o_also_print_unreplaced = 0; mode = REPLACE; } int num_files = argc - 1; if(num_files > 1 && !o_no_print_fname) { o_print_fname = 1; } const char** fnames; const char* def_fname = "/dev/stdin"; if(num_files == 0) { num_files = 1; fnames = &def_fname; } else { fnames = &argv[1]; } for(int fidx = 0; fidx < num_files; fidx++) { const char* fname = fnames[fidx]; std::ifstream ins(fname); if(fnames == &def_fname) { //for output compatibility with grep fname = "(standard input)"; } if(!ins) { std::cerr << appname << " " << fname << ':' << strerror(errno) << std::endl; } else { long long count = 0; std::string line; while(std::getline(ins, line)) { std::string *to_print = NULL; std::string in(line); bool matched; if(mode == SEARCH) { matched = match(in, pat, o_full_line); to_print = &in; to_print = (matched ^ o_negate_match) ? to_print : NULL; } else if(mode == REPLACE) { // need to pick: (-o) Extract, (default) Replace, (-g)GlobalReplace // also, print non matching lines? (-p) std::string out; if(o_print_match) { matched = extract(in, pat, rep, &out, o_global) > 0; to_print = &out; } else { matched = replace(&in, pat, rep, o_global) > 0; to_print = &in; } to_print = (matched ^ o_negate_match) ? to_print : NULL; if(o_also_print_unreplaced && !to_print && !o_count) { out = std::string(line); to_print = &out; } } if(to_print) { count++; if(!o_count && !o_list) { if(o_print_fname) { std::cout << fname << ":"; } std::cout << *to_print << std::endl; } } } if(o_count) { if(o_print_fname) { std::cout << fname << ":"; } std::cout << count << std::endl; } else if(o_list && (count > 0) ^ o_neg_list) { std::cout << fname << std::endl; } ins.close(); } } } <commit_msg>fixed long-arg processing<commit_after>#include <re2/re2.h> #include <iostream> #include <fstream> #include <errno.h> #include <getopt.h> int extract(const re2::StringPiece &text, const re2::RE2& pattern, const re2::StringPiece &rewrite, std::string *out, bool global) { return global ? RE2::GlobalExtract(text, pattern, rewrite, out) : RE2::Extract(text, pattern, rewrite, out) ? 1 : 0; } int replace(std::string *text, const re2::RE2& pattern, const re2::StringPiece &rewrite, bool global) { return global ? RE2::GlobalReplace(text, pattern, rewrite) : RE2::Replace(text, pattern, rewrite) ? 1 : 0; } bool match(const re2::StringPiece &text, const re2::RE2& pattern, bool whole_line) { return whole_line ? RE2::FullMatch(text, pattern) : RE2::PartialMatch(text, pattern); } int main(int argc, const char **argv) { const char *appname = argv[0]; const char *apn = argv[0]; while(*apn) { if(*apn++ == '/') { appname = apn; } } int o_global = 0, o_usage = 0, o_print_match = 0, o_also_print_unreplaced = 0, o_negate_match = 0, o_substitute = 0, o_print_fname = 0, o_no_print_fname = 0, o_count = 0, o_list = 0, o_neg_list = 0, o_literal = 0, o_case_insensitive = 0, o_full_line = 0; enum {SEARCH, REPLACE} mode; const struct option options[] = { {"help",no_argument,&o_usage,'?'}, {"global",no_argument,&o_global,'g'}, {"invert-match",no_argument,&o_negate_match,'v'}, {"only-matching",no_argument,&o_global,'o'}, {"subtitute",required_argument,&o_substitute,'s'}, {"print-all",no_argument,&o_also_print_unreplaced,'p'}, {"print-names",no_argument,&o_print_fname,'H'}, {"no-print-names",no_argument,&o_no_print_fname,'h'}, {"count",no_argument,&o_count,'c'}, {"files-with-matches",no_argument,&o_list,'l'}, {"files-without-match",no_argument,&o_neg_list,'L'}, {"ignore-case",no_argument,&o_case_insensitive,'i'}, {"fixed-strings",no_argument,&o_literal,'F'}, {"line-regexp",no_argument,&o_full_line,'x'}, { NULL, 0, NULL, 0 } }; std::string rep; char c; while((c = getopt_long(argc, (char *const *)argv, "?ogvgs:pHhclLiFx", (const struct option *)&options[0], NULL))!=-1){ switch(c) { case 0: break; case 'g': o_global = 1; break; case 'o': o_print_match = 1; break; case 'p': o_also_print_unreplaced = 1; break; case 'v': o_negate_match = 1; break; case 's': rep=std::string(optarg); o_substitute = 1; break; case 'H': o_print_fname = 1; break; case 'h': o_no_print_fname = 1; break; case 'c': o_count = 1; break; case 'l': o_list = 1; break; case 'L': o_neg_list = 1; break; case 'F': o_literal = 1; break; case 'i': case 'y': o_case_insensitive = 1; break; case 'x': o_full_line = 1; break; default: o_usage = 1; } } argc -= optind; argv += optind; if(o_neg_list){ o_list = 1; } /*for(const struct option *o=&options[0];o->name;o++){ std::cout << o->name << ':' << *(o->flag) << std::endl; } std::cout << "ARGC: " << argc << std::endl; for(int i=0;i<argc;i++){ std::cout << "ARGV[" << i << "]: " << argv[i] << std::endl; } std::cout << std::endl;*/ if(argc >= 1){ mode=o_substitute?REPLACE:SEARCH; } else { o_usage = 1; } if(o_usage) { std::cout << appname << " [-?ogvgpHhclLiFx][-s substitution] pattern file1..." << std::endl << std:: endl << "TEXT text to search" << std::endl << "PATTERN re2 expression to apply" << std::endl << "REPLACEMENT optional replacement string, supports \\0 .. \\9 references" << std::endl << "FLAGS modifiers to operation" << std::endl << std::endl << " -?, --help: display help" << std::endl << " -v, --invert-match: invert match" << std::endl << " -o, --only-matching: only print matching portion" << std::endl << " -s substitution, --sub=substitution do substitution" << std::endl << " -g, --global: global search/replace, default is one per line" << std::endl << " -p, --print-all: (when replacing) print lines where no replacement was made" << std::endl << " -H, --print-names: always print file name" << std::endl << " -h, --no-print-names: never print file name" << std::endl << " -c, --count: print match count instead of normal output" << std::endl << " -l, --files-with-matches: list matching files instead of normal output" << std::endl << " -L, --files-without-match: list nonmatching files instead of normal output" << std::endl << " -i, --ignore-case: ignore case when matching; same as (?i)" << std::endl << " -F, --fixed-strings: treat pattern argument as literal string" << std::endl << " -x, --line-regexp: match whole lines only" << std::endl << std::endl; return 0; } re2::RE2::Options opts(re2::RE2::DefaultOptions); if(o_case_insensitive) { opts.set_case_sensitive(false); } if(o_literal) { opts.set_literal(true); } RE2::RE2 pat(argv[0], opts); //rationalize flags if(o_negate_match && o_print_match) { o_print_match = 0; } if(mode == SEARCH && o_print_match) { //o_print_match for SEARCH uses REPLACE code with constant repstr rep = std::string("\\0"); o_also_print_unreplaced = 0; mode = REPLACE; } int num_files = argc - 1; if(num_files > 1 && !o_no_print_fname) { o_print_fname = 1; } const char** fnames; const char* def_fname = "/dev/stdin"; if(num_files == 0) { num_files = 1; fnames = &def_fname; } else { fnames = &argv[1]; } for(int fidx = 0; fidx < num_files; fidx++) { const char* fname = fnames[fidx]; std::ifstream ins(fname); if(fnames == &def_fname) { //for output compatibility with grep fname = "(standard input)"; } if(!ins) { std::cerr << appname << " " << fname << ':' << strerror(errno) << std::endl; } else { long long count = 0; std::string line; while(std::getline(ins, line)) { std::string *to_print = NULL; std::string in(line); bool matched; if(mode == SEARCH) { matched = match(in, pat, o_full_line); to_print = &in; to_print = (matched ^ o_negate_match) ? to_print : NULL; } else if(mode == REPLACE) { // need to pick: (-o) Extract, (default) Replace, (-g)GlobalReplace // also, print non matching lines? (-p) std::string out; if(o_print_match) { matched = extract(in, pat, rep, &out, o_global) > 0; to_print = &out; } else { matched = replace(&in, pat, rep, o_global) > 0; to_print = &in; } to_print = (matched ^ o_negate_match) ? to_print : NULL; if(o_also_print_unreplaced && !to_print && !o_count) { out = std::string(line); to_print = &out; } } if(to_print) { count++; if(!o_count && !o_list) { if(o_print_fname) { std::cout << fname << ":"; } std::cout << *to_print << std::endl; } } } if(o_count) { if(o_print_fname) { std::cout << fname << ":"; } std::cout << count << std::endl; } else if(o_list && (count > 0) ^ o_neg_list) { std::cout << fname << std::endl; } ins.close(); } } } <|endoftext|>
<commit_before>#include <re2/re2.h> #include <iostream> #include <fstream> #include <errno.h> int extract(const re2::StringPiece &text, const re2::RE2& pattern, const re2::StringPiece &rewrite, std::string *out, bool global) { return global?RE2::GlobalExtract(text, pattern, rewrite, out): RE2::Extract(text, pattern, rewrite, out)?1:0; } int replace(std::string *text, const re2::RE2& pattern, const re2::StringPiece &rewrite, bool global) { return global?RE2::GlobalReplace(text, pattern, rewrite): RE2::Replace(text, pattern, rewrite)?1:0; } bool match(const re2::StringPiece &text, const re2::RE2& pattern, bool whole_line) { return whole_line?RE2::FullMatch(text, pattern): RE2::PartialMatch(text, pattern); } int main(int argc, const char** argv) { const char *appname=argv[0]; const char *apn=argv[0]; while(*apn) { if(*apn++ == '/') { appname=apn; } } int o_global=0, o_usage=0, o_print_match=0, o_also_print_unreplaced=0, o_negate_match=0, o_substitute=0, o_print_fname=0, o_no_print_fname=0, o_count = 0, o_list = 0, o_neg_list = 0, o_literal = 0, o_case_insensitive = 0, o_full_line = 0; enum {SEARCH,REPLACE} mode; if(argc>1) { if(argv[1][0] == '-') { if ( argv[1][1] == '-') { //ignore standalone '--' as argv[1]; } else { // we have flags const char* fs = argv[1]+1; char c; while((c=*fs++)) { switch (c) { case 'g': o_global = 1; break; case 'o': o_print_match = 1; break; case 'p': o_also_print_unreplaced = 1; break; case 'v': o_negate_match = 1; break; case 's': o_substitute = 1; break; case 'H': o_print_fname = 1; break; case 'h': o_no_print_fname = 1; break; case 'c': o_count = 1; break; case 'l': o_list = 1; break; case 'L': o_list = 1; o_neg_list = 1; break; case 'F': o_literal = 1; break; case 'i': case 'y': o_case_insensitive = 1; break; case 'x': o_full_line = 1; break; default: o_usage = 1; } } } argv[1] = argv[0]; argv++; argc--; } } else { o_usage = 1; } int files_arg; if(!o_substitute && argc >= 2) { mode = SEARCH; files_arg = 2; } else if(o_substitute && argc >= 3) { mode = REPLACE; files_arg = 3; } else { o_usage = 1; } if(o_usage) { std::cout << appname << " [-flags] pattern [replacement] file1..." << std::endl << std:: endl << "TEXT text to search" << std::endl << "PATTERN re2 expression to apply" << std::endl << "REPLACEMENT optional replacement string, supports \\0 .. \\9 references" << std::endl << "FLAGS modifiers to operation" << std::endl << std::endl << " h: display help" << std::endl << " v: invert match" << std::endl << " o: only print matching portion" << std::endl << " s: do substitution" << std::endl << " g: global search/replace, default is one per line" << std::endl << " p: (when replacing) print lines where no replacement was made" << std::endl << " H: always print file name" << std::endl << " h: never print file name" << std::endl << " c: print match count instead of normal output" << std::endl << " l: list matching files instead of normal output" << std::endl << " L: list nonmatching files instead of normal output" << std::endl << " i: ignore case when matching; same as (?i)" << std::endl << " F: treat pattern argument as literal string" << std::endl << " x: match whole lines only" << std::endl << std::endl; return 0; } re2::RE2::Options opts(re2::RE2::DefaultOptions); if(o_case_insensitive) { opts.set_case_sensitive(false); } if(o_literal) { opts.set_literal(true); } RE2::RE2 pat(argv[1],opts); //rationalize flags if(o_negate_match && o_print_match) { o_print_match = 0; } std::string rep; if(mode == REPLACE) { rep = std::string(argv[2]); } else if(mode == SEARCH && o_print_match) { //o_print_match for SEARCH uses REPLACE code with constant repstr rep = std::string("\\0"); o_also_print_unreplaced = 0; mode = REPLACE; } int num_files = argc - files_arg; if(num_files > 1 && !o_no_print_fname) { o_print_fname = 1; } const char** fnames; const char* def_fname="/dev/stdin"; if(num_files == 0) { num_files = 1; fnames = &def_fname; } else { fnames = &argv[files_arg]; } for(int fidx = 0; fidx < num_files; fidx++) { const char* fname = fnames[fidx]; std::ifstream ins(fname); if(fnames == &def_fname) { //for output compatibility with grep fname = "(standard input)"; } if(!ins) { std::cerr << appname << " " << fname << ':' << strerror(errno) << std::endl; } else { long long count = 0; std::string line; while (std::getline(ins, line)) { std::string *to_print = NULL; std::string in(line); bool matched; if(mode == SEARCH) { matched = match(in, pat,o_full_line); to_print = &in; to_print=(matched ^ o_negate_match)?to_print:NULL; } else if(mode == REPLACE) { // need to pick: (-o) Extract, (default) Replace, (-g)GlobalReplace // also, print non matching lines? (-p) std::string out; if(o_print_match) { matched = extract(in, pat, rep, &out, o_global) > 0; to_print = &out; } else { matched = replace(&in, pat, rep, o_global) > 0; to_print = &in; } to_print=(matched ^ o_negate_match)?to_print:NULL; if(o_also_print_unreplaced && !to_print && !o_count) { out = std::string(line); to_print = &out; } } if(to_print) { count++; if(!o_count && !o_list) { if(o_print_fname) { std::cout << fname << ":"; } std::cout << *to_print << std::endl; } } } if(o_count) { if(o_print_fname) { std::cout << fname << ":"; } std::cout << count << std::endl; } else if(o_list && (count > 0) ^ o_neg_list) { std::cout << fname << std::endl; } ins.close(); } } } <commit_msg>more whitespace cleanup<commit_after>#include <re2/re2.h> #include <iostream> #include <fstream> #include <errno.h> int extract(const re2::StringPiece &text, const re2::RE2& pattern, const re2::StringPiece &rewrite, std::string *out, bool global) { return global ? RE2::GlobalExtract(text, pattern, rewrite, out) : RE2::Extract(text, pattern, rewrite, out) ? 1 : 0; } int replace(std::string *text, const re2::RE2& pattern, const re2::StringPiece &rewrite, bool global) { return global ? RE2::GlobalReplace(text, pattern, rewrite) : RE2::Replace(text, pattern, rewrite) ? 1 : 0; } bool match(const re2::StringPiece &text, const re2::RE2& pattern, bool whole_line) { return whole_line ? RE2::FullMatch(text, pattern) : RE2::PartialMatch(text, pattern); } int main(int argc, const char** argv) { const char *appname = argv[0]; const char *apn = argv[0]; while(*apn) { if(*apn++ == '/') { appname = apn; } } int o_global = 0, o_usage = 0, o_print_match = 0, o_also_print_unreplaced = 0, o_negate_match = 0, o_substitute = 0, o_print_fname = 0, o_no_print_fname = 0, o_count = 0, o_list = 0, o_neg_list = 0, o_literal = 0, o_case_insensitive = 0, o_full_line = 0; enum {SEARCH, REPLACE} mode; if(argc > 1) { if(argv[1][0] == '-') { if(argv[1][1] == '-') { //ignore standalone '--' as argv[1]; } else { // we have flags const char* fs = argv[1] + 1; char c; while((c = *fs++)) { switch(c) { case 'g': o_global = 1; break; case 'o': o_print_match = 1; break; case 'p': o_also_print_unreplaced = 1; break; case 'v': o_negate_match = 1; break; case 's': o_substitute = 1; break; case 'H': o_print_fname = 1; break; case 'h': o_no_print_fname = 1; break; case 'c': o_count = 1; break; case 'l': o_list = 1; break; case 'L': o_list = 1; o_neg_list = 1; break; case 'F': o_literal = 1; break; case 'i': case 'y': o_case_insensitive = 1; break; case 'x': o_full_line = 1; break; default: o_usage = 1; } } } argv[1] = argv[0]; argv++; argc--; } } else { o_usage = 1; } int files_arg; if(!o_substitute && argc >= 2) { mode = SEARCH; files_arg = 2; } else if(o_substitute && argc >= 3) { mode = REPLACE; files_arg = 3; } else { o_usage = 1; } if(o_usage) { std::cout << appname << " [-flags] pattern [replacement] file1..." << std::endl << std:: endl << "TEXT text to search" << std::endl << "PATTERN re2 expression to apply" << std::endl << "REPLACEMENT optional replacement string, supports \\0 .. \\9 references" << std::endl << "FLAGS modifiers to operation" << std::endl << std::endl << " h: display help" << std::endl << " v: invert match" << std::endl << " o: only print matching portion" << std::endl << " s: do substitution" << std::endl << " g: global search/replace, default is one per line" << std::endl << " p: (when replacing) print lines where no replacement was made" << std::endl << " H: always print file name" << std::endl << " h: never print file name" << std::endl << " c: print match count instead of normal output" << std::endl << " l: list matching files instead of normal output" << std::endl << " L: list nonmatching files instead of normal output" << std::endl << " i: ignore case when matching; same as (?i)" << std::endl << " F: treat pattern argument as literal string" << std::endl << " x: match whole lines only" << std::endl << std::endl; return 0; } re2::RE2::Options opts(re2::RE2::DefaultOptions); if(o_case_insensitive) { opts.set_case_sensitive(false); } if(o_literal) { opts.set_literal(true); } RE2::RE2 pat(argv[1], opts); //rationalize flags if(o_negate_match && o_print_match) { o_print_match = 0; } std::string rep; if(mode == REPLACE) { rep = std::string(argv[2]); } else if(mode == SEARCH && o_print_match) { //o_print_match for SEARCH uses REPLACE code with constant repstr rep = std::string("\\0"); o_also_print_unreplaced = 0; mode = REPLACE; } int num_files = argc - files_arg; if(num_files > 1 && !o_no_print_fname) { o_print_fname = 1; } const char** fnames; const char* def_fname = "/dev/stdin"; if(num_files == 0) { num_files = 1; fnames = &def_fname; } else { fnames = &argv[files_arg]; } for(int fidx = 0; fidx < num_files; fidx++) { const char* fname = fnames[fidx]; std::ifstream ins(fname); if(fnames == &def_fname) { //for output compatibility with grep fname = "(standard input)"; } if(!ins) { std::cerr << appname << " " << fname << ':' << strerror(errno) << std::endl; } else { long long count = 0; std::string line; while(std::getline(ins, line)) { std::string *to_print = NULL; std::string in(line); bool matched; if(mode == SEARCH) { matched = match(in, pat, o_full_line); to_print = &in; to_print = (matched ^ o_negate_match) ? to_print : NULL; } else if(mode == REPLACE) { // need to pick: (-o) Extract, (default) Replace, (-g)GlobalReplace // also, print non matching lines? (-p) std::string out; if(o_print_match) { matched = extract(in, pat, rep, &out, o_global) > 0; to_print = &out; } else { matched = replace(&in, pat, rep, o_global) > 0; to_print = &in; } to_print = (matched ^ o_negate_match) ? to_print : NULL; if(o_also_print_unreplaced && !to_print && !o_count) { out = std::string(line); to_print = &out; } } if(to_print) { count++; if(!o_count && !o_list) { if(o_print_fname) { std::cout << fname << ":"; } std::cout << *to_print << std::endl; } } } if(o_count) { if(o_print_fname) { std::cout << fname << ":"; } std::cout << count << std::endl; } else if(o_list && (count > 0) ^ o_neg_list) { std::cout << fname << std::endl; } ins.close(); } } } <|endoftext|>
<commit_before>#include "node.h" #include <iostream> #include <thread> #include <sstream> #include <mutex> #include <tuple> #include <cstring> #include <cerrno> #include <sys/types.h> #include <sys/socket.h> #include <netdb.h> using namespace DVSim; Node::Node(const NodeConfig& config) : node_name_(config.node_name), port_(config.port)//, should_interrupt_(false) { for (auto& nbor : config.neighbors) { NodeName nbor_name; Distance nbor_dist; std::string nbor_ip; std::tie(nbor_name, nbor_dist, nbor_ip) = nbor; // Add to neighbor and distance vector tables nbors_.insert(std::make_pair( nbor_name, std::move(IPAndDist(nbor_ip, nbor_dist)))); dv_.insert(std::make_pair( nbor_name, std::move(DistAndNextHop(nbor_dist, nbor_name)))); } } // Print neighbors table. Need to lock access to tables before printing. void Node::print_nbors_table() { std::cout << "Neighbor Table" << std::endl; std::unique_lock<std::mutex> lg(table_mutex_); for (const auto& entry : nbors_) { NodeName name; std::string ip; Distance d; IPAndDist id; std::tie(name, id) = entry; std::tie(ip, d) = id; std::cout << name << "\t" << ip << "\t" << d << std::endl; } } // Print distance vector table. Need to lock access to tables before printing. void Node::print_dv_table() { std::cout << "Distance Vector Table" << std::endl; std::unique_lock<std::mutex> lg(table_mutex_); for (const auto& entry : dv_) { NodeName name; DistAndNextHop dn; Distance d; NextHop next_hop; std::tie(name, dn) = entry; std::tie(d, next_hop) = dn; std::cout << name << "\t" << d << "\t" << next_hop << std::endl; } } // Procedure that spawns a new thread and periodically sends current distance // vector table to neighbors void Node::periodic_send(int32_t interval_ms) { std::thread([this, interval_ms]() { while (true) { std::cout << "periodic send to neighbors" << std::endl; this->nbor_broadcast(); std::this_thread::sleep_for(std::chrono::milliseconds(interval_ms)); } }).detach(); } // Sends update to neighbor. Note that it must lock the two tables before using // them void Node::nbor_broadcast() { // Lock tables before we do anything std::unique_lock<std::mutex> lock(table_mutex_); std::string msg = create_message(); std::vector<std::pair<NodeName, std::string>> nbors; for (const auto nbor : nbors_) { nbors.emplace_back(nbor.first, nbor.second.first); } // Done with critical section stuff lock.unlock(); // Send messages to neighbors for (const auto& pair : nbors) { NodeName name; std::string ip_addr; std::tie(name, ip_addr) = pair; std::cout << msg << std::endl; send_message(ip_addr, msg); } } // Send a msg to the specified ip_addr void Node::send_message(const std::string& ip_addr, const std::string& msg) { // Networking code to set up address/socket struct addrinfo hints; std::memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; std::string port_str = std::to_string(port_); struct addrinfo *server_info; int err = getaddrinfo(ip_addr.c_str(), port_str.c_str(), &hints, &server_info); if (err != 0) { std::cerr << "[get_addr_por]: getaddrinfo " << gai_strerror(err) << std::endl; return; } // Loop through to find socket to bind to int sock; struct addrinfo *p; for (p = server_info; p != NULL; p = p->ai_next) { // Get a socket sock = socket(p->ai_family, p->ai_socktype, p->ai_protocol); if (sock == -1) { perror("[get_addr_port]: socket"); continue; } // Connect to it if (connect(sock, p->ai_addr, p->ai_addrlen) == -1) { close(sock); perror("[send_message]: connect"); continue; } break; } // Did we bind to a socket? if (p == NULL) { std::cerr << "[get_addr_port]: could not get socket" << std::endl; return; } freeaddrinfo(server_info); // Add msg len to the beginning of the msg (+1 for null terminator) uint32_t msg_size = uint32_t(msg.size() + 1); uint32_t buf_size = msg_size + uint32_t(sizeof(msg_size)); auto buf = std::unique_ptr<char>(new char[buf_size]); uint32_t net_order_msg_size = htonl(msg_size); std::memcpy(buf.get(), &net_order_msg_size, sizeof(net_order_msg_size)); std::strncpy(buf.get() + sizeof(net_order_msg_size), msg.c_str(), msg_size); // Send (and make sure all data gets sent) ssize_t send_len = send(sock, buf.get(), buf_size, 0); if (send_len == -1) { perror("[send_message]: send"); return; } while (send_len < buf_size) { send_len += send(sock, buf.get() + send_len, buf_size - uint32_t(send_len), 0); } } // Main entry point to start the algorithm void Node::start() { // Start the periodic send std::cout << "Initial routing table" << std::endl; print_dv_table(); std::cout << std::endl; periodic_send(); std::this_thread::sleep_for(std::chrono::milliseconds(5000)); while (true) { // receive_connection() is blocking! int newsock = receive_connection(); if (newsock == -1) { std::cerr << "[start]: couldn't receive connection" << std::endl; std::this_thread::sleep_for(std::chrono::milliseconds(1000)); continue; } // Spawn thread to handle responses std::thread([this, newsock]() { std::string serialized_msg = this->receive_message(newsock); DVMessage msg = deserialize(serialized_msg); std::cout << "received message from " << msg.sender << std::endl; std::cout << serialized_msg << std::endl; if (this->update_dv_table(msg)) { this->nbor_broadcast(); } }).detach(); } } int32_t Node::receive_connection() { // Starting to connect to socket for receiving struct addrinfo hints; std::memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_PASSIVE; std::string port_str = std::to_string(port_); struct addrinfo *server_info; int err = getaddrinfo(nullptr, port_str.c_str(), &hints, &server_info); if (err != 0) { std::cerr << "[get_addr_por]: getaddrinfo " << gai_strerror(err) << std::endl; return -1; } // Loop through until we find a socket to bind to struct addrinfo* p; int sock; for(p = server_info; p != NULL; p = p->ai_next) { if ((sock = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) { perror("[receive_connection]: socket"); continue; } // Fix the "port unavailable" message int32_t yes = 1; if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int32_t)) == -1) { perror("[receive_connection]: setsockopt"); return -1; } // bind to the socket if (bind(sock, p->ai_addr, p->ai_addrlen) == -1) { close(sock); perror("[receive_connection]: bind"); continue; } break; } freeaddrinfo(server_info); // Check if we actually bound to a socket if (p == NULL) { std::cerr << "[receive_connection]: could not bind to receiver socket" << std::endl; return -1; } // Listen on socket if (listen(sock, 10) != 0) { perror("[receive_connection]: listen"); return -1; } // Accept connection on that socket struct sockaddr_storage their_addr; socklen_t sin_size; int newsock = accept(sock, (struct sockaddr*) &their_addr, &sin_size); if (newsock == -1) { perror("[receive_connection]: accept"); return -1; } return newsock; } // Receive message from node connected through conn std::string Node::receive_message(int32_t conn) { // Receive first sizeof(int32_t) bytes for message size uint32_t msg_size; uint32_t bytes_recvd = 0; while (bytes_recvd < sizeof(msg_size)) { ssize_t bytecount = recv(conn, (uint32_t *)&msg_size + bytes_recvd, sizeof(msg_size), 0); if (bytecount == -1) { perror("[receive_message]: recv"); continue; } bytes_recvd += bytecount; } msg_size = ntohl(msg_size); // Receive the next msg_size bytes that contain the message // XXX Need + 1 for null terminator? auto buf = std::unique_ptr<char>(new char[bytes_recvd]); bytes_recvd = 0; while (bytes_recvd < msg_size) { ssize_t bytecount = recv(conn, buf.get() + bytes_recvd, msg_size, 0); if (bytecount == -1) { perror("[receive_message]: recv"); continue; } bytes_recvd += bytecount; } // Returns copy of buf return std::string(buf.get()); } bool Node::update_dv_table(const DVMessage& msg) { // Lock access while messing with tables std::lock_guard<std::mutex> lg(table_mutex_); bool did_update_table = false; for (const auto& triplet : msg.entries) { NodeName node; Distance sender_to_node_dist; NextHop node_nh; std::tie(node, sender_to_node_dist, node_nh) = triplet; // Distance to sender (neighbor) if (dv_.find(msg.sender) == std::end(dv_)) { std::cerr << "[update_tables]: sender " << msg.sender << " not in dv table" << std::endl; continue; } Distance dist_to_sender = std::get<0>(dv_[msg.sender]); // node is not currently in the table - make a new entry if (dv_.find(node) == std::end(dv_)) { // Distance will be dist to sender + distance provided by sender DistAndNextHop dnh = DistAndNextHop(dist_to_sender + sender_to_node_dist, msg.sender); dv_.emplace(node, std::move(dnh)); did_update_table = true; } // otherwise node is in table - update if necessary Distance recv_to_node_dist; NextHop recv_to_node_nh; std::tie(recv_to_node_dist, recv_to_node_nh) = dv_[node]; // Only update if dist to sender + sender to node less than what we've // already got if (dist_to_sender + sender_to_node_dist < recv_to_node_dist) { dv_[node].first = dist_to_sender + sender_to_node_dist; dv_[node].second = msg.sender; did_update_table = true; } } return did_update_table; } /* * XXX Assumes tables have already been locked * Serializes the dv_ table into the expected format: * sender_name * number_of_destinations * dest_1_name dist_1 * dest_2_name dist_2 * dest_3_name dist_3 * dest_4_name dist_4 * dest_5_name dist_5 * * Puts a \r\n\r\n at the end of the message */ std::string Node::create_message() { std::string msg; std::stringstream ss(msg); ss << node_name_ << std::endl; ss << dv_.size() << std::endl; for (const auto& dest : dv_) { NodeName n; DistAndNextHop dnh; Distance d; NextHop nh; std::tie(n, dnh) = dest; std::tie(d, nh) = dnh; ss << n << " " << d; } return ss.str(); } <commit_msg>More fixes<commit_after>#include "node.h" #include <iostream> #include <thread> #include <sstream> #include <mutex> #include <tuple> #include <cstring> #include <cerrno> #include <sys/types.h> #include <sys/socket.h> #include <netdb.h> using namespace DVSim; Node::Node(const NodeConfig& config) : node_name_(config.node_name), port_(config.port)//, should_interrupt_(false) { for (auto& nbor : config.neighbors) { NodeName nbor_name; Distance nbor_dist; std::string nbor_ip; std::tie(nbor_name, nbor_dist, nbor_ip) = nbor; // Add to neighbor and distance vector tables nbors_.insert(std::make_pair( nbor_name, std::move(IPAndDist(nbor_ip, nbor_dist)))); dv_.insert(std::make_pair( nbor_name, std::move(DistAndNextHop(nbor_dist, nbor_name)))); } } // Print neighbors table. Need to lock access to tables before printing. void Node::print_nbors_table() { std::cout << "Neighbor Table" << std::endl; std::unique_lock<std::mutex> lg(table_mutex_); for (const auto& entry : nbors_) { NodeName name; std::string ip; Distance d; IPAndDist id; std::tie(name, id) = entry; std::tie(ip, d) = id; std::cout << name << "\t" << ip << "\t" << d << std::endl; } } // Print distance vector table. Need to lock access to tables before printing. void Node::print_dv_table() { std::cout << "Distance Vector Table" << std::endl; std::unique_lock<std::mutex> lg(table_mutex_); for (const auto& entry : dv_) { NodeName name; DistAndNextHop dn; Distance d; NextHop next_hop; std::tie(name, dn) = entry; std::tie(d, next_hop) = dn; std::cout << name << "\t" << d << "\t" << next_hop << std::endl; } } // Procedure that spawns a new thread and periodically sends current distance // vector table to neighbors void Node::periodic_send(int32_t interval_ms) { std::thread([this, interval_ms]() { while (true) { std::cout << "periodic send to neighbors" << std::endl; this->nbor_broadcast(); std::this_thread::sleep_for(std::chrono::milliseconds(interval_ms)); } }).detach(); } // Sends update to neighbor. Note that it must lock the two tables before using // them void Node::nbor_broadcast() { // Lock tables before we do anything std::unique_lock<std::mutex> lock(table_mutex_); std::string msg = create_message(); std::vector<std::pair<NodeName, std::string>> nbors; for (const auto nbor : nbors_) { nbors.emplace_back(nbor.first, nbor.second.first); } // Done with critical section stuff lock.unlock(); // Send messages to neighbors for (const auto& pair : nbors) { NodeName name; std::string ip_addr; std::tie(name, ip_addr) = pair; std::cout << msg << std::endl; send_message(ip_addr, msg); } } // Send a msg to the specified ip_addr void Node::send_message(const std::string& ip_addr, const std::string& msg) { // Networking code to set up address/socket struct addrinfo hints; std::memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; std::string port_str = std::to_string(port_); struct addrinfo *server_info; int err = getaddrinfo(ip_addr.c_str(), port_str.c_str(), &hints, &server_info); if (err != 0) { std::cerr << "[get_addr_por]: getaddrinfo " << gai_strerror(err) << std::endl; return; } // Loop through to find socket to bind to int sock; struct addrinfo *p; for (p = server_info; p != NULL; p = p->ai_next) { // Get a socket sock = socket(p->ai_family, p->ai_socktype, p->ai_protocol); if (sock == -1) { perror("[get_addr_port]: socket"); continue; } // Connect to it if (connect(sock, p->ai_addr, p->ai_addrlen) == -1) { close(sock); perror("[send_message]: connect"); continue; } break; } // Did we bind to a socket? if (p == NULL) { std::cerr << "[get_addr_port]: could not get socket" << std::endl; return; } freeaddrinfo(server_info); // Add msg len to the beginning of the msg (+1 for null terminator) uint32_t msg_size = uint32_t(msg.size() + 1); uint32_t buf_size = msg_size + uint32_t(sizeof(msg_size)); auto buf = std::unique_ptr<char>(new char[buf_size]); uint32_t net_order_msg_size = htonl(msg_size); std::memcpy(buf.get(), &net_order_msg_size, sizeof(net_order_msg_size)); std::strncpy(buf.get() + sizeof(net_order_msg_size), msg.c_str(), msg_size); // Send (and make sure all data gets sent) ssize_t send_len = send(sock, buf.get(), buf_size, 0); if (send_len == -1) { perror("[send_message]: send"); return; } while (send_len < buf_size) { send_len += send(sock, buf.get() + send_len, buf_size - uint32_t(send_len), 0); } } // Main entry point to start the algorithm void Node::start() { // Start the periodic send std::cout << "Initial routing table" << std::endl; print_dv_table(); std::cout << std::endl; periodic_send(); std::this_thread::sleep_for(std::chrono::milliseconds(5000)); while (true) { // receive_connection() is blocking! int newsock = receive_connection(); if (newsock == -1) { std::cerr << "[start]: couldn't receive connection" << std::endl; std::this_thread::sleep_for(std::chrono::milliseconds(1000)); continue; } // Spawn thread to handle responses std::thread([this, newsock]() { std::string serialized_msg = this->receive_message(newsock); DVMessage msg = deserialize(serialized_msg); std::cout << "received message from " << msg.sender << std::endl; std::cout << serialized_msg << std::endl; if (this->update_dv_table(msg)) { this->nbor_broadcast(); } }).detach(); } } int32_t Node::receive_connection() { // Starting to connect to socket for receiving struct addrinfo hints; std::memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_PASSIVE; std::string port_str = std::to_string(port_); struct addrinfo *server_info; int err = getaddrinfo(nullptr, port_str.c_str(), &hints, &server_info); if (err != 0) { std::cerr << "[get_addr_por]: getaddrinfo " << gai_strerror(err) << std::endl; return -1; } // Loop through until we find a socket to bind to struct addrinfo* p; int sock; for(p = server_info; p != NULL; p = p->ai_next) { if ((sock = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) { perror("[receive_connection]: socket"); continue; } // Fix the "port unavailable" message int32_t yes = 1; if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int32_t)) == -1) { perror("[receive_connection]: setsockopt"); return -1; } // bind to the socket if (bind(sock, p->ai_addr, p->ai_addrlen) == -1) { close(sock); perror("[receive_connection]: bind"); continue; } break; } freeaddrinfo(server_info); // Check if we actually bound to a socket if (p == NULL) { std::cerr << "[receive_connection]: could not bind to receiver socket" << std::endl; return -1; } // Listen on socket if (listen(sock, 10) != 0) { perror("[receive_connection]: listen"); return -1; } // Accept connection on that socket struct sockaddr_storage their_addr; socklen_t sin_size; int newsock = accept(sock, (struct sockaddr*) &their_addr, &sin_size); if (newsock == -1) { perror("[receive_connection]: accept"); return -1; } return newsock; } // Receive message from node connected through conn std::string Node::receive_message(int32_t conn) { // Receive first sizeof(int32_t) bytes for message size uint32_t msg_size; uint32_t bytes_recvd = 0; while (bytes_recvd < sizeof(msg_size)) { ssize_t bytecount = recv(conn, (uint32_t *)&msg_size + bytes_recvd, sizeof(msg_size), 0); if (bytecount == -1) { perror("[receive_message]: recv"); continue; } bytes_recvd += bytecount; } msg_size = ntohl(msg_size); // Receive the next msg_size bytes that contain the message // XXX Need + 1 for null terminator? auto buf = std::unique_ptr<char>(new char[bytes_recvd]); bytes_recvd = 0; while (bytes_recvd < msg_size) { ssize_t bytecount = recv(conn, buf.get() + bytes_recvd, msg_size, 0); if (bytecount == -1) { perror("[receive_message]: recv"); continue; } bytes_recvd += bytecount; } // Returns copy of buf return std::string(buf.get()); } bool Node::update_dv_table(const DVMessage& msg) { // Lock access while messing with tables std::lock_guard<std::mutex> lg(table_mutex_); bool did_update_table = false; for (const auto& triplet : msg.entries) { NodeName node; Distance sender_to_node_dist; NextHop node_nh; std::tie(node, sender_to_node_dist, node_nh) = triplet; // Distance to sender (neighbor) if (dv_.find(msg.sender) == std::end(dv_)) { std::cerr << "[update_tables]: sender " << msg.sender << " not in dv table" << std::endl; continue; } Distance dist_to_sender = std::get<0>(dv_[msg.sender]); // node is not currently in the table - make a new entry if (dv_.find(node) == std::end(dv_)) { // Distance will be dist to sender + distance provided by sender DistAndNextHop dnh = DistAndNextHop(dist_to_sender + sender_to_node_dist, msg.sender); dv_.insert(std::make_pair(node, std::move(dnh))); did_update_table = true; } // otherwise node is in table - update if necessary Distance recv_to_node_dist; NextHop recv_to_node_nh; std::tie(recv_to_node_dist, recv_to_node_nh) = dv_[node]; // Only update if dist to sender + sender to node less than what we've // already got if (dist_to_sender + sender_to_node_dist < recv_to_node_dist) { dv_[node].first = dist_to_sender + sender_to_node_dist; dv_[node].second = msg.sender; did_update_table = true; } } return did_update_table; } /* * XXX Assumes tables have already been locked * Serializes the dv_ table into the expected format: * sender_name * number_of_destinations * dest_1_name dist_1 * dest_2_name dist_2 * dest_3_name dist_3 * dest_4_name dist_4 * dest_5_name dist_5 * * Puts a \r\n\r\n at the end of the message */ std::string Node::create_message() { std::string msg; std::stringstream ss(msg); ss << node_name_ << std::endl; ss << dv_.size() << std::endl; for (const auto& dest : dv_) { NodeName n; DistAndNextHop dnh; Distance d; NextHop nh; std::tie(n, dnh) = dest; std::tie(d, nh) = dnh; ss << n << " " << d; } return ss.str(); } <|endoftext|>
<commit_before>/* discovery.cpp -*- C++ -*- Rémi Attab (remi.attab@gmail.com), 26 Dec 2013 FreeBSD-style copyright and disclaimer apply Implementation of the node discovery database. */ #include "discovery.h" #include "pack.h" #include "lockless/bits.h" #include <set> #include <vector> #include <algorithm> #include <functional> namespace slick { /******************************************************************************/ /* UTILS */ /******************************************************************************/ template<typename It, typename Rng> It pickRandom(It it, It last, Rng& rng) { std::uniform_int_distribution<size_t> dist(std::distance(it, last) - 1); std::advance(it, dist(rng)); return it; } template<typename T, typename It, typename Rng> std::set<T> pickRandom(It first, It last, size_t n, Rng& rng) { std::set<T> result; while (result.size() < n) result.insert(*pickRandom(first, last, rng)); return std::move(result); } /******************************************************************************/ /* WATCH */ /******************************************************************************/ DistributedDiscovery::Watch:: Watch(WatchFn watch) : watch(std::move(watch)) { static std::atomic<WatchHandle> handleCounter{0}; handle = ++handleCounter; } /******************************************************************************/ /* PROTOCOL */ /******************************************************************************/ namespace msg { static const std::string Init = "_slick_disc_"; static constexpr uint32_t Version = 1; typedef uint16_t Type; static constexpr Type Keys = 1; static constexpr Type Query = 2; static constexpr Type Nodes = 3; static constexpr Type Fetch = 4; static constexpr Type Data = 5; } // namespace msg /******************************************************************************/ /* DISTRIBUTED DISCOVERY */ /******************************************************************************/ size_t DistributedDiscovery:: timerPeriod() { enum { BasePeriod = 60 }; std::uniform_int_distribution<size_t>dist(BasePeriod, BasePeriod * 2); return dist(rng); } DistributedDiscovery:: DistributedDiscovery(const std::vector<Address>& seed, Port port) : keyTTL_(DefaultKeyTTL), nodeTTL_(DefaultNodeTTL), myId(UUID::random()), rng(lockless::wall()), endpoint(port), timer(timerPeriod()) // \todo add randomness { myNode = endpoint.interfaces(); double now = lockless::wall(); for (auto& addr : seed) nodes.emplace(UUID::random(), NodeLocation({addr}), SeedTTL, now); using namespace std::placeholders; endpoint.onPayload = bind(&DistributedDiscovery::onPayload, this, _1, _2); endpoint.onNewConnection = bind(&DistributedDiscovery::onConnect, this, _1); endpoint.onLostConnection = bind(&DistributedDiscovery::onDisconnect, this, _1); poller.add(endpoint); retracts.onOperation = std::bind(&DistributedDiscovery::retract, this, _1); poller.add(retracts); publishes.onOperation = std::bind(&DistributedDiscovery::publish, this, _1, _2); poller.add(publishes); typedef void (DistributedDiscovery::*DiscoverFn) (const std::string&, Watch&&); DiscoverFn discoverFn = &DistributedDiscovery::discover; discovers.onOperation = std::bind(discoverFn, this, _1, _2); poller.add(discovers); forgets.onOperation = std::bind(&DistributedDiscovery::forget, this, _1, _2); poller.add(forgets); timer.onTimer = bind(&DistributedDiscovery::onTimer, this, _1); poller.add(timer); } void DistributedDiscovery:: poll() { isPollThread.set(); poller.poll(); } void DistributedDiscovery:: shutdown() { isPollThread.unset(); retracts.poll(); publishes.poll(); discovers.poll(); forgets.poll(); } void DistributedDiscovery:: onPayload(ConnectionHandle handle, Payload&& data) { auto& conn = connections[handle]; auto it = data.cbegin(), last = data.cend(); if (!conn) it = onInit(conn, it, last); while (it != last) { msg::Type type; it = unpack(type, it, last); switch(type) { case msg::Keys: it = onKeys(conn, it, last); break; case msg::Query: it = onQuery(conn, it, last); break; case msg::Nodes: it = onNodes(conn, it, last); break; case msg::Fetch: it = onFetch(conn, it, last); break; case msg::Data: it = onData(conn, it, last); break; default: assert(false); }; } } Discovery::WatchHandle DistributedDiscovery:: discover(const std::string& key, const WatchFn& fn) { Watch watch(fn); auto handle = watch.handle; discover(key, std::move(watch)); return handle; } void DistributedDiscovery:: discover(const std::string& key, Watch&& watch) { if (!isPollThread()) { discovers.defer(key, watch); return; } if (!watches.count(key)) { std::vector<QueryItem> items = { key }; endpoint.broadcast(packAll(msg::Query, myNode, items)); } watches[key].insert(std::move(watch)); for (const auto& node : keys[key]) doFetch(key, node.id, node.addrs); } void DistributedDiscovery:: forget(const std::string& key, WatchHandle handle) { if (!isPollThread()) { forgets.defer(key, handle); return; } auto& list = watches[key]; list.erase(Watch(handle)); if (list.empty()) watches.erase(key); } void DistributedDiscovery:: publish(const std::string& key, Payload&& data) { if (!isPollThread()) { publishes.defer(key, std::move(data)); return; } this->data[key] = Data(std::move(data)); std::vector<KeyItem> items; items.emplace_back(key, myId, myNode, keyTTL_); endpoint.broadcast(packAll(msg::Keys, items)); } void DistributedDiscovery:: retract(const std::string& key) { if (!isPollThread()) { retracts.defer(key); return; } data.erase(key); } void DistributedDiscovery:: onConnect(ConnectionHandle handle) { auto& conn = connections[handle]; conn.handle = handle; auto head = std::make_tuple(msg::Init, msg::Version); Payload data; if (conn.pendingFetch.empty()) data = pack(head); else { data = packAll(head, msg::Fetch, conn.pendingFetch); conn.pendingFetch.clear(); } endpoint.send(handle, std::move(data)); } void DistributedDiscovery:: onDisconnect(ConnectionHandle handle) { connections.erase(handle); } ConstPackIt DistributedDiscovery:: onInit(ConnState& conn, ConstPackIt it, ConstPackIt last) { std::string init; it = unpackAll(it, last, init, conn.version); if (init != msg::Init) { endpoint.disconnect(conn.handle); return last; } assert(conn.version == msg::Version); if (!data.empty()) { std::vector<KeyItem> items; items.reserve(data.size()); for (const auto& key : data) items.emplace_back(key.first, key.second.id, myNode, keyTTL_); endpoint.send(conn.handle, packAll(msg::Keys, items)); } if (!watches.empty()) { std::vector<QueryItem> items; items.reserve(watches.size()); for (const auto& watch : watches) items.emplace_back(watch.first); auto msg = packAll(msg::Query, myNode, items); endpoint.send(conn.handle, std::move(msg)); } if (!nodes.empty()) { double now = lockless::wall(); size_t numPicks = lockless::log2(nodes.size()); std::vector<NodeItem> items; items.reserve(numPicks + 1); items.emplace_back(myId, myNode, nodeTTL_); auto picks = pickRandom<Item>(nodes.begin(), nodes.end(), numPicks, rng); for (const auto& node : picks) { size_t ttl = node.ttl(now); if (!ttl) continue; items.emplace_back(node.id, node.addrs, ttl); } endpoint.send(conn.handle, packAll(msg::Nodes, items)); } return it; } ConstPackIt DistributedDiscovery:: onKeys(ConnState&, ConstPackIt it, ConstPackIt last) { std::vector<KeyItem> items; it = unpack(items, it, last); std::vector<KeyItem> toForward; toForward.reserve(items.size()); double now = lockless::wall(); for (auto& item : items) { std::string key = std::move(std::get<0>(item)); Item value(std::move(item), now); auto& list = keys[key]; auto it = list.find(value); if (it != list.end()) { it->setTTL(value.ttl(now), now); continue; } if (watches.count(key)) doFetch(key, value.id, value.addrs); toForward.emplace_back(key, value.id, value.addrs, value.ttl(now)); list.insert(std::move(value)); } if (!toForward.empty()) endpoint.broadcast(packAll(msg::Keys, toForward)); return it; } ConstPackIt DistributedDiscovery:: onQuery(ConnState& conn, ConstPackIt it, ConstPackIt last) { NodeLocation node; std::vector<QueryItem> items; it = unpackAll(it, last, node, items); std::vector<KeyItem> reply; reply.reserve(items.size()); double now = lockless::wall(); for (const auto& key : items) { auto it = keys.find(key); if (it == keys.end()) continue; for (const auto& node : it->second) { if (!node.ttl(now)) continue; reply.emplace_back(key, node.id, node.addrs, node.ttl(now)); } } if (!reply.empty()) endpoint.send(conn.handle, packAll(msg::Keys, reply)); return it; } ConstPackIt DistributedDiscovery:: onNodes(ConnState&, ConstPackIt it, ConstPackIt last) { std::vector<NodeItem> items; it = unpack(items, it, last); std::vector<NodeItem> toForward; toForward.reserve(items.size()); double now = lockless::wall(); for (auto& item : items) { Item value(std::move(item), now); auto it = nodes.find(value); if (it != nodes.end()) { it->setTTL(value.ttl(now), now); continue; } toForward.emplace_back(value.id, value.addrs, value.ttl(now)); nodes.insert(std::move(value)); } if (!toForward.empty()) endpoint.broadcast(packAll(msg::Nodes, toForward)); return it; } void DistributedDiscovery:: doFetch(const std::string& key, const UUID& id, const NodeLocation& node) { auto socket = Socket::connect(node); if (!socket) return; ConnectionHandle handle = socket.fd(); connections[handle].pendingFetch.emplace_back(key, id); ConnectionHandle sameHandle = endpoint.connect(std::move(socket)); assert(handle == sameHandle); } ConstPackIt DistributedDiscovery:: onFetch(ConnState& conn, ConstPackIt it, ConstPackIt last) { std::vector<FetchItem> items; it = unpack(items, it, last); std::vector<DataItem> reply; reply.reserve(items.size()); for (auto& item : items) { std::string key; UUID id; std::tie(key, id) = std::move(item); auto it = data.find(key); if (it == data.end() || it->second.id != id) continue; reply.emplace_back(key, it->second.data); } if (!reply.empty()) endpoint.send(conn.handle, packAll(msg::Data, reply)); return it; } ConstPackIt DistributedDiscovery:: onData(ConnState&, ConstPackIt it, ConstPackIt last) { std::vector<DataItem> items; it = unpack(items, it, last); for (auto& item : items) { std::string key; Payload payload; std::tie(key, payload) = std::move(item); auto it = watches.find(key); if (it == watches.end()) continue; for (const auto& watch : it->second) watch.watch(watch.handle, payload); } return it; } void DistributedDiscovery:: onTimer(size_t) { double now = lockless::wall(); while(!nodes.empty() && expireItem(nodes, now)); while(!keys.empty() && expireKeys(now)); rotateConnections(); } bool DistributedDiscovery:: expireItem(SortedVector<Item>& list, double now) { assert(!list.empty()); auto it = pickRandom(list.begin(), list.end(), rng); if (it->ttl(now)) return false; list.erase(it); return true; } bool DistributedDiscovery:: expireKeys(double now) { assert(!keys.empty()); auto it = pickRandom(keys.begin(), keys.end(), rng); if (!expireItem(it->second, now)) return false; if (it->second.empty()) keys.erase(it); return true; } void DistributedDiscovery:: rotateConnections() { size_t targetSize = lockless::log2(nodes.size()); size_t disconnects = lockless::log2(targetSize); if (connections.size() - disconnects > targetSize) disconnects = connections.size() - targetSize; std::set<ConnectionHandle> toDisconnect; if (disconnects >= connections.size()) { for (const auto& conn : connections) toDisconnect.insert(conn.second.handle); } else { for (size_t i = 0; i < disconnects; ++i) { std::uniform_int_distribution<size_t> dist(0, connections.size() -1); auto it = connections.begin(); std::advance(it, dist(rng)); toDisconnect.insert(it->second.handle); } } // Need to defer the call because the call could invalidate our connection // iterator through our onLostConnection callback. for (auto conn : toDisconnect) endpoint.disconnect(conn); size_t connects = targetSize - connections.size(); auto picks = pickRandom<Item>(nodes.begin(), nodes.end(), connects, rng); for (const auto& node : picks) endpoint.connect(node.addrs); } } // slick <commit_msg>Tweaked the period calc.<commit_after>/* discovery.cpp -*- C++ -*- Rémi Attab (remi.attab@gmail.com), 26 Dec 2013 FreeBSD-style copyright and disclaimer apply Implementation of the node discovery database. */ #include "discovery.h" #include "pack.h" #include "lockless/bits.h" #include <set> #include <vector> #include <algorithm> #include <functional> namespace slick { /******************************************************************************/ /* UTILS */ /******************************************************************************/ template<typename It, typename Rng> It pickRandom(It it, It last, Rng& rng) { std::uniform_int_distribution<size_t> dist(std::distance(it, last) - 1); std::advance(it, dist(rng)); return it; } template<typename T, typename It, typename Rng> std::set<T> pickRandom(It first, It last, size_t n, Rng& rng) { std::set<T> result; while (result.size() < n) result.insert(*pickRandom(first, last, rng)); return std::move(result); } /******************************************************************************/ /* WATCH */ /******************************************************************************/ DistributedDiscovery::Watch:: Watch(WatchFn watch) : watch(std::move(watch)) { static std::atomic<WatchHandle> handleCounter{0}; handle = ++handleCounter; } /******************************************************************************/ /* PROTOCOL */ /******************************************************************************/ namespace msg { static const std::string Init = "_slick_disc_"; static constexpr uint32_t Version = 1; typedef uint16_t Type; static constexpr Type Keys = 1; static constexpr Type Query = 2; static constexpr Type Nodes = 3; static constexpr Type Fetch = 4; static constexpr Type Data = 5; } // namespace msg /******************************************************************************/ /* DISTRIBUTED DISCOVERY */ /******************************************************************************/ size_t DistributedDiscovery:: timerPeriod() { enum { BasePeriod = 60 }; size_t min = BasePeriod / 2, max = min + BasePeriod; return std::uniform_int_distribution<size_t> dist(min, max)(rng); } DistributedDiscovery:: DistributedDiscovery(const std::vector<Address>& seed, Port port) : keyTTL_(DefaultKeyTTL), nodeTTL_(DefaultNodeTTL), myId(UUID::random()), rng(lockless::wall()), endpoint(port), timer(timerPeriod()) { myNode = endpoint.interfaces(); double now = lockless::wall(); for (auto& addr : seed) nodes.emplace(UUID::random(), NodeLocation({addr}), SeedTTL, now); using namespace std::placeholders; endpoint.onPayload = bind(&DistributedDiscovery::onPayload, this, _1, _2); endpoint.onNewConnection = bind(&DistributedDiscovery::onConnect, this, _1); endpoint.onLostConnection = bind(&DistributedDiscovery::onDisconnect, this, _1); poller.add(endpoint); retracts.onOperation = std::bind(&DistributedDiscovery::retract, this, _1); poller.add(retracts); publishes.onOperation = std::bind(&DistributedDiscovery::publish, this, _1, _2); poller.add(publishes); typedef void (DistributedDiscovery::*DiscoverFn) (const std::string&, Watch&&); DiscoverFn discoverFn = &DistributedDiscovery::discover; discovers.onOperation = std::bind(discoverFn, this, _1, _2); poller.add(discovers); forgets.onOperation = std::bind(&DistributedDiscovery::forget, this, _1, _2); poller.add(forgets); timer.onTimer = bind(&DistributedDiscovery::onTimer, this, _1); poller.add(timer); } void DistributedDiscovery:: poll() { isPollThread.set(); poller.poll(); } void DistributedDiscovery:: shutdown() { isPollThread.unset(); retracts.poll(); publishes.poll(); discovers.poll(); forgets.poll(); } void DistributedDiscovery:: onPayload(ConnectionHandle handle, Payload&& data) { auto& conn = connections[handle]; auto it = data.cbegin(), last = data.cend(); if (!conn) it = onInit(conn, it, last); while (it != last) { msg::Type type; it = unpack(type, it, last); switch(type) { case msg::Keys: it = onKeys(conn, it, last); break; case msg::Query: it = onQuery(conn, it, last); break; case msg::Nodes: it = onNodes(conn, it, last); break; case msg::Fetch: it = onFetch(conn, it, last); break; case msg::Data: it = onData(conn, it, last); break; default: assert(false); }; } } Discovery::WatchHandle DistributedDiscovery:: discover(const std::string& key, const WatchFn& fn) { Watch watch(fn); auto handle = watch.handle; discover(key, std::move(watch)); return handle; } void DistributedDiscovery:: discover(const std::string& key, Watch&& watch) { if (!isPollThread()) { discovers.defer(key, watch); return; } if (!watches.count(key)) { std::vector<QueryItem> items = { key }; endpoint.broadcast(packAll(msg::Query, myNode, items)); } watches[key].insert(std::move(watch)); for (const auto& node : keys[key]) doFetch(key, node.id, node.addrs); } void DistributedDiscovery:: forget(const std::string& key, WatchHandle handle) { if (!isPollThread()) { forgets.defer(key, handle); return; } auto& list = watches[key]; list.erase(Watch(handle)); if (list.empty()) watches.erase(key); } void DistributedDiscovery:: publish(const std::string& key, Payload&& data) { if (!isPollThread()) { publishes.defer(key, std::move(data)); return; } this->data[key] = Data(std::move(data)); std::vector<KeyItem> items; items.emplace_back(key, myId, myNode, keyTTL_); endpoint.broadcast(packAll(msg::Keys, items)); } void DistributedDiscovery:: retract(const std::string& key) { if (!isPollThread()) { retracts.defer(key); return; } data.erase(key); } void DistributedDiscovery:: onConnect(ConnectionHandle handle) { auto& conn = connections[handle]; conn.handle = handle; auto head = std::make_tuple(msg::Init, msg::Version); Payload data; if (conn.pendingFetch.empty()) data = pack(head); else { data = packAll(head, msg::Fetch, conn.pendingFetch); conn.pendingFetch.clear(); } endpoint.send(handle, std::move(data)); } void DistributedDiscovery:: onDisconnect(ConnectionHandle handle) { connections.erase(handle); } ConstPackIt DistributedDiscovery:: onInit(ConnState& conn, ConstPackIt it, ConstPackIt last) { std::string init; it = unpackAll(it, last, init, conn.version); if (init != msg::Init) { endpoint.disconnect(conn.handle); return last; } assert(conn.version == msg::Version); if (!data.empty()) { std::vector<KeyItem> items; items.reserve(data.size()); for (const auto& key : data) items.emplace_back(key.first, key.second.id, myNode, keyTTL_); endpoint.send(conn.handle, packAll(msg::Keys, items)); } if (!watches.empty()) { std::vector<QueryItem> items; items.reserve(watches.size()); for (const auto& watch : watches) items.emplace_back(watch.first); auto msg = packAll(msg::Query, myNode, items); endpoint.send(conn.handle, std::move(msg)); } if (!nodes.empty()) { double now = lockless::wall(); size_t numPicks = lockless::log2(nodes.size()); std::vector<NodeItem> items; items.reserve(numPicks + 1); items.emplace_back(myId, myNode, nodeTTL_); auto picks = pickRandom<Item>(nodes.begin(), nodes.end(), numPicks, rng); for (const auto& node : picks) { size_t ttl = node.ttl(now); if (!ttl) continue; items.emplace_back(node.id, node.addrs, ttl); } endpoint.send(conn.handle, packAll(msg::Nodes, items)); } return it; } ConstPackIt DistributedDiscovery:: onKeys(ConnState&, ConstPackIt it, ConstPackIt last) { std::vector<KeyItem> items; it = unpack(items, it, last); std::vector<KeyItem> toForward; toForward.reserve(items.size()); double now = lockless::wall(); for (auto& item : items) { std::string key = std::move(std::get<0>(item)); Item value(std::move(item), now); auto& list = keys[key]; auto it = list.find(value); if (it != list.end()) { it->setTTL(value.ttl(now), now); continue; } if (watches.count(key)) doFetch(key, value.id, value.addrs); toForward.emplace_back(key, value.id, value.addrs, value.ttl(now)); list.insert(std::move(value)); } if (!toForward.empty()) endpoint.broadcast(packAll(msg::Keys, toForward)); return it; } ConstPackIt DistributedDiscovery:: onQuery(ConnState& conn, ConstPackIt it, ConstPackIt last) { NodeLocation node; std::vector<QueryItem> items; it = unpackAll(it, last, node, items); std::vector<KeyItem> reply; reply.reserve(items.size()); double now = lockless::wall(); for (const auto& key : items) { auto it = keys.find(key); if (it == keys.end()) continue; for (const auto& node : it->second) { if (!node.ttl(now)) continue; reply.emplace_back(key, node.id, node.addrs, node.ttl(now)); } } if (!reply.empty()) endpoint.send(conn.handle, packAll(msg::Keys, reply)); return it; } ConstPackIt DistributedDiscovery:: onNodes(ConnState&, ConstPackIt it, ConstPackIt last) { std::vector<NodeItem> items; it = unpack(items, it, last); std::vector<NodeItem> toForward; toForward.reserve(items.size()); double now = lockless::wall(); for (auto& item : items) { Item value(std::move(item), now); auto it = nodes.find(value); if (it != nodes.end()) { it->setTTL(value.ttl(now), now); continue; } toForward.emplace_back(value.id, value.addrs, value.ttl(now)); nodes.insert(std::move(value)); } if (!toForward.empty()) endpoint.broadcast(packAll(msg::Nodes, toForward)); return it; } void DistributedDiscovery:: doFetch(const std::string& key, const UUID& id, const NodeLocation& node) { auto socket = Socket::connect(node); if (!socket) return; ConnectionHandle handle = socket.fd(); connections[handle].pendingFetch.emplace_back(key, id); ConnectionHandle sameHandle = endpoint.connect(std::move(socket)); assert(handle == sameHandle); } ConstPackIt DistributedDiscovery:: onFetch(ConnState& conn, ConstPackIt it, ConstPackIt last) { std::vector<FetchItem> items; it = unpack(items, it, last); std::vector<DataItem> reply; reply.reserve(items.size()); for (auto& item : items) { std::string key; UUID id; std::tie(key, id) = std::move(item); auto it = data.find(key); if (it == data.end() || it->second.id != id) continue; reply.emplace_back(key, it->second.data); } if (!reply.empty()) endpoint.send(conn.handle, packAll(msg::Data, reply)); return it; } ConstPackIt DistributedDiscovery:: onData(ConnState&, ConstPackIt it, ConstPackIt last) { std::vector<DataItem> items; it = unpack(items, it, last); for (auto& item : items) { std::string key; Payload payload; std::tie(key, payload) = std::move(item); auto it = watches.find(key); if (it == watches.end()) continue; for (const auto& watch : it->second) watch.watch(watch.handle, payload); } return it; } void DistributedDiscovery:: onTimer(size_t) { double now = lockless::wall(); while(!nodes.empty() && expireItem(nodes, now)); while(!keys.empty() && expireKeys(now)); rotateConnections(); } bool DistributedDiscovery:: expireItem(SortedVector<Item>& list, double now) { assert(!list.empty()); auto it = pickRandom(list.begin(), list.end(), rng); if (it->ttl(now)) return false; list.erase(it); return true; } bool DistributedDiscovery:: expireKeys(double now) { assert(!keys.empty()); auto it = pickRandom(keys.begin(), keys.end(), rng); if (!expireItem(it->second, now)) return false; if (it->second.empty()) keys.erase(it); return true; } void DistributedDiscovery:: rotateConnections() { size_t targetSize = lockless::log2(nodes.size()); size_t disconnects = lockless::log2(targetSize); if (connections.size() - disconnects > targetSize) disconnects = connections.size() - targetSize; std::set<ConnectionHandle> toDisconnect; if (disconnects >= connections.size()) { for (const auto& conn : connections) toDisconnect.insert(conn.second.handle); } else { for (size_t i = 0; i < disconnects; ++i) { std::uniform_int_distribution<size_t> dist(0, connections.size() -1); auto it = connections.begin(); std::advance(it, dist(rng)); toDisconnect.insert(it->second.handle); } } // Need to defer the call because the call could invalidate our connection // iterator through our onLostConnection callback. for (auto conn : toDisconnect) endpoint.disconnect(conn); size_t connects = targetSize - connections.size(); auto picks = pickRandom<Item>(nodes.begin(), nodes.end(), connects, rng); for (const auto& node : picks) endpoint.connect(node.addrs); } } // slick <|endoftext|>
<commit_before>#include "std.h" #include "path.h" #include "system.h" #include "sync.h" #include "hash.h" #ifdef WINDOWS #include <direct.h> #include <Shlwapi.h> #include <Shlobj.h> #pragma comment(lib, "shlwapi.lib") #pragma comment(lib, "shell32.lib") static bool partEq(const String &a, const String &b) { return _stricmp(a.c_str(), b.c_str()) == 0; } static int partCmp(const String &a, const String &b) { return _stricmp(a.c_str(), b.c_str()); } static size_t partHash(const String &part) { size_t r = 5381; for (nat i = 0; i < part.size(); i++) r = ((r << 5) + r) + tolower(part[i]); return r; } static const char separator = '\\'; static const char *separatorStr = "\\"; #else #include <cstring> #include <unistd.h> #include <dirent.h> #include <sys/types.h> #include <sys/stat.h> static bool partEq(const String &a, const String &b) { return a == b; } static int partCmp(const String &a, const String &b) { return strcmp(a.c_str(), b.c_str()); } static size_t partHash(const String &part) { size_t r = 5381; for (nat i = 0; i < part.size(); i++) r = ((r << 5) + r) + part[i]; return r; } static const char separator = '/'; static const char *separatorStr = "/"; #endif ////////////////////////////////////////////////////////////////////////// // The Path class ////////////////////////////////////////////////////////////////////////// #ifdef WINDOWS Path Path::cwd() { char tmp[MAX_PATH + 1]; _getcwd(tmp, MAX_PATH + 1); Path r(tmp); r.makeDir(); return r; } Path Path::home() { char tmp[MAX_PATH + 1] = { 0 }; SHGetFolderPath(NULL, CSIDL_PROFILE, NULL, 0, tmp); Path r(tmp); r.makeDir(); return r; } void Path::deleteFile() const { DeleteFile(toS(*this).c_str()); } void Path::deleteDir() const { RemoveDirectory(toS(*this).c_str()); } bool Path::isAbsolute() const { if (parts.size() == 0) return false; const String &first = parts.front(); if (first.size() < 2) return false; return first[1] == L':'; } vector<Path> Path::children() const { vector<Path> result; String searchStr = toS(*this); if (!isDir()) searchStr += "\\"; searchStr += "*"; WIN32_FIND_DATA findData; HANDLE h = FindFirstFile(searchStr.c_str(), &findData); if (h == INVALID_HANDLE_VALUE) return result; do { if (strcmp(findData.cFileName, "..") != 0 && strcmp(findData.cFileName, ".") != 0) { result.push_back(*this + findData.cFileName); if (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) result.back().makeDir(); } } while (FindNextFile(h, &findData)); FindClose(h); return result; } void Path::createDir() const { if (exists()) return; if (isEmpty()) return; parent().createDir(); CreateDirectory(toS(*this).c_str(), NULL); } Timestamp fromFileTime(FILETIME ft); FileInfo Path::info() const { FileInfo result(false); HANDLE hFile = CreateFile(toS(*this).c_str(), 0, /* We only want metadata */ FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE, /* Allow access to others */ NULL, /* Security attributes */ OPEN_EXISTING, /* Action if not existing */ FILE_ATTRIBUTE_NORMAL, NULL /* Template file */); if (hFile != INVALID_HANDLE_VALUE) { result.exists = true; FILETIME cTime, mTime; if (GetFileTime(hFile, &cTime, NULL, &mTime) == TRUE) { result.mTime = fromFileTime(mTime); result.cTime = fromFileTime(cTime); } else { // This is likely an implementation bug. WARNING("Failed to retrieve file times for file " << *this); } CloseHandle(hFile); } return result; } // We can do exists() cheaper than stat() on Windows. bool Path::exists() const { return GetFileAttributes(toS(*this).c_str()) != INVALID_FILE_ATTRIBUTES; } #else Path Path::cwd() { char tmp[512] = { 0 }; if (!getcwd(tmp, 512)) WARNING("Failed to get cwd!"); Path r(tmp); r.makeDir(); return r; } Path Path::home() { Path r(getenv("HOME")); r.makeDir(); return r; } void Path::deleteFile() const { unlink(toS(*this).c_str()); } void Path::deleteDir() const { rmdir(toS(*this).c_str()); } bool Path::isAbsolute() const { if (parts.size() == 0) return false; return parts.front().empty(); } vector<Path> Path::children() const { vector<Path> result; DIR *h = opendir(toS(*this).c_str()); if (h == null) return result; dirent *d; struct stat s; while ((d = readdir(h)) != null) { if (strcmp(d->d_name, "..") != 0 && strcmp(d->d_name, ".") != 0) { result.push_back(*this + d->d_name); if (stat(toS(result.back()).c_str(), &s) == 0) { if (S_ISDIR(s.st_mode)) result.back().makeDir(); } else { result.pop_back(); } } } closedir(h); return result; } void Path::createDir() const { if (exists()) return; if (isEmpty()) return; parent().createDir(); mkdir(toS(*this).c_str(), 0777); } Timestamp fromFileTime(time_t); FileInfo Path::info() const { FileInfo result(false); struct stat s; if (stat(toS(*this).c_str(), &s) == 0) { result.exists = true; result.mTime = fromFileTime(s.st_mtime); result.cTime = fromFileTime(s.st_ctime); } return result; } bool Path::exists() const { return fileInfo(*this).exists; } #endif Timestamp Path::mTime() const { return info().mTime; } Timestamp Path::cTime() const { return info().cTime; } bool Path::equal(const String &a, const String &b) { return partEq(a, b); } Path::Path(const String &path) : isDirectory(false) { parseStr(path); simplify(); } Path::Path() : isDirectory(false) {} void Path::parseStr(const String &str) { if (str.empty()) return; nat numPaths = std::count(str.begin(), str.end(), '\\'); numPaths += std::count(str.begin(), str.end(), '/'); parts.reserve(numPaths + 1); if (str[0] == '\\' || str[0] == '/') parts.push_back(""); nat startAt = 0; for (nat i = 0; i < str.size(); i++) { if (str[i] == '\\' || str[i] == '/') { if (i > startAt) { parts.push_back(str.substr(startAt, i - startAt)); } startAt = i + 1; } } if (str.size() > startAt) { parts.push_back(str.substr(startAt)); isDirectory = false; } else { isDirectory = true; } } void Path::simplify() { vector<String>::iterator i = parts.begin(); while (i != parts.end()) { if (*i == ".") { // Safely removed. i = parts.erase(i); } else if (*i == ".." && i != parts.begin() && *(i - 1) != "..") { // Remove previous path. i = parts.erase(--i); i = parts.erase(i); } else { // Nothing to do, continue. ++i; } } } std::ostream &operator <<(std::ostream &to, const Path &path) { join(to, path.parts, separatorStr); if (path.parts.empty()) to << '.'; if (path.isDir()) to << separatorStr; return to; } bool Path::operator ==(const Path &o) const { if (isDirectory != o.isDirectory) return false; if (parts.size() != o.parts.size()) return false; for (nat i = 0; i < parts.size(); i++) if (!partEq(parts[i], o.parts[i])) return false; return true; } bool Path::operator <(const Path &o) const { for (nat i = 0; i < parts.size(); i++) { if (o.parts.size() <= i) return false; int r = partCmp(parts[i], o.parts[i]); if (r != 0) return r < 0; } if (parts.size() < o.parts.size()) return true; if (isDirectory != o.isDirectory) return o.isDirectory; return false; } bool Path::operator >(const Path &o) const { return o < *this; } size_t Path::hash() const { // djb2-inspired hash size_t r = 5381; for (nat i = 0; i < parts.size(); i++) r = ((r << 5) + r) + partHash(parts[i]); return r; } Path Path::operator +(const Path &other) const { Path result(*this); result += other; return result; } Path &Path::operator +=(const Path &other) { assert(!other.isAbsolute()); isDirectory = other.isDirectory; parts.insert(parts.end(), other.parts.begin(), other.parts.end()); simplify(); return *this; } Path Path::operator +(const String &name) const { Path result(*this); result += name; return result; } Path &Path::operator +=(const String &name) { parts.push_back(name); isDirectory = false; return *this; } Path Path::parent() const { Path result(*this); result.parts.pop_back(); result.isDirectory = true; return result; } String Path::first() const { return parts.front(); } String Path::title() const { return parts.back(); } String Path::titleNoExt() const { String t = title(); nat last = t.rfind('.'); return t.substr(0, last); } String Path::ext() const { String t = title(); nat p = t.rfind('.'); if (p == String::npos) return ""; else return t.substr(p + 1); } void Path::makeExt(const String &str) { if (str.empty()) { parts.back() = titleNoExt(); } else { parts.back() = titleNoExt() + "." + str; } } void Path::makeTitle(const String &str) { parts.back() = str; } bool Path::isDir() const { return isDirectory; } bool Path::isEmpty() const { return parts.size() == 0; } Path Path::makeRelative(const Path &to) const { Path result; result.isDirectory = isDirectory; bool equal = true; nat consumed = 0; for (nat i = 0; i < to.parts.size(); i++) { if (!equal) { result.parts.push_back(".."); } else if (i >= parts.size()) { result.parts.push_back(".."); equal = false; } else if (!partEq(to.parts[i], parts[i])) { result.parts.push_back(".."); equal = false; } else { consumed++; } } for (nat i = consumed; i < parts.size(); i++) { result.parts.push_back(parts[i]); } return result; } Path Path::makeAbsolute() const { return makeAbsolute(Path::cwd()); } Path Path::makeAbsolute(const Path &to) const { if (isAbsolute()) return *this; return to + *this; } bool Path::isChild(const Path &path) const { if (parts.size() <= path.parts.size()) return false; for (nat i = 0; i < path.parts.size(); i++) { if (!partEq(parts[i], path.parts[i])) return false; } return true; } void Path::recursiveDelete() const { if (!exists()) return; if (isDir()) { vector<Path> sub = children(); for (nat i = 0; i < sub.size(); i++) { sub[i].recursiveDelete(); } deleteDir(); } else { deleteFile(); } } <commit_msg>Simplified the hash functions in Path a bit.<commit_after>#include "std.h" #include "path.h" #include "system.h" #include "sync.h" #include "hash.h" #ifdef WINDOWS #include <direct.h> #include <Shlwapi.h> #include <Shlobj.h> #pragma comment(lib, "shlwapi.lib") #pragma comment(lib, "shell32.lib") static bool partEq(const String &a, const String &b) { return _stricmp(a.c_str(), b.c_str()) == 0; } static int partCmp(const String &a, const String &b) { return _stricmp(a.c_str(), b.c_str()); } static void partHash(size_t &state, const String &part) { for (nat i = 0; i < part.size(); i++) state = ((state << 5) + state) + tolower(part[i]); } static const char separator = '\\'; static const char *separatorStr = "\\"; #else #include <cstring> #include <unistd.h> #include <dirent.h> #include <sys/types.h> #include <sys/stat.h> static bool partEq(const String &a, const String &b) { return a == b; } static int partCmp(const String &a, const String &b) { return strcmp(a.c_str(), b.c_str()); } static size_t partHash(size_t &state, const String &part) { for (nat i = 0; i < part.size(); i++) state = ((state << 5) + state) + part[i]; return r; } static const char separator = '/'; static const char *separatorStr = "/"; #endif ////////////////////////////////////////////////////////////////////////// // The Path class ////////////////////////////////////////////////////////////////////////// #ifdef WINDOWS Path Path::cwd() { char tmp[MAX_PATH + 1]; _getcwd(tmp, MAX_PATH + 1); Path r(tmp); r.makeDir(); return r; } Path Path::home() { char tmp[MAX_PATH + 1] = { 0 }; SHGetFolderPath(NULL, CSIDL_PROFILE, NULL, 0, tmp); Path r(tmp); r.makeDir(); return r; } void Path::deleteFile() const { DeleteFile(toS(*this).c_str()); } void Path::deleteDir() const { RemoveDirectory(toS(*this).c_str()); } bool Path::isAbsolute() const { if (parts.size() == 0) return false; const String &first = parts.front(); if (first.size() < 2) return false; return first[1] == L':'; } vector<Path> Path::children() const { vector<Path> result; String searchStr = toS(*this); if (!isDir()) searchStr += "\\"; searchStr += "*"; WIN32_FIND_DATA findData; HANDLE h = FindFirstFile(searchStr.c_str(), &findData); if (h == INVALID_HANDLE_VALUE) return result; do { if (strcmp(findData.cFileName, "..") != 0 && strcmp(findData.cFileName, ".") != 0) { result.push_back(*this + findData.cFileName); if (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) result.back().makeDir(); } } while (FindNextFile(h, &findData)); FindClose(h); return result; } void Path::createDir() const { if (exists()) return; if (isEmpty()) return; parent().createDir(); CreateDirectory(toS(*this).c_str(), NULL); } Timestamp fromFileTime(FILETIME ft); FileInfo Path::info() const { FileInfo result(false); HANDLE hFile = CreateFile(toS(*this).c_str(), 0, /* We only want metadata */ FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE, /* Allow access to others */ NULL, /* Security attributes */ OPEN_EXISTING, /* Action if not existing */ FILE_ATTRIBUTE_NORMAL, NULL /* Template file */); if (hFile != INVALID_HANDLE_VALUE) { result.exists = true; FILETIME cTime, mTime; if (GetFileTime(hFile, &cTime, NULL, &mTime) == TRUE) { result.mTime = fromFileTime(mTime); result.cTime = fromFileTime(cTime); } else { // This is likely an implementation bug. WARNING("Failed to retrieve file times for file " << *this); } CloseHandle(hFile); } return result; } // We can do exists() cheaper than stat() on Windows. bool Path::exists() const { return GetFileAttributes(toS(*this).c_str()) != INVALID_FILE_ATTRIBUTES; } #else Path Path::cwd() { char tmp[512] = { 0 }; if (!getcwd(tmp, 512)) WARNING("Failed to get cwd!"); Path r(tmp); r.makeDir(); return r; } Path Path::home() { Path r(getenv("HOME")); r.makeDir(); return r; } void Path::deleteFile() const { unlink(toS(*this).c_str()); } void Path::deleteDir() const { rmdir(toS(*this).c_str()); } bool Path::isAbsolute() const { if (parts.size() == 0) return false; return parts.front().empty(); } vector<Path> Path::children() const { vector<Path> result; DIR *h = opendir(toS(*this).c_str()); if (h == null) return result; dirent *d; struct stat s; while ((d = readdir(h)) != null) { if (strcmp(d->d_name, "..") != 0 && strcmp(d->d_name, ".") != 0) { result.push_back(*this + d->d_name); if (stat(toS(result.back()).c_str(), &s) == 0) { if (S_ISDIR(s.st_mode)) result.back().makeDir(); } else { result.pop_back(); } } } closedir(h); return result; } void Path::createDir() const { if (exists()) return; if (isEmpty()) return; parent().createDir(); mkdir(toS(*this).c_str(), 0777); } Timestamp fromFileTime(time_t); FileInfo Path::info() const { FileInfo result(false); struct stat s; if (stat(toS(*this).c_str(), &s) == 0) { result.exists = true; result.mTime = fromFileTime(s.st_mtime); result.cTime = fromFileTime(s.st_ctime); } return result; } bool Path::exists() const { return fileInfo(*this).exists; } #endif Timestamp Path::mTime() const { return info().mTime; } Timestamp Path::cTime() const { return info().cTime; } bool Path::equal(const String &a, const String &b) { return partEq(a, b); } Path::Path(const String &path) : isDirectory(false) { parseStr(path); simplify(); } Path::Path() : isDirectory(false) {} void Path::parseStr(const String &str) { if (str.empty()) return; nat numPaths = std::count(str.begin(), str.end(), '\\'); numPaths += std::count(str.begin(), str.end(), '/'); parts.reserve(numPaths + 1); if (str[0] == '\\' || str[0] == '/') parts.push_back(""); nat startAt = 0; for (nat i = 0; i < str.size(); i++) { if (str[i] == '\\' || str[i] == '/') { if (i > startAt) { parts.push_back(str.substr(startAt, i - startAt)); } startAt = i + 1; } } if (str.size() > startAt) { parts.push_back(str.substr(startAt)); isDirectory = false; } else { isDirectory = true; } } void Path::simplify() { vector<String>::iterator i = parts.begin(); while (i != parts.end()) { if (*i == ".") { // Safely removed. i = parts.erase(i); } else if (*i == ".." && i != parts.begin() && *(i - 1) != "..") { // Remove previous path. i = parts.erase(--i); i = parts.erase(i); } else { // Nothing to do, continue. ++i; } } } std::ostream &operator <<(std::ostream &to, const Path &path) { join(to, path.parts, separatorStr); if (path.parts.empty()) to << '.'; if (path.isDir()) to << separatorStr; return to; } bool Path::operator ==(const Path &o) const { if (isDirectory != o.isDirectory) return false; if (parts.size() != o.parts.size()) return false; for (nat i = 0; i < parts.size(); i++) if (!partEq(parts[i], o.parts[i])) return false; return true; } bool Path::operator <(const Path &o) const { for (nat i = 0; i < parts.size(); i++) { if (o.parts.size() <= i) return false; int r = partCmp(parts[i], o.parts[i]); if (r != 0) return r < 0; } if (parts.size() < o.parts.size()) return true; if (isDirectory != o.isDirectory) return o.isDirectory; return false; } bool Path::operator >(const Path &o) const { return o < *this; } size_t Path::hash() const { // djb2-inspired hash size_t r = 5381; for (nat i = 0; i < parts.size(); i++) { partHash(r, parts[i]); r = ((r << 5) + r) + '/'; // To differentiate between different divisions of slashes. } return r; } Path Path::operator +(const Path &other) const { Path result(*this); result += other; return result; } Path &Path::operator +=(const Path &other) { assert(!other.isAbsolute()); isDirectory = other.isDirectory; parts.insert(parts.end(), other.parts.begin(), other.parts.end()); simplify(); return *this; } Path Path::operator +(const String &name) const { Path result(*this); result += name; return result; } Path &Path::operator +=(const String &name) { parts.push_back(name); isDirectory = false; return *this; } Path Path::parent() const { Path result(*this); result.parts.pop_back(); result.isDirectory = true; return result; } String Path::first() const { return parts.front(); } String Path::title() const { return parts.back(); } String Path::titleNoExt() const { String t = title(); nat last = t.rfind('.'); return t.substr(0, last); } String Path::ext() const { String t = title(); nat p = t.rfind('.'); if (p == String::npos) return ""; else return t.substr(p + 1); } void Path::makeExt(const String &str) { if (str.empty()) { parts.back() = titleNoExt(); } else { parts.back() = titleNoExt() + "." + str; } } void Path::makeTitle(const String &str) { parts.back() = str; } bool Path::isDir() const { return isDirectory; } bool Path::isEmpty() const { return parts.size() == 0; } Path Path::makeRelative(const Path &to) const { Path result; result.isDirectory = isDirectory; bool equal = true; nat consumed = 0; for (nat i = 0; i < to.parts.size(); i++) { if (!equal) { result.parts.push_back(".."); } else if (i >= parts.size()) { result.parts.push_back(".."); equal = false; } else if (!partEq(to.parts[i], parts[i])) { result.parts.push_back(".."); equal = false; } else { consumed++; } } for (nat i = consumed; i < parts.size(); i++) { result.parts.push_back(parts[i]); } return result; } Path Path::makeAbsolute() const { return makeAbsolute(Path::cwd()); } Path Path::makeAbsolute(const Path &to) const { if (isAbsolute()) return *this; return to + *this; } bool Path::isChild(const Path &path) const { if (parts.size() <= path.parts.size()) return false; for (nat i = 0; i < path.parts.size(); i++) { if (!partEq(parts[i], path.parts[i])) return false; } return true; } void Path::recursiveDelete() const { if (!exists()) return; if (isDir()) { vector<Path> sub = children(); for (nat i = 0; i < sub.size(); i++) { sub[i].recursiveDelete(); } deleteDir(); } else { deleteFile(); } } <|endoftext|>
<commit_before>#include <stdlib.h> #include <iostream> #include <vector> #include <unistd.h> #include <dirent.h> #include "omp.h" void helpCheck(char *argv[]) { if (argv[1] == std::string("-h") || argv[1] == std::string("--help")) { std::cout << "\nptxv - Parallel Tar XZ by Ryan Chui (2017)\n" << std::endl; exit(0); } } void findAll(int *numFiles, const char *cwd) { DIR *dir; struct dirent *ent; // Check if cwd is a directory if ((dir = opendir(cwd)) != NULL) { // Get all file paths within directory. while ((ent = readdir (dir)) != NULL) { std::string fileBuff = std::string(ent -> d_name); if (fileBuff != "." && fileBuff != "..") { DIR *dir2; std::string filePath = std::string(cwd) + "/" + fileBuff; // Check if file path is a directory. if ((dir2 = opendir(filePath.c_str())) != NULL) { closedir(dir2); findAll(numFiles, filePath.c_str()); } else { *numFiles += 1; } } } closedir(dir); } } void getPaths(std::vector<std::string> *filePaths, const char *cwd, std::string rootPath) { DIR *dir; struct dirent *ent; // Check if cwd is a directory if ((dir = opendir(cwd)) != NULL) { // Get all file paths within directory. while ((ent = readdir (dir)) != NULL) { std::string fileBuff = std::string(ent -> d_name); if (fileBuff != "." && fileBuff != "..") { DIR *dir2; std::string filePath = std::string(cwd) + "/" + fileBuff; // Check if file path is a directory. if ((dir2 = opendir(filePath.c_str())) != NULL) { closedir(dir2); getPaths(filePaths, filePath.c_str(), rootPath + fileBuff + "/"); } else { filePaths->push_back(rootPath + fileBuff); } } } closedir(dir); } } void compress(std::vector<std::string> *filePaths) { // #pragma omp parallel for schedule(dynamic) for (int i = 0; i < filePaths->size(); ++i) { std::cout << filePaths->at(i) << std::endl; std::string command = "XZ_OPT=-9 tar cJvf test." + std::to_string(i) + ".tar.xz " + filePaths->at(i); system(command.c_str()); } } char cwd [PATH_MAX]; int main(int argc, char *argv[]) { int *numFiles = new int(0); if (argc > 1) { helpCheck(argv); } getcwd(cwd, PATH_MAX); findAll(numFiles, cwd); // std::cout << *numFiles << std::endl; std::vector<std::string> *filePaths = new std::vector<std::string>(); getPaths(filePaths, cwd, ""); compress(filePaths); delete(numFiles); return 0; } <commit_msg>Adding parallelism<commit_after>#include <stdlib.h> #include <iostream> #include <vector> #include <unistd.h> #include <dirent.h> #include "omp.h" void helpCheck(char *argv[]) { if (argv[1] == std::string("-h") || argv[1] == std::string("--help")) { std::cout << "\nptxv - Parallel Tar XZ by Ryan Chui (2017)\n" << std::endl; exit(0); } } void findAll(int *numFiles, const char *cwd) { DIR *dir; struct dirent *ent; // Check if cwd is a directory if ((dir = opendir(cwd)) != NULL) { // Get all file paths within directory. while ((ent = readdir (dir)) != NULL) { std::string fileBuff = std::string(ent -> d_name); if (fileBuff != "." && fileBuff != "..") { DIR *dir2; std::string filePath = std::string(cwd) + "/" + fileBuff; // Check if file path is a directory. if ((dir2 = opendir(filePath.c_str())) != NULL) { closedir(dir2); findAll(numFiles, filePath.c_str()); } else { *numFiles += 1; } } } closedir(dir); } } void getPaths(std::vector<std::string> *filePaths, const char *cwd, std::string rootPath) { DIR *dir; struct dirent *ent; // Check if cwd is a directory if ((dir = opendir(cwd)) != NULL) { // Get all file paths within directory. while ((ent = readdir (dir)) != NULL) { std::string fileBuff = std::string(ent -> d_name); if (fileBuff != "." && fileBuff != "..") { DIR *dir2; std::string filePath = std::string(cwd) + "/" + fileBuff; // Check if file path is a directory. if ((dir2 = opendir(filePath.c_str())) != NULL) { closedir(dir2); getPaths(filePaths, filePath.c_str(), rootPath + fileBuff + "/"); } else { filePaths->push_back(rootPath + fileBuff); } } } closedir(dir); } } void compress(std::vector<std::string> *filePaths) { #pragma omp parallel for schedule(dynamic) for (int i = 0; i < filePaths->size(); ++i) { std::cout << filePaths->at(i) << std::endl; std::string command = "XZ_OPT=-9 tar cJvf test." + std::to_string(i) + ".tar.xz " + filePaths->at(i); system(command.c_str()); } } char cwd [PATH_MAX]; int main(int argc, char *argv[]) { int *numFiles = new int(0); if (argc > 1) { helpCheck(argv); } getcwd(cwd, PATH_MAX); findAll(numFiles, cwd); // std::cout << *numFiles << std::endl; std::vector<std::string> *filePaths = new std::vector<std::string>(); getPaths(filePaths, cwd, ""); compress(filePaths); delete(numFiles); return 0; } <|endoftext|>
<commit_before>#include <stdlib.h> #include <iostream> #include <vector> #include <unistd.h> #include <dirent.h> #include "omp.h" void helpCheck(char *argv[]) { if (argv[1] == std::string("-h") || argv[1] == std::string("--help")) { std::cout << "\nptxv - Parallel Tar XZ by Ryan Chui (2017)\n" << std::endl; exit(0); } } void findAll(int *numFiles, const char *cwd) { DIR *dir; struct dirent *ent; // Check if cwd is a directory if ((dir = opendir(cwd)) != NULL) { // Get all file paths within directory. while ((ent = readdir (dir)) != NULL) { std::string fileBuff = std::string(ent -> d_name); if (fileBuff != "." && fileBuff != "..") { DIR *dir2; std::string filePath = std::string(cwd) + "/" + fileBuff; // Check if file path is a directory. if ((dir2 = opendir(filePath.c_str())) != NULL) { closedir(dir2); findAll(numFiles, filePath.c_str()); } else { *numFiles += 1; } } } closedir(dir); } } void getPaths(std::vector<std::string> *filePaths, const char *cwd, std::string rootPath) { DIR *dir; struct dirent *ent; // Check if cwd is a directory if ((dir = opendir(cwd)) != NULL) { // Get all file paths within directory. while ((ent = readdir (dir)) != NULL) { std::string fileBuff = std::string(ent -> d_name); if (fileBuff != "." && fileBuff != "..") { DIR *dir2; std::string filePath = std::string(cwd) + "/" + fileBuff; // Check if file path is a directory. if ((dir2 = opendir(filePath.c_str())) != NULL) { closedir(dir2); getPaths(filePaths, filePath.c_str(), rootPath + fileBuff + "/"); } else { filePaths->push_back(rootPath + fileBuff); } } } closedir(dir); } } void compress(std::vector<std::string> *filePaths) { #pragma omp parallel for schedule(dynamic) for (unsigned long long int i = 0; i < filePaths->size(); ++i) { std::cout << filePaths->at(i) << std::endl; std::string command = "XZ_OPT=-9 tar cJf test." + std::to_string(i) + ".tar.xz " + filePaths->at(i); system(command.c_str()); } } char cwd [PATH_MAX]; int main(int argc, char *argv[]) { int *numFiles = new int(0); if (argc > 1) { helpCheck(argv); } getcwd(cwd, PATH_MAX); findAll(numFiles, cwd); // std::cout << *numFiles << std::endl; std::vector<std::string> *filePaths = new std::vector<std::string>(); getPaths(filePaths, cwd, ""); compress(filePaths); delete(numFiles); return 0; } <commit_msg>Testing block sizes<commit_after>#include <stdlib.h> #include <iostream> #include <vector> #include <unistd.h> #include <dirent.h> #include "omp.h" void helpCheck(char *argv[]) { if (argv[1] == std::string("-h") || argv[1] == std::string("--help")) { std::cout << "\nptxv - Parallel Tar XZ by Ryan Chui (2017)\n" << std::endl; exit(0); } } void findAll(int *numFiles, const char *cwd) { DIR *dir; struct dirent *ent; // Check if cwd is a directory if ((dir = opendir(cwd)) != NULL) { // Get all file paths within directory. while ((ent = readdir (dir)) != NULL) { std::string fileBuff = std::string(ent -> d_name); if (fileBuff != "." && fileBuff != "..") { DIR *dir2; std::string filePath = std::string(cwd) + "/" + fileBuff; // Check if file path is a directory. if ((dir2 = opendir(filePath.c_str())) != NULL) { closedir(dir2); findAll(numFiles, filePath.c_str()); } else { *numFiles += 1; } } } closedir(dir); } } void getPaths(std::vector<std::string> *filePaths, const char *cwd, std::string rootPath) { DIR *dir; struct dirent *ent; // Check if cwd is a directory if ((dir = opendir(cwd)) != NULL) { // Get all file paths within directory. while ((ent = readdir (dir)) != NULL) { std::string fileBuff = std::string(ent -> d_name); if (fileBuff != "." && fileBuff != "..") { DIR *dir2; std::string filePath = std::string(cwd) + "/" + fileBuff; // Check if file path is a directory. if ((dir2 = opendir(filePath.c_str())) != NULL) { closedir(dir2); getPaths(filePaths, filePath.c_str(), rootPath + fileBuff + "/"); } else { filePaths->push_back(rootPath + fileBuff); } } } closedir(dir); } } void compress(std::vector<std::string> *filePaths) { unsigned long long int filePathSize = filePaths->size(); unsigned long long int blockSize = (filePathSize / omp_get_max_threads()) + 1; std::cout << blockSize << std::endl; // #pragma omp parallel for schedule(dynamic) // for (unsigned long long int i = 0; i < filePaths->size(); ++i) { // std::cout << filePaths->at(i) << std::endl; // std::string command = "XZ_OPT=-9 tar cJf test." + std::to_string(i) + ".tar.xz " + filePaths->at(i); // system(command.c_str()); // } } char cwd [PATH_MAX]; int main(int argc, char *argv[]) { int *numFiles = new int(0); if (argc > 1) { helpCheck(argv); } getcwd(cwd, PATH_MAX); findAll(numFiles, cwd); // std::cout << *numFiles << std::endl; std::vector<std::string> *filePaths = new std::vector<std::string>(); getPaths(filePaths, cwd, ""); compress(filePaths); delete(numFiles); return 0; } <|endoftext|>
<commit_before>/* * The contnts of this file may be overwritten at any time! */ #include <iostream> #include <cstdlib> // rand /* #include "utils/intpoint.h" #include "utils/polygon.h" // Test whether polygon.inside(point) returns correct results. void test_poly_inside_and_centerOfMass() { { Polygon poly; poly.add(Point(2000,2000)); // / poly.add(Point(1000,1000)); // / / poly.add(Point(1100,100)); // |/ assert (!poly.inside(Point(-2000,1000))); assert (poly.inside(Point(1010,1000))); assert (!poly.inside(Point(5000,1000))); assert (poly.inside(Point(1111,1100))); assert (!poly.inside(Point(2001,2001))); assert (poly.inside(Point(1999,1998))); std::cerr << "poly.centerOfMass() = " << poly.centerOfMass() << std::endl; Point center = poly.centerOfMass(); for (int i = 0 ; i < 1000; i++) { Point translation(rand()%4000 - 2000, rand()%4000 - 2000); Polygon translated; for (Point& p : poly) { translated.add(p + translation); } Point translated_center = center + translation; if (vSize2(translated.centerOfMass() - translated_center) > 5*5) { std::cerr << "ERROR! test failed! " << std::endl; std::cerr << "translated.centerOfMass() = " << translated.centerOfMass() << std::endl; std::cerr << "translated_center = " << translated_center << std::endl; } } } { Polygon poly; poly.add(Point(0,0)); poly.add(Point(100,0)); // poly.add(Point(100,100)); // |\ /| poly.add(Point(50,50)); // | \/ | poly.add(Point(0,100)); // |____| assert (poly.inside(Point(60,50))); assert (!poly.inside(Point(50,60))); assert (poly.inside(Point(60,40))); assert (poly.inside(Point(50,40))); assert (!poly.inside(Point(-1,100))); assert (!poly.inside(Point(-10,-10))); std::cerr << "poly.centerOfMass() = " << poly.centerOfMass() << std::endl; Point center = poly.centerOfMass(); for (int i = 0 ; i < 1000; i++) { Point translation(rand()%4000 - 2000, rand()%4000 - 2000); Polygon translated; for (Point& p : poly) { translated.add(p + translation); } Point translated_center = center + translation; if (vSize2(translated.centerOfMass() - translated_center) > 5*5) { std::cerr << "ERROR! test failed! " << std::endl; std::cerr << "translated.centerOfMass() = " << translated.centerOfMass() << std::endl; std::cerr << "translated_center = " << translated_center << std::endl; } } } { Polygon poly; poly.add(Point( 0,2000)); // |\ . poly.add(Point( 0, 0)); // | > . poly.add(Point(1000,1000)); // |/ assert (poly.inside(Point(500,1000))); assert (poly.inside(Point(200,500))); assert (poly.inside(Point(200,1500))); assert (poly.inside(Point(800,1000))); assert (!poly.inside(Point(-10,1000))); assert (!poly.inside(Point(1100,1000))); assert (!poly.inside(Point(600,500))); assert (!poly.inside(Point(600,1500))); assert (!poly.inside(Point(2000,1000))); std::cerr << "poly.centerOfMass() = " << poly.centerOfMass() << std::endl; Point center = poly.centerOfMass(); for (int i = 0 ; i < 1000; i++) { Point translation(rand()%4000 - 2000, rand()%4000 - 2000); Polygon translated; for (Point& p : poly) { translated.add(translation - Point(-p.X, p.Y)); } Point translated_center = translation - Point(-center.X, center.Y); if (vSize2(translated.centerOfMass() - translated_center) > 5*5) { std::cerr << "ERROR! test failed! " << std::endl; std::cerr << "translated.centerOfMass() = " << translated.centerOfMass() << std::endl; std::cerr << "translated_center = " << translated_center << std::endl; } } } }*/ /* struct LocationItem { Point p; int i; LocationItem(Point p, int i) : p(p), i(i) {}; LocationItem() : p(0,0), i(-1) {}; }; #include "utils/BucketGrid2D.h" void test_BucketGrid2D() { BucketGrid2D<LocationItem> bg(1000); for (int i = 0; i < 20000; i++) { Point p(rand()%100000, rand()%100000); LocationItem li(p, i); bg.insert(p, li); } // {Point p(00,00); int i = 1; bg.insert(p, i);} // {Point p(05,05); int i = 2; bg.insert(p, i);} // {Point p(14,15); int i = 3; bg.insert(p, i);} // {Point p(25,25); int i = 4; bg.insert(p, i);} // {Point p(39,39); int i = 5; bg.insert(p, i);} // {Point p(300,300); int i = 6; bg.insert(p, i);} Point to(rand()%100000,rand()%100000); std::cerr << to << std::endl; LocationItem result; if (bg.findNearestObject(to, result)) { std::cerr << "best: " << result.p << std::endl; } else { std::cerr << "nothing found!" << std::endl; } //bg.debug(); }*/ /* #include <math.h> #include "utils/gettime.h" #include "utils/polygonUtils.h" void test_findClosestConnection() { srand(1234); if (false) { Polygon poly2; poly2.add(Point(0,300)); poly2.add(Point(100,300)); // ____ poly2.add(Point(100,200)); // | | poly2.add(Point(50,250)); // | /\ | poly2.add(Point(0,200)); // |/ \| Polygon poly1; poly1.add(Point(0,0)); poly1.add(Point(100,0)); // poly1.add(Point(100,100)); // |\ /| poly1.add(Point(50,50)); // | \/ | poly1.add(Point(0,100)); // |____| ClosestPolygonPoint result1 (poly1); ClosestPolygonPoint result2 (poly2); findSmallestConnection(result1, result2, 3); std::cerr << result1.location << " -- " << result2.location << std::endl; } if (false) { Polygon poly2; poly2.add(Point(0,300)); poly2.add(Point(100,300)); // ____ poly2.add(Point(100,200)); // | | poly2.add(Point(50,250)); // | /\ | poly2.add(Point(10,105)); // |/ \| Polygon poly1; poly1.add(Point(0,0)); poly1.add(Point(100,0)); // poly1.add(Point(100,100)); // |\ /| poly1.add(Point(50,50)); // | \/ | poly1.add(Point(0,100)); // |____| ClosestPolygonPoint result1 (poly1); ClosestPolygonPoint result2 (poly2); findSmallestConnection(result1, result2, 3); std::cerr << result1.location << " -- " << result2.location << std::endl; } double creationTime = 0; double evalTime = 0; long totalLength = 0; TimeKeeper timer; for (int i = 0; i < 10000; i++) { // for vizualization as csv with e.g. Rstudio Polygon poly1; double dist = 100; for (double a = 0; a < 360; a += 1) { dist += int(rand()%3) -1; Point p(static_cast<int>(dist * std::cos(a/180.0*3.1415)), static_cast<int>(dist * std::sin(a/180.0*3.1415))); p = p + Point(0, 200); if ( a ==0) poly1.add(p); else poly1.add((poly1.back() + p) / 2); // std::cerr << poly1.back().X << ", " << poly1.back().Y << std::endl; } // std::cerr << " " << std::endl; Polygon poly2; dist = 100; for (double a = 0; a < 360; a += 1) { dist += int(rand()%3) - 1; Point p(static_cast<int>(dist * std::cos(a/180.0*3.1415)), static_cast<int>(dist * std::sin(a/180.0*3.1415))); if ( a ==0) poly2.add(p); else poly2.add((poly2.back() + p) / 2); // std::cerr << poly2.back().X << ", " << poly2.back().Y << std::endl; } creationTime += timer.restart(); ClosestPolygonPoint result1 (poly1); ClosestPolygonPoint result2 (poly2); findSmallestConnection(result1, result2, 240); totalLength += vSize(result1.location - result2.location); evalTime += timer.restart(); // std::cerr << " " << std::endl; // std::cerr << result1.location.X << " , " << result1.location.Y << std::endl; // std::cerr << result2.location.X << " , " << result2.location.Y << std::endl; // std::cerr << " " << std::endl; } std::cerr << "creationTime : " << creationTime << std::endl; std::cerr << "evalTime : " << evalTime << std::endl; std::cerr << "totalLength : " << totalLength << std::endl; } */ #include "utils/polygon.h" namespace cura { void test_clipper() { Polygon p; p.emplace_back(0, 11004); p.emplace_back(0, 10129); p.emplace_back(0, 9185); p.emplace_back(0, 8477); p.emplace_back(1, 8491); p.emplace_back(418, 8861); p.emplace_back(1080, 9389); p.emplace_back(2106, 10142); p.emplace_back(3000, 10757); p.emplace_back(3000, 12010); p.emplace_back(3000, 12790); p.emplace_back(3000, 13485); p.emplace_back(3000, 14088); p.emplace_back(3000, 14601); p.emplace_back(3000, 15354); p.emplace_back(3000, 24867); p.emplace_back(3000, 25469); p.emplace_back(3000, 26303); p.emplace_back(3000, 27421); p.emplace_back(3000, 28242); p.emplace_back(2107, 28856); p.emplace_back(1080, 29610); p.emplace_back(608, 29986); p.emplace_back(1, 30508); p.emplace_back(1, 30522); p.emplace_back(0, 11772); Polygons polys; polys.add(p); // polys.debugOutputHTML("output/problem_test.html", true); // polys.offset(-400).debugOutputHTML("output/problem_test_offset.html", true); polys.removeDegenerateVerts(); // polys.offset(-400).debugOutputHTML("output/problem_test_offset_solved.html", true); } int main(int argc, char **argv) { // test_findClosestConnection(); test_clipper(); } }//namespace cura<commit_msg>deleted ancient test.cpp<commit_after><|endoftext|>
<commit_before>#include "Date.h" #include "Admin.h" #include <iostream> #include <string> #include <vector> using namespace std; int main() { // Tests the Date class Date* d = new Date(5, 5, 1994); cout << "My birthday is " << d->print(1) << endl; // Tests the Role class string c = "Rin-chan"; string v = "Kagamine Rin"; Role* r1 = new Role(c, v); r1->print(); Role* r2 = new Role(); r2->add(); r2->print(); return 0; } <commit_msg>added more test cases<commit_after>#include "Date.h" #include "Admin.h" #include <iostream> #include <string> #include <vector> using namespace std; int main() { // Tests the Date class cout << "Date class" << endl; Date* d = new Date(12, 27, 2007); cout << "My birthday is " << d->print(1) << endl; cout << endl; unsigned month, day, year; cout << "What is your birthday?" << endl << "Month: "; cin >> month; cout << "Date: "; cin >> day; cout << "Year: "; cin >> year; Date* birthday = new Date(month, day, year); cout << "Your birthday is " << birthday->print() << endl; cout << endl; // Tests the Role class cout << "Role class" << endl; string c = "Rin-chan"; string v = "Kagamine Rin"; Role* r1 = new Role(c, v); r1->print(); cout << endl; cout << "Time to add a new Role" << endl; Role* r2 = new Role(); r2->add(); cout << "The new role is "; r2->print(); cout << endl; cout << "We will now remove " << r2->getRole() << "/" << r2->getVocal() << endl; r2->remove(); cout << "The role has been cleared!" << endl; r2->print(); return 0; } <|endoftext|>
<commit_before>/* Copyright (c) 2009, 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 <ctime> #include <string> #include <cstdio> #include <boost/limits.hpp> #include <boost/version.hpp> #include "libtorrent/config.hpp" #include "libtorrent/time.hpp" #ifndef _WIN32 #include <unistd.h> #endif namespace libtorrent { namespace aux { // used to cache the current time // every 100 ms. This is cheaper // than a system call and can be // used where more accurate time // is not necessary ptime g_current_time; } ptime const& TORRENT_EXPORT time_now() { return aux::g_current_time; } char const* time_now_string() { // time_t t = std::time(0); // tm* timeinfo = std::localtime(&t); // static char str[200]; // std::strftime(str, 200, "%b %d %X", timeinfo); // return str; static const ptime start = time_now_hires(); static char ret[200]; int t = total_milliseconds(time_now_hires() - start); int h = t / 1000 / 60 / 60; t -= h * 60 * 60 * 1000; int m = t / 1000 / 60; t -= m * 60 * 1000; int s = t / 1000; t -= s * 1000; int ms = t; snprintf(ret, sizeof(ret), "%02d:%02d:%02d.%03d", h, m, s, ms); return ret; } std::string log_time() { static const ptime start = time_now_hires(); char ret[200]; snprintf(ret, sizeof(ret), "%"PRId64, total_microseconds(time_now_hires() - start)); return ret; } } #if defined TORRENT_USE_BOOST_DATE_TIME #include <boost/date_time/microsec_time_clock.hpp> namespace libtorrent { ptime time_now_hires() { return boost::date_time::microsec_clock<ptime>::universal_time(); } ptime min_time() { return boost::posix_time::ptime(boost::posix_time::min_date_time); } ptime max_time() { return boost::posix_time::ptime(boost::posix_time::max_date_time); } time_duration seconds(int s) { return boost::posix_time::seconds(s); } time_duration milliseconds(int s) { return boost::posix_time::milliseconds(s); } time_duration microsec(int s) { return boost::posix_time::microsec(s); } time_duration minutes(int s) { return boost::posix_time::minutes(s); } time_duration hours(int s) { return boost::posix_time::hours(s); } int total_seconds(time_duration td) { return td.total_seconds(); } int total_milliseconds(time_duration td) { return td.total_milliseconds(); } boost::int64_t total_microseconds(time_duration td) { return td.total_microseconds(); } } #else // TORRENT_USE_BOOST_DATE_TIME namespace libtorrent { ptime min_time() { return ptime(0); } ptime max_time() { return ptime((std::numeric_limits<boost::uint64_t>::max)()); } } #if defined TORRENT_USE_ABSOLUTE_TIME #include <mach/mach_time.h> #include <boost/cstdint.hpp> #include "libtorrent/assert.hpp" // high precision timer for darwin intel and ppc namespace libtorrent { ptime time_now_hires() { static mach_timebase_info_data_t timebase_info = {0,0}; if (timebase_info.denom == 0) mach_timebase_info(&timebase_info); boost::uint64_t at = mach_absolute_time(); // make sure we don't overflow TORRENT_ASSERT((at >= 0 && at >= at / 1000 * timebase_info.numer / timebase_info.denom) || (at < 0 && at < at / 1000 * timebase_info.numer / timebase_info.denom)); return ptime(at / 1000 * timebase_info.numer / timebase_info.denom); } } #elif defined TORRENT_USE_QUERY_PERFORMANCE_TIMER #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif #include <windows.h> #include "libtorrent/assert.hpp" namespace libtorrent { namespace aux { boost::int64_t performance_counter_to_microseconds(boost::int64_t pc) { static LARGE_INTEGER performace_counter_frequency = {0,0}; if (performace_counter_frequency.QuadPart == 0) QueryPerformanceFrequency(&performace_counter_frequency); #ifdef TORRENT_DEBUG // make sure we don't overflow boost::int64_t ret = (pc * 1000 / performace_counter_frequency.QuadPart) * 1000; TORRENT_ASSERT((pc >= 0 && pc >= ret) || (pc < 0 && pc < ret)); #endif return (pc * 1000 / performace_counter_frequency.QuadPart) * 1000; } boost::int64_t microseconds_to_performance_counter(boost::int64_t ms) { static LARGE_INTEGER performace_counter_frequency = {0,0}; if (performace_counter_frequency.QuadPart == 0) QueryPerformanceFrequency(&performace_counter_frequency); #ifdef TORRENT_DEBUG // make sure we don't overflow boost::int64_t ret = (ms / 1000) * performace_counter_frequency.QuadPart / 1000; TORRENT_ASSERT((ms >= 0 && ms <= ret) || (ms < 0 && ms > ret)); #endif return (ms / 1000) * performace_counter_frequency.QuadPart / 1000; } } ptime time_now_hires() { LARGE_INTEGER now; QueryPerformanceCounter(&now); return ptime(now.QuadPart); } } #elif defined TORRENT_USE_CLOCK_GETTIME #include <time.h> #include "libtorrent/assert.hpp" namespace libtorrent { ptime time_now_hires() { timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); return ptime(boost::uint64_t(ts.tv_sec) * 1000000 + ts.tv_nsec / 1000); } } #elif defined TORRENT_USE_SYSTEM_TIME #include <kernel/OS.h> namespace libtorrent { ptime time_now_hires() { return ptime(system_time()); } } #endif // TORRENT_USE_SYSTEM_TIME #endif // TORRENT_USE_BOOST_DATE_TIME <commit_msg>fix windows DLL build<commit_after>/* Copyright (c) 2009, 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 <ctime> #include <string> #include <cstdio> #include <boost/limits.hpp> #include <boost/version.hpp> #include "libtorrent/config.hpp" #include "libtorrent/time.hpp" #ifndef _WIN32 #include <unistd.h> #endif namespace libtorrent { namespace aux { // used to cache the current time // every 100 ms. This is cheaper // than a system call and can be // used where more accurate time // is not necessary ptime g_current_time; } TORRENT_EXPORT ptime const& time_now() { return aux::g_current_time; } char const* time_now_string() { // time_t t = std::time(0); // tm* timeinfo = std::localtime(&t); // static char str[200]; // std::strftime(str, 200, "%b %d %X", timeinfo); // return str; static const ptime start = time_now_hires(); static char ret[200]; int t = total_milliseconds(time_now_hires() - start); int h = t / 1000 / 60 / 60; t -= h * 60 * 60 * 1000; int m = t / 1000 / 60; t -= m * 60 * 1000; int s = t / 1000; t -= s * 1000; int ms = t; snprintf(ret, sizeof(ret), "%02d:%02d:%02d.%03d", h, m, s, ms); return ret; } std::string log_time() { static const ptime start = time_now_hires(); char ret[200]; snprintf(ret, sizeof(ret), "%"PRId64, total_microseconds(time_now_hires() - start)); return ret; } } #if defined TORRENT_USE_BOOST_DATE_TIME #include <boost/date_time/microsec_time_clock.hpp> namespace libtorrent { ptime time_now_hires() { return boost::date_time::microsec_clock<ptime>::universal_time(); } ptime min_time() { return boost::posix_time::ptime(boost::posix_time::min_date_time); } ptime max_time() { return boost::posix_time::ptime(boost::posix_time::max_date_time); } time_duration seconds(int s) { return boost::posix_time::seconds(s); } time_duration milliseconds(int s) { return boost::posix_time::milliseconds(s); } time_duration microsec(int s) { return boost::posix_time::microsec(s); } time_duration minutes(int s) { return boost::posix_time::minutes(s); } time_duration hours(int s) { return boost::posix_time::hours(s); } int total_seconds(time_duration td) { return td.total_seconds(); } int total_milliseconds(time_duration td) { return td.total_milliseconds(); } boost::int64_t total_microseconds(time_duration td) { return td.total_microseconds(); } } #else // TORRENT_USE_BOOST_DATE_TIME namespace libtorrent { ptime min_time() { return ptime(0); } ptime max_time() { return ptime((std::numeric_limits<boost::uint64_t>::max)()); } } #if defined TORRENT_USE_ABSOLUTE_TIME #include <mach/mach_time.h> #include <boost/cstdint.hpp> #include "libtorrent/assert.hpp" // high precision timer for darwin intel and ppc namespace libtorrent { ptime time_now_hires() { static mach_timebase_info_data_t timebase_info = {0,0}; if (timebase_info.denom == 0) mach_timebase_info(&timebase_info); boost::uint64_t at = mach_absolute_time(); // make sure we don't overflow TORRENT_ASSERT((at >= 0 && at >= at / 1000 * timebase_info.numer / timebase_info.denom) || (at < 0 && at < at / 1000 * timebase_info.numer / timebase_info.denom)); return ptime(at / 1000 * timebase_info.numer / timebase_info.denom); } } #elif defined TORRENT_USE_QUERY_PERFORMANCE_TIMER #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif #include <windows.h> #include "libtorrent/assert.hpp" namespace libtorrent { namespace aux { boost::int64_t performance_counter_to_microseconds(boost::int64_t pc) { static LARGE_INTEGER performace_counter_frequency = {0,0}; if (performace_counter_frequency.QuadPart == 0) QueryPerformanceFrequency(&performace_counter_frequency); #ifdef TORRENT_DEBUG // make sure we don't overflow boost::int64_t ret = (pc * 1000 / performace_counter_frequency.QuadPart) * 1000; TORRENT_ASSERT((pc >= 0 && pc >= ret) || (pc < 0 && pc < ret)); #endif return (pc * 1000 / performace_counter_frequency.QuadPart) * 1000; } boost::int64_t microseconds_to_performance_counter(boost::int64_t ms) { static LARGE_INTEGER performace_counter_frequency = {0,0}; if (performace_counter_frequency.QuadPart == 0) QueryPerformanceFrequency(&performace_counter_frequency); #ifdef TORRENT_DEBUG // make sure we don't overflow boost::int64_t ret = (ms / 1000) * performace_counter_frequency.QuadPart / 1000; TORRENT_ASSERT((ms >= 0 && ms <= ret) || (ms < 0 && ms > ret)); #endif return (ms / 1000) * performace_counter_frequency.QuadPart / 1000; } } ptime time_now_hires() { LARGE_INTEGER now; QueryPerformanceCounter(&now); return ptime(now.QuadPart); } } #elif defined TORRENT_USE_CLOCK_GETTIME #include <time.h> #include "libtorrent/assert.hpp" namespace libtorrent { ptime time_now_hires() { timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); return ptime(boost::uint64_t(ts.tv_sec) * 1000000 + ts.tv_nsec / 1000); } } #elif defined TORRENT_USE_SYSTEM_TIME #include <kernel/OS.h> namespace libtorrent { ptime time_now_hires() { return ptime(system_time()); } } #endif // TORRENT_USE_SYSTEM_TIME #endif // TORRENT_USE_BOOST_DATE_TIME <|endoftext|>
<commit_before>// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* * Ceph - scalable distributed file system * * Copyright (C) 2004-2006 Sage Weil <sage@newdream.net> * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <sys/stat.h> #include <iostream> #include <string> using namespace std; #include "config.h" #include "mon/MonMap.h" #include "mds/MDS.h" #include "osd/OSDMap.h" #include "msg/SimpleMessenger.h" #include "common/Timer.h" #include "common/common_init.h" #include "mon/MonClient.h" #include "osdc/Objecter.h" #include "messages/MOSDGetMap.h" #include "libs3.h" void usage() { cerr << "usage: c3 -i name [flags] [--mds rank] [--shadow rank]\n"; cerr << " -m monitorip:port\n"; cerr << " connect to monitor at given address\n"; cerr << " --debug_mds n\n"; cerr << " debug MDS level (e.g. 10)\n"; generic_server_usage(); } class C3 : public Dispatcher { MonMap monmap; OSDMap osdmap; MonClient mc; Messenger *messenger; bool _dispatch(Message *m); bool dispatch_impl(Message *m); Objecter *objecter; Mutex lock; class C_WriteAck : public Context { object_t oid; loff_t start; size_t length; public: tid_t tid; C_WriteAck(object_t o, loff_t s, size_t l) : oid(o), start(s), length(l) {} void finish(int r) { cerr << "WriteAck finish" << std::endl; } }; class C_WriteCommit : public Context { object_t oid; loff_t start; size_t length; public: tid_t tid; C_WriteCommit(object_t o, loff_t s, size_t l) : oid(o), start(s), length(l) {} void finish(int r) { cerr << "WriteCommit finish" << std::endl; } }; class C_ReadCommit : public Context { object_t oid; loff_t start; size_t length; bufferlist *bl; public: tid_t tid; C_ReadCommit(object_t o, loff_t s, size_t l, bufferlist *b) : oid(o), start(s), length(l), bl(b) {} void finish(int r) { char *buf = bl->c_str(); cerr << "ReadCommit finish" << std::endl; for (size_t i=0; i<bl->length(); i++) cerr << (int)buf[i] << " "; cerr << std::endl; } }; public: C3() : messenger(NULL), lock("c3") {} bool init(); void write(); void read(); }; bool C3::init() { // get monmap if (mc.get_monmap(&monmap) < 0) return false; rank.bind(); cout << "starting c3." << g_conf.id << " at " << rank.get_rank_addr() << " fsid " << monmap.get_fsid() << std::endl; messenger = rank.register_entity(entity_name_t::MDS(-1)); assert_warn(messenger); if (!messenger) return false; rank.set_policy(entity_name_t::TYPE_MON, Rank::Policy::lossy_fail_after(1.0)); rank.set_policy(entity_name_t::TYPE_MDS, Rank::Policy::lossless()); rank.set_policy(entity_name_t::TYPE_OSD, Rank::Policy::lossless()); rank.set_policy(entity_name_t::TYPE_CLIENT, Rank::Policy::lossless()); // mds does its own timeout/markdown rank.start(1); objecter = new Objecter(messenger, &monmap, &osdmap, lock); if (!objecter) return false; objecter->set_client_incarnation(0); lock.Lock(); objecter->init(); messenger->set_dispatcher(this); lock.Unlock(); return true; } bool C3::dispatch_impl(Message *m) { bool ret; // verify protocol version if (m->get_orig_source().is_mds() && m->get_header().mds_protocol != CEPH_MDS_PROTOCOL) { dout(0) << "mds protocol v " << (int)m->get_header().mds_protocol << " != my " << CEPH_MDS_PROTOCOL << " from " << m->get_orig_source_inst() << " " << *m << dendl; delete m; return true; } if (m->get_header().mdsc_protocol != CEPH_MDSC_PROTOCOL) { dout(0) << "mdsc protocol v " << (int)m->get_header().mdsc_protocol << " != my " << CEPH_MDSC_PROTOCOL << " from " << m->get_orig_source_inst() << " " << *m << dendl; delete m; return true; } if (m->get_orig_source().is_mon() && m->get_header().monc_protocol != CEPH_MONC_PROTOCOL) { dout(0) << "monc protocol v " << (int)m->get_header().monc_protocol << " != my " << CEPH_MONC_PROTOCOL << " from " << m->get_orig_source_inst() << " " << *m << dendl; delete m; return true; } if (m->get_orig_source().is_osd() && m->get_header().osdc_protocol != CEPH_OSDC_PROTOCOL) { dout(0) << "osdc protocol v " << (int)m->get_header().osdc_protocol << " != my " << CEPH_OSDC_PROTOCOL << " from " << m->get_orig_source_inst() << " " << *m << dendl; delete m; return true; } lock.Lock(); ret = _dispatch(m); lock.Unlock(); return ret; } bool C3::_dispatch(Message *m) { switch (m->get_type()) { // OSD case CEPH_MSG_OSD_OPREPLY: objecter->handle_osd_op_reply((class MOSDOpReply*)m); break; case CEPH_MSG_OSD_MAP: objecter->handle_osd_map((MOSDMap*)m); break; default: return false; } return true; } void C3::write() { SnapContext snapc; object_t oid(0x1020, 0); loff_t off = 0; size_t len = 1024; bufferlist bl; utime_t ut = g_clock.now(); char buf[len]; for (size_t i=0; i<len; i++) buf[i] = i%20; bl.append(buf, len); C_WriteAck *onack = new C_WriteAck(oid, off, len); C_WriteCommit *oncommit = new C_WriteCommit(oid, off, len); ceph_object_layout layout = objecter->osdmap->file_to_object_layout(oid, g_default_mds_dir_layout); dout(0) << "going to write" << dendl; objecter->write(oid, layout, off, len, snapc, bl, ut, 0, onack, oncommit); dout(0) << "after write call" << dendl; } void C3::read() { SnapContext snapc; object_t oid(0x1020, 0); loff_t off = 0; size_t len = 1024; bufferlist *bl = new bufferlist; C_ReadCommit *oncommit = new C_ReadCommit(oid, off, len, bl); ceph_object_layout layout = objecter->osdmap->file_to_object_layout(oid, g_default_mds_dir_layout); dout(0) << "going to read" << dendl; objecter->read(oid, layout, off, len, bl, 0, oncommit); dout(0) << "after read call" << dendl; } int main(int argc, const char **argv) { vector<const char*> args; argv_to_vec(argc, argv, args); env_to_vec(args); common_init(args, "ccc", true); // mds specific args for (unsigned i=0; i<args.size(); i++) { cerr << "unrecognized arg " << args[i] << std::endl; usage(); } if (!g_conf.id) { cerr << "must specify '-i name' with the cmds instance name" << std::endl; usage(); } if (g_conf.clock_tare) g_clock.tare(); C3 c3; c3.init(); c3.write(); c3.read(); rank.wait(); // cd on exit, so that gmon.out (if any) goes into a separate directory for each node. char s[20]; sprintf(s, "gmon/%d", getpid()); if (mkdir(s, 0755) == 0) chdir(s); generic_dout(0) << "stopped." << dendl; return 0; } <commit_msg>c3: add mount/umount to mon client<commit_after>// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* * Ceph - scalable distributed file system * * Copyright (C) 2004-2006 Sage Weil <sage@newdream.net> * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <sys/stat.h> #include <iostream> #include <string> using namespace std; #include "config.h" #include "mon/MonMap.h" #include "mds/MDS.h" #include "osd/OSDMap.h" #include "msg/SimpleMessenger.h" #include "common/Timer.h" #include "common/common_init.h" #include "mon/MonClient.h" #include "osdc/Objecter.h" #include "messages/MOSDGetMap.h" #include "messages/MClientMount.h" #include "messages/MClientMountAck.h" #include "libs3.h" void usage() { cerr << "usage: c3 -i name [flags] [--mds rank] [--shadow rank]\n"; cerr << " -m monitorip:port\n"; cerr << " connect to monitor at given address\n"; cerr << " --debug_mds n\n"; cerr << " debug MDS level (e.g. 10)\n"; generic_server_usage(); } class C3 : public Dispatcher { MonMap monmap; OSDMap osdmap; Messenger *messenger; MonClient *mc; bool _dispatch(Message *m); bool dispatch_impl(Message *m); Objecter *objecter; Mutex lock; class C_WriteAck : public Context { object_t oid; loff_t start; size_t length; public: tid_t tid; C_WriteAck(object_t o, loff_t s, size_t l) : oid(o), start(s), length(l) {} void finish(int r) { cerr << "WriteAck finish r=" << r << std::endl; } }; class C_WriteCommit : public Context { object_t oid; loff_t start; size_t length; public: tid_t tid; C_WriteCommit(object_t o, loff_t s, size_t l) : oid(o), start(s), length(l) {} void finish(int r) { cerr << "WriteCommit finish r=" << r << std::endl; } }; class C_ReadCommit : public Context { object_t oid; loff_t start; size_t length; bufferlist *bl; public: tid_t tid; C_ReadCommit(object_t o, loff_t s, size_t l, bufferlist *b) : oid(o), start(s), length(l), bl(b) {} void finish(int r) { char *buf = bl->c_str(); cerr << "ReadCommit finish r=" << r << std::endl; for (size_t i=0; i<bl->length(); i++) cerr << (int)buf[i] << " "; cerr << std::endl; } }; public: C3() : messenger(NULL), mc(NULL), lock("c3") {} ~C3(); bool init(); void write(); void read(); }; bool C3::init() { mc = new MonClient(&monmap, messenger); MonMap *mm = mc->get_monmap(); // get monmap if (!mm) return false; rank.bind(); cout << "starting c3." << g_conf.id << " at " << rank.get_rank_addr() << " fsid " << mm->get_fsid() << std::endl; messenger = rank.register_entity(entity_name_t::MDS(-1)); assert_warn(messenger); if (!messenger) return false; rank.set_policy(entity_name_t::TYPE_MON, Rank::Policy::lossy_fail_after(1.0)); rank.set_policy(entity_name_t::TYPE_MDS, Rank::Policy::lossless()); rank.set_policy(entity_name_t::TYPE_OSD, Rank::Policy::lossless()); rank.set_policy(entity_name_t::TYPE_CLIENT, Rank::Policy::lossless()); // mds does its own timeout/markdown rank.start(1); objecter = new Objecter(messenger, mm, &osdmap, lock); if (!objecter) return false; lock.Lock(); messenger->set_dispatcher(this); objecter->set_client_incarnation(0); objecter->init(); lock.Unlock(); return true; } C3::~C3() { if (messenger) delete messenger; if (mc) delete mc; } bool C3::dispatch_impl(Message *m) { bool ret; // verify protocol version if (m->get_orig_source().is_mds() && m->get_header().mds_protocol != CEPH_MDS_PROTOCOL) { dout(0) << "mds protocol v " << (int)m->get_header().mds_protocol << " != my " << CEPH_MDS_PROTOCOL << " from " << m->get_orig_source_inst() << " " << *m << dendl; delete m; return true; } if (m->get_header().mdsc_protocol != CEPH_MDSC_PROTOCOL) { dout(0) << "mdsc protocol v " << (int)m->get_header().mdsc_protocol << " != my " << CEPH_MDSC_PROTOCOL << " from " << m->get_orig_source_inst() << " " << *m << dendl; delete m; return true; } if (m->get_orig_source().is_mon() && m->get_header().monc_protocol != CEPH_MONC_PROTOCOL) { dout(0) << "monc protocol v " << (int)m->get_header().monc_protocol << " != my " << CEPH_MONC_PROTOCOL << " from " << m->get_orig_source_inst() << " " << *m << dendl; delete m; return true; } if (m->get_orig_source().is_osd() && m->get_header().osdc_protocol != CEPH_OSDC_PROTOCOL) { dout(0) << "osdc protocol v " << (int)m->get_header().osdc_protocol << " != my " << CEPH_OSDC_PROTOCOL << " from " << m->get_orig_source_inst() << " " << *m << dendl; delete m; return true; } lock.Lock(); ret = _dispatch(m); lock.Unlock(); return ret; } bool C3::_dispatch(Message *m) { switch (m->get_type()) { // OSD case CEPH_MSG_OSD_OPREPLY: objecter->handle_osd_op_reply((class MOSDOpReply*)m); break; case CEPH_MSG_OSD_MAP: objecter->handle_osd_map((MOSDMap*)m); break; default: return false; } return true; } void C3::write() { SnapContext snapc; object_t oid(0x1030, 0); loff_t off = 0; size_t len = 1024; bufferlist bl; utime_t ut = g_clock.now(); char buf[len]; for (size_t i=0; i<len; i++) buf[i] = i%10; bl.append(buf, len); C_WriteAck *onack = new C_WriteAck(oid, off, len); C_WriteCommit *oncommit = new C_WriteCommit(oid, off, len); ceph_object_layout layout = objecter->osdmap->make_object_layout(oid, 0); dout(0) << "going to write" << dendl; objecter->write(oid, layout, off, len, snapc, bl, ut, 0, onack, oncommit); dout(0) << "after write call" << dendl; } void C3::read() { SnapContext snapc; object_t oid(0x1030, 0); loff_t off = 0; size_t len = 1024; bufferlist *bl = new bufferlist; C_ReadCommit *oncommit = new C_ReadCommit(oid, off, len, bl); ceph_object_layout layout = objecter->osdmap->make_object_layout(oid, 0); dout(0) << "going to read" << dendl; objecter->read(oid, layout, off, len, bl, 0, oncommit); dout(0) << "after read call" << dendl; } int main(int argc, const char **argv) { vector<const char*> args; argv_to_vec(argc, argv, args); env_to_vec(args); common_init(args, "ccc", true); // mds specific args for (unsigned i=0; i<args.size(); i++) { cerr << "unrecognized arg " << args[i] << std::endl; usage(); } if (!g_conf.id) { cerr << "must specify '-i name' with the cmds instance name" << std::endl; usage(); } if (g_conf.clock_tare) g_clock.tare(); C3 c3; c3.init(); c3.write(); sleep(1); c3.read(); rank.wait(); // cd on exit, so that gmon.out (if any) goes into a separate directory for each node. char s[20]; sprintf(s, "gmon/%d", getpid()); if (mkdir(s, 0755) == 0) chdir(s); generic_dout(0) << "stopped." << dendl; return 0; } <|endoftext|>
<commit_before>#include "catch.hpp" #include <ginseng/ginseng.hpp> #include <array> #include <memory> using DB = ginseng::database; using ginseng::deny; using ginseng::optional; using ent_id = DB::ent_id; using com_id = DB::com_id; TEST_CASE("Entities can be added and removed from a database", "[ginseng]") { DB db; REQUIRE(db.size() == 0); ent_id ent1 = db.create_entity(); REQUIRE(db.size() == 1); ent_id ent2 = db.create_entity(); REQUIRE(db.size() == 2); db.destroy_entity(ent2); REQUIRE(db.size() == 1); db.destroy_entity(ent1); REQUIRE(db.size() == 0); } TEST_CASE("Components can be added, accessed, and removed from entities", "[ginseng]") { DB db; auto ent = db.create_entity(); struct ComA { int x; }; struct ComB { double y; }; db.create_component(ent, ComA{7}); REQUIRE(db.has_component<ComA>(ent) == true); ComA *com1ptr1 = &db.get_component<ComA>(ent); REQUIRE(com1ptr1 != nullptr); db.create_component(ent, ComB{4.2}); REQUIRE(db.has_component<ComB>(ent) == true); ComB *com2ptr1 = &db.get_component<ComB>(ent); REQUIRE(com2ptr1 != nullptr); REQUIRE(&db.get_component<ComA>(ent) == com1ptr1); REQUIRE(db.get_component<ComA>(ent).x == 7); REQUIRE(&db.get_component<ComB>(ent) == com2ptr1); REQUIRE(db.get_component<ComB>(ent).y == 4.2); db.destroy_component<ComA>(ent); REQUIRE(&db.get_component<ComB>(ent) == com2ptr1); REQUIRE(db.get_component<ComB>(ent).y == 4.2); db.destroy_component<ComB>(ent); } TEST_CASE("Databases can visit entities with specific components", "[ginseng]") { DB db; struct ID { int id; }; struct Data1 { double val; }; struct Data2 { std::unique_ptr<int> no_move; }; int next_id = 0; auto make_ent = [&](bool give_Data1, bool give_Data2) { auto ent = db.create_entity(); db.create_component(ent, ID{next_id}); ++next_id; if (give_Data1) { db.create_component(ent, Data1{7}); } if (give_Data2) { db.create_component(ent, Data2{nullptr}); } return ent; }; make_ent(false, false); make_ent(true, false); make_ent(true, false); make_ent(false, true); make_ent(false, true); make_ent(false, true); make_ent(true, true); make_ent(true, true); make_ent(true, true); make_ent(true, true); REQUIRE(next_id == 10); REQUIRE(db.size() == next_id); std::array<int,10> visited; std::array<int,10> expected_visited; visited = {}; expected_visited = {{1,1,1,1,1,1,1,1,1,1}}; db.visit([&](ID& id){ ++visited[id.id]; }); REQUIRE(visited == expected_visited); visited = {}; expected_visited = {{0,1,1,0,0,0,1,1,1,1}}; db.visit([&](ID& id, Data1&){ ++visited[id.id]; }); REQUIRE(visited == expected_visited); visited = {}; expected_visited = {{0,0,0,1,1,1,1,1,1,1}}; db.visit([&](ID& id, Data2&){ ++visited[id.id]; }); REQUIRE(visited == expected_visited); visited = {}; expected_visited = {{0,0,0,0,0,0,1,1,1,1}}; db.visit([&](ID& id, Data1&, Data2&){ ++visited[id.id]; }); REQUIRE(visited == expected_visited); visited = {}; expected_visited = {{1,0,0,1,1,1,0,0,0,0}}; db.visit([&](ID& id, deny<Data1>){ ++visited[id.id]; }); REQUIRE(visited == expected_visited); visited = {}; expected_visited = {{0,0,0,1,1,1,0,0,0,0}}; db.visit([&](ID& id, deny<Data1>, Data2&){ ++visited[id.id]; }); REQUIRE(visited == expected_visited); visited = {}; expected_visited = {{0,1,1,0,0,0,0,0,0,0}}; db.visit([&](ID& id, Data1&, deny<Data2>){ ++visited[id.id]; }); REQUIRE(visited == expected_visited); visited = {}; expected_visited = {{1,0,0,0,0,0,0,0,0,0}}; db.visit([&](ID& id, deny<Data1>, deny<Data2>){ ++visited[id.id]; }); REQUIRE(visited == expected_visited); int num_visited = 0; db.visit([&](deny<ID>){ ++num_visited; }); REQUIRE(num_visited == 0); } TEST_CASE("optional can be used instead of components", "[ginseng]") { DB db; struct Data {}; struct Data2 {}; auto ent = db.create_entity(); db.create_component(ent,Data{}); int visited = 0; optional<Data> mdata; optional<Data2> mdata2; db.visit([&](optional<Data> data, optional<Data2> data2){ ++visited; mdata = data; mdata2 = data2; }); REQUIRE(visited == 1); REQUIRE(bool(mdata) == true); REQUIRE(bool(mdata2) == false); } TEST_CASE("deleted entites are not revisited", "[ginseng]") { DB db; struct Data {}; auto ent = db.create_entity(); db.create_entity(); db.create_entity(); int visited = 0; db.visit([&](ent_id eid){ ++visited; db.create_component(eid, Data{}); }); REQUIRE(visited == 3); visited = 0; db.visit([&](ent_id eid, Data&){ ++visited; }); REQUIRE(visited == 3); db.destroy_entity(ent); visited = 0; db.visit([&](ent_id eid){ ++visited; }); REQUIRE(visited == 2); visited = 0; db.visit([&](ent_id eid, Data&){ ++visited; }); REQUIRE(visited == 2); } <commit_msg>Added minor test assertions<commit_after>#include "catch.hpp" #include <ginseng/ginseng.hpp> #include <array> #include <memory> using DB = ginseng::database; using ginseng::deny; using ginseng::optional; using ent_id = DB::ent_id; using com_id = DB::com_id; TEST_CASE("Entities can be added and removed from a database", "[ginseng]") { DB db; REQUIRE(db.size() == 0); ent_id ent1 = db.create_entity(); REQUIRE(db.size() == 1); ent_id ent2 = db.create_entity(); REQUIRE(db.size() == 2); db.destroy_entity(ent2); REQUIRE(db.size() == 1); db.destroy_entity(ent1); REQUIRE(db.size() == 0); } TEST_CASE("Components can be added, accessed, and removed from entities", "[ginseng]") { DB db; auto ent = db.create_entity(); struct ComA { int x; }; struct ComB { double y; }; db.create_component(ent, ComA{7}); REQUIRE(db.has_component<ComA>(ent) == true); ComA *com1ptr1 = &db.get_component<ComA>(ent); REQUIRE(com1ptr1 != nullptr); db.create_component(ent, ComB{4.2}); REQUIRE(db.has_component<ComB>(ent) == true); ComB *com2ptr1 = &db.get_component<ComB>(ent); REQUIRE(com2ptr1 != nullptr); REQUIRE(&db.get_component<ComA>(ent) == com1ptr1); REQUIRE(db.get_component<ComA>(ent).x == 7); REQUIRE(&db.get_component<ComB>(ent) == com2ptr1); REQUIRE(db.get_component<ComB>(ent).y == 4.2); db.destroy_component<ComA>(ent); REQUIRE(db.has_component<ComA>(ent) == false); REQUIRE(db.has_component<ComB>(ent) == true); REQUIRE(&db.get_component<ComB>(ent) == com2ptr1); REQUIRE(db.get_component<ComB>(ent).y == 4.2); db.destroy_component<ComB>(ent); REQUIRE(db.has_component<ComA>(ent) == false); REQUIRE(db.has_component<ComB>(ent) == false); } TEST_CASE("Databases can visit entities with specific components", "[ginseng]") { DB db; struct ID { int id; }; struct Data1 { double val; }; struct Data2 { std::unique_ptr<int> no_move; }; int next_id = 0; auto make_ent = [&](bool give_Data1, bool give_Data2) { auto ent = db.create_entity(); db.create_component(ent, ID{next_id}); ++next_id; if (give_Data1) { db.create_component(ent, Data1{7}); } if (give_Data2) { db.create_component(ent, Data2{nullptr}); } return ent; }; make_ent(false, false); make_ent(true, false); make_ent(true, false); make_ent(false, true); make_ent(false, true); make_ent(false, true); make_ent(true, true); make_ent(true, true); make_ent(true, true); make_ent(true, true); REQUIRE(next_id == 10); REQUIRE(db.size() == next_id); std::array<int,10> visited; std::array<int,10> expected_visited; visited = {}; expected_visited = {{1,1,1,1,1,1,1,1,1,1}}; db.visit([&](ID& id){ ++visited[id.id]; }); REQUIRE(visited == expected_visited); visited = {}; expected_visited = {{0,1,1,0,0,0,1,1,1,1}}; db.visit([&](ID& id, Data1&){ ++visited[id.id]; }); REQUIRE(visited == expected_visited); visited = {}; expected_visited = {{0,0,0,1,1,1,1,1,1,1}}; db.visit([&](ID& id, Data2&){ ++visited[id.id]; }); REQUIRE(visited == expected_visited); visited = {}; expected_visited = {{0,0,0,0,0,0,1,1,1,1}}; db.visit([&](ID& id, Data1&, Data2&){ ++visited[id.id]; }); REQUIRE(visited == expected_visited); visited = {}; expected_visited = {{1,0,0,1,1,1,0,0,0,0}}; db.visit([&](ID& id, deny<Data1>){ ++visited[id.id]; }); REQUIRE(visited == expected_visited); visited = {}; expected_visited = {{0,0,0,1,1,1,0,0,0,0}}; db.visit([&](ID& id, deny<Data1>, Data2&){ ++visited[id.id]; }); REQUIRE(visited == expected_visited); visited = {}; expected_visited = {{0,1,1,0,0,0,0,0,0,0}}; db.visit([&](ID& id, Data1&, deny<Data2>){ ++visited[id.id]; }); REQUIRE(visited == expected_visited); visited = {}; expected_visited = {{1,0,0,0,0,0,0,0,0,0}}; db.visit([&](ID& id, deny<Data1>, deny<Data2>){ ++visited[id.id]; }); REQUIRE(visited == expected_visited); int num_visited = 0; db.visit([&](deny<ID>){ ++num_visited; }); REQUIRE(num_visited == 0); } TEST_CASE("optional can be used instead of components", "[ginseng]") { DB db; struct Data {}; struct Data2 {}; auto ent = db.create_entity(); db.create_component(ent,Data{}); int visited = 0; optional<Data> mdata; optional<Data2> mdata2; db.visit([&](optional<Data> data, optional<Data2> data2){ ++visited; mdata = data; mdata2 = data2; }); REQUIRE(visited == 1); REQUIRE(bool(mdata) == true); REQUIRE(bool(mdata2) == false); } TEST_CASE("deleted entites are not revisited", "[ginseng]") { DB db; struct Data {}; auto ent = db.create_entity(); db.create_entity(); db.create_entity(); int visited = 0; db.visit([&](ent_id eid){ ++visited; db.create_component(eid, Data{}); }); REQUIRE(visited == 3); visited = 0; db.visit([&](ent_id eid, Data&){ ++visited; }); REQUIRE(visited == 3); db.destroy_entity(ent); visited = 0; db.visit([&](ent_id eid){ ++visited; }); REQUIRE(visited == 2); visited = 0; db.visit([&](ent_id eid, Data&){ ++visited; }); REQUIRE(visited == 2); } <|endoftext|>
<commit_before>#include <istream> #include <sstream> #include <utility> #include "token.hh" #include "util.hh" using namespace std; inline Token::Token(const std::string& s, Type t) : type_(t), str_(s){} inline Token::Token(std::string&& s, Type t) : type_(t), str_(move(s)){} inline Token::Token(const Number& n) : type_(Type::number), num_(n){} inline Token::Token(Number&& n) : type_(Type::number), num_(move(n)){} inline constexpr Token::Token(bool b) : type_(Type::boolean), b_(b){} inline constexpr Token::Token(char c) : type_(Type::character), c_(c){} inline constexpr Token::Token(Notation n) : type_(Type::notation), not_(n){} template<typename T> inline void Token::init_from_other(T other){ type_ = other.type_; switch(other.type_){ case Type::uninitialized: break; case Type::identifier: case Type::string: new (&this->str_) string(move(other.str_)); break; case Type::boolean: this->b_ = other.b_; break; case Type::number: new (&this->num_) Number(move(other.num_)); break; case Type::character: this->c_ = other.c_; break; case Type::notation: this->not_ = other.not_; break; default: UNEXP_DEFAULT(); } } Token::Token(const Token& other){ init_from_other<const Token&>(forward<const Token>(other)); } Token::Token(Token&& other){ init_from_other<Token&&>(forward<Token>(other)); } template<typename T> inline Token& Token::assign_from_other(T other){ if(this->type_ == other.type_ || (this->type_ == Type::identifier && other.type_ == Type::string) || (this->type_ == Type::string && other.type_ == Type::identifier)){ switch(this->type_){ case Type::uninitialized: break; case Type::identifier: case Type::string: this->type_ = other.type_; this->str_ = move(other.str_); break; case Type::boolean: this->b_ = other.b_; break; case Type::number: this->num_ = move(other.num_); break; case Type::character: this->c_ = other.c_; break; case Type::notation: this->not_ = move(other.not_); break; default: UNEXP_DEFAULT(); } }else{ this->~Token(); new (this) Token(move(other)); } return *this; } Token& Token::operator=(const Token& other){ return assign_from_other<const Token&>(forward<const Token>(other)); } Token& Token::operator=(Token&& other){ return assign_from_other<Token&&>(forward<Token>(other)); } Token::~Token(){ switch(type_){ case Type::identifier: case Type::string: str_.~string(); break; case Type::number: num_.~Number(); break; case Type::uninitialized: case Type::boolean: case Type::character: case Type::notation: break; default: //UNEXP_DEFAULT(); break; } type_ = Type::uninitialized; } // // tokenizer funcs // namespace { template<typename charT> inline constexpr bool is_delimiter(charT c){ return isspace(c) || c == '(' || c == ')' || c == '"' || c == ';' || c == EOF; } template<typename charT> inline bool is_special_initial(charT c){ switch(c){ case '!': case '$': case '%': case '&': case '*': case '/': case ':': case '<': case '=': case '>': case '?': case '^': case '_': case '~': return true; default: return false; } } void skip_intertoken_space(FILE* f){ decltype(fgetc(f)) c; while((c = fgetc(f)) != EOF){ if(isspace(c)){ continue; }else if(c == ';'){ do{ c = fgetc(f); }while(c != EOF && c != '\n'); assert(c == EOF || c == '\n'); //ungetc(c, f); // it is meaningless.. }else{ ungetc(c, f); return; } } } Token tokenize_identifier(FILE* f, char first_char){ string s; s.push_back(first_char); // subsequent auto c = fgetc(f); while(!is_delimiter(c) || isalpha(c) || is_special_initial(c) || isdigit(c) || c == '+' || c == '-' || c == '.' || c == '@'){ s.push_back(c); c = fgetc(f); } ungetc(c, f); return Token{s, Token::Type::identifier}; } Token tokenize_character(FILE* f){ // function for checking character-name const auto check_name = [&](const char* str) -> bool { for(const char* c = str; *c; ++c){ auto get_c = fgetc(f); if(get_c != *c || is_delimiter(get_c)){ ungetc(get_c, f); return false; } } return true; }; auto ret_char = fgetc(f); // check character name switch(ret_char){ case EOF: return {}; case 's': if(check_name("pace")){ ret_char = ' '; } break; case 'n': if(check_name("ewline")){ ret_char = '\n'; } break; } return Token{static_cast<char>(ret_char)}; } Token tokenize_string(FILE* f){ decltype(fgetc(f)) c; string s; while((c = fgetc(f)) != EOF){ switch(c){ case '"': return Token{s, Token::Type::string}; case '\\': c = fgetc(f); switch(c){ case '"': case '\\': s.push_back(c); break; default: goto error; } break; default: s.push_back(c); } } error: return {}; } Token tokenize_number(FILE* f, char read_c = 0){ static const auto is_n_char = [](char c) -> bool { switch(c){ case '+': case '-': case '.': case '@': case 'i': case 'e': case 's': case 'f': case 'd': case 'l': case '#': case 'b': case 'o': case 'x': return true; default: return isxdigit(c); } }; decltype(fgetc(f)) c; stringstream s; if(read_c) s.put(read_c); while(is_n_char(c = fgetc(f))){ s.put(c); } ungetc(c, f); if(auto n = parse_number(s)){ // TODO: push back unused chars. return Token{n}; }else{ return Token{}; } } } // namespace Token tokenize(FILE* f){ skip_intertoken_space(f); switch(auto c = fgetc(f)){ case '(': return Token{Token::Notation::l_paren}; case ')': return Token{Token::Notation::r_paren}; case '\'': return Token{Token::Notation::quote}; case '`': return Token{Token::Notation::quasiquote}; case '[': return Token{Token::Notation::l_bracket}; case ']': return Token{Token::Notation::r_bracket}; case '{': return Token{Token::Notation::l_brace}; case '}': return Token{Token::Notation::r_brace}; case '|': return Token{Token::Notation::bar}; case ',': { auto c2 = fgetc(f); if(c2 == '@'){ return Token{Token::Notation::comma_at}; }else{ ungetc(c2, f); return Token{Token::Notation::comma}; } } case '.': { int dots = 1; auto c2 = fgetc(f); while(c2 == '.'){ ++dots; c2 = fgetc(f); } ungetc(c2, f); switch(dots){ case 1: return Token{Token::Notation::dot}; case 3: return Token{"...", Token::Type::identifier}; default: goto error; } } case '"': return tokenize_string(f); case '+': case '-': { auto c2 = fgetc(f); if(is_delimiter(c2)){ return Token{string(1, c), Token::Type::identifier}; }else{ ungetc(c2, f); return tokenize_number(f, c); } } case '#': switch(auto sharp_c = fgetc(f)){ case '(': return Token{Token::Notation::vector_paren}; case 't': return Token{true}; case 'f': return Token{false}; case '\\': return tokenize_character(f); case 'i': case 'e': case 'b': case 'o': case 'd': case 'x': ungetc(sharp_c, f); return tokenize_number(f, '#'); default: goto error; } default: if(isalpha(c) || is_special_initial(c)){ return tokenize_identifier(f, c); }else if(isdigit(c)){ ungetc(c, f); return tokenize_number(f); }else{ goto error; } } error: return {}; } const char* stringify(Token::Notation n){ switch(n){ case Token::Notation::l_paren: return "left parensis"; case Token::Notation::r_paren: return "right parensis"; case Token::Notation::vector_paren: return "vector parensis"; case Token::Notation::quote: return "quote"; case Token::Notation::quasiquote: return "backquote"; case Token::Notation::comma: return "comma"; case Token::Notation::comma_at: return "comma+at"; case Token::Notation::dot: return "dot"; case Token::Notation::l_bracket: return "left bracket"; case Token::Notation::r_bracket: return "right bracket"; case Token::Notation::l_brace: return "left brace"; case Token::Notation::r_brace: return "right brace"; case Token::Notation::bar: return "bar"; default: return "(unknown token notation)"; } } const char* stringify(Token::Type t){ switch(t){ case Token::Type::uninitialized: return "uninitialized"; case Token::Type::identifier: return "identifier"; case Token::Type::string: return "string"; case Token::Type::boolean: return "boolean"; case Token::Type::number: return "number"; case Token::Type::character: return "character"; case Token::Type::notation: return "notation"; default: return "(unknown token type)"; } } void describe(FILE* f, Token::Type t){ fputs(stringify(t), f); } void describe(FILE* f, Token::Notation n){ fputs(stringify(n), f); } void describe(FILE* f, const Token& tok){ const auto t = tok.type(); fprintf(f, "Token: %s(", stringify(t)); switch(t){ case Token::Type::uninitialized: break; case Token::Type::identifier: case Token::Type::string: fputs(tok.get<string>().c_str(), f); break; case Token::Type::boolean: fputs(tok.get<bool>() ? "true" : "false", f); break; case Token::Type::number: describe(f, tok.get<Number>()); break; case Token::Type::character: fputc(tok.get<char>(), f); break; case Token::Type::notation: describe(f, tok.get<Token::Notation>()); break; default: UNEXP_DEFAULT(); } fputc(')', f); } <commit_msg>bitly cleanup in token<commit_after>#include <istream> #include <sstream> #include <utility> #include "token.hh" #include "util.hh" using namespace std; inline Token::Token(const std::string& s, Type t) : type_(t), str_(s){} inline Token::Token(std::string&& s, Type t) : type_(t), str_(move(s)){} inline Token::Token(const Number& n) : type_(Type::number), num_(n){} inline Token::Token(Number&& n) : type_(Type::number), num_(move(n)){} inline constexpr Token::Token(bool b) : type_(Type::boolean), b_(b){} inline constexpr Token::Token(char c) : type_(Type::character), c_(c){} inline constexpr Token::Token(Notation n) : type_(Type::notation), not_(n){} template<typename T> inline void Token::init_from_other(T other){ type_ = other.type_; switch(other.type_){ case Type::uninitialized: break; case Type::identifier: case Type::string: new (&this->str_) string(move(other.str_)); break; case Type::boolean: this->b_ = other.b_; break; case Type::number: new (&this->num_) Number(move(other.num_)); break; case Type::character: this->c_ = other.c_; break; case Type::notation: this->not_ = other.not_; break; default: UNEXP_DEFAULT(); } } Token::Token(const Token& other){ init_from_other<const Token&>(forward<const Token>(other)); } Token::Token(Token&& other){ init_from_other<Token&&>(forward<Token>(other)); } template<typename T> inline Token& Token::assign_from_other(T other){ if(this->type_ == other.type_ || (this->type_ == Type::identifier && other.type_ == Type::string) || (this->type_ == Type::string && other.type_ == Type::identifier)){ switch(this->type_){ case Type::uninitialized: break; case Type::identifier: case Type::string: this->type_ = other.type_; this->str_ = move(other.str_); break; case Type::boolean: this->b_ = other.b_; break; case Type::number: this->num_ = move(other.num_); break; case Type::character: this->c_ = other.c_; break; case Type::notation: this->not_ = move(other.not_); break; default: UNEXP_DEFAULT(); } }else{ this->~Token(); new (this) Token(move(other)); } return *this; } Token& Token::operator=(const Token& other){ return assign_from_other<const Token&>(forward<const Token>(other)); } Token& Token::operator=(Token&& other){ return assign_from_other<Token&&>(forward<Token>(other)); } Token::~Token(){ switch(type_){ case Type::identifier: case Type::string: str_.~string(); break; case Type::number: num_.~Number(); break; case Type::uninitialized: case Type::boolean: case Type::character: case Type::notation: break; default: //UNEXP_DEFAULT(); break; } type_ = Type::uninitialized; } // // tokenizer funcs // namespace { template<typename charT> inline constexpr bool is_delimiter(charT c){ return isspace(c) || c == '(' || c == ')' || c == '"' || c == ';' || c == EOF; } template<typename charT> inline bool is_special_initial(charT c){ switch(c){ case '!': case '$': case '%': case '&': case '*': case '/': case ':': case '<': case '=': case '>': case '?': case '^': case '_': case '~': return true; default: return false; } } void skip_intertoken_space(FILE* f){ decltype(fgetc(f)) c; while((c = fgetc(f)) != EOF && (isspace(c) || c == ';')){ if(c == ';'){ decltype(fgetc(f)) c2; do{ c2 = fgetc(f); }while(c2 != EOF && c2 != '\n'); } } ungetc(c, f); } Token tokenize_identifier(FILE* f, char first_char){ string s; s.push_back(first_char); // subsequent decltype(fgetc(f)) c; while((c = fgetc(f)) != EOF && (!is_delimiter(c) || isalpha(c) || is_special_initial(c) || isdigit(c) || c == '+' || c == '-' || c == '.' || c == '@')){ s.push_back(c); } ungetc(c, f); return Token{s, Token::Type::identifier}; } Token tokenize_character(FILE* f){ // function for checking character-name const auto check_name = [&](const char* str) -> bool { for(const char* c = str; *c; ++c){ auto get_c = fgetc(f); if(get_c != *c || is_delimiter(get_c)){ ungetc(get_c, f); return false; } } return true; }; auto ret_char = fgetc(f); // check character name switch(ret_char){ case EOF: return {}; case 's': if(check_name("pace")){ ret_char = ' '; } break; case 'n': if(check_name("ewline")){ ret_char = '\n'; } break; } return Token{static_cast<char>(ret_char)}; } Token tokenize_string(FILE* f){ decltype(fgetc(f)) c; string s; while((c = fgetc(f)) != EOF){ switch(c){ case '"': return Token{s, Token::Type::string}; case '\\': c = fgetc(f); switch(c){ case '"': case '\\': s.push_back(c); break; default: goto error; } break; default: s.push_back(c); } } error: return {}; } Token tokenize_number(FILE* f, char read_c = 0){ static const auto is_n_char = [](char c) -> bool { switch(c){ case '+': case '-': case '.': case '@': case 'i': case 'e': case 's': case 'f': case 'd': case 'l': case '#': case 'b': case 'o': case 'x': return true; default: return isxdigit(c); } }; decltype(fgetc(f)) c; stringstream s; if(read_c) s.put(read_c); while(is_n_char(c = fgetc(f))){ s.put(c); } ungetc(c, f); if(auto n = parse_number(s)){ // TODO: push back unused chars. return Token{n}; }else{ return Token{}; } } } // namespace Token tokenize(FILE* f){ skip_intertoken_space(f); switch(auto c = fgetc(f)){ case '(': return Token{Token::Notation::l_paren}; case ')': return Token{Token::Notation::r_paren}; case '\'': return Token{Token::Notation::quote}; case '`': return Token{Token::Notation::quasiquote}; case '[': return Token{Token::Notation::l_bracket}; case ']': return Token{Token::Notation::r_bracket}; case '{': return Token{Token::Notation::l_brace}; case '}': return Token{Token::Notation::r_brace}; case '|': return Token{Token::Notation::bar}; case ',': { auto c2 = fgetc(f); if(c2 == '@'){ return Token{Token::Notation::comma_at}; }else{ ungetc(c2, f); return Token{Token::Notation::comma}; } } case '.': { int dots = 1; auto c2 = fgetc(f); while(c2 == '.'){ ++dots; c2 = fgetc(f); } ungetc(c2, f); switch(dots){ case 1: return Token{Token::Notation::dot}; case 3: return Token{"...", Token::Type::identifier}; default: goto error; } } case '"': return tokenize_string(f); case '+': case '-': { auto c2 = fgetc(f); if(is_delimiter(c2)){ return Token{string(1, c), Token::Type::identifier}; }else{ ungetc(c2, f); return tokenize_number(f, c); } } case '#': switch(auto sharp_c = fgetc(f)){ case '(': return Token{Token::Notation::vector_paren}; case 't': return Token{true}; case 'f': return Token{false}; case '\\': return tokenize_character(f); case 'i': case 'e': case 'b': case 'o': case 'd': case 'x': ungetc(sharp_c, f); return tokenize_number(f, '#'); default: goto error; } default: if(isalpha(c) || is_special_initial(c)){ return tokenize_identifier(f, c); }else if(isdigit(c)){ ungetc(c, f); return tokenize_number(f); }else{ goto error; } } error: return {}; } const char* stringify(Token::Notation n){ switch(n){ case Token::Notation::l_paren: return "left parensis"; case Token::Notation::r_paren: return "right parensis"; case Token::Notation::vector_paren: return "vector parensis"; case Token::Notation::quote: return "quote"; case Token::Notation::quasiquote: return "backquote"; case Token::Notation::comma: return "comma"; case Token::Notation::comma_at: return "comma+at"; case Token::Notation::dot: return "dot"; case Token::Notation::l_bracket: return "left bracket"; case Token::Notation::r_bracket: return "right bracket"; case Token::Notation::l_brace: return "left brace"; case Token::Notation::r_brace: return "right brace"; case Token::Notation::bar: return "bar"; default: return "(unknown token notation)"; } } const char* stringify(Token::Type t){ switch(t){ case Token::Type::uninitialized: return "uninitialized"; case Token::Type::identifier: return "identifier"; case Token::Type::string: return "string"; case Token::Type::boolean: return "boolean"; case Token::Type::number: return "number"; case Token::Type::character: return "character"; case Token::Type::notation: return "notation"; default: return "(unknown token type)"; } } void describe(FILE* f, Token::Type t){ fputs(stringify(t), f); } void describe(FILE* f, Token::Notation n){ fputs(stringify(n), f); } void describe(FILE* f, const Token& tok){ const auto t = tok.type(); fprintf(f, "Token: %s(", stringify(t)); switch(t){ case Token::Type::uninitialized: break; case Token::Type::identifier: case Token::Type::string: fputs(tok.get<string>().c_str(), f); break; case Token::Type::boolean: fputs(tok.get<bool>() ? "true" : "false", f); break; case Token::Type::number: describe(f, tok.get<Number>()); break; case Token::Type::character: fputc(tok.get<char>(), f); break; case Token::Type::notation: describe(f, tok.get<Token::Notation>()); break; default: UNEXP_DEFAULT(); } fputc(')', f); } <|endoftext|>
<commit_before>#include <random> #include <utility> #include <algorithm> #include <tuple> #include <cmath> #include <experimental/filesystem> #include <opencv2/opencv.hpp> #include "train.hh" #include "window.hh" #include "mblbp.hh" #include "params.hh" namespace fs = std::experimental::filesystem; namespace chrono = std::chrono; using data_t = std::vector<std::pair<std::vector<unsigned char>, char>>; /* Estimate the memory used by a data set ** ** Paramaters ** ---------- ** data : data_t ** Dataset where each sample is represented as a vector of features ** ** Return ** ------ ** size_in_bytes : long ** Estimated size of the dataset in bytes */ long estimate_memory_size(data_t data) { int n_samples = data.size(); int n_features = data[0].first.size(); return n_samples * n_features * sizeof(unsigned char); } /* Generate all MB-LBP features inside a window ** The size of the window is defined in "parameters.hh" ** ** Return ** ------ ** features : std::vector<mblbp_feature> ** All features contained in a window */ static std::vector<mblbp_feature> mblbp_all_features() { std::vector<mblbp_feature> features; for(int block_w = min_block_size; block_w <= max_block_size; block_w += 3) for(int block_h = min_block_size; block_h <= max_block_size; block_h += 3) for(int x = 0; x <= initial_window_w - block_w; ++x) for(int y = 0; y <= initial_window_h - block_h; ++y) features.push_back(mblbp_feature(x, y, block_w, block_h)); return features; } static std::vector<unsigned char> mblbp_calculate_all_features( const cv::Mat &integral, const std::vector<mblbp_feature> &all_features) { int n_features = all_features.size(); std::vector<unsigned char> calculated_features(n_features); window base_window(0, 0, integral.rows, integral.cols, 1.0); for(int i = 0; i < n_features; ++i) calculated_features[i] = mblbp_calculate_feature(integral, base_window, all_features[i]); return calculated_features; } static data_t load_data(const std::vector<mblbp_feature> &all_features, const std::string &positive_path, const std::string &negative_path) { chrono::steady_clock::time_point begin = chrono::steady_clock::now(); data_t data; std::vector<std::string> positive_paths; std::vector<std::string> negative_paths; for(auto& directory_entry : fs::directory_iterator(positive_path)) positive_paths.push_back(directory_entry.path().string()); std::cout << positive_paths.size() << " positive samples" << std::endl; #pragma omp parallel for //for(std::size_t i = 0; i < positive_paths.size(); ++i) for(std::size_t i = 0; i < 1000; ++i) { cv::Mat img, integral; img = cv::imread(positive_paths[i], CV_LOAD_IMAGE_GRAYSCALE); cv::integral(img, integral); std::vector<unsigned char> features = mblbp_calculate_all_features( integral, all_features); #pragma omp critical(add_features_positive) { data.push_back(std::make_pair(features, 1)); } } for(auto& directory_entry : fs::directory_iterator(negative_path)) negative_paths.push_back(directory_entry.path().string()); std::cout << negative_paths.size() << " negative samples" << std::endl; #pragma omp parallel for //for(std::size_t i = 0; i < negative_paths.size(); ++i) for(std::size_t i = 0; i < 1000; ++i) { cv::Mat img, integral; img = cv::imread(negative_paths[i], CV_LOAD_IMAGE_GRAYSCALE); cv::integral(img, integral); std::vector<unsigned char> features = mblbp_calculate_all_features( integral, all_features); #pragma omp critical(add_features_negative) { data.push_back(std::make_pair(features, -1)); } } chrono::steady_clock::time_point end = chrono::steady_clock::now(); auto duration = chrono::duration_cast<chrono::seconds>(end - begin); int elapsed = duration.count(); std::cout << "loading data took " << elapsed << "s" << std::endl; return data; } static void shuffle_data(data_t &data) { std::random_device rd; std::mt19937 g(rd()); std::shuffle(data.begin(), data.end(), g); } static std::tuple<double, double, double, double> evaluate( const mblbp_classifier &classifier, const data_t &validation_set) { int n_samples = validation_set.size(); if(n_samples == 0) return std::make_tuple(0.0, 0.0, 0.0, 0.0); // tp: true positive, fn: false negative, etc. int n_tp = 0, n_tn = 0, n_fp = 0, n_fn = 0; char real_label, classification_label; int n_positive = 0, n_negative = 0; for(int i = 0; i < n_samples; ++i) { real_label = validation_set[i].second; if(real_label == 1) n_positive++; else n_negative++; // calculate classification_label classification_label = 1; for(const auto& sc : classifier.strong_classifiers) { double sum = 0; for(const auto& wc : sc.weak_classifiers) { unsigned char feature_value = validation_set[i].first[wc.k]; sum += wc.regression_parameters[feature_value]; } if(sum < 0) { classification_label = -1; break; } } if(real_label == 1) { if(classification_label == 1) n_tp++; else n_fn++; } else { if(classification_label == -1) n_tn++; else n_fp++; } } double tp_rate = (double)n_tp / n_positive; // true positive rate double tn_rate = (double)n_tn / n_negative; // true negative rate double fp_rate = (double)n_fp / n_positive; // false positive rate double fn_rate = (double)n_fn / n_negative; // false negative rate auto rates = std::make_tuple(tp_rate, tn_rate, fp_rate, fn_rate); return rates; } mblbp_classifier train(const std::string &positive_path, const std::string &negative_path) { std::cout << std::string(10, '-') << std::endl; std::cout << "start training" << std::endl; std::cout << std::string(10, '-') << std::endl; std::cout << "using " << initial_window_w << "x" << initial_window_h << " windows" << std::endl; mblbp_classifier classifier; // retrieve all features for the configured initial window size auto all_features = mblbp_all_features(); int n_features = all_features.size(); std::cout << n_features << " features / image (" << sizeof(unsigned char) * n_features << " bytes)" << std::endl; // construct one weak_classifier per feature std::vector<weak_classifier> all_weak_classifiers; for(int k = 0; k < n_features; ++k) all_weak_classifiers.push_back(weak_classifier(all_features[k], k)); std::cout << std::string(10, '-') << std::endl; std::cout << "calculating all MB-LBP features on all samples" << std::endl; data_t data = load_data(all_features, positive_path, negative_path); std::cout << "shuffling data" << std::endl; shuffle_data(data); std::cout << data.size() << " samples in dataset" << std::endl; std::cout << estimate_memory_size(data) << " bytes in memory" << std::endl; // split dataset std::size_t split_idx = 2 * data.size() / 3; data_t training_set(data.begin(), data.begin() + split_idx); data_t validation_set(data.begin() + split_idx, data.end()); std::cout << training_set.size() << " samples in training set" << std::endl; std::cout << validation_set.size() << " samples in validation set" << std::endl; std::cout << std::string(10, '-') << std::endl; // weights initialization to 1 / n_samples std::vector<double> weights(training_set.size()); std::fill_n(weights.begin(), training_set.size(), 1.0 / training_set.size()); // current rates on validation set double detection_rate, tp_rate, tn_rate, fp_rate, fn_rate; int n_iter = 1; do { std::cout << "iteration #" << n_iter << std::endl; strong_classifier new_strong_classifier; // select train_n_weak_per_strong weak classifiers for(int n_weak = 0; n_weak < train_n_weak_per_strong; ++n_weak) { int best_idx = -1; // index of the best weak_classifier (smallest wse) double best_wse; // current smallest (best) wse, used to update best_idx // update all weak classifiers regression parameters #pragma omp parallel for for(std::size_t wc_idx = 0 ; wc_idx < all_weak_classifiers.size(); wc_idx++) { weak_classifier &wc = all_weak_classifiers[wc_idx]; for(int j = 0; j < 255; ++j) { double numerator = 0, denominator = 0; for(std::size_t i = 0; i < training_set.size(); ++i) { if(training_set[i].first[wc.k] == j) { numerator += weights[i] * training_set[i].second; denominator += weights[i]; } } if(denominator != 0) wc.regression_parameters[j] = numerator / denominator; else wc.regression_parameters[j] = 0; } double wse = 0; for(std::size_t i = 0; i < training_set.size(); ++i) { double value = wc.regression_parameters[training_set[i].first[wc.k]]; wse += weights[i] * std::pow(value - training_set[i].second, 2); } #pragma omp critical(best_wse_update) { if(best_idx < 0 || wse < best_wse) { best_wse = wse; best_idx = wc_idx; } } } std::cout << "best wse " << best_wse << std::endl; // get a copy of the best weak_classifier before deleting it weak_classifier best_weak_classifier(all_weak_classifiers[best_idx]); weak_classifier &bwc = best_weak_classifier; std::cout << "new weak_classifier:" << std::endl; std::cout << " feature:" << std::endl; std::cout << " (x, y) = (" << bwc.feature.x << ", " << bwc.feature.y << ")" << std::endl; std::cout << " block_w = " << bwc.feature.block_w << std::endl; std::cout << " block_h = " << bwc.feature.block_h << std::endl; std::cout << " k = " << bwc.k << std::endl; std::cout << " regression_parameters = [ "; for(int i = 0; i < 255; ++i) std::cout << bwc.regression_parameters[i] << " "; std::cout << "]" << std::endl; // delete selected weak_classifier from the whole set all_weak_classifiers.erase(all_weak_classifiers.begin() + best_idx); // add new weak_classifier to the strong_classifier new_strong_classifier.weak_classifiers.push_back(best_weak_classifier); // update weights double sum = 0; for(std::size_t i = 0; i < weights.size(); ++i) { double value = bwc.regression_parameters[training_set[i].first[bwc.k]]; weights[i] = weights[i] * std::exp(-training_set[i].second * value); sum += weights[i]; } for(std::size_t i = 0; i < weights.size(); ++i) weights[i] /= sum; } // add new strong_classifier to the mblbp_classifier classifier.strong_classifiers.push_back(new_strong_classifier); // calculate new detection and miss rates std::tie(tp_rate, tn_rate, fp_rate, fn_rate) = evaluate(classifier, validation_set); detection_rate = tp_rate; std::cout << "detection_rate = " << detection_rate << std::endl; std::cout << "true positive = " << tp_rate << std::endl; std::cout << "true negative = " << tn_rate << std::endl; std::cout << "false positive = " << fp_rate << std::endl; std::cout << "false negative = " << fn_rate << std::endl; n_iter++; } while(classifier.strong_classifiers.size() < train_n_strong && (detection_rate < target_detection_rate || fp_rate > target_fp_rate)); return classifier; } <commit_msg>regression parameters defaults to 1<commit_after>#include <random> #include <utility> #include <algorithm> #include <tuple> #include <cmath> #include <experimental/filesystem> #include <opencv2/opencv.hpp> #include "train.hh" #include "window.hh" #include "mblbp.hh" #include "params.hh" namespace fs = std::experimental::filesystem; namespace chrono = std::chrono; using data_t = std::vector<std::pair<std::vector<unsigned char>, char>>; /* Estimate the memory used by a data set ** ** Paramaters ** ---------- ** data : data_t ** Dataset where each sample is represented as a vector of features ** ** Return ** ------ ** size_in_bytes : long ** Estimated size of the dataset in bytes */ long estimate_memory_size(data_t data) { int n_samples = data.size(); int n_features = data[0].first.size(); return n_samples * n_features * sizeof(unsigned char); } /* Generate all MB-LBP features inside a window ** The size of the window is defined in "parameters.hh" ** ** Return ** ------ ** features : std::vector<mblbp_feature> ** All features contained in a window */ static std::vector<mblbp_feature> mblbp_all_features() { std::vector<mblbp_feature> features; for(int block_w = min_block_size; block_w <= max_block_size; block_w += 3) for(int block_h = min_block_size; block_h <= max_block_size; block_h += 3) for(int x = 0; x <= initial_window_w - block_w; ++x) for(int y = 0; y <= initial_window_h - block_h; ++y) features.push_back(mblbp_feature(x, y, block_w, block_h)); return features; } static std::vector<unsigned char> mblbp_calculate_all_features( const cv::Mat &integral, const std::vector<mblbp_feature> &all_features) { int n_features = all_features.size(); std::vector<unsigned char> calculated_features(n_features); window base_window(0, 0, integral.rows, integral.cols, 1.0); for(int i = 0; i < n_features; ++i) calculated_features[i] = mblbp_calculate_feature(integral, base_window, all_features[i]); return calculated_features; } static data_t load_data(const std::vector<mblbp_feature> &all_features, const std::string &positive_path, const std::string &negative_path) { chrono::steady_clock::time_point begin = chrono::steady_clock::now(); data_t data; std::vector<std::string> positive_paths; std::vector<std::string> negative_paths; for(auto& directory_entry : fs::directory_iterator(positive_path)) positive_paths.push_back(directory_entry.path().string()); std::cout << positive_paths.size() << " positive samples" << std::endl; #pragma omp parallel for //for(std::size_t i = 0; i < positive_paths.size(); ++i) for(std::size_t i = 0; i < 1000; ++i) { cv::Mat img, integral; img = cv::imread(positive_paths[i], CV_LOAD_IMAGE_GRAYSCALE); cv::integral(img, integral); std::vector<unsigned char> features = mblbp_calculate_all_features( integral, all_features); #pragma omp critical(add_features_positive) { data.push_back(std::make_pair(features, 1)); } } for(auto& directory_entry : fs::directory_iterator(negative_path)) negative_paths.push_back(directory_entry.path().string()); std::cout << negative_paths.size() << " negative samples" << std::endl; #pragma omp parallel for //for(std::size_t i = 0; i < negative_paths.size(); ++i) for(std::size_t i = 0; i < 1000; ++i) { cv::Mat img, integral; img = cv::imread(negative_paths[i], CV_LOAD_IMAGE_GRAYSCALE); cv::integral(img, integral); std::vector<unsigned char> features = mblbp_calculate_all_features( integral, all_features); #pragma omp critical(add_features_negative) { data.push_back(std::make_pair(features, -1)); } } chrono::steady_clock::time_point end = chrono::steady_clock::now(); auto duration = chrono::duration_cast<chrono::seconds>(end - begin); int elapsed = duration.count(); std::cout << "loading data took " << elapsed << "s" << std::endl; return data; } static void shuffle_data(data_t &data) { std::random_device rd; std::mt19937 g(rd()); std::shuffle(data.begin(), data.end(), g); } static std::tuple<double, double, double, double> evaluate( const mblbp_classifier &classifier, const data_t &validation_set) { int n_samples = validation_set.size(); if(n_samples == 0) return std::make_tuple(0.0, 0.0, 0.0, 0.0); // tp: true positive, fn: false negative, etc. int n_tp = 0, n_tn = 0, n_fp = 0, n_fn = 0; char real_label, classification_label; int n_positive = 0, n_negative = 0; for(int i = 0; i < n_samples; ++i) { real_label = validation_set[i].second; if(real_label == 1) n_positive++; else n_negative++; // calculate classification_label classification_label = 1; for(const auto& sc : classifier.strong_classifiers) { double sum = 0; for(const auto& wc : sc.weak_classifiers) { unsigned char feature_value = validation_set[i].first[wc.k]; sum += wc.regression_parameters[feature_value]; } if(sum < 0) { classification_label = -1; break; } } if(real_label == 1) { if(classification_label == 1) n_tp++; else n_fn++; } else { if(classification_label == -1) n_tn++; else n_fp++; } } double tp_rate = (double)n_tp / n_positive; // true positive rate double tn_rate = (double)n_tn / n_negative; // true negative rate double fp_rate = (double)n_fp / n_positive; // false positive rate double fn_rate = (double)n_fn / n_negative; // false negative rate auto rates = std::make_tuple(tp_rate, tn_rate, fp_rate, fn_rate); return rates; } mblbp_classifier train(const std::string &positive_path, const std::string &negative_path) { std::cout << std::string(10, '-') << std::endl; std::cout << "start training" << std::endl; std::cout << std::string(10, '-') << std::endl; std::cout << "using " << initial_window_w << "x" << initial_window_h << " windows" << std::endl; mblbp_classifier classifier; // retrieve all features for the configured initial window size auto all_features = mblbp_all_features(); int n_features = all_features.size(); std::cout << n_features << " features / image (" << sizeof(unsigned char) * n_features << " bytes)" << std::endl; // construct one weak_classifier per feature std::vector<weak_classifier> all_weak_classifiers; for(int k = 0; k < n_features; ++k) all_weak_classifiers.push_back(weak_classifier(all_features[k], k)); std::cout << std::string(10, '-') << std::endl; std::cout << "calculating all MB-LBP features on all samples" << std::endl; data_t data = load_data(all_features, positive_path, negative_path); std::cout << "shuffling data" << std::endl; shuffle_data(data); std::cout << data.size() << " samples in dataset" << std::endl; std::cout << estimate_memory_size(data) << " bytes in memory" << std::endl; // split dataset std::size_t split_idx = 2 * data.size() / 3; data_t training_set(data.begin(), data.begin() + split_idx); data_t validation_set(data.begin() + split_idx, data.end()); std::cout << training_set.size() << " samples in training set" << std::endl; std::cout << validation_set.size() << " samples in validation set" << std::endl; std::cout << std::string(10, '-') << std::endl; // weights initialization to 1 / n_samples std::vector<double> weights(training_set.size()); std::fill_n(weights.begin(), training_set.size(), 1.0 / training_set.size()); // current rates on validation set double detection_rate, tp_rate, tn_rate, fp_rate, fn_rate; int n_iter = 1; do { std::cout << "iteration #" << n_iter << std::endl; strong_classifier new_strong_classifier; // select train_n_weak_per_strong weak classifiers for(int n_weak = 0; n_weak < train_n_weak_per_strong; ++n_weak) { int best_idx = -1; // index of the best weak_classifier (smallest wse) double best_wse; // current smallest (best) wse, used to update best_idx // update all weak classifiers regression parameters #pragma omp parallel for for(std::size_t wc_idx = 0 ; wc_idx < all_weak_classifiers.size(); wc_idx++) { weak_classifier &wc = all_weak_classifiers[wc_idx]; for(int j = 0; j < 255; ++j) { double numerator = 0, denominator = 0; for(std::size_t i = 0; i < training_set.size(); ++i) { if(training_set[i].first[wc.k] == j) { numerator += weights[i] * training_set[i].second; denominator += weights[i]; } } if(denominator != 0) wc.regression_parameters[j] = numerator / denominator; else wc.regression_parameters[j] = 1; } double wse = 0; for(std::size_t i = 0; i < training_set.size(); ++i) { double value = wc.regression_parameters[training_set[i].first[wc.k]]; wse += weights[i] * std::pow(value - training_set[i].second, 2); } #pragma omp critical(best_wse_update) { if(best_idx < 0 || wse < best_wse) { best_wse = wse; best_idx = wc_idx; } } } std::cout << "best wse " << best_wse << std::endl; // get a copy of the best weak_classifier before deleting it weak_classifier best_weak_classifier(all_weak_classifiers[best_idx]); weak_classifier &bwc = best_weak_classifier; std::cout << "new weak_classifier:" << std::endl; std::cout << " feature:" << std::endl; std::cout << " (x, y) = (" << bwc.feature.x << ", " << bwc.feature.y << ")" << std::endl; std::cout << " block_w = " << bwc.feature.block_w << std::endl; std::cout << " block_h = " << bwc.feature.block_h << std::endl; std::cout << " k = " << bwc.k << std::endl; std::cout << " regression_parameters = [ "; for(int i = 0; i < 255; ++i) std::cout << bwc.regression_parameters[i] << " "; std::cout << "]" << std::endl; // delete selected weak_classifier from the whole set all_weak_classifiers.erase(all_weak_classifiers.begin() + best_idx); // add new weak_classifier to the strong_classifier new_strong_classifier.weak_classifiers.push_back(best_weak_classifier); // update weights double sum = 0; for(std::size_t i = 0; i < weights.size(); ++i) { double value = bwc.regression_parameters[training_set[i].first[bwc.k]]; weights[i] = weights[i] * std::exp(-training_set[i].second * value); sum += weights[i]; } for(std::size_t i = 0; i < weights.size(); ++i) weights[i] /= sum; } // add new strong_classifier to the mblbp_classifier classifier.strong_classifiers.push_back(new_strong_classifier); // calculate new detection and miss rates std::tie(tp_rate, tn_rate, fp_rate, fn_rate) = evaluate(classifier, validation_set); detection_rate = tp_rate; std::cout << "detection_rate = " << detection_rate << std::endl; std::cout << "true positive = " << tp_rate << std::endl; std::cout << "true negative = " << tn_rate << std::endl; std::cout << "false positive = " << fp_rate << std::endl; std::cout << "false negative = " << fn_rate << std::endl; n_iter++; } while(classifier.strong_classifiers.size() < train_n_strong && (detection_rate < target_detection_rate || fp_rate > target_fp_rate)); return classifier; } <|endoftext|>
<commit_before>/* Copyright (C) 2011 Xavier Pujol. This file is part of fplll. fplll 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. fplll 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 fplll. If not, see <http://www.gnu.org/licenses/>. */ #include "util.h" #ifdef DEBUG int debugDepth = 0; #endif FPLLL_BEGIN_NAMESPACE enum MinPrecAlgo { MINPREC_GSO, MINPREC_L2 }; /* State of LDConvHelper (declared in nr.h, must be defined in exactly one source file) */ #ifdef FPLLL_WITH_LONG_DOUBLE mpfr_t LDConvHelper::temp; bool LDConvHelper::tempInitialized = false; #endif /* State of the random generator (declared in nr.h, must be defined in exactly one source file) */ bool RandGen::initialized = false; gmp_randstate_t RandGen::gmpState; static int computeMinPrec(double& rho, int d, double delta, double eta, double epsilon, MinPrecAlgo algo) { int oldprec = Float::setprec(53); Float fMinprec, fRho, fD, fEta, fDelta, fEpsilon, tmp1, tmp2; // These four conversions are exact fD = static_cast<double>(d); fEta = eta; fDelta = delta; fEpsilon = epsilon; if (algo == MINPREC_L2) { // eta - 0.5 is an exact fp operation if (fEpsilon > eta - 0.5) fEpsilon = eta - 0.5; tmp1 = 1.0; tmp1.sub(tmp1, fDelta, GMP_RNDD); if (fEpsilon > tmp1) fEpsilon = tmp1; // now fEpsilon <= min(epsilon, eta - 0.5, 1 - delta); } // Computes tmp1 >= (1 + eta) ^ 2 + epsilon tmp1 = 1.0; // exact tmp1.add(fEta, tmp1, GMP_RNDU); // >= 1 + eta tmp1.mul(tmp1, tmp1, GMP_RNDU); // >= (1 + eta) ^ 2 tmp1.add(tmp1, fEpsilon, GMP_RNDU); // Computes tmp2 <= delta - eta ^ 2 tmp2.mul(fEta, fEta, GMP_RNDU); tmp2.sub(fDelta, tmp2, GMP_RNDD); FPLLL_CHECK(tmp2 > 0, "invalid LLL parameters, eta must be < sqrt(delta)"); // Computes rho >= ((1 + eta) ^ 2 + epsilon) / (delta - eta ^ 2) fRho.div(tmp1, tmp2, GMP_RNDU); rho = fRho.get_d(GMP_RNDU); /* Computes minprec >= constant + 2 * log2(d) - log2(epsilon) + d * log2(rho) (constant = 5 for GSO, 10 for LLL) */ tmp1.log(fD, GMP_RNDU); // >= log(d) tmp1.mul_2si(tmp1, 1); // >= 2 * log(d) tmp2.log(fEpsilon, GMP_RNDD); // <= log(epsilon) (<= 0) tmp1.sub(tmp1, tmp2, GMP_RNDU); // >= 2 * log(d) - log(epsilon) tmp2.log(fRho, GMP_RNDU); // >= log(rho) tmp2.mul(fD, tmp2, GMP_RNDU); // >= d * log(rho) tmp1.add(tmp1, tmp2, GMP_RNDU); // >= 2*log(d)-log(epsilon)+d*log(rho) tmp2 = 2.0; // exact tmp2.log(tmp2, GMP_RNDD); // <= log(2) tmp1.div(tmp1, tmp2, GMP_RNDU); // >= 2*log2(d)-log2(epsilon)+d*log2(rho) tmp2 = (algo == MINPREC_L2) ? 10.0 : 5.0; fMinprec.add(tmp1, tmp2, GMP_RNDU); int minprec = static_cast<int>(ceil(fMinprec.get_d(GMP_RNDU))); Float::setprec(oldprec); return minprec; } int gsoMinPrec(double& rho, int d, double delta, double eta, double epsilon) { return computeMinPrec(rho, d, delta, eta, epsilon, MINPREC_GSO); } int l2MinPrec(int d, double delta, double eta, double epsilon) { double rho; return computeMinPrec(rho, d, delta, eta, epsilon, MINPREC_L2); } /** * Computes the volume of a d-dimensional hypersphere of radius 1. */ void sphereVolume(Float& volume, int d) { Float rtmp1; volume = pow(M_PI, (double)(d / 2)); if (d % 2 == 0) for (int i = 1; i <= d / 2; i++) { rtmp1 = (double) i; volume.div(volume, rtmp1); } else for (int i = 0; i <= d / 2; i++) { rtmp1 = 2.0 / (double)(2 * i + 1); volume.mul(volume, rtmp1); } } /** * Estimates the cost of the enumeration for SVP. */ void costEstimate(Float& cost, const Float& bound, const Matrix<Float>& r, int dimMax) { Float det, levelCost, tmp1; det = 1.0; cost = 0.0; for (int i = dimMax - 1; i >= 0; i--) { tmp1.div(bound, r(i, i)); det.mul(det, tmp1); levelCost.sqrt(det); sphereVolume(tmp1, dimMax - i); levelCost.mul(levelCost, tmp1); cost.add(cost, levelCost); } } #ifdef FPLLL_V3_COMPAT void gramSchmidt(const IntMatrix& b, Matrix<Float>& mu, FloatVect& rdiag) { int d = b.getRows(); int n = b.getCols(); Matrix<Float> r(d, d); Integer dotProd; Float coeff; FPLLL_DEBUG_CHECK(mu.getRows() == d && mu.getCols() == d); if (static_cast<int>(rdiag.size()) != d) rdiag.resize(d); for (int i = 0; i < d; i++) { for (int j = 0; j <= i; j++) { dotProd = 0; for (int k = 0; k < n; k++) { dotProd.addmul(b(i, k), b(j, k)); } coeff.set_z(dotProd); for (int k = 0; k < j; k++) { coeff.submul(mu(j, k), r(i, k)); } r(i, j) = coeff; mu(i, j).div(coeff, r(j, j)); } rdiag[i].set(r(i, i)); } } #endif // #ifdef FPLLL_V3_COMPAT FPLLL_END_NAMESPACE <commit_msg>try to fix for https://gforge.inria.fr/tracker/?func=detail&group_id=1015&atid=4076&aid=20305<commit_after>/* Copyright (C) 2011 Xavier Pujol. This file is part of fplll. fplll 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. fplll 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 fplll. If not, see <http://www.gnu.org/licenses/>. */ #include "util.h" #ifdef DEBUG int debugDepth = 0; #endif FPLLL_BEGIN_NAMESPACE enum MinPrecAlgo { MINPREC_GSO, MINPREC_L2 }; /* State of LDConvHelper (declared in nr.h, must be defined in exactly one source file) */ #ifdef FPLLL_WITH_LONG_DOUBLE mpfr_t LDConvHelper::temp; bool LDConvHelper::tempInitialized = false; #endif /* State of the random generator (declared in nr.h, must be defined in exactly one source file) */ bool RandGen::initialized = false; gmp_randstate_t RandGen::gmpState; static int computeMinPrec(double& rho, int d, double delta, double eta, double epsilon, MinPrecAlgo algo) { int oldprec = Float::setprec(53); Float fMinprec, fRho, fD, fEta, fDelta, fEpsilon, tmp1, tmp2; // These four conversions are exact fD = static_cast<double>(d); fEta = eta; fDelta = delta; fEpsilon = epsilon; if (algo == MINPREC_L2) { // eta - 0.5 is an exact fp operation if (fEpsilon > eta - 0.5) fEpsilon = eta - 0.5; tmp1 = 1.0; tmp1.sub(tmp1, fDelta, GMP_RNDD); if (fEpsilon > tmp1) fEpsilon = tmp1; // now fEpsilon <= min(epsilon, eta - 0.5, 1 - delta); } // Computes tmp1 >= (1 + eta) ^ 2 + epsilon tmp1 = 1.0; // exact tmp1.add(fEta, tmp1, GMP_RNDU); // >= 1 + eta tmp1.mul(tmp1, tmp1, GMP_RNDU); // >= (1 + eta) ^ 2 tmp1.add(tmp1, fEpsilon, GMP_RNDU); // Computes tmp2 <= delta - eta ^ 2 tmp2.mul(fEta, fEta, GMP_RNDU); tmp2.sub(fDelta, tmp2, GMP_RNDD); FPLLL_CHECK(tmp2 > 0, "invalid LLL parameters, eta must be < sqrt(delta)"); // Computes rho >= ((1 + eta) ^ 2 + epsilon) / (delta - eta ^ 2) fRho.div(tmp1, tmp2, GMP_RNDU); rho = fRho.get_d(GMP_RNDU); /* Computes minprec >= constant + 2 * log2(d) - log2(epsilon) + d * log2(rho) (constant = 5 for GSO, 10 for LLL) */ tmp1.log(fD, GMP_RNDU); // >= log(d) tmp1.mul_2si(tmp1, 1); // >= 2 * log(d) tmp2.log(fEpsilon, GMP_RNDD); // <= log(epsilon) (<= 0) tmp1.sub(tmp1, tmp2, GMP_RNDU); // >= 2 * log(d) - log(epsilon) tmp2.log(fRho, GMP_RNDU); // >= log(rho) tmp2.mul(fD, tmp2, GMP_RNDU); // >= d * log(rho) tmp1.add(tmp1, tmp2, GMP_RNDU); // >= 2*log(d)-log(epsilon)+d*log(rho) tmp2 = 2.0; // exact tmp2.log(tmp2, GMP_RNDD); // <= log(2) tmp1.div(tmp1, tmp2, GMP_RNDU); // >= 2*log2(d)-log2(epsilon)+d*log2(rho) tmp2 = (algo == MINPREC_L2) ? 10.0 : 5.0; fMinprec.add(tmp1, tmp2, GMP_RNDU); int minprec = static_cast<int>(ceil(fMinprec.get_d(GMP_RNDU))); mpfr_free_cache(); Float::setprec(oldprec); return minprec; } int gsoMinPrec(double& rho, int d, double delta, double eta, double epsilon) { return computeMinPrec(rho, d, delta, eta, epsilon, MINPREC_GSO); } int l2MinPrec(int d, double delta, double eta, double epsilon) { double rho; return computeMinPrec(rho, d, delta, eta, epsilon, MINPREC_L2); } /** * Computes the volume of a d-dimensional hypersphere of radius 1. */ void sphereVolume(Float& volume, int d) { Float rtmp1; volume = pow(M_PI, (double)(d / 2)); if (d % 2 == 0) for (int i = 1; i <= d / 2; i++) { rtmp1 = (double) i; volume.div(volume, rtmp1); } else for (int i = 0; i <= d / 2; i++) { rtmp1 = 2.0 / (double)(2 * i + 1); volume.mul(volume, rtmp1); } } /** * Estimates the cost of the enumeration for SVP. */ void costEstimate(Float& cost, const Float& bound, const Matrix<Float>& r, int dimMax) { Float det, levelCost, tmp1; det = 1.0; cost = 0.0; for (int i = dimMax - 1; i >= 0; i--) { tmp1.div(bound, r(i, i)); det.mul(det, tmp1); levelCost.sqrt(det); sphereVolume(tmp1, dimMax - i); levelCost.mul(levelCost, tmp1); cost.add(cost, levelCost); } } #ifdef FPLLL_V3_COMPAT void gramSchmidt(const IntMatrix& b, Matrix<Float>& mu, FloatVect& rdiag) { int d = b.getRows(); int n = b.getCols(); Matrix<Float> r(d, d); Integer dotProd; Float coeff; FPLLL_DEBUG_CHECK(mu.getRows() == d && mu.getCols() == d); if (static_cast<int>(rdiag.size()) != d) rdiag.resize(d); for (int i = 0; i < d; i++) { for (int j = 0; j <= i; j++) { dotProd = 0; for (int k = 0; k < n; k++) { dotProd.addmul(b(i, k), b(j, k)); } coeff.set_z(dotProd); for (int k = 0; k < j; k++) { coeff.submul(mu(j, k), r(i, k)); } r(i, j) = coeff; mu(i, j).div(coeff, r(j, j)); } rdiag[i].set(r(i, i)); } } #endif // #ifdef FPLLL_V3_COMPAT FPLLL_END_NAMESPACE <|endoftext|>
<commit_before>#include <json/util.hpp> #include <json/value.hpp> #include <sstream> namespace JSON { void stringtojsonstream(const std::string &s, std::ostream &o) { o << "\""; for (std::string::const_iterator I = s.begin(); I != s.end(); I++) { switch(*I) { case '\"': o << "\\\""; break; case '\\': o << "\\\\"; break; case '\b': o << "\\b"; break; case '\f': o << "\\f"; break; case '\n': o << "\\n"; break; case '\r': o << "\\r"; break; case '\t': o << "\\t"; break; default: o << *I; break; } } o << "\""; } void jsonstringtostring(std::string &s, std::istream &i) { std::ostringstream o; int c = i.get(); if (c != '\"') { throw ParserError(c); } for (;;) { if (i.eof()) { throw ParserError("eof detected on stream"); } c = i.get(); if (c == '\"') { break; } if (c == '\\') { c = i.get(); switch(c) { case '\"': o << '\"'; break; case '\\': o << '\\'; break; case 'b': o << '\b'; break; case 'f': o << '\f'; break; case 'n': o << '\n'; break; case 'r': o << '\r'; break; case 't': o << '\t'; break; default: o << c; break; } } else { o << static_cast<char>(c); } } s = o.str(); } }; <commit_msg>JSON::jsonstringtostring() fix for parsing '\/'<commit_after>#include <json/util.hpp> #include <json/value.hpp> #include <sstream> namespace JSON { void stringtojsonstream(const std::string &s, std::ostream &o) { o << "\""; for (std::string::const_iterator I = s.begin(); I != s.end(); I++) { switch(*I) { case '\"': o << "\\\""; break; case '\\': o << "\\\\"; break; case '\b': o << "\\b"; break; case '\f': o << "\\f"; break; case '\n': o << "\\n"; break; case '\r': o << "\\r"; break; case '\t': o << "\\t"; break; default: o << *I; break; } } o << "\""; } void jsonstringtostring(std::string &s, std::istream &i) { std::ostringstream o; char c = i.get(); if (c != '\"') { throw ParserError(c); } for (;;) { if (i.eof()) { throw ParserError("eof detected on stream"); } c = i.get(); if (c == '\"') { break; } if (c == '\\') { c = i.get(); switch(c) { case '\"': o << '\"'; break; case '\\': o << '\\'; break; case 'b': o << '\b'; break; case 'f': o << '\f'; break; case 'n': o << '\n'; break; case 'r': o << '\r'; break; case 't': o << '\t'; break; default: o << c; break; } } else { o << c; } } s = o.str(); } }; <|endoftext|>
<commit_before>// Copyright (c) 2011-2017 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <sync.h> #include <logging.h> #include <utilstrencodings.h> #include <stdio.h> #include <map> #include <memory> #include <set> #ifdef DEBUG_LOCKCONTENTION #if !defined(HAVE_THREAD_LOCAL) static_assert(false, "thread_local is not supported"); #endif void PrintLockContention(const char* pszName, const char* pszFile, int nLine) { LogPrintf("LOCKCONTENTION: %s\n", pszName); LogPrintf("Locker: %s:%d\n", pszFile, nLine); } #endif /* DEBUG_LOCKCONTENTION */ #ifdef DEBUG_LOCKORDER // // Early deadlock detection. // Problem being solved: // Thread 1 locks A, then B, then C // Thread 2 locks D, then C, then A // --> may result in deadlock between the two threads, depending on when they run. // Solution implemented here: // Keep track of pairs of locks: (A before B), (A before C), etc. // Complain if any thread tries to lock in a different order. // struct CLockLocation { CLockLocation(const char* pszName, const char* pszFile, int nLine, bool fTryIn) { mutexName = pszName; sourceFile = pszFile; sourceLine = nLine; fTry = fTryIn; } std::string ToString() const { return mutexName + " " + sourceFile + ":" + itostr(sourceLine) + (fTry ? " (TRY)" : ""); } private: bool fTry; std::string mutexName; std::string sourceFile; int sourceLine; }; typedef std::vector<std::pair<void*, CLockLocation> > LockStack; typedef std::map<std::pair<void*, void*>, LockStack> LockOrders; typedef std::set<std::pair<void*, void*> > InvLockOrders; struct LockData { // Very ugly hack: as the global constructs and destructors run single // threaded, we use this boolean to know whether LockData still exists, // as DeleteLock can get called by global CCriticalSection destructors // after LockData disappears. bool available; LockData() : available(true) {} ~LockData() { available = false; } LockOrders lockorders; InvLockOrders invlockorders; std::mutex dd_mutex; } static lockdata; static thread_local std::unique_ptr<LockStack> lockstack; static void potential_deadlock_detected(const std::pair<void*, void*>& mismatch, const LockStack& s1, const LockStack& s2) { LogPrintf("POTENTIAL DEADLOCK DETECTED\n"); LogPrintf("Previous lock order was:\n"); for (const std::pair<void*, CLockLocation> & i : s2) { if (i.first == mismatch.first) { LogPrintf(" (1)"); /* Continued */ } if (i.first == mismatch.second) { LogPrintf(" (2)"); /* Continued */ } LogPrintf(" %s\n", i.second.ToString()); } LogPrintf("Current lock order is:\n"); for (const std::pair<void*, CLockLocation> & i : s1) { if (i.first == mismatch.first) { LogPrintf(" (1)"); /* Continued */ } if (i.first == mismatch.second) { LogPrintf(" (2)"); /* Continued */ } LogPrintf(" %s\n", i.second.ToString()); } assert(false); } static void push_lock(void* c, const CLockLocation& locklocation) { if (!lockstack) lockstack.reset(new LockStack); std::lock_guard<std::mutex> lock(lockdata.dd_mutex); lockstack->push_back(std::make_pair(c, locklocation)); for (const std::pair<void*, CLockLocation> & i : (*lockstack)) { if (i.first == c) break; std::pair<void*, void*> p1 = std::make_pair(i.first, c); if (lockdata.lockorders.count(p1)) continue; lockdata.lockorders[p1] = (*lockstack); std::pair<void*, void*> p2 = std::make_pair(c, i.first); lockdata.invlockorders.insert(p2); if (lockdata.lockorders.count(p2)) potential_deadlock_detected(p1, lockdata.lockorders[p2], lockdata.lockorders[p1]); } } static void pop_lock() { (*lockstack).pop_back(); } void EnterCritical(const char* pszName, const char* pszFile, int nLine, void* cs, bool fTry) { push_lock(cs, CLockLocation(pszName, pszFile, nLine, fTry)); } void LeaveCritical() { pop_lock(); } std::string LocksHeld() { std::string result; for (const std::pair<void*, CLockLocation> & i : *lockstack) result += i.second.ToString() + std::string("\n"); return result; } void AssertLockHeldInternal(const char* pszName, const char* pszFile, int nLine, void* cs) { for (const std::pair<void*, CLockLocation> & i : *lockstack) if (i.first == cs) return; fprintf(stderr, "Assertion failed: lock %s not held in %s:%i; locks held:\n%s", pszName, pszFile, nLine, LocksHeld().c_str()); abort(); } void AssertLockNotHeldInternal(const char* pszName, const char* pszFile, int nLine, void* cs) { for (const std::pair<void*, CLockLocation>& i : *lockstack) { if (i.first == cs) { fprintf(stderr, "Assertion failed: lock %s held in %s:%i; locks held:\n%s", pszName, pszFile, nLine, LocksHeld().c_str()); abort(); } } } void DeleteLock(void* cs) { if (!lockdata.available) { // We're already shutting down. return; } std::lock_guard<std::mutex> lock(lockdata.dd_mutex); std::pair<void*, void*> item = std::make_pair(cs, nullptr); LockOrders::iterator it = lockdata.lockorders.lower_bound(item); while (it != lockdata.lockorders.end() && it->first.first == cs) { std::pair<void*, void*> invitem = std::make_pair(it->first.second, it->first.first); lockdata.invlockorders.erase(invitem); lockdata.lockorders.erase(it++); } InvLockOrders::iterator invit = lockdata.invlockorders.lower_bound(item); while (invit != lockdata.invlockorders.end() && invit->first == cs) { std::pair<void*, void*> invinvitem = std::make_pair(invit->second, invit->first); lockdata.lockorders.erase(invinvitem); lockdata.invlockorders.erase(invit++); } } #endif /* DEBUG_LOCKORDER */ <commit_msg>qa: Initialize lockstack to prevent null pointer deref<commit_after>// Copyright (c) 2011-2017 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <sync.h> #include <logging.h> #include <utilstrencodings.h> #include <stdio.h> #include <map> #include <memory> #include <set> #ifdef DEBUG_LOCKCONTENTION #if !defined(HAVE_THREAD_LOCAL) static_assert(false, "thread_local is not supported"); #endif void PrintLockContention(const char* pszName, const char* pszFile, int nLine) { LogPrintf("LOCKCONTENTION: %s\n", pszName); LogPrintf("Locker: %s:%d\n", pszFile, nLine); } #endif /* DEBUG_LOCKCONTENTION */ #ifdef DEBUG_LOCKORDER // // Early deadlock detection. // Problem being solved: // Thread 1 locks A, then B, then C // Thread 2 locks D, then C, then A // --> may result in deadlock between the two threads, depending on when they run. // Solution implemented here: // Keep track of pairs of locks: (A before B), (A before C), etc. // Complain if any thread tries to lock in a different order. // struct CLockLocation { CLockLocation(const char* pszName, const char* pszFile, int nLine, bool fTryIn) { mutexName = pszName; sourceFile = pszFile; sourceLine = nLine; fTry = fTryIn; } std::string ToString() const { return mutexName + " " + sourceFile + ":" + itostr(sourceLine) + (fTry ? " (TRY)" : ""); } private: bool fTry; std::string mutexName; std::string sourceFile; int sourceLine; }; typedef std::vector<std::pair<void*, CLockLocation> > LockStack; typedef std::map<std::pair<void*, void*>, LockStack> LockOrders; typedef std::set<std::pair<void*, void*> > InvLockOrders; struct LockData { // Very ugly hack: as the global constructs and destructors run single // threaded, we use this boolean to know whether LockData still exists, // as DeleteLock can get called by global CCriticalSection destructors // after LockData disappears. bool available; LockData() : available(true) {} ~LockData() { available = false; } LockOrders lockorders; InvLockOrders invlockorders; std::mutex dd_mutex; } static lockdata; static thread_local LockStack g_lockstack; static void potential_deadlock_detected(const std::pair<void*, void*>& mismatch, const LockStack& s1, const LockStack& s2) { LogPrintf("POTENTIAL DEADLOCK DETECTED\n"); LogPrintf("Previous lock order was:\n"); for (const std::pair<void*, CLockLocation> & i : s2) { if (i.first == mismatch.first) { LogPrintf(" (1)"); /* Continued */ } if (i.first == mismatch.second) { LogPrintf(" (2)"); /* Continued */ } LogPrintf(" %s\n", i.second.ToString()); } LogPrintf("Current lock order is:\n"); for (const std::pair<void*, CLockLocation> & i : s1) { if (i.first == mismatch.first) { LogPrintf(" (1)"); /* Continued */ } if (i.first == mismatch.second) { LogPrintf(" (2)"); /* Continued */ } LogPrintf(" %s\n", i.second.ToString()); } assert(false); } static void push_lock(void* c, const CLockLocation& locklocation) { std::lock_guard<std::mutex> lock(lockdata.dd_mutex); g_lockstack.push_back(std::make_pair(c, locklocation)); for (const std::pair<void*, CLockLocation>& i : g_lockstack) { if (i.first == c) break; std::pair<void*, void*> p1 = std::make_pair(i.first, c); if (lockdata.lockorders.count(p1)) continue; lockdata.lockorders[p1] = g_lockstack; std::pair<void*, void*> p2 = std::make_pair(c, i.first); lockdata.invlockorders.insert(p2); if (lockdata.lockorders.count(p2)) potential_deadlock_detected(p1, lockdata.lockorders[p2], lockdata.lockorders[p1]); } } static void pop_lock() { g_lockstack.pop_back(); } void EnterCritical(const char* pszName, const char* pszFile, int nLine, void* cs, bool fTry) { push_lock(cs, CLockLocation(pszName, pszFile, nLine, fTry)); } void LeaveCritical() { pop_lock(); } std::string LocksHeld() { std::string result; for (const std::pair<void*, CLockLocation>& i : g_lockstack) result += i.second.ToString() + std::string("\n"); return result; } void AssertLockHeldInternal(const char* pszName, const char* pszFile, int nLine, void* cs) { for (const std::pair<void*, CLockLocation>& i : g_lockstack) if (i.first == cs) return; fprintf(stderr, "Assertion failed: lock %s not held in %s:%i; locks held:\n%s", pszName, pszFile, nLine, LocksHeld().c_str()); abort(); } void AssertLockNotHeldInternal(const char* pszName, const char* pszFile, int nLine, void* cs) { for (const std::pair<void*, CLockLocation>& i : g_lockstack) { if (i.first == cs) { fprintf(stderr, "Assertion failed: lock %s held in %s:%i; locks held:\n%s", pszName, pszFile, nLine, LocksHeld().c_str()); abort(); } } } void DeleteLock(void* cs) { if (!lockdata.available) { // We're already shutting down. return; } std::lock_guard<std::mutex> lock(lockdata.dd_mutex); std::pair<void*, void*> item = std::make_pair(cs, nullptr); LockOrders::iterator it = lockdata.lockorders.lower_bound(item); while (it != lockdata.lockorders.end() && it->first.first == cs) { std::pair<void*, void*> invitem = std::make_pair(it->first.second, it->first.first); lockdata.invlockorders.erase(invitem); lockdata.lockorders.erase(it++); } InvLockOrders::iterator invit = lockdata.invlockorders.lower_bound(item); while (invit != lockdata.invlockorders.end() && invit->first == cs) { std::pair<void*, void*> invinvitem = std::make_pair(invit->second, invit->first); lockdata.lockorders.erase(invinvitem); lockdata.invlockorders.erase(invit++); } } #endif /* DEBUG_LOCKORDER */ <|endoftext|>
<commit_before>// Test.cpp // Sean Jones #define GLFW_INCLUDE_GLU #include <GLFW/glfw3.h> #include <chrono> #include <glm/glm.hpp> #include <glm/gtx/constants.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> using namespace std::chrono; GLFWwindow* window; bool running = true; // Value to keep track of current orientation on axis float orientation = 0.0f; bool initialise() { // Set Color to cyan glClearColor(0.0f, 1.0f, 1.0f, 1.0f); //Enable face culling glEnable(GL_CULL_FACE); return true; } // initialise //updates the application void update(double deltaTime) { // Check if escape pressed or window is closed running = !glfwGetKey(window, GLFW_KEY_ESCAPE) && !glfwWindowShouldClose(window); // Rotate at half a rotation (pi radians) per second orientation += (deltaTime * glm::pi<float>()); } // update //renders the application void render() { // Create rotation transform. Use Z-axis glm::mat4 model = glm::rotate(glm::mat4(10.f), glm::degrees(orientation), glm::vec3(0.0f, 0.0f, 1.0f)); // Set the matrix we are using glMatrixMode(GL_MODELVIEW); // Load the matrix (use it) glLoadMatrixf(glm::value_ptr(model)); // Clear the screen glClear(GL_COLOR_BUFFER_BIT); //Set the colour glColor4f(1.0f, 0.0f, 0.0f, 1.0f); //Render a Triangel glBegin(GL_TRIANGLES); glColor3f(1.0f, 0.0f, 0.0f); glVertex3f(0.0f, 0.5f, 0.0f); glColor3f(0.0f, 1.0f, 0.0f); glVertex3f(-0.5f, -0.5f, 0.0f); glColor3f(0.0f, 0.0f, 1.0f); glVertex3f(0.5f, -0.5f, 0.0f); glEnd(); // Swap front and back buffers glfwSwapBuffers(window); // Load the identity matrix (ensures transformation is reset) } // render int main(void) { /* Initialize the library */ if (!glfwInit()) { return -1; } /* Create a windowed mode window and its OpenGL context */ window = glfwCreateWindow(640, 480, "Hello World", NULL, NULL); if (!window) { glfwTerminate(); return -1; } /* Make the window's context current */ glfwMakeContextCurrent(window); //initialise the window if (!initialise()) { glfwTerminate(); return -1; } // Monitor the elapsed time per frame auto currentTimeStamp = system_clock::now(); auto prevTimeStamp = system_clock::now(); /* Loop until the user closes the window */ while (!glfwWindowShouldClose(window)) { // Get current time currentTimeStamp = system_clock::now(); // Calculate elapsed time auto elapsed = duration_cast<milliseconds>(currentTimeStamp - prevTimeStamp); //Convert to fractions of a second auto seconds = double(elapsed.count()) / 1000.0; // Update Application update(seconds); //Render scene render(); /* Swap front and back buffers */ glfwSwapBuffers(window); /* Poll for and process events */ glfwPollEvents(); // set the previous time stamp to current time stamp prevTimeStamp = currentTimeStamp; } // Main Loop glfwTerminate(); return 0; } // main <commit_msg>Completed Exercise 5.2.1<commit_after>// Test.cpp // Sean Jones #define GLFW_INCLUDE_GLU #include <GLFW/glfw3.h> #include <chrono> #include <glm/glm.hpp> #include <glm/gtx/constants.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> using namespace std::chrono; GLFWwindow* window; bool running = true; // Value to keep track of current orientation on axis float orientation = 0.0f; bool initialise() { // Set Color to cyan glClearColor(0.0f, 1.0f, 1.0f, 1.0f); return true; } // initialise //updates the application void update(double deltaTime) { // Check if escape pressed or window is closed running = !glfwGetKey(window, GLFW_KEY_ESCAPE) && !glfwWindowShouldClose(window); // Rotate at half a rotation (pi radians) per second orientation += (deltaTime * glm::pi<float>()); } // update //renders the application void render() { // Create rotation transform. Use Z-axis glm::mat4 model = glm::rotate(glm::mat4(10.f), glm::degrees(orientation), glm::vec3(0.0f, 1.0f, 0.0f)); // Set the matrix we are using glMatrixMode(GL_MODELVIEW); // Load the matrix (use it) glLoadMatrixf(glm::value_ptr(model)); // Clear the screen glClear(GL_COLOR_BUFFER_BIT); //Set the colour glColor4f(1.0f, 0.0f, 0.0f, 1.0f); //Render a Triangel glBegin(GL_TRIANGLES); glColor3f(1.0f, 0.0f, 0.0f); glVertex3f(0.0f, 0.5f, 0.0f); glColor3f(0.0f, 1.0f, 0.0f); glVertex3f(-0.5f, -0.5f, 0.0f); glColor3f(0.0f, 0.0f, 1.0f); glVertex3f(0.5f, -0.5f, 0.0f); glEnd(); // Swap front and back buffers glfwSwapBuffers(window); // Load the identity matrix (ensures transformation is reset) } // render int main(void) { /* Initialize the library */ if (!glfwInit()) { return -1; } /* Create a windowed mode window and its OpenGL context */ window = glfwCreateWindow(640, 480, "Hello World", NULL, NULL); if (!window) { glfwTerminate(); return -1; } /* Make the window's context current */ glfwMakeContextCurrent(window); //initialise the window if (!initialise()) { glfwTerminate(); return -1; } // Monitor the elapsed time per frame auto currentTimeStamp = system_clock::now(); auto prevTimeStamp = system_clock::now(); /* Loop until the user closes the window */ while (!glfwWindowShouldClose(window)) { // Get current time currentTimeStamp = system_clock::now(); // Calculate elapsed time auto elapsed = duration_cast<milliseconds>(currentTimeStamp - prevTimeStamp); //Convert to fractions of a second auto seconds = double(elapsed.count()) / 1000.0; // Update Application update(seconds); //Render scene render(); /* Swap front and back buffers */ glfwSwapBuffers(window); /* Poll for and process events */ glfwPollEvents(); // set the previous time stamp to current time stamp prevTimeStamp = currentTimeStamp; } // Main Loop glfwTerminate(); return 0; } // main <|endoftext|>
<commit_before>/********************************* ** Tsunagari Tile Engine ** ** tile.cpp ** ** Copyright 2011-2012 OmegaSDG ** *********************************/ #include <boost/foreach.hpp> #include "area.h" #include "python.h" #include "python_optional.h" #include "tile.h" #include "window.h" FlagManip::FlagManip(unsigned* flags) : flags(flags) { } bool FlagManip::isNowalk() const { return (*flags & TILE_NOWALK) != 0; } bool FlagManip::isNowalkPlayer() const { return (*flags & TILE_NOWALK_PLAYER) != 0; } bool FlagManip::isNowalkNPC() const { return (*flags & TILE_NOWALK_NPC) != 0; } void FlagManip::setNowalk(bool nowalk) { *flags = (*flags & ~TILE_NOWALK) | TILE_NOWALK * nowalk; } void FlagManip::setNowalkPlayer(bool nowalk) { *flags = (*flags & ~TILE_NOWALK_PLAYER) | TILE_NOWALK_PLAYER * nowalk; } void FlagManip::setNowalkNPC(bool nowalk) { *flags = (*flags & ~TILE_NOWALK_NPC) | TILE_NOWALK_NPC * nowalk; } Exit::Exit() { } Exit::Exit(const std::string area, int x, int y, double z) : area(area), coord(x, y, z) { } TileBase::TileBase() : parent(NULL), flags(0x0) { } bool TileBase::hasFlag(unsigned flag) const { return flags & flag || (parent && parent->hasFlag(flag)); } FlagManip TileBase::flagManip() { return FlagManip(&flags); } TileType* TileBase::getType() { return (TileType*)parent; } void TileBase::setType(TileType* type) { parent = type; } void TileBase::onEnterScripts(Entity* triggeredBy) { runScripts(triggeredBy, onEnter); if (parent) parent->onEnterScripts(triggeredBy); } void TileBase::onLeaveScripts(Entity* triggeredBy) { runScripts(triggeredBy, onLeave); if (parent) parent->onLeaveScripts(triggeredBy); } void TileBase::onUseScripts(Entity* triggeredBy) { runScripts(triggeredBy, onUse); if (parent) parent->onUseScripts(triggeredBy); } void TileBase::runScripts(Entity* triggeredBy, const std::vector<std::string>& events) { BOOST_FOREACH(const std::string& script, events) { Resourcer* rc = Resourcer::instance(); pythonSetGlobal("entity", triggeredBy); pythonSetGlobal("tile", this); rc->runPythonScript(script); } } Tile::Tile() { } Tile::Tile(Area* area, int x, int y, int z) : TileBase(), area(area), x(x), y(y), z(z) { memset(exits, 0, sizeof(exits)); } Tile& Tile::offset(int x, int y) { return area->getTile(this->x + x, this->y + y, z); } Exit* Tile::getNormalExit() { return exits[EXIT_NORMAL]; } void Tile::setNormalExit(Exit exit) { Exit** norm = &exits[EXIT_NORMAL]; if (*norm) delete *norm; *norm = new Exit(exit); } Exit* Tile::exitAt(int x, int y) { switch (x) { case -1: return y == 0 ? exits[EXIT_LEFT] : NULL; case 0: switch (y) { case -1: return exits[EXIT_UP]; case 0: return exits[EXIT_NORMAL]; case 1: return exits[EXIT_DOWN]; default: return NULL; } break; case 1: return y == 0 ? exits[EXIT_RIGHT] : NULL; default: return NULL; } } TileType::TileType() : TileBase() { } TileType::TileType(TiledImage& img) : TileBase() { anim.addFrame(img.front()); img.pop_front(); } bool TileType::needsRedraw(const Area& area) const { const int millis = GameWindow::getWindow().time(); return anim.needsRedraw(millis) && visibleIn(area, area.visibleTiles()); } bool TileType::visibleIn(const Area& area, const icube_t& tiles) const { for (int z = tiles.z1; z != tiles.z2; z++) { for (int y = tiles.y1; y != tiles.y2; y++) { for (int x = tiles.x1; x != tiles.x2; x++) { icoord pos(x, y, z); // Do this check before passing _tiles_ to fn. if (area.inBounds(pos)) { const Tile& tile = area.getTile(pos); if (tile.parent == this) return true; } } } } return false; } Exit pythonNewExit(std::string area, int x, int y, double z) { return Exit(area, x, y, z); } void exportTile() { boost::python::class_<FlagManip> ("FlagManipulator", boost::python::no_init) .add_property("nowalk", &FlagManip::isNowalk, &FlagManip::setNowalk) .add_property("nowalk_player", &FlagManip::isNowalkPlayer, &FlagManip::setNowalkPlayer) .add_property("nowalk_npc", &FlagManip::isNowalkNPC, &FlagManip::setNowalkNPC) ; boost::python::class_<TileBase> ("TileBase", boost::python::no_init) .add_property("flags", &TileBase::flagManip) .add_property("type", make_function( static_cast<TileType* (TileBase::*) ()> (&TileBase::getType), boost::python::return_value_policy< boost::python::reference_existing_object >() ), &TileBase::setType ) .def("onEnterScripts", &TileBase::onEnterScripts) .def("onLeaveScripts", &TileBase::onLeaveScripts) .def("onUseScripts", &TileBase::onUseScripts) ; boost::python::class_<Tile, boost::python::bases<TileBase> > ("Tile", boost::python::no_init) .def_readonly("x", &Tile::x) .def_readonly("y", &Tile::y) .def_readonly("z", &Tile::z) .add_property("exit", make_function( static_cast<Exit* (Tile::*) ()> (&Tile::getNormalExit), boost::python::return_value_policy< boost::python::reference_existing_object >() ), &Tile::setNormalExit ) .def("offset", &Tile::offset, boost::python::return_value_policy< boost::python::reference_existing_object >() ) ; boost::python::class_<TileType, boost::python::bases<TileBase> > ("TileType", boost::python::no_init) ; boost::python::class_<Exit> ("Exit", boost::python::init< const std::string, int, int, double >()) .def_readwrite("area", &Exit::area) .def_readwrite("coord", &Exit::coord) ; pythonAddFunction("newExit", pythonNewExit); } <commit_msg>cleanup exportTile<commit_after>/********************************* ** Tsunagari Tile Engine ** ** tile.cpp ** ** Copyright 2011-2012 OmegaSDG ** *********************************/ #include <boost/foreach.hpp> #include "area.h" #include "python.h" #include "python_optional.h" #include "tile.h" #include "window.h" FlagManip::FlagManip(unsigned* flags) : flags(flags) { } bool FlagManip::isNowalk() const { return (*flags & TILE_NOWALK) != 0; } bool FlagManip::isNowalkPlayer() const { return (*flags & TILE_NOWALK_PLAYER) != 0; } bool FlagManip::isNowalkNPC() const { return (*flags & TILE_NOWALK_NPC) != 0; } void FlagManip::setNowalk(bool nowalk) { *flags = (*flags & ~TILE_NOWALK) | TILE_NOWALK * nowalk; } void FlagManip::setNowalkPlayer(bool nowalk) { *flags = (*flags & ~TILE_NOWALK_PLAYER) | TILE_NOWALK_PLAYER * nowalk; } void FlagManip::setNowalkNPC(bool nowalk) { *flags = (*flags & ~TILE_NOWALK_NPC) | TILE_NOWALK_NPC * nowalk; } Exit::Exit() { } Exit::Exit(const std::string area, int x, int y, double z) : area(area), coord(x, y, z) { } TileBase::TileBase() : parent(NULL), flags(0x0) { } bool TileBase::hasFlag(unsigned flag) const { return flags & flag || (parent && parent->hasFlag(flag)); } FlagManip TileBase::flagManip() { return FlagManip(&flags); } TileType* TileBase::getType() { return (TileType*)parent; } void TileBase::setType(TileType* type) { parent = type; } void TileBase::onEnterScripts(Entity* triggeredBy) { runScripts(triggeredBy, onEnter); if (parent) parent->onEnterScripts(triggeredBy); } void TileBase::onLeaveScripts(Entity* triggeredBy) { runScripts(triggeredBy, onLeave); if (parent) parent->onLeaveScripts(triggeredBy); } void TileBase::onUseScripts(Entity* triggeredBy) { runScripts(triggeredBy, onUse); if (parent) parent->onUseScripts(triggeredBy); } void TileBase::runScripts(Entity* triggeredBy, const std::vector<std::string>& events) { BOOST_FOREACH(const std::string& script, events) { Resourcer* rc = Resourcer::instance(); pythonSetGlobal("entity", triggeredBy); pythonSetGlobal("tile", this); rc->runPythonScript(script); } } Tile::Tile() { } Tile::Tile(Area* area, int x, int y, int z) : TileBase(), area(area), x(x), y(y), z(z) { memset(exits, 0, sizeof(exits)); } Tile& Tile::offset(int x, int y) { return area->getTile(this->x + x, this->y + y, z); } Exit* Tile::getNormalExit() { return exits[EXIT_NORMAL]; } void Tile::setNormalExit(Exit exit) { Exit** norm = &exits[EXIT_NORMAL]; if (*norm) delete *norm; *norm = new Exit(exit); } Exit* Tile::exitAt(int x, int y) { switch (x) { case -1: return y == 0 ? exits[EXIT_LEFT] : NULL; case 0: switch (y) { case -1: return exits[EXIT_UP]; case 0: return exits[EXIT_NORMAL]; case 1: return exits[EXIT_DOWN]; default: return NULL; } break; case 1: return y == 0 ? exits[EXIT_RIGHT] : NULL; default: return NULL; } } TileType::TileType() : TileBase() { } TileType::TileType(TiledImage& img) : TileBase() { anim.addFrame(img.front()); img.pop_front(); } bool TileType::needsRedraw(const Area& area) const { const int millis = GameWindow::getWindow().time(); return anim.needsRedraw(millis) && visibleIn(area, area.visibleTiles()); } bool TileType::visibleIn(const Area& area, const icube_t& tiles) const { for (int z = tiles.z1; z != tiles.z2; z++) { for (int y = tiles.y1; y != tiles.y2; y++) { for (int x = tiles.x1; x != tiles.x2; x++) { icoord pos(x, y, z); // Do this check before passing _tiles_ to fn. if (area.inBounds(pos)) { const Tile& tile = area.getTile(pos); if (tile.parent == this) return true; } } } } return false; } Exit pythonNewExit(std::string area, int x, int y, double z) { return Exit(area, x, y, z); } void exportTile() { using namespace boost::python; class_<FlagManip> ("FlagManipulator", no_init) .add_property("nowalk", &FlagManip::isNowalk, &FlagManip::setNowalk) .add_property("nowalk_player", &FlagManip::isNowalkPlayer, &FlagManip::setNowalkPlayer) .add_property("nowalk_npc", &FlagManip::isNowalkNPC, &FlagManip::setNowalkNPC) ; class_<TileBase> ("TileBase", no_init) .add_property("flags", &TileBase::flagManip) .add_property("type", make_function( static_cast<TileType* (TileBase::*) ()> (&TileBase::getType), return_value_policy<reference_existing_object>()), &TileBase::setType) .def("onEnterScripts", &TileBase::onEnterScripts) .def("onLeaveScripts", &TileBase::onLeaveScripts) .def("onUseScripts", &TileBase::onUseScripts) ; class_<Tile, bases<TileBase> > ("Tile", no_init) .def_readonly("x", &Tile::x) .def_readonly("y", &Tile::y) .def_readonly("z", &Tile::z) .add_property("exit", make_function( static_cast<Exit* (Tile::*) ()> (&Tile::getNormalExit), return_value_policy<reference_existing_object>()), &Tile::setNormalExit) .def("offset", &Tile::offset, return_value_policy<reference_existing_object>()) ; class_<TileType, bases<TileBase> > ("TileType", no_init) ; class_<Exit> ("Exit", no_init) .def_readwrite("area", &Exit::area) .def_readwrite("coord", &Exit::coord) ; pythonAddFunction("newExit", pythonNewExit); } <|endoftext|>
<commit_before>#include <iostream> #include <string> #include <sstream> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <curl/curl.h> #include <sys/utsname.h> static const char* const ANSI_COLOR_RESET_FG = "\x1b[39m"; static const char* const ANSI_COLOR_TITLE_FG = ANSI_COLOR_RESET_FG; static const char* const ANSI_COLOR_EXPLANATION_FG = ANSI_COLOR_RESET_FG; static const char* const ANSI_COLOR_COMMENT_FG = "\x1b[32m"; static const char* const ANSI_COLOR_CODE_FG = "\x1b[31m"; static const char* const ANSI_COLOR_CODE_PLACEHOLDER_FG = "\x1b[34m"; static const char* const ANSI_BOLD_ON = "\x1b[1m"; static const char* const ANSI_BOLD_OFF = "\x1b[22m"; // Constants. std::string const kBaseUrl = "http://raw.github.com/tldr-pages/tldr/master/pages"; void init_response(struct response* r); size_t writeCallback(char* raw, size_t size, size_t nmemb, std::string* data); // Fetching. std::string getUrlForArgAndPlatform(std::string const& arg, std::string const& platform); std::string getUrlForArg(std::string const& arg); std::string getContentForUrl(std::string const& url); // Utilities. void replaceAll(std::string& str, std::string const& from, std::string const& to); int main(int argc, char* argv[]) { struct utsname sys; uname(&sys); if (argc > 1) { std::string arg(argv[1]); std::string url = getUrlForArg(arg); std::string urlForPlatform = getUrlForArgAndPlatform(arg, sys.sysname); std::string response = getContentForUrl(urlForPlatform); if (response.empty()) { response = getContentForUrl(url); } replaceAll(response, "{{", ANSI_COLOR_CODE_PLACEHOLDER_FG); replaceAll(response, "}}", ANSI_COLOR_RESET_FG); std::string const stripPrefix("#"); std::string const explainPrefix(">"); std::string const commentPrefix("-"); std::string const codePrefix("`"); std::stringstream ss(response); std::string line; bool firstComment = true; while (std::getline(ss, line, '\n')) { // Title if (line.compare(0, stripPrefix.size(), stripPrefix) == 0) { replaceAll(line, "#", ANSI_COLOR_TITLE_FG); std::cout << std::endl << ANSI_BOLD_ON << line << ANSI_BOLD_OFF << ANSI_COLOR_RESET_FG << std::endl; } // Command explanation else if (line.compare(0, explainPrefix.size(), explainPrefix) == 0) { replaceAll(line, explainPrefix, ANSI_COLOR_EXPLANATION_FG); std::cout << line << ANSI_COLOR_RESET_FG << std::endl; } // Example comment else if (line.compare(0, commentPrefix.size(), commentPrefix) == 0) { if (firstComment) { std::cout << std::endl; firstComment = false; } replaceAll(line, commentPrefix, ANSI_COLOR_COMMENT_FG); std::cout << line << ANSI_COLOR_RESET_FG << std::endl; } // Code example else if (line.compare(0, codePrefix.size(), codePrefix) == 0) { // Remove trailing backtick (`). line = line.substr(0, line.size() - 1); // Replace first backtick (`) with three spaces for aligned indentation. replaceAll(line, "`", " "); std::cout << ANSI_COLOR_CODE_FG << line << ANSI_COLOR_RESET_FG << std::endl << std::endl; } } } } // ===================================== // URL determination. // ===================================== std::string getUrlForArgAndPlatform(std::string const& arg, std::string const& platform) { int isLinux = !platform.compare("Linux"); int isOSX = !platform.compare("Darwin"); std::string platformUrlDelimiter; if (isLinux) { platformUrlDelimiter = "linux"; } else if (isOSX) { platformUrlDelimiter = "osx"; } else { platformUrlDelimiter = "common"; } std::string url(kBaseUrl); url += "/" + platformUrlDelimiter + "/" + arg + ".md"; return url; } std::string getUrlForArg(std::string const& arg) { return getUrlForArgAndPlatform(arg, "common"); } // ===================================== // Curl Fetching. // ===================================== size_t writeCallback(char* raw, size_t size, size_t nmemb, std::string* data) { if (data == NULL) { return 0; } data->append(raw, size * nmemb); return size * nmemb; } std::string getContentForUrl(std::string const& url) { CURL* curl; CURLcode res; std::string response; curl = curl_easy_init(); if (curl) { curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writeCallback); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response); res = curl_easy_perform(curl); if (res == CURLE_OK) { long httpCode = 0; curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &httpCode); if (httpCode == 200) { curl_easy_cleanup(curl); return response; } else { curl_easy_cleanup(curl); return ""; } } curl_easy_cleanup(curl); } return ""; } // ===================================== // Utilities. // ===================================== void replaceAll(std::string& str, std::string const& from, std::string const& to) { if (from.empty()) { return; } size_t start_pos = 0; while ((start_pos = str.find(from, start_pos)) != std::string::npos) { str.replace(start_pos, from.length(), to); start_pos += to.length(); } } <commit_msg>allow multiple word input<commit_after>#include <iostream> #include <string> #include <sstream> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <curl/curl.h> #include <sys/utsname.h> static const char* const ANSI_COLOR_RESET_FG = "\x1b[39m"; static const char* const ANSI_COLOR_TITLE_FG = ANSI_COLOR_RESET_FG; static const char* const ANSI_COLOR_EXPLANATION_FG = ANSI_COLOR_RESET_FG; static const char* const ANSI_COLOR_COMMENT_FG = "\x1b[32m"; static const char* const ANSI_COLOR_CODE_FG = "\x1b[31m"; static const char* const ANSI_COLOR_CODE_PLACEHOLDER_FG = "\x1b[34m"; static const char* const ANSI_BOLD_ON = "\x1b[1m"; static const char* const ANSI_BOLD_OFF = "\x1b[22m"; // Constants. std::string const kBaseUrl = "http://raw.github.com/tldr-pages/tldr/master/pages"; void init_response(struct response* r); size_t writeCallback(char* raw, size_t size, size_t nmemb, std::string* data); // Fetching. std::string getUrlForArgAndPlatform(std::string const& arg, std::string const& platform); std::string getUrlForArg(std::string const& arg); std::string getContentForUrl(std::string const& url); // Utilities. void replaceAll(std::string& str, std::string const& from, std::string const& to); int main(int argc, char* argv[]) { struct utsname sys; uname(&sys); if (argc > 1) { int i = 2; std::string arg(argv[1]); while (i < argc) { arg += "-" + std::string(argv[i++]); } std::string url = getUrlForArg(arg); std::string urlForPlatform = getUrlForArgAndPlatform(arg, sys.sysname); std::string response = getContentForUrl(urlForPlatform); if (response.empty()) { response = getContentForUrl(url); } replaceAll(response, "{{", ANSI_COLOR_CODE_PLACEHOLDER_FG); replaceAll(response, "}}", ANSI_COLOR_RESET_FG); std::string const stripPrefix("#"); std::string const explainPrefix(">"); std::string const commentPrefix("-"); std::string const codePrefix("`"); std::stringstream ss(response); std::string line; bool firstComment = true; while (std::getline(ss, line, '\n')) { // Title if (line.compare(0, stripPrefix.size(), stripPrefix) == 0) { replaceAll(line, "#", ANSI_COLOR_TITLE_FG); std::cout << std::endl << ANSI_BOLD_ON << line << ANSI_BOLD_OFF << ANSI_COLOR_RESET_FG << std::endl; } // Command explanation else if (line.compare(0, explainPrefix.size(), explainPrefix) == 0) { replaceAll(line, explainPrefix, ANSI_COLOR_EXPLANATION_FG); std::cout << line << ANSI_COLOR_RESET_FG << std::endl; } // Example comment else if (line.compare(0, commentPrefix.size(), commentPrefix) == 0) { if (firstComment) { std::cout << std::endl; firstComment = false; } replaceAll(line, commentPrefix, ANSI_COLOR_COMMENT_FG); std::cout << line << ANSI_COLOR_RESET_FG << std::endl; } // Code example else if (line.compare(0, codePrefix.size(), codePrefix) == 0) { // Remove trailing backtick (`). line = line.substr(0, line.size() - 1); // Replace first backtick (`) with three spaces for aligned indentation. replaceAll(line, "`", " "); std::cout << ANSI_COLOR_CODE_FG << line << ANSI_COLOR_RESET_FG << std::endl << std::endl; } } } } // ===================================== // URL determination. // ===================================== std::string getUrlForArgAndPlatform(std::string const& arg, std::string const& platform) { int isLinux = !platform.compare("Linux"); int isOSX = !platform.compare("Darwin"); std::string platformUrlDelimiter; if (isLinux) { platformUrlDelimiter = "linux"; } else if (isOSX) { platformUrlDelimiter = "osx"; } else { platformUrlDelimiter = "common"; } std::string url(kBaseUrl); url += "/" + platformUrlDelimiter + "/" + arg + ".md"; return url; } std::string getUrlForArg(std::string const& arg) { return getUrlForArgAndPlatform(arg, "common"); } // ===================================== // Curl Fetching. // ===================================== size_t writeCallback(char* raw, size_t size, size_t nmemb, std::string* data) { if (data == NULL) { return 0; } data->append(raw, size * nmemb); return size * nmemb; } std::string getContentForUrl(std::string const& url) { CURL* curl; CURLcode res; std::string response; curl = curl_easy_init(); if (curl) { curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writeCallback); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response); res = curl_easy_perform(curl); if (res == CURLE_OK) { long httpCode = 0; curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &httpCode); if (httpCode == 200) { curl_easy_cleanup(curl); return response; } else { curl_easy_cleanup(curl); return ""; } } curl_easy_cleanup(curl); } return ""; } // ===================================== // Utilities. // ===================================== void replaceAll(std::string& str, std::string const& from, std::string const& to) { if (from.empty()) { return; } size_t start_pos = 0; while ((start_pos = str.find(from, start_pos)) != std::string::npos) { str.replace(start_pos, from.length(), to); start_pos += to.length(); } } <|endoftext|>
<commit_before>/* * Copyright (C) 2009 Toni Gundogdu. * * This file is part of cclive. * * cclive 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. * * cclive is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ #include <algorithm> #include <fstream> #include <string> #include <vector> #include <map> #include "hosthandler.h" #include "opts.h" const double Util::fileExists(const std::string& path) { std::ifstream f; f.open(path.c_str(), std::ios::binary); double len = 0; if (f.is_open()) { f.seekg(0, std::ios::end); len = f.tellg(); f.close(); } return len; } const std::string Util::subStr(const std::string& src, const std::string& begin, const std::string& end, const bool& croak_if_not_found /*=true*/) { const std::string::size_type begin_pos = src.find(begin); if (begin_pos == std::string::npos && croak_if_not_found) throw HostHandler::ParseException("not found: "+begin); const std::string::size_type end_pos = src.find(end, begin_pos + begin.length()); if (end_pos == std::string::npos && croak_if_not_found) throw HostHandler::ParseException("not found: "+end); const std::string::size_type from = begin_pos + begin.length(); const std::string::size_type len = end_pos - begin_pos - begin.length(); return src.substr(from, len); } const std::string Util::rsubStr(const std::string& src, const std::string& begin, const std::string& end, const bool& croak_if_not_found /*=true*/) { const std::string::size_type end_pos = src.rfind(end); if (end_pos == std::string::npos && croak_if_not_found) throw HostHandler::ParseException("not found: "+end); const std::string::size_type begin_pos = src.rfind(begin, end_pos - end.length()); if (begin_pos == std::string::npos && croak_if_not_found) throw HostHandler::ParseException("not found: "+begin); const std::string::size_type from = begin_pos + begin.length(); const std::string::size_type len = end_pos - begin_pos - begin.length(); return src.substr(from, len); } std::string& Util::subStrReplace( std::string& src, const std::string& what, const std::string& with) { std::string::size_type pos; while ((pos = src.find(what)) != std::string::npos) src.replace(pos, what.size(), with); return src; } std::string& Util::nocookieToYoutube(std::string& url) { // Convert alternate domain youtube-nocookie.com // to youtube.com domain. return Util::subStrReplace(url, "-nocookie", ""); } std::string& Util::embedToPage(std::string& url) { typedef std::map<std::string, std::string> mapstr; mapstr m; m["/v/"] = "/watch?v="; // youtube m["googleplayer.swf"] = "videoplay"; // google m["/pl/"] = "/videos/"; // sevenload m["/e/"] = "/view?i="; // liveleak m["/moogaloop.swf?clip_id="] = "/"; // vimeo m["/embed/"] = "/"; // redtube for (mapstr::const_iterator iter = m.begin(); iter != m.end(); ++iter) { Util::subStrReplace(url, iter->first, iter->second); } return url; } std::string& Util::lastfmToYoutube(std::string& url) { const std::string::size_type pos = url.find("+1-"); if (pos != std::string::npos) { const std::string id = url.substr(pos+3); url = "http://youtube.com/watch?v=" + id; } return url; } std::string& Util::toLower(std::string& src) { std::transform(src.begin(), src.end(), src.begin(), tolower); return src; } typedef std::vector<std::string> STRV; STRV Util::tokenize(const std::string& src, const std::string& delims) { std::string::size_type last = src.find_first_not_of(delims); std::string::size_type pos = src.find_first_of(delims, last); STRV v; while (std::string::npos != pos || std::string::npos != last) { v.push_back( src.substr(last, pos-last) ); last = src.find_first_not_of(delims, pos); pos = src.find_first_of(delims, last); } return v; } std::string Util::parseFormatMap(const std::string& host) { const Options opts = optsmgr.getOptions(); std::string fmt; if (opts.format_map_given) { pcrecpp::RE re(host + ":(.*?)(\\||$)"); re.PartialMatch(opts.format_map_arg, &fmt); } if (opts.format_given) // Override. fmt = opts.format_arg; return fmt; } <commit_msg>parseFormatMap: return "flv" as default.<commit_after>/* * Copyright (C) 2009 Toni Gundogdu. * * This file is part of cclive. * * cclive 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. * * cclive is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ #include <algorithm> #include <fstream> #include <string> #include <vector> #include <map> #include "hosthandler.h" #include "opts.h" const double Util::fileExists(const std::string& path) { std::ifstream f; f.open(path.c_str(), std::ios::binary); double len = 0; if (f.is_open()) { f.seekg(0, std::ios::end); len = f.tellg(); f.close(); } return len; } const std::string Util::subStr(const std::string& src, const std::string& begin, const std::string& end, const bool& croak_if_not_found /*=true*/) { const std::string::size_type begin_pos = src.find(begin); if (begin_pos == std::string::npos && croak_if_not_found) throw HostHandler::ParseException("not found: "+begin); const std::string::size_type end_pos = src.find(end, begin_pos + begin.length()); if (end_pos == std::string::npos && croak_if_not_found) throw HostHandler::ParseException("not found: "+end); const std::string::size_type from = begin_pos + begin.length(); const std::string::size_type len = end_pos - begin_pos - begin.length(); return src.substr(from, len); } const std::string Util::rsubStr(const std::string& src, const std::string& begin, const std::string& end, const bool& croak_if_not_found /*=true*/) { const std::string::size_type end_pos = src.rfind(end); if (end_pos == std::string::npos && croak_if_not_found) throw HostHandler::ParseException("not found: "+end); const std::string::size_type begin_pos = src.rfind(begin, end_pos - end.length()); if (begin_pos == std::string::npos && croak_if_not_found) throw HostHandler::ParseException("not found: "+begin); const std::string::size_type from = begin_pos + begin.length(); const std::string::size_type len = end_pos - begin_pos - begin.length(); return src.substr(from, len); } std::string& Util::subStrReplace( std::string& src, const std::string& what, const std::string& with) { std::string::size_type pos; while ((pos = src.find(what)) != std::string::npos) src.replace(pos, what.size(), with); return src; } std::string& Util::nocookieToYoutube(std::string& url) { // Convert alternate domain youtube-nocookie.com // to youtube.com domain. return Util::subStrReplace(url, "-nocookie", ""); } std::string& Util::embedToPage(std::string& url) { typedef std::map<std::string, std::string> mapstr; mapstr m; m["/v/"] = "/watch?v="; // youtube m["googleplayer.swf"] = "videoplay"; // google m["/pl/"] = "/videos/"; // sevenload m["/e/"] = "/view?i="; // liveleak m["/moogaloop.swf?clip_id="] = "/"; // vimeo m["/embed/"] = "/"; // redtube for (mapstr::const_iterator iter = m.begin(); iter != m.end(); ++iter) { Util::subStrReplace(url, iter->first, iter->second); } return url; } std::string& Util::lastfmToYoutube(std::string& url) { const std::string::size_type pos = url.find("+1-"); if (pos != std::string::npos) { const std::string id = url.substr(pos+3); url = "http://youtube.com/watch?v=" + id; } return url; } std::string& Util::toLower(std::string& src) { std::transform(src.begin(), src.end(), src.begin(), tolower); return src; } typedef std::vector<std::string> STRV; STRV Util::tokenize(const std::string& src, const std::string& delims) { std::string::size_type last = src.find_first_not_of(delims); std::string::size_type pos = src.find_first_of(delims, last); STRV v; while (std::string::npos != pos || std::string::npos != last) { v.push_back( src.substr(last, pos-last) ); last = src.find_first_not_of(delims, pos); pos = src.find_first_of(delims, last); } return v; } std::string Util::parseFormatMap(const std::string& host) { const Options opts = optsmgr.getOptions(); std::string fmt; if (opts.format_map_given) { pcrecpp::RE re(host + ":(.*?)(\\||$)"); re.PartialMatch(opts.format_map_arg, &fmt); } if (opts.format_given) // Override. fmt = opts.format_arg; if (fmt.empty()) fmt = "flv"; return fmt; } <|endoftext|>
<commit_before>#include "utils.h" gchar* getStr(Handle<Object> opts, const gchar* name) { NanUtf8String* str = NULL; if (opts->Has(H(name))) { Handle<Value> opt = opts->Get(H(name)); if (opt->IsString()) { str = new NanUtf8String(opt); } } if (str != NULL && str->Size() > 1) { return **str; } else { return NULL; } } NanCallback* getCb(Handle<Object> opts, const gchar* name) { NanCallback* cb = NULL; if (opts->Has(H(name))) { Handle<Value> opt = opts->Get(H(name)); if (opt->IsFunction()) { cb = new NanCallback(opt.As<Function>()); } } return cb; } // actually, the dict is a (key, arrayOfStrings) map void update_soup_headers_with_dict(SoupMessageHeaders* headers, GVariant* dict) { if (headers == NULL) return; GVariantIter iter; GVariant* val = NULL; gchar* key; g_variant_iter_init(&iter, dict); while (g_variant_iter_next(&iter, "{sv}", &key, &val)) { if (val == NULL) { soup_message_headers_remove(headers, key); } else { soup_message_headers_replace(headers, key, g_variant_get_string(val, NULL)); } g_variant_unref(val); g_free(key); } } GVariant* soup_headers_to_gvariant_dict(SoupMessageHeaders* headers) { GVariantBuilder builder; g_variant_builder_init(&builder, G_VARIANT_TYPE_VARDICT); if (headers != NULL) { SoupMessageHeadersIter iter; soup_message_headers_iter_init(&iter, headers); while (true) { const char* name; const char* value; if (!soup_message_headers_iter_next(&iter, &name, &value)) break; g_variant_builder_add(&builder, "{sv}", name, g_variant_new_string(value)); } } return g_variant_builder_end(&builder); } <commit_msg>fixed deprecated method<commit_after>#include "utils.h" gchar* getStr(Handle<Object> opts, const gchar* name) { NanUtf8String* str = NULL; if (opts->Has(H(name))) { Handle<Value> opt = opts->Get(H(name)); if (opt->IsString()) { str = new NanUtf8String(opt); } } if (str != NULL && str->length() > 1) { return **str; } else { return NULL; } } NanCallback* getCb(Handle<Object> opts, const gchar* name) { NanCallback* cb = NULL; if (opts->Has(H(name))) { Handle<Value> opt = opts->Get(H(name)); if (opt->IsFunction()) { cb = new NanCallback(opt.As<Function>()); } } return cb; } // actually, the dict is a (key, arrayOfStrings) map void update_soup_headers_with_dict(SoupMessageHeaders* headers, GVariant* dict) { if (headers == NULL) return; GVariantIter iter; GVariant* val = NULL; gchar* key; g_variant_iter_init(&iter, dict); while (g_variant_iter_next(&iter, "{sv}", &key, &val)) { if (val == NULL) { soup_message_headers_remove(headers, key); } else { soup_message_headers_replace(headers, key, g_variant_get_string(val, NULL)); } g_variant_unref(val); g_free(key); } } GVariant* soup_headers_to_gvariant_dict(SoupMessageHeaders* headers) { GVariantBuilder builder; g_variant_builder_init(&builder, G_VARIANT_TYPE_VARDICT); if (headers != NULL) { SoupMessageHeadersIter iter; soup_message_headers_iter_init(&iter, headers); while (true) { const char* name; const char* value; if (!soup_message_headers_iter_next(&iter, &name, &value)) break; g_variant_builder_add(&builder, "{sv}", name, g_variant_new_string(value)); } } return g_variant_builder_end(&builder); } <|endoftext|>
<commit_before>/** * v8cgi - (fast)cgi binary */ #include <v8.h> #include <v8-debug.h> #include <stdlib.h> #include <string.h> #include "app.h" #include "path.h" #ifdef FASTCGI # include <fcgi_stdio.h> # include <signal.h> #endif /** * Format for command line arguments * * as you can see if you wish to pass any arguments to v8, you MUST * put a -- surrounded by whitespace after all the v8 arguments * * any arguments after the v8_args but before the program_file are * used by v8cgi. */ static const char * v8cgi_usage = "v8cgi [v8_args --] [-v] [-h] [-c path] [-d port] program_file [argument ...]"; class v8cgi_CGI : public v8cgi_App { public: /** * Initialize from command line */ int init(int argc, char ** argv) { v8cgi_App::init(); this->argv0 = (argc > 0 ? path_normalize(argv[0]) : std::string("")); if (argc == 1) { /* no command-line arguments, try looking for CGI env vars */ this->fromEnvVars(); } try { this->process_args(argc, argv); } catch (std::string e) { this->error(e.c_str(), __FILE__, __LINE__); return 1; } return 0; } /** * STDIN reader */ size_t reader(char * destination, size_t amount) { return fread((void *) destination, sizeof(char), amount, stdin); } /** * STDOUT writer */ size_t writer(const char * data, size_t amount) { return fwrite((void *) data, sizeof(char), amount, stdout); fwrite((void *) "\n", sizeof(char), 1, stdout); } /** * STDERR error */ void error(const char * data, const char * file, int line) { fwrite((void *) data, sizeof(char), strlen(data), stderr); fwrite((void *) "\n", sizeof(char), 1, stderr); } void fromEnvVars() { char * env = getenv("PATH_TRANSLATED"); if (!env) { env = getenv("SCRIPT_FILENAME"); } if (env) { this->mainfile = std::string(env); } } private: std::string argv0; const char * instanceType() { return "cli"; } const char * executableName() { return this->argv0.c_str(); } /** * Process command line arguments. */ void process_args(int argc, char ** argv) { std::string err = "Invalid command line usage.\n"; err += "Correct usage: "; err += v8cgi_usage; /* see the v8cgi_usage definition for the format */ int index = 0; /* see if we have v8 options */ bool have_v8args = false; for (; index < argc; ++index) { /* FIXME: if there is a standalone "--" after the name of the script then this breaks. I can't figure out a solution to this, so for now we don't support any standalone "--" after the script name. One solution (and the way it currently works) is to require "--" before all other args even if no v8 args are used, but that seems I don't like this, but it is where we are right now. */ if (std::string(argv[index]) == "--") { /* treat all previous arguments as v8 arguments */ int v8argc = index; v8::V8::SetFlagsFromCommandLine(&v8argc, argv, true); index++; /* skip over the "--" */ have_v8args = true; break; } } /* if there were no v8 args, then reset index to the first argument */ if (!have_v8args) { index = 1; } /* scan for v8cgi-specific arguments now */ while (index < argc) { std::string optname(argv[index]); if (optname[0] != '-') { break; } /* not starting with "-" => mainfile */ if (optname.length() != 2) { throw err; } /* one-character options only */ index++; /* skip the option name */ switch (optname[1]) { case 'c': if (index >= argc) { throw err; } /* missing option value */ this->cfgfile = argv[index]; #ifdef VERBOSE printf("cfgfile: %s\n", argv[index]); #endif index++; /* skip the option value */ break; case 'd': if (index >= argc) { throw err; } /* missing option value */ v8::Debug::EnableAgent("v8cgi", atoi(argv[index])); #ifdef VERBOSE printf("port: %s\n", argv[index]); #endif index++; /* skip the option value */ break; case 'h': printf(v8cgi_usage); printf("\n"); break; case 'v': printf("v8cgi version %s", STRING(VERSION)); printf("\n"); break; default: throw err; break; } } if (index < argc) { /* argv[index] is the program file */ this->mainfile = argv[index]; /* expand mainfile to absolute path */ if (!path_isabsolute(this->mainfile)) { std::string tmp = path_getcwd(); tmp += "/"; tmp += this->mainfile; this->mainfile = path_normalize(this->mainfile); } index++; /* skip over the program_file */ } /* all the rest of the arguments are arguments to the program_file */ for (; index < argc; ++index) { #ifdef VERBOSE printf("program_arg: %s\n", argv[index]); #endif this->mainfile_args.push_back(std::string(argv[index])); } } }; #ifdef FASTCGI /** * This is true only after we receive a signal to terminate */ bool exit_requested = false; void handle_sigterm(int param) { exit_requested = true; } void handle_sigusr1(int param) { exit_requested = true; } #endif extern char ** environ; int main(int argc, char ** argv) { int result = 0; v8cgi_CGI cgi; result = cgi.init(argc, argv); // if (result) { exit(result); } #ifdef FASTCGI signal(SIGTERM, handle_sigterm); signal(SIGUSR1, handle_sigusr1); /** * FastCGI main loop */ while (FCGI_Accept() >= 0 && !exit_requested) { cgi.fromEnvVars(); #endif result = cgi.execute(environ); #ifdef FASTCGI if (exit_requested) { FCGI_SetExitStatus(0); exit(0); } else { FCGI_SetExitStatus(result); } } #endif return result; } <commit_msg>forgotten commented line<commit_after>/** * v8cgi - (fast)cgi binary */ #include <v8.h> #include <v8-debug.h> #include <stdlib.h> #include <string.h> #include "app.h" #include "path.h" #ifdef FASTCGI # include <fcgi_stdio.h> # include <signal.h> #endif /** * Format for command line arguments * * as you can see if you wish to pass any arguments to v8, you MUST * put a -- surrounded by whitespace after all the v8 arguments * * any arguments after the v8_args but before the program_file are * used by v8cgi. */ static const char * v8cgi_usage = "v8cgi [v8_args --] [-v] [-h] [-c path] [-d port] program_file [argument ...]"; class v8cgi_CGI : public v8cgi_App { public: /** * Initialize from command line */ int init(int argc, char ** argv) { v8cgi_App::init(); this->argv0 = (argc > 0 ? path_normalize(argv[0]) : std::string("")); if (argc == 1) { /* no command-line arguments, try looking for CGI env vars */ this->fromEnvVars(); } try { this->process_args(argc, argv); } catch (std::string e) { this->error(e.c_str(), __FILE__, __LINE__); return 1; } return 0; } /** * STDIN reader */ size_t reader(char * destination, size_t amount) { return fread((void *) destination, sizeof(char), amount, stdin); } /** * STDOUT writer */ size_t writer(const char * data, size_t amount) { return fwrite((void *) data, sizeof(char), amount, stdout); fwrite((void *) "\n", sizeof(char), 1, stdout); } /** * STDERR error */ void error(const char * data, const char * file, int line) { fwrite((void *) data, sizeof(char), strlen(data), stderr); fwrite((void *) "\n", sizeof(char), 1, stderr); } void fromEnvVars() { char * env = getenv("PATH_TRANSLATED"); if (!env) { env = getenv("SCRIPT_FILENAME"); } if (env) { this->mainfile = std::string(env); } } private: std::string argv0; const char * instanceType() { return "cli"; } const char * executableName() { return this->argv0.c_str(); } /** * Process command line arguments. */ void process_args(int argc, char ** argv) { std::string err = "Invalid command line usage.\n"; err += "Correct usage: "; err += v8cgi_usage; /* see the v8cgi_usage definition for the format */ int index = 0; /* see if we have v8 options */ bool have_v8args = false; for (; index < argc; ++index) { /* FIXME: if there is a standalone "--" after the name of the script then this breaks. I can't figure out a solution to this, so for now we don't support any standalone "--" after the script name. One solution (and the way it currently works) is to require "--" before all other args even if no v8 args are used, but that seems I don't like this, but it is where we are right now. */ if (std::string(argv[index]) == "--") { /* treat all previous arguments as v8 arguments */ int v8argc = index; v8::V8::SetFlagsFromCommandLine(&v8argc, argv, true); index++; /* skip over the "--" */ have_v8args = true; break; } } /* if there were no v8 args, then reset index to the first argument */ if (!have_v8args) { index = 1; } /* scan for v8cgi-specific arguments now */ while (index < argc) { std::string optname(argv[index]); if (optname[0] != '-') { break; } /* not starting with "-" => mainfile */ if (optname.length() != 2) { throw err; } /* one-character options only */ index++; /* skip the option name */ switch (optname[1]) { case 'c': if (index >= argc) { throw err; } /* missing option value */ this->cfgfile = argv[index]; #ifdef VERBOSE printf("cfgfile: %s\n", argv[index]); #endif index++; /* skip the option value */ break; case 'd': if (index >= argc) { throw err; } /* missing option value */ v8::Debug::EnableAgent("v8cgi", atoi(argv[index])); #ifdef VERBOSE printf("port: %s\n", argv[index]); #endif index++; /* skip the option value */ break; case 'h': printf(v8cgi_usage); printf("\n"); break; case 'v': printf("v8cgi version %s", STRING(VERSION)); printf("\n"); break; default: throw err; break; } } if (index < argc) { /* argv[index] is the program file */ this->mainfile = argv[index]; /* expand mainfile to absolute path */ if (!path_isabsolute(this->mainfile)) { std::string tmp = path_getcwd(); tmp += "/"; tmp += this->mainfile; this->mainfile = path_normalize(this->mainfile); } index++; /* skip over the program_file */ } /* all the rest of the arguments are arguments to the program_file */ for (; index < argc; ++index) { #ifdef VERBOSE printf("program_arg: %s\n", argv[index]); #endif this->mainfile_args.push_back(std::string(argv[index])); } } }; #ifdef FASTCGI /** * This is true only after we receive a signal to terminate */ bool exit_requested = false; void handle_sigterm(int param) { exit_requested = true; } void handle_sigusr1(int param) { exit_requested = true; } #endif extern char ** environ; int main(int argc, char ** argv) { int result = 0; v8cgi_CGI cgi; result = cgi.init(argc, argv); if (result) { exit(result); } #ifdef FASTCGI signal(SIGTERM, handle_sigterm); signal(SIGUSR1, handle_sigusr1); /** * FastCGI main loop */ while (FCGI_Accept() >= 0 && !exit_requested) { cgi.fromEnvVars(); #endif result = cgi.execute(environ); #ifdef FASTCGI if (exit_requested) { FCGI_SetExitStatus(0); exit(0); } else { FCGI_SetExitStatus(result); } } #endif return result; } <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2017 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ // mapnik #include <mapnik/warp.hpp> #include <mapnik/config.hpp> #include <mapnik/image.hpp> #include <mapnik/image_scaling_traits.hpp> #include <mapnik/image_util.hpp> #include <mapnik/geometry/box2d.hpp> #include <mapnik/view_transform.hpp> #include <mapnik/raster.hpp> #include <mapnik/proj_transform.hpp> #include <mapnik/safe_cast.hpp> #pragma GCC diagnostic push #include <mapnik/warning_ignore_agg.hpp> #include "agg_image_filters.h" #include "agg_trans_bilinear.h" #include "agg_span_interpolator_linear.h" #include "agg_span_image_filter_rgba.h" #include "agg_rendering_buffer.h" #include "agg_pixfmt_rgba.h" #include "agg_rasterizer_scanline_aa.h" #include "agg_basics.h" #include "agg_scanline_bin.h" #include "agg_renderer_scanline.h" #include "agg_span_allocator.h" #include "agg_image_accessors.h" #include "agg_renderer_scanline.h" #pragma GCC diagnostic pop namespace mapnik { template <typename T> MAPNIK_DECL void warp_image (T & target, T const& source, proj_transform const& prj_trans, box2d<double> const& target_ext, box2d<double> const& source_ext, double offset_x, double offset_y, unsigned mesh_size, scaling_method_e scaling_method, double filter_factor, boost::optional<double> const & nodata_value) { using image_type = T; using pixel_type = typename image_type::pixel_type; using pixfmt_pre = typename detail::agg_scaling_traits<image_type>::pixfmt_pre; using color_type = typename detail::agg_scaling_traits<image_type>::color_type; using renderer_base = agg::renderer_base<pixfmt_pre>; using interpolator_type = typename detail::agg_scaling_traits<image_type>::interpolator_type; constexpr std::size_t pixel_size = sizeof(pixel_type); view_transform ts(source.width(), source.height(), source_ext); view_transform tt(target.width(), target.height(), target_ext, offset_x, offset_y); std::size_t mesh_nx = std::ceil(source.width()/double(mesh_size) + 1); std::size_t mesh_ny = std::ceil(source.height()/double(mesh_size) + 1); image_gray64f xs(mesh_nx, mesh_ny, false); image_gray64f ys(mesh_nx, mesh_ny, false); // Precalculate reprojected mesh for(std::size_t j = 0; j < mesh_ny; ++j) { for (std::size_t i=0; i<mesh_nx; ++i) { xs(i,j) = std::min(i*mesh_size,source.width()); ys(i,j) = std::min(j*mesh_size,source.height()); ts.backward(&xs(i,j), &ys(i,j)); } } prj_trans.backward(xs.data(), ys.data(), nullptr, mesh_nx*mesh_ny); agg::rasterizer_scanline_aa<> rasterizer; agg::scanline_bin scanline; agg::rendering_buffer buf(target.bytes(), target.width(), target.height(), target.width() * pixel_size); pixfmt_pre pixf(buf); renderer_base rb(pixf); rasterizer.clip_box(0, 0, target.width(), target.height()); agg::rendering_buffer buf_tile( const_cast<unsigned char*>(source.bytes()), source.width(), source.height(), source.width() * pixel_size); pixfmt_pre pixf_tile(buf_tile); using img_accessor_type = agg::image_accessor_clone<pixfmt_pre>; img_accessor_type ia(pixf_tile); agg::span_allocator<color_type> sa; // Project mesh cells into target interpolating raster inside each one for (std::size_t j = 0; j < mesh_ny - 1; ++j) { for (std::size_t i = 0; i < mesh_nx - 1; ++i) { double polygon[8] = {xs(i,j), ys(i,j), xs(i+1,j), ys(i+1,j), xs(i+1,j+1), ys(i+1,j+1), xs(i,j+1), ys(i,j+1)}; tt.forward(polygon+0, polygon+1); tt.forward(polygon+2, polygon+3); tt.forward(polygon+4, polygon+5); tt.forward(polygon+6, polygon+7); rasterizer.reset(); rasterizer.move_to_d(std::floor(polygon[0]), std::floor(polygon[1])); rasterizer.line_to_d(std::floor(polygon[2]), std::floor(polygon[3])); rasterizer.line_to_d(std::floor(polygon[4]), std::floor(polygon[5])); rasterizer.line_to_d(std::floor(polygon[6]), std::floor(polygon[7])); std::size_t x0 = i * mesh_size; std::size_t y0 = j * mesh_size; std::size_t x1 = (i+1) * mesh_size; std::size_t y1 = (j+1) * mesh_size; x1 = std::min(x1, source.width()); y1 = std::min(y1, source.height()); agg::trans_affine tr(polygon, x0, y0, x1, y1); if (tr.is_valid()) { interpolator_type interpolator(tr); if (scaling_method == SCALING_NEAR) { using span_gen_type = typename detail::agg_scaling_traits<image_type>::span_image_filter; span_gen_type sg(ia, interpolator); agg::render_scanlines_bin(rasterizer, scanline, rb, sa, sg); } else { using span_gen_type = typename detail::agg_scaling_traits<image_type>::span_image_resample_affine; agg::image_filter_lut filter; detail::set_scaling_method(filter, scaling_method, filter_factor); boost::optional<typename span_gen_type::value_type> nodata; if (nodata_value) { nodata = safe_cast<typename span_gen_type::value_type>(*nodata_value); } span_gen_type sg(ia, interpolator, filter, nodata); agg::render_scanlines_bin(rasterizer, scanline, rb, sa, sg); } } } } } namespace detail { struct warp_image_visitor { warp_image_visitor (raster & target_raster, proj_transform const& prj_trans, box2d<double> const& source_ext, double offset_x, double offset_y, unsigned mesh_size, scaling_method_e scaling_method, double filter_factor, boost::optional<double> const & nodata_value) : target_raster_(target_raster), prj_trans_(prj_trans), source_ext_(source_ext), offset_x_(offset_x), offset_y_(offset_y), mesh_size_(mesh_size), scaling_method_(scaling_method), filter_factor_(filter_factor), nodata_value_(nodata_value) {} void operator() (image_null const&) const {} template <typename T> void operator() (T const& source) const { using image_type = T; //source and target image data types must match if (target_raster_.data_.template is<image_type>()) { image_type & target = util::get<image_type>(target_raster_.data_); warp_image (target, source, prj_trans_, target_raster_.ext_, source_ext_, offset_x_, offset_y_, mesh_size_, scaling_method_, filter_factor_, nodata_value_); } } raster & target_raster_; proj_transform const& prj_trans_; box2d<double> const& source_ext_; double offset_x_; double offset_y_; unsigned mesh_size_; scaling_method_e scaling_method_; double filter_factor_; boost::optional<double> const & nodata_value_; }; } void reproject_and_scale_raster(raster & target, raster const& source, proj_transform const& prj_trans, double offset_x, double offset_y, unsigned mesh_size, scaling_method_e scaling_method, boost::optional<double> const & nodata_value) { detail::warp_image_visitor warper(target, prj_trans, source.ext_, offset_x, offset_y, mesh_size, scaling_method, source.get_filter_factor(), nodata_value); util::apply_visitor(warper, source.data_); } void reproject_and_scale_raster(raster & target, raster const& source, proj_transform const& prj_trans, double offset_x, double offset_y, unsigned mesh_size, scaling_method_e scaling_method) { reproject_and_scale_raster(target, source, prj_trans, offset_x, offset_y, mesh_size, scaling_method, boost::optional<double>()); } template MAPNIK_DECL void warp_image (image_rgba8&, image_rgba8 const&, proj_transform const&, box2d<double> const&, box2d<double> const&, double, double, unsigned, scaling_method_e, double, boost::optional<double> const &); template MAPNIK_DECL void warp_image (image_gray8&, image_gray8 const&, proj_transform const&, box2d<double> const&, box2d<double> const&, double, double, unsigned, scaling_method_e, double, boost::optional<double> const &); template MAPNIK_DECL void warp_image (image_gray16&, image_gray16 const&, proj_transform const&, box2d<double> const&, box2d<double> const&, double, double, unsigned, scaling_method_e, double, boost::optional<double> const &); template MAPNIK_DECL void warp_image (image_gray32f&, image_gray32f const&, proj_transform const&, box2d<double> const&, box2d<double> const&, double, double, unsigned, scaling_method_e, double, boost::optional<double> const &); }// namespace mapnik <commit_msg>Fix seams of mesh faces when warping transparent raster<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2017 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ // mapnik #include <mapnik/warp.hpp> #include <mapnik/config.hpp> #include <mapnik/image.hpp> #include <mapnik/image_scaling_traits.hpp> #include <mapnik/image_util.hpp> #include <mapnik/geometry/box2d.hpp> #include <mapnik/view_transform.hpp> #include <mapnik/raster.hpp> #include <mapnik/proj_transform.hpp> #include <mapnik/safe_cast.hpp> #pragma GCC diagnostic push #include <mapnik/warning_ignore_agg.hpp> #include "agg_image_filters.h" #include "agg_trans_bilinear.h" #include "agg_span_interpolator_linear.h" #include "agg_span_image_filter_rgba.h" #include "agg_rendering_buffer.h" #include "agg_pixfmt_rgba.h" #include "agg_rasterizer_scanline_aa.h" #include "agg_basics.h" #include "agg_scanline_bin.h" #include "agg_renderer_scanline.h" #include "agg_span_allocator.h" #include "agg_image_accessors.h" #include "agg_renderer_scanline.h" #pragma GCC diagnostic pop namespace mapnik { template <typename T> struct pixel_format { using type = typename detail::agg_scaling_traits<T>::pixfmt_pre; }; template <> struct pixel_format<image_rgba8> { struct src_blender { using color_type = agg::rgba8; using order_type = agg::order_rgba; using value_type = typename color_type::value_type; static inline void blend_pix(unsigned /*op*/, value_type* p, unsigned cr, unsigned cg, unsigned cb, unsigned ca, unsigned cover) { agg::comp_op_rgba_src<color_type, order_type>::blend_pix(p, cr, cg, cb, ca, cover); } }; // Use comp_op_src to fix seams between faces of the mesh using type = agg::pixfmt_custom_blend_rgba<src_blender, agg::rendering_buffer>; }; template <typename T> MAPNIK_DECL void warp_image (T & target, T const& source, proj_transform const& prj_trans, box2d<double> const& target_ext, box2d<double> const& source_ext, double offset_x, double offset_y, unsigned mesh_size, scaling_method_e scaling_method, double filter_factor, boost::optional<double> const & nodata_value) { using image_type = T; using pixel_type = typename image_type::pixel_type; using pixfmt_pre = typename detail::agg_scaling_traits<image_type>::pixfmt_pre; using color_type = typename detail::agg_scaling_traits<image_type>::color_type; using output_pixfmt_type = typename pixel_format<T>::type; using renderer_base = agg::renderer_base<output_pixfmt_type>; using interpolator_type = typename detail::agg_scaling_traits<image_type>::interpolator_type; constexpr std::size_t pixel_size = sizeof(pixel_type); view_transform ts(source.width(), source.height(), source_ext); view_transform tt(target.width(), target.height(), target_ext, offset_x, offset_y); std::size_t mesh_nx = std::ceil(source.width()/double(mesh_size) + 1); std::size_t mesh_ny = std::ceil(source.height()/double(mesh_size) + 1); image_gray64f xs(mesh_nx, mesh_ny, false); image_gray64f ys(mesh_nx, mesh_ny, false); // Precalculate reprojected mesh for(std::size_t j = 0; j < mesh_ny; ++j) { for (std::size_t i=0; i<mesh_nx; ++i) { xs(i,j) = std::min(i*mesh_size,source.width()); ys(i,j) = std::min(j*mesh_size,source.height()); ts.backward(&xs(i,j), &ys(i,j)); } } prj_trans.backward(xs.data(), ys.data(), nullptr, mesh_nx*mesh_ny); agg::rasterizer_scanline_aa<> rasterizer; agg::scanline_bin scanline; agg::rendering_buffer buf(target.bytes(), target.width(), target.height(), target.width() * pixel_size); output_pixfmt_type pixf(buf); renderer_base rb(pixf); rasterizer.clip_box(0, 0, target.width(), target.height()); agg::rendering_buffer buf_tile( const_cast<unsigned char*>(source.bytes()), source.width(), source.height(), source.width() * pixel_size); pixfmt_pre pixf_tile(buf_tile); using img_accessor_type = agg::image_accessor_clone<pixfmt_pre>; img_accessor_type ia(pixf_tile); agg::span_allocator<color_type> sa; // Project mesh cells into target interpolating raster inside each one for (std::size_t j = 0; j < mesh_ny - 1; ++j) { for (std::size_t i = 0; i < mesh_nx - 1; ++i) { double polygon[8] = {xs(i,j), ys(i,j), xs(i+1,j), ys(i+1,j), xs(i+1,j+1), ys(i+1,j+1), xs(i,j+1), ys(i,j+1)}; tt.forward(polygon+0, polygon+1); tt.forward(polygon+2, polygon+3); tt.forward(polygon+4, polygon+5); tt.forward(polygon+6, polygon+7); rasterizer.reset(); rasterizer.move_to_d(std::floor(polygon[0]), std::floor(polygon[1])); rasterizer.line_to_d(std::floor(polygon[2]), std::floor(polygon[3])); rasterizer.line_to_d(std::floor(polygon[4]), std::floor(polygon[5])); rasterizer.line_to_d(std::floor(polygon[6]), std::floor(polygon[7])); std::size_t x0 = i * mesh_size; std::size_t y0 = j * mesh_size; std::size_t x1 = (i+1) * mesh_size; std::size_t y1 = (j+1) * mesh_size; x1 = std::min(x1, source.width()); y1 = std::min(y1, source.height()); agg::trans_affine tr(polygon, x0, y0, x1, y1); if (tr.is_valid()) { interpolator_type interpolator(tr); if (scaling_method == SCALING_NEAR) { using span_gen_type = typename detail::agg_scaling_traits<image_type>::span_image_filter; span_gen_type sg(ia, interpolator); agg::render_scanlines_bin(rasterizer, scanline, rb, sa, sg); } else { using span_gen_type = typename detail::agg_scaling_traits<image_type>::span_image_resample_affine; agg::image_filter_lut filter; detail::set_scaling_method(filter, scaling_method, filter_factor); boost::optional<typename span_gen_type::value_type> nodata; if (nodata_value) { nodata = safe_cast<typename span_gen_type::value_type>(*nodata_value); } span_gen_type sg(ia, interpolator, filter, nodata); agg::render_scanlines_bin(rasterizer, scanline, rb, sa, sg); } } } } } namespace detail { struct warp_image_visitor { warp_image_visitor (raster & target_raster, proj_transform const& prj_trans, box2d<double> const& source_ext, double offset_x, double offset_y, unsigned mesh_size, scaling_method_e scaling_method, double filter_factor, boost::optional<double> const & nodata_value) : target_raster_(target_raster), prj_trans_(prj_trans), source_ext_(source_ext), offset_x_(offset_x), offset_y_(offset_y), mesh_size_(mesh_size), scaling_method_(scaling_method), filter_factor_(filter_factor), nodata_value_(nodata_value) {} void operator() (image_null const&) const {} template <typename T> void operator() (T const& source) const { using image_type = T; //source and target image data types must match if (target_raster_.data_.template is<image_type>()) { image_type & target = util::get<image_type>(target_raster_.data_); warp_image (target, source, prj_trans_, target_raster_.ext_, source_ext_, offset_x_, offset_y_, mesh_size_, scaling_method_, filter_factor_, nodata_value_); } } raster & target_raster_; proj_transform const& prj_trans_; box2d<double> const& source_ext_; double offset_x_; double offset_y_; unsigned mesh_size_; scaling_method_e scaling_method_; double filter_factor_; boost::optional<double> const & nodata_value_; }; } void reproject_and_scale_raster(raster & target, raster const& source, proj_transform const& prj_trans, double offset_x, double offset_y, unsigned mesh_size, scaling_method_e scaling_method, boost::optional<double> const & nodata_value) { detail::warp_image_visitor warper(target, prj_trans, source.ext_, offset_x, offset_y, mesh_size, scaling_method, source.get_filter_factor(), nodata_value); util::apply_visitor(warper, source.data_); } void reproject_and_scale_raster(raster & target, raster const& source, proj_transform const& prj_trans, double offset_x, double offset_y, unsigned mesh_size, scaling_method_e scaling_method) { reproject_and_scale_raster(target, source, prj_trans, offset_x, offset_y, mesh_size, scaling_method, boost::optional<double>()); } template MAPNIK_DECL void warp_image (image_rgba8&, image_rgba8 const&, proj_transform const&, box2d<double> const&, box2d<double> const&, double, double, unsigned, scaling_method_e, double, boost::optional<double> const &); template MAPNIK_DECL void warp_image (image_gray8&, image_gray8 const&, proj_transform const&, box2d<double> const&, box2d<double> const&, double, double, unsigned, scaling_method_e, double, boost::optional<double> const &); template MAPNIK_DECL void warp_image (image_gray16&, image_gray16 const&, proj_transform const&, box2d<double> const&, box2d<double> const&, double, double, unsigned, scaling_method_e, double, boost::optional<double> const &); template MAPNIK_DECL void warp_image (image_gray32f&, image_gray32f const&, proj_transform const&, box2d<double> const&, box2d<double> const&, double, double, unsigned, scaling_method_e, double, boost::optional<double> const &); }// namespace mapnik <|endoftext|>
<commit_before>/* * Copyright (c) 2012 Christoph Schulz * * 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 "zxing.h" #include "image.h" #include "util.h" #include <zxing/Binarizer.h> #include <zxing/BinaryBitmap.h> #include <zxing/LuminanceSource.h> #include <zxing/MultiFormatReader.h> #include <zxing/ReaderException.h> #include <zxing/Result.h> #include <zxing/common/Array.h> #include <zxing/common/HybridBinarizer.h> #include <zxing/multi/GenericMultipleBarcodeReader.h> #include <node_buffer.h> using namespace v8; using namespace node; class PixSource : public zxing::LuminanceSource { public: PixSource(Pix* pix, bool take = false); ~PixSource(); zxing::ArrayRef<char> getRow(int y, zxing::ArrayRef<char> row) const; zxing::ArrayRef<char> getMatrix() const; bool isCropSupported() const; zxing::Ref<zxing::LuminanceSource> crop(int left, int top, int width, int height) const; bool isRotateSupported() const; zxing::Ref<zxing::LuminanceSource> rotateCounterClockwise() const; private: PIX* pix_; }; PixSource::PixSource(Pix* pix, bool take) : LuminanceSource(pix ? pix->w : 0, pix ? pix->h : 0) { if (take) { assert(pix->d == 8); pix_ = pix; } else { pix_ = pixConvertTo8(pix, 0); } } PixSource::~PixSource() { pixDestroy(&pix_); } zxing::ArrayRef<char> PixSource::getRow(int y, zxing::ArrayRef<char> row) const { if (!row) { row = zxing::ArrayRef<char>(getWidth()); } if (static_cast<uint32_t>(y) < pix_->h) { uint32_t *line = pix_->data + (pix_->wpl * y); for (int x = 0; x < getWidth(); ++x) { row[x] = GET_DATA_BYTE(line, x); } } return row; } zxing::ArrayRef<char> PixSource::getMatrix() const { zxing::ArrayRef<char> matrix(getWidth() * getHeight()); char* m = &matrix[0]; uint32_t *line = pix_->data; for (uint32_t y = 0; y < pix_->h; ++y) { for (uint32_t x = 0; x < pix_->w; ++x) { *m = (char)GET_DATA_BYTE(line, x); ++m; } line += pix_->wpl; } return matrix; } bool PixSource::isRotateSupported() const { return true; } zxing::Ref<zxing::LuminanceSource> PixSource::rotateCounterClockwise() const { // Rotate 90 degree counterclockwise. if (pix_->w != 0 && pix_->h != 0) { Pix *rotatedPix = pixRotate90(pix_, -1); return zxing::Ref<PixSource>(new PixSource(rotatedPix, true)); } else { return zxing::Ref<PixSource>(new PixSource(pix_)); } } bool PixSource::isCropSupported() const { return true; } zxing::Ref<zxing::LuminanceSource> PixSource::crop(int left, int top, int width, int height) const { BOX *box = boxCreate(left, top, width, height); PIX *croppedPix = pixClipRectangle(pix_, box, 0); boxDestroy(&box); return zxing::Ref<PixSource>(new PixSource(croppedPix, true)); } const zxing::BarcodeFormat::Value ZXing::BARCODEFORMATS[] = { zxing::BarcodeFormat::QR_CODE, zxing::BarcodeFormat::DATA_MATRIX, zxing::BarcodeFormat::PDF_417, zxing::BarcodeFormat::UPC_E, zxing::BarcodeFormat::UPC_A, zxing::BarcodeFormat::EAN_8, zxing::BarcodeFormat::EAN_13, zxing::BarcodeFormat::CODE_128, zxing::BarcodeFormat::CODE_39, zxing::BarcodeFormat::ITF, zxing::BarcodeFormat::AZTEC }; const size_t ZXing::BARCODEFORMATS_LENGTH = 11; void ZXing::Init(Handle<Object> target) { Local<FunctionTemplate> constructor_template = FunctionTemplate::New(New); constructor_template->SetClassName(String::NewSymbol("ZXing")); constructor_template->InstanceTemplate()->SetInternalFieldCount(1); Local<ObjectTemplate> proto = constructor_template->PrototypeTemplate(); proto->SetAccessor(String::NewSymbol("image"), GetImage, SetImage); proto->SetAccessor(String::NewSymbol("formats"), GetFormats, SetFormats); proto->SetAccessor(String::NewSymbol("tryHarder"), GetTryHarder, SetTryHarder); proto->Set(String::NewSymbol("findCode"), FunctionTemplate::New(FindCode)->GetFunction()); target->Set(String::NewSymbol("ZXing"), Persistent<Function>::New(constructor_template->GetFunction())); } Handle<Value> ZXing::New(const Arguments &args) { HandleScope scope; Local<Object> image; if (args.Length() == 1 && Image::HasInstance(args[0])) { image = args[0]->ToObject(); } else if (args.Length() != 0) { return THROW(TypeError, "cannot convert argument list to " "() or " "(image: Image)"); } ZXing* obj = new ZXing(); if (!image.IsEmpty()) { obj->image_ = Persistent<Object>::New(image->ToObject()); } obj->Wrap(args.This()); return args.This(); } Handle<Value> ZXing::GetImage(Local<String> prop, const AccessorInfo &info) { ZXing* obj = ObjectWrap::Unwrap<ZXing>(info.This()); return obj->image_; } void ZXing::SetImage(Local<String> prop, Local<Value> value, const AccessorInfo &info) { ZXing* obj = ObjectWrap::Unwrap<ZXing>(info.This()); if (Image::HasInstance(value)) { if (!obj->image_.IsEmpty()) { obj->image_.Dispose(); obj->image_.Clear(); } obj->image_ = Persistent<Object>::New(value->ToObject()); } else { THROW(TypeError, "value must be of type Image"); } } Handle<Value> ZXing::GetFormats(Local<String> prop, const AccessorInfo &info) { HandleScope scope; ZXing* obj = ObjectWrap::Unwrap<ZXing>(info.This()); Local<Object> format = Object::New(); for (size_t i = 0; i < BARCODEFORMATS_LENGTH; ++i) { format->Set(String::NewSymbol(zxing::BarcodeFormat::barcodeFormatNames[BARCODEFORMATS[i]]), Boolean::New(obj->hints_.containsFormat(BARCODEFORMATS[i]))); } return scope.Close(format); } void ZXing::SetFormats(Local<String> prop, Local<Value> value, const AccessorInfo &info) { ZXing* obj = ObjectWrap::Unwrap<ZXing>(info.This()); if (value->IsObject()) { Local<Object> format = value->ToObject(); obj->hints_.clear(); for (size_t i = 0; i < BARCODEFORMATS_LENGTH; ++i) { if (format->Get(String::NewSymbol(zxing::BarcodeFormat::barcodeFormatNames[BARCODEFORMATS[i]]))->BooleanValue()) { obj->hints_.addFormat(BARCODEFORMATS[i]); } } obj->reader_->setHints(obj->hints_); } else { THROW(TypeError, "value must be of type object"); } } Handle<Value> ZXing::GetTryHarder(Local<String> prop, const AccessorInfo &info) { ZXing* obj = ObjectWrap::Unwrap<ZXing>(info.This()); return Boolean::New(obj->hints_.getTryHarder()); } void ZXing::SetTryHarder(Local<String> prop, Local<Value> value, const AccessorInfo &info) { ZXing* obj = ObjectWrap::Unwrap<ZXing>(info.This()); if (value->IsBoolean()) { obj->hints_.setTryHarder(value->BooleanValue()); } else { THROW(TypeError, "value must be of type bool"); } } Handle<Value> ZXing::FindCode(const Arguments &args) { HandleScope scope; ZXing* obj = ObjectWrap::Unwrap<ZXing>(args.This()); if (obj->image_.IsEmpty()) { return THROW(Error, "No image set"); } try { zxing::Ref<PixSource> source(new PixSource(Image::Pixels(obj->image_))); zxing::Ref<zxing::Binarizer> binarizer(new zxing::HybridBinarizer(source)); zxing::Ref<zxing::BinaryBitmap> binary(new zxing::BinaryBitmap(binarizer)); zxing::Ref<zxing::Result> result(obj->reader_->decode(binary, obj->hints_)); Local<Object> object = Object::New(); std::string resultStr = result->getText()->getText(); object->Set(String::NewSymbol("type"), String::New(zxing::BarcodeFormat::barcodeFormatNames[result->getBarcodeFormat()])); object->Set(String::NewSymbol("data"), String::New(resultStr.c_str())); object->Set(String::NewSymbol("buffer"), node::Buffer::New((char*)resultStr.data(), resultStr.length())->handle_); Local<Array> points = Array::New(); for (int i = 0; i < result->getResultPoints()->size(); ++i) { Local<Object> point = Object::New(); point->Set(String::NewSymbol("x"), Number::New(result->getResultPoints()[i]->getX())); point->Set(String::NewSymbol("y"), Number::New(result->getResultPoints()[i]->getY())); points->Set(i, point); } object->Set(String::NewSymbol("points"), points); return scope.Close(object); } catch (const zxing::ReaderException& e) { if (strcmp(e.what(), "No code detected") == 0) { return scope.Close(Null()); } else { return THROW(Error, e.what()); } } catch (const zxing::IllegalArgumentException& e) { return THROW(Error, e.what()); } catch (const zxing::Exception& e) { return THROW(Error, e.what()); } catch (const std::exception& e) { return THROW(Error, e.what()); } catch (...) { return THROW(Error, "Uncaught exception"); } } ZXing::ZXing() : hints_(zxing::DecodeHints::DEFAULT_HINT), reader_(new zxing::MultiFormatReader) { } ZXing::~ZXing() { } <commit_msg>Setting ZXing#formats no longer sets tryHarder to false<commit_after>/* * Copyright (c) 2012 Christoph Schulz * * 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 "zxing.h" #include "image.h" #include "util.h" #include <zxing/Binarizer.h> #include <zxing/BinaryBitmap.h> #include <zxing/LuminanceSource.h> #include <zxing/MultiFormatReader.h> #include <zxing/ReaderException.h> #include <zxing/Result.h> #include <zxing/common/Array.h> #include <zxing/common/HybridBinarizer.h> #include <zxing/multi/GenericMultipleBarcodeReader.h> #include <node_buffer.h> using namespace v8; using namespace node; class PixSource : public zxing::LuminanceSource { public: PixSource(Pix* pix, bool take = false); ~PixSource(); zxing::ArrayRef<char> getRow(int y, zxing::ArrayRef<char> row) const; zxing::ArrayRef<char> getMatrix() const; bool isCropSupported() const; zxing::Ref<zxing::LuminanceSource> crop(int left, int top, int width, int height) const; bool isRotateSupported() const; zxing::Ref<zxing::LuminanceSource> rotateCounterClockwise() const; private: PIX* pix_; }; PixSource::PixSource(Pix* pix, bool take) : LuminanceSource(pix ? pix->w : 0, pix ? pix->h : 0) { if (take) { assert(pix->d == 8); pix_ = pix; } else { pix_ = pixConvertTo8(pix, 0); } } PixSource::~PixSource() { pixDestroy(&pix_); } zxing::ArrayRef<char> PixSource::getRow(int y, zxing::ArrayRef<char> row) const { if (!row) { row = zxing::ArrayRef<char>(getWidth()); } if (static_cast<uint32_t>(y) < pix_->h) { uint32_t *line = pix_->data + (pix_->wpl * y); for (int x = 0; x < getWidth(); ++x) { row[x] = GET_DATA_BYTE(line, x); } } return row; } zxing::ArrayRef<char> PixSource::getMatrix() const { zxing::ArrayRef<char> matrix(getWidth() * getHeight()); char* m = &matrix[0]; uint32_t *line = pix_->data; for (uint32_t y = 0; y < pix_->h; ++y) { for (uint32_t x = 0; x < pix_->w; ++x) { *m = (char)GET_DATA_BYTE(line, x); ++m; } line += pix_->wpl; } return matrix; } bool PixSource::isRotateSupported() const { return true; } zxing::Ref<zxing::LuminanceSource> PixSource::rotateCounterClockwise() const { // Rotate 90 degree counterclockwise. if (pix_->w != 0 && pix_->h != 0) { Pix *rotatedPix = pixRotate90(pix_, -1); return zxing::Ref<PixSource>(new PixSource(rotatedPix, true)); } else { return zxing::Ref<PixSource>(new PixSource(pix_)); } } bool PixSource::isCropSupported() const { return true; } zxing::Ref<zxing::LuminanceSource> PixSource::crop(int left, int top, int width, int height) const { BOX *box = boxCreate(left, top, width, height); PIX *croppedPix = pixClipRectangle(pix_, box, 0); boxDestroy(&box); return zxing::Ref<PixSource>(new PixSource(croppedPix, true)); } const zxing::BarcodeFormat::Value ZXing::BARCODEFORMATS[] = { zxing::BarcodeFormat::QR_CODE, zxing::BarcodeFormat::DATA_MATRIX, zxing::BarcodeFormat::PDF_417, zxing::BarcodeFormat::UPC_E, zxing::BarcodeFormat::UPC_A, zxing::BarcodeFormat::EAN_8, zxing::BarcodeFormat::EAN_13, zxing::BarcodeFormat::CODE_128, zxing::BarcodeFormat::CODE_39, zxing::BarcodeFormat::ITF, zxing::BarcodeFormat::AZTEC }; const size_t ZXing::BARCODEFORMATS_LENGTH = 11; void ZXing::Init(Handle<Object> target) { Local<FunctionTemplate> constructor_template = FunctionTemplate::New(New); constructor_template->SetClassName(String::NewSymbol("ZXing")); constructor_template->InstanceTemplate()->SetInternalFieldCount(1); Local<ObjectTemplate> proto = constructor_template->PrototypeTemplate(); proto->SetAccessor(String::NewSymbol("image"), GetImage, SetImage); proto->SetAccessor(String::NewSymbol("formats"), GetFormats, SetFormats); proto->SetAccessor(String::NewSymbol("tryHarder"), GetTryHarder, SetTryHarder); proto->Set(String::NewSymbol("findCode"), FunctionTemplate::New(FindCode)->GetFunction()); target->Set(String::NewSymbol("ZXing"), Persistent<Function>::New(constructor_template->GetFunction())); } Handle<Value> ZXing::New(const Arguments &args) { HandleScope scope; Local<Object> image; if (args.Length() == 1 && Image::HasInstance(args[0])) { image = args[0]->ToObject(); } else if (args.Length() != 0) { return THROW(TypeError, "cannot convert argument list to " "() or " "(image: Image)"); } ZXing* obj = new ZXing(); if (!image.IsEmpty()) { obj->image_ = Persistent<Object>::New(image->ToObject()); } obj->Wrap(args.This()); return args.This(); } Handle<Value> ZXing::GetImage(Local<String> prop, const AccessorInfo &info) { ZXing* obj = ObjectWrap::Unwrap<ZXing>(info.This()); return obj->image_; } void ZXing::SetImage(Local<String> prop, Local<Value> value, const AccessorInfo &info) { ZXing* obj = ObjectWrap::Unwrap<ZXing>(info.This()); if (Image::HasInstance(value)) { if (!obj->image_.IsEmpty()) { obj->image_.Dispose(); obj->image_.Clear(); } obj->image_ = Persistent<Object>::New(value->ToObject()); } else { THROW(TypeError, "value must be of type Image"); } } Handle<Value> ZXing::GetFormats(Local<String> prop, const AccessorInfo &info) { HandleScope scope; ZXing* obj = ObjectWrap::Unwrap<ZXing>(info.This()); Local<Object> format = Object::New(); for (size_t i = 0; i < BARCODEFORMATS_LENGTH; ++i) { format->Set(String::NewSymbol(zxing::BarcodeFormat::barcodeFormatNames[BARCODEFORMATS[i]]), Boolean::New(obj->hints_.containsFormat(BARCODEFORMATS[i]))); } return scope.Close(format); } void ZXing::SetFormats(Local<String> prop, Local<Value> value, const AccessorInfo &info) { ZXing* obj = ObjectWrap::Unwrap<ZXing>(info.This()); if (value->IsObject()) { Local<Object> format = value->ToObject(); bool tryHarder = obj->hints_.getTryHarder(); obj->hints_.clear(); obj->hints_.setTryHarder(tryHarder); for (size_t i = 0; i < BARCODEFORMATS_LENGTH; ++i) { if (format->Get(String::NewSymbol(zxing::BarcodeFormat::barcodeFormatNames[BARCODEFORMATS[i]]))->BooleanValue()) { obj->hints_.addFormat(BARCODEFORMATS[i]); } } } else { THROW(TypeError, "value must be of type object"); } } Handle<Value> ZXing::GetTryHarder(Local<String> prop, const AccessorInfo &info) { ZXing* obj = ObjectWrap::Unwrap<ZXing>(info.This()); return Boolean::New(obj->hints_.getTryHarder()); } void ZXing::SetTryHarder(Local<String> prop, Local<Value> value, const AccessorInfo &info) { ZXing* obj = ObjectWrap::Unwrap<ZXing>(info.This()); if (value->IsBoolean()) { obj->hints_.setTryHarder(value->BooleanValue()); } else { THROW(TypeError, "value must be of type bool"); } } Handle<Value> ZXing::FindCode(const Arguments &args) { HandleScope scope; ZXing* obj = ObjectWrap::Unwrap<ZXing>(args.This()); if (obj->image_.IsEmpty()) { return THROW(Error, "No image set"); } try { zxing::Ref<PixSource> source(new PixSource(Image::Pixels(obj->image_))); zxing::Ref<zxing::Binarizer> binarizer(new zxing::HybridBinarizer(source)); zxing::Ref<zxing::BinaryBitmap> binary(new zxing::BinaryBitmap(binarizer)); zxing::Ref<zxing::Result> result(obj->reader_->decode(binary, obj->hints_)); Local<Object> object = Object::New(); std::string resultStr = result->getText()->getText(); object->Set(String::NewSymbol("type"), String::New(zxing::BarcodeFormat::barcodeFormatNames[result->getBarcodeFormat()])); object->Set(String::NewSymbol("data"), String::New(resultStr.c_str())); object->Set(String::NewSymbol("buffer"), node::Buffer::New((char*)resultStr.data(), resultStr.length())->handle_); Local<Array> points = Array::New(); for (int i = 0; i < result->getResultPoints()->size(); ++i) { Local<Object> point = Object::New(); point->Set(String::NewSymbol("x"), Number::New(result->getResultPoints()[i]->getX())); point->Set(String::NewSymbol("y"), Number::New(result->getResultPoints()[i]->getY())); points->Set(i, point); } object->Set(String::NewSymbol("points"), points); return scope.Close(object); } catch (const zxing::ReaderException& e) { if (strcmp(e.what(), "No code detected") == 0) { return scope.Close(Null()); } else { return THROW(Error, e.what()); } } catch (const zxing::IllegalArgumentException& e) { return THROW(Error, e.what()); } catch (const zxing::Exception& e) { return THROW(Error, e.what()); } catch (const std::exception& e) { return THROW(Error, e.what()); } catch (...) { return THROW(Error, "Uncaught exception"); } } ZXing::ZXing() : hints_(zxing::DecodeHints::DEFAULT_HINT), reader_(new zxing::MultiFormatReader) { } ZXing::~ZXing() { } <|endoftext|>
<commit_before>/* * Copyright (c) 2017 The WebRTC 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 in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "test/fuzzers/audio_processing_fuzzer_helper.h" #include <algorithm> #include <array> #include <cmath> #include <limits> #include "api/audio/audio_frame.h" #include "modules/audio_processing/include/audio_processing.h" #include "rtc_base/checks.h" namespace webrtc { namespace { bool ValidForApm(float x) { return std::isfinite(x) && -1.0f <= x && x <= 1.0f; } void GenerateFloatFrame(test::FuzzDataHelper* fuzz_data, size_t input_rate, size_t num_channels, float* const* float_frames) { const size_t samples_per_input_channel = rtc::CheckedDivExact(input_rate, static_cast<size_t>(100)); RTC_DCHECK_LE(samples_per_input_channel, 480); for (size_t i = 0; i < num_channels; ++i) { std::fill(float_frames[i], float_frames[i] + samples_per_input_channel, 0); const size_t read_bytes = sizeof(float) * samples_per_input_channel; if (fuzz_data->CanReadBytes(read_bytes)) { rtc::ArrayView<const uint8_t> byte_array = fuzz_data->ReadByteArray(read_bytes); memmove(float_frames[i], byte_array.begin(), read_bytes); } // Sanitize input. for (size_t j = 0; j < samples_per_input_channel; ++j) { if (!ValidForApm(float_frames[i][j])) { float_frames[i][j] = 0.f; } } } } void GenerateFixedFrame(test::FuzzDataHelper* fuzz_data, size_t input_rate, size_t num_channels, AudioFrame* fixed_frame) { const size_t samples_per_input_channel = rtc::CheckedDivExact(input_rate, static_cast<size_t>(100)); fixed_frame->samples_per_channel_ = samples_per_input_channel; fixed_frame->sample_rate_hz_ = input_rate; fixed_frame->num_channels_ = num_channels; RTC_DCHECK_LE(samples_per_input_channel * num_channels, AudioFrame::kMaxDataSizeSamples); for (size_t i = 0; i < samples_per_input_channel * num_channels; ++i) { fixed_frame->mutable_data()[i] = fuzz_data->ReadOrDefaultValue<int16_t>(0); } } } // namespace void FuzzAudioProcessing(test::FuzzDataHelper* fuzz_data, std::unique_ptr<AudioProcessing> apm) { AudioFrame fixed_frame; std::array<float, 480> float_frame1; std::array<float, 480> float_frame2; std::array<float* const, 2> float_frame_ptrs = { &float_frame1[0], &float_frame2[0], }; float* const* ptr_to_float_frames = &float_frame_ptrs[0]; using Rate = AudioProcessing::NativeRate; const Rate rate_kinds[] = {Rate::kSampleRate8kHz, Rate::kSampleRate16kHz, Rate::kSampleRate32kHz, Rate::kSampleRate48kHz}; // We may run out of fuzz data in the middle of a loop iteration. In // that case, default values will be used for the rest of that // iteration. while (fuzz_data->CanReadBytes(1)) { const bool is_float = fuzz_data->ReadOrDefaultValue(true); // Decide input/output rate for this iteration. const auto input_rate = static_cast<size_t>(fuzz_data->SelectOneOf(rate_kinds)); const auto output_rate = static_cast<size_t>(fuzz_data->SelectOneOf(rate_kinds)); const int num_channels = fuzz_data->ReadOrDefaultValue(true) ? 2 : 1; const uint8_t stream_delay = fuzz_data->ReadOrDefaultValue<uint8_t>(0); // API call needed for AEC-2 and AEC-m to run. apm->set_stream_delay_ms(stream_delay); const bool key_pressed = fuzz_data->ReadOrDefaultValue(true); apm->set_stream_key_pressed(key_pressed); // Make the APM call depending on capture/render mode and float / // fix interface. const bool is_capture = fuzz_data->ReadOrDefaultValue(true); // Fill the arrays with audio samples from the data. int apm_return_code = AudioProcessing::Error::kNoError; if (is_float) { GenerateFloatFrame(fuzz_data, input_rate, num_channels, ptr_to_float_frames); if (is_capture) { apm_return_code = apm->ProcessStream( ptr_to_float_frames, StreamConfig(input_rate, num_channels), StreamConfig(output_rate, num_channels), ptr_to_float_frames); } else { apm_return_code = apm->ProcessReverseStream( ptr_to_float_frames, StreamConfig(input_rate, 1), StreamConfig(output_rate, 1), ptr_to_float_frames); } } else { GenerateFixedFrame(fuzz_data, input_rate, num_channels, &fixed_frame); if (is_capture) { apm_return_code = apm->ProcessStream(&fixed_frame); } else { apm_return_code = apm->ProcessReverseStream(&fixed_frame); } } // Cover stats gathering code paths. static_cast<void>(apm->GetStatistics(true /*has_remote_tracks*/)); static_cast<void>(apm->UpdateHistogramsOnCallEnd()); RTC_DCHECK_NE(apm_return_code, AudioProcessing::kBadDataLengthError); } } } // namespace webrtc <commit_msg>Remove deprecated call to UpdateHistogramsOnCallEnd<commit_after>/* * Copyright (c) 2017 The WebRTC 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 in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "test/fuzzers/audio_processing_fuzzer_helper.h" #include <algorithm> #include <array> #include <cmath> #include <limits> #include "api/audio/audio_frame.h" #include "modules/audio_processing/include/audio_processing.h" #include "rtc_base/checks.h" namespace webrtc { namespace { bool ValidForApm(float x) { return std::isfinite(x) && -1.0f <= x && x <= 1.0f; } void GenerateFloatFrame(test::FuzzDataHelper* fuzz_data, size_t input_rate, size_t num_channels, float* const* float_frames) { const size_t samples_per_input_channel = rtc::CheckedDivExact(input_rate, static_cast<size_t>(100)); RTC_DCHECK_LE(samples_per_input_channel, 480); for (size_t i = 0; i < num_channels; ++i) { std::fill(float_frames[i], float_frames[i] + samples_per_input_channel, 0); const size_t read_bytes = sizeof(float) * samples_per_input_channel; if (fuzz_data->CanReadBytes(read_bytes)) { rtc::ArrayView<const uint8_t> byte_array = fuzz_data->ReadByteArray(read_bytes); memmove(float_frames[i], byte_array.begin(), read_bytes); } // Sanitize input. for (size_t j = 0; j < samples_per_input_channel; ++j) { if (!ValidForApm(float_frames[i][j])) { float_frames[i][j] = 0.f; } } } } void GenerateFixedFrame(test::FuzzDataHelper* fuzz_data, size_t input_rate, size_t num_channels, AudioFrame* fixed_frame) { const size_t samples_per_input_channel = rtc::CheckedDivExact(input_rate, static_cast<size_t>(100)); fixed_frame->samples_per_channel_ = samples_per_input_channel; fixed_frame->sample_rate_hz_ = input_rate; fixed_frame->num_channels_ = num_channels; RTC_DCHECK_LE(samples_per_input_channel * num_channels, AudioFrame::kMaxDataSizeSamples); for (size_t i = 0; i < samples_per_input_channel * num_channels; ++i) { fixed_frame->mutable_data()[i] = fuzz_data->ReadOrDefaultValue<int16_t>(0); } } } // namespace void FuzzAudioProcessing(test::FuzzDataHelper* fuzz_data, std::unique_ptr<AudioProcessing> apm) { AudioFrame fixed_frame; std::array<float, 480> float_frame1; std::array<float, 480> float_frame2; std::array<float* const, 2> float_frame_ptrs = { &float_frame1[0], &float_frame2[0], }; float* const* ptr_to_float_frames = &float_frame_ptrs[0]; using Rate = AudioProcessing::NativeRate; const Rate rate_kinds[] = {Rate::kSampleRate8kHz, Rate::kSampleRate16kHz, Rate::kSampleRate32kHz, Rate::kSampleRate48kHz}; // We may run out of fuzz data in the middle of a loop iteration. In // that case, default values will be used for the rest of that // iteration. while (fuzz_data->CanReadBytes(1)) { const bool is_float = fuzz_data->ReadOrDefaultValue(true); // Decide input/output rate for this iteration. const auto input_rate = static_cast<size_t>(fuzz_data->SelectOneOf(rate_kinds)); const auto output_rate = static_cast<size_t>(fuzz_data->SelectOneOf(rate_kinds)); const int num_channels = fuzz_data->ReadOrDefaultValue(true) ? 2 : 1; const uint8_t stream_delay = fuzz_data->ReadOrDefaultValue<uint8_t>(0); // API call needed for AEC-2 and AEC-m to run. apm->set_stream_delay_ms(stream_delay); const bool key_pressed = fuzz_data->ReadOrDefaultValue(true); apm->set_stream_key_pressed(key_pressed); // Make the APM call depending on capture/render mode and float / // fix interface. const bool is_capture = fuzz_data->ReadOrDefaultValue(true); // Fill the arrays with audio samples from the data. int apm_return_code = AudioProcessing::Error::kNoError; if (is_float) { GenerateFloatFrame(fuzz_data, input_rate, num_channels, ptr_to_float_frames); if (is_capture) { apm_return_code = apm->ProcessStream( ptr_to_float_frames, StreamConfig(input_rate, num_channels), StreamConfig(output_rate, num_channels), ptr_to_float_frames); } else { apm_return_code = apm->ProcessReverseStream( ptr_to_float_frames, StreamConfig(input_rate, 1), StreamConfig(output_rate, 1), ptr_to_float_frames); } } else { GenerateFixedFrame(fuzz_data, input_rate, num_channels, &fixed_frame); if (is_capture) { apm_return_code = apm->ProcessStream(&fixed_frame); } else { apm_return_code = apm->ProcessReverseStream(&fixed_frame); } } // Cover stats gathering code paths. static_cast<void>(apm->GetStatistics(true /*has_remote_tracks*/)); RTC_DCHECK_NE(apm_return_code, AudioProcessing::kBadDataLengthError); } } } // namespace webrtc <|endoftext|>
<commit_before>#include "Text.h" Text::Text() : Blittable(), font(nullptr), text("") { color.r = color.g = color.b = 255; bg_color.r = bg_color.g = bg_color.b = 0; } Text::~Text() { } void Text::set_font(Font* const font) { this->font = font; return; } void Text::set_text(const std::string& text, SDL_Renderer* r) { assert(r); destroy(); SDL_Surface* surface = nullptr; RenderMode rm = font->get_render_mode(); if(rm == RenderMode::Solid) surface = TTF_RenderText_Solid(font->get_font(), text.c_str(), color); else if(rm == RenderMode::Shaded) surface = TTF_RenderText_Shaded(font->get_font(), text.c_str(), color, bg_color); else surface = TTF_RenderText_Blended(font->get_font(), text.c_str(), color); assert(surface); texture = SDL_CreateTextureFromSurface(r, surface); assert(texture); SDL_QueryTexture(texture, nullptr, nullptr, &info.w, &info.w); return; } std::string Text::get_text() { return text; } void Text::set_color(const Uint8 r, const Uint8 g, const Uint8 b) { color.r = r; color.g = g; color.b = b; return; } void Text::set_bg_color(const Uint8 r, const Uint8 g, const Uint8 b) { bg_color.r = r; bg_color.g = g; bg_color.b = b; return; } <commit_msg>Set height in Text properly.<commit_after>#include "Text.h" Text::Text() : Blittable(), font(nullptr), text("") { color.r = color.g = color.b = 255; bg_color.r = bg_color.g = bg_color.b = 0; } Text::~Text() { } void Text::set_font(Font* const font) { this->font = font; return; } void Text::set_text(const std::string& text, SDL_Renderer* r) { assert(r); destroy(); SDL_Surface* surface = nullptr; RenderMode rm = font->get_render_mode(); if(rm == RenderMode::Solid) surface = TTF_RenderText_Solid(font->get_font(), text.c_str(), color); else if(rm == RenderMode::Shaded) surface = TTF_RenderText_Shaded(font->get_font(), text.c_str(), color, bg_color); else surface = TTF_RenderText_Blended(font->get_font(), text.c_str(), color); assert(surface); texture = SDL_CreateTextureFromSurface(r, surface); assert(texture); SDL_QueryTexture(texture, nullptr, nullptr, &info.w, &info.h); return; } std::string Text::get_text() { return text; } void Text::set_color(const Uint8 r, const Uint8 g, const Uint8 b) { color.r = r; color.g = g; color.b = b; return; } void Text::set_bg_color(const Uint8 r, const Uint8 g, const Uint8 b) { bg_color.r = r; bg_color.g = g; bg_color.b = b; return; } <|endoftext|>
<commit_before>#pragma once #include <eosio/chain/block.hpp> #include <eosio/chain/block_timestamp.hpp> #include <stdint.h> #include <string_view> namespace eosio { namespace blockvault { using watermark_t = std::pair<uint32_t, eosio::chain::block_timestamp_type>; class sync_callback { public: virtual void on_snapshot(const char* snapshot_filename) = 0; virtual void on_block(std::string_view block) = 0; }; class block_vault_interface { public: virtual ~block_vault_interface() {} /// /// \brief The primary method for adding constructed blocks to the Block /// Vault. If a proposed constructed block is accepted, the Block Vault /// cluster will guarantee that no future proposed blocks will be accepted /// which is in conflict with this block due to double production or finality /// violations. If the Block Vault cannot make that guarantee for any reason, /// it must reject the proposal. /// /// /// \param watermark The producer watermark implied by accepting this block. /// /// \param lib The LIB implied by accepting this block. /// /// \param block A signed constructed block. /// /// \param handler The callback function to inform caller whether the block has accepted the Block Vault or not. virtual void async_propose_constructed_block(watermark_t watermark, uint32_t lib, eosio::chain::signed_block_ptr block, std::function<void(bool)> handler) = 0; /// /// \brief The primary method for adding externally discovered blocks to the /// Block Vault. If an external block is accepted, the Block Vault cluster /// will guarantee that all future nodeos nodes will know about this block OR /// about an accepted snapshot state that exceeds this block's block height /// before proposing a constructed block. If the implied LIB of this block /// conflicts with the Block Vault state, then it will be rejected. If the /// block is older than the currently available snapshot, it is still /// accepted but will not affect the Block Vault cluster state. /// /// \param lib The LIB implied by accepting this block. /// /// \param block A signed externally discovered block. /// /// \param handler The callback function to inform caller whether the block has accepted the Block Vault or not. /// virtual void async_append_external_block(uint32_t lib, eosio::chain::signed_block_ptr block, std::function<void(bool)> handler) = 0; /// /// \brief The primary method for a nodeos node to offer snapshot data to /// Block Vault that facilitates log pruning. If a snapshot's height is /// greater than the current snapshot AND less than or equal to the current /// implied LIB height, it will be accepted, and Block Vault will be able to /// prune its state internally. Otherwise, it should reject the proposed /// snapshot. /// /// \param snapshot_filename the filename of snapshot. /// /// \param watermark The producer watermark at the block height of this snapshot. /// virtual bool propose_snapshot(watermark_t watermark, const char* snapshot_filename) = 0; /// /// \brief The primary method for bringing a new nodeos node into sync with /// the Block Vault. This is the primary method for bringing a new nodeos /// node into sync with the Block Vault. Syncing is semi-session based, a /// syncing nodeos will establish a session with a single Block Vault node, /// stored on that node for the duration of the syncing process. This /// session is used to guarantee that the Block Vault node does not prune any /// data that will be needed to complete this sync process until it is /// completed OR the session is timed-out. This session is not replicated /// amongst other Block Vault nodes. As a result, if the syncing process is /// interrupted due to inability to communicate with the chosen Block Vault /// node, it must restart from the beginning with a new node. /// /// \param block_id The BlockID of the best known final block on the client /// /// \param callback The callback object to receive the snapshot and blocks /// virtual void sync(const eosio::chain::block_id_type& block_id, sync_callback& callback) = 0; }; } // namespace blockvault } // namespace eosio <commit_msg>modify interface<commit_after>#pragma once #include <eosio/chain/block.hpp> #include <eosio/chain/block_timestamp.hpp> #include <stdint.h> #include <string_view> namespace eosio { namespace blockvault { using watermark_t = std::pair<uint32_t, eosio::chain::block_timestamp_type>; class sync_callback { public: virtual void on_snapshot(const char* snapshot_filename) = 0; virtual void on_block(eosio::chain::signed_block_ptr block) = 0; }; class block_vault_interface { public: virtual ~block_vault_interface() {} /// /// \brief The primary method for adding constructed blocks to the Block /// Vault. If a proposed constructed block is accepted, the Block Vault /// cluster will guarantee that no future proposed blocks will be accepted /// which is in conflict with this block due to double production or finality /// violations. If the Block Vault cannot make that guarantee for any reason, /// it must reject the proposal. /// /// /// \param watermark The producer watermark implied by accepting this block. /// /// \param lib The LIB implied by accepting this block. /// /// \param block A signed constructed block. /// /// \param handler The callback function to inform caller whether the block has accepted the Block Vault or not. virtual void async_propose_constructed_block(watermark_t watermark, uint32_t lib, eosio::chain::signed_block_ptr block, std::function<void(bool)> handler) = 0; /// /// \brief The primary method for adding externally discovered blocks to the /// Block Vault. If an external block is accepted, the Block Vault cluster /// will guarantee that all future nodeos nodes will know about this block OR /// about an accepted snapshot state that exceeds this block's block height /// before proposing a constructed block. If the implied LIB of this block /// conflicts with the Block Vault state, then it will be rejected. If the /// block is older than the currently available snapshot, it is still /// accepted but will not affect the Block Vault cluster state. /// /// \param lib The LIB implied by accepting this block. /// /// \param block A signed externally discovered block. /// /// \param handler The callback function to inform caller whether the block has accepted the Block Vault or not. /// virtual void async_append_external_block(uint32_t lib, eosio::chain::signed_block_ptr block, std::function<void(bool)> handler) = 0; /// /// \brief The primary method for a nodeos node to offer snapshot data to /// Block Vault that facilitates log pruning. If a snapshot's height is /// greater than the current snapshot AND less than or equal to the current /// implied LIB height, it will be accepted, and Block Vault will be able to /// prune its state internally. Otherwise, it should reject the proposed /// snapshot. /// /// \param snapshot_filename the filename of snapshot. /// /// \param watermark The producer watermark at the block height of this snapshot. /// virtual bool propose_snapshot(watermark_t watermark, const char* snapshot_filename) = 0; /// /// \brief The primary method for bringing a new nodeos node into sync with /// the Block Vault. This is the primary method for bringing a new nodeos /// node into sync with the Block Vault. Syncing is semi-session based, a /// syncing nodeos will establish a session with a single Block Vault node, /// stored on that node for the duration of the syncing process. This /// session is used to guarantee that the Block Vault node does not prune any /// data that will be needed to complete this sync process until it is /// completed OR the session is timed-out. This session is not replicated /// amongst other Block Vault nodes. As a result, if the syncing process is /// interrupted due to inability to communicate with the chosen Block Vault /// node, it must restart from the beginning with a new node. /// /// \param block_id The BlockID of the best known final block on the client /// /// \param callback The callback object to receive the snapshot and blocks /// virtual void sync(const eosio::chain::block_id_type* block_id, sync_callback& callback) = 0; }; } // namespace blockvault } // namespace eosio <|endoftext|>
<commit_before>/* * Copyright (c) 2015, Nagoya University * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of Autoware 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. */ // ROS includes #include <ros/ros.h> #include <geometry_msgs/TwistStamped.h> #include <geometry_msgs/PoseStamped.h> #include <std_msgs/Float32.h> #include "vehicle_socket/CanInfo.h" namespace vel_pose_mux { struct VehicleInfo { double wheel_base; double minimum_turning_radius; double maximum_steering_angle; }; inline double kmph2mps(double velocity_kmph) { return (velocity_kmph * 1000) / (60 * 60); } inline double mps2kmph(double velocity_mps) { return (velocity_mps * 60 * 60) / 1000; } // convert degree to radian inline double deg2rad(double deg) { return deg * M_PI / 180; } // convert degree to radian inline double rad2deg(double rad) { return rad * 180 / M_PI; } void callbackFromCanInfoAndPublishAsTwistStamped(const vehicle_socket::CanInfoConstPtr &msg, ros::Publisher *pub_twist_stamped, ros::Publisher *pub_float, const VehicleInfo &vehicle_info) { geometry_msgs::TwistStamped tw; tw.header = msg->header; // linear velocity tw.twist.linear.x = kmph2mps(msg->speed); // km/h -> m/s // angular velocity double maximum_tire_angle = rad2deg(asin(vehicle_info.wheel_base / vehicle_info.minimum_turning_radius)); //[degree] double current_tire_angle = msg->angle * maximum_tire_angle / vehicle_info.maximum_steering_angle; // steering [degree] -> tire [degree] tw.twist.angular.z = sin(deg2rad(current_tire_angle)) * kmph2mps(msg->speed) / vehicle_info.wheel_base; pub_twist_stamped->publish(tw); std_msgs::Float32 fl; fl.data = msg->speed; pub_float->publish(fl); } void callbackFromCanInfoAndPublishAsTwistStamped(const vehicle_socket::CanInfoConstPtr &msg, ros::Publisher *pub_twist_stamped, ros::Publisher *pub_float) { geometry_msgs::TwistStamped tw; tw.header = msg->header; // linear velocity tw.twist.linear.x = kmph2mps(msg->speed); // km/h -> m/s pub_twist_stamped->publish(tw); std_msgs::Float32 fl; fl.data = msg->speed; pub_float->publish(fl); } void callbackFromPoseStampedAndPublish(const geometry_msgs::PoseStampedConstPtr &msg, ros::Publisher *pub_message) { pub_message->publish(*msg); } void callbackFromTwistStampedAndPublish(const geometry_msgs::TwistStampedConstPtr &msg, ros::Publisher *pub_twist_stamped, ros::Publisher *pub_float) { pub_twist_stamped->publish(*msg); std_msgs::Float32 fl; fl.data = mps2kmph(msg->twist.linear.x); pub_float->publish(fl); } } // namespace int main(int argc, char **argv) { // set up ros ros::init(argc, argv, "vel_pose_mux"); ros::NodeHandle nh; ros::NodeHandle private_nh("~"); int32_t pose_mux_select, vel_mux_select; bool sim_mode; // setting params private_nh.param<int32_t>("pose_mux_select", pose_mux_select, int32_t(0)); // ROS_INFO_STREAM("pose_mux_select : " << pose_mux_select); private_nh.param<int32_t>("vel_mux_select", vel_mux_select, int32_t(1)); // ROS_INFO_STREAM("vel_mux_select : " << vel_mux_select); private_nh.param<bool>("sim_mode", sim_mode, false); // ROS_INFO_STREAM("sim_mode : " << sim_mode); bool vehicle_info_flag = false; vel_pose_mux::VehicleInfo vehicle_info; if (!nh.hasParam("/vehicle_info/wheel_base") || !nh.hasParam("/vehicle_info/minimum_turning_radius") || !nh.hasParam("/vehicle_info/maximum_steering_angle")) { ROS_INFO("vehicle_info is not set"); } else { private_nh.getParam("/vehicle_info/wheel_base", vehicle_info.wheel_base); // ROS_INFO_STREAM("wheel_base : " << wheel_base); private_nh.getParam("/vehicle_info/minimum_turning_radius", vehicle_info.minimum_turning_radius); // ROS_INFO_STREAM("minimum_turning_radius : " << minimum_turning_radius); private_nh.getParam("/vehicle_info/maximum_steering_angle", vehicle_info.maximum_steering_angle); //[degree: // ROS_INFO_STREAM("maximum_steering_angle : " << maximum_steering_angle); vehicle_info_flag = true; } // publish topic ros::Publisher vel_publisher = nh.advertise<geometry_msgs::TwistStamped>("current_velocity", 10); ros::Publisher pose_publisher = nh.advertise<geometry_msgs::PoseStamped>("current_pose", 10); ros::Publisher linear_viz_publisher = nh.advertise<std_msgs::Float32>("linear_velocity_viz",10); // subscribe topic ros::Subscriber pose_subcscriber; ros::Subscriber vel_subcscriber; if (sim_mode) { vel_subcscriber = nh.subscribe<geometry_msgs::TwistStamped>( "sim_velocity", 10, boost::bind(vel_pose_mux::callbackFromTwistStampedAndPublish, _1, &vel_publisher, &linear_viz_publisher)); pose_subcscriber = nh.subscribe<geometry_msgs::PoseStamped>( "sim_pose", 10, boost::bind(vel_pose_mux::callbackFromPoseStampedAndPublish, _1, &pose_publisher)); } else { // pose switch (pose_mux_select) { case 0: // ndt_localizer { pose_subcscriber = nh.subscribe<geometry_msgs::PoseStamped>( "ndt_pose", 10, boost::bind(vel_pose_mux::callbackFromPoseStampedAndPublish, _1, &pose_publisher)); break; } case 1: // gnss { pose_subcscriber = nh.subscribe<geometry_msgs::PoseStamped>( "gnss_pose", 10, boost::bind(vel_pose_mux::callbackFromPoseStampedAndPublish, _1, &pose_publisher)); break; } default: break; } // velocity switch (vel_mux_select) { case 0: // ndt_localizer { vel_subcscriber = nh.subscribe<geometry_msgs::TwistStamped>( "estimate_twist", 10, boost::bind(vel_pose_mux::callbackFromTwistStampedAndPublish, _1, &vel_publisher, &linear_viz_publisher)); break; } case 1: // CAN { if (vehicle_info_flag) // has vehicle info { vel_subcscriber = nh.subscribe<vehicle_socket::CanInfo>( "can_info", 10, boost::bind(vel_pose_mux::callbackFromCanInfoAndPublishAsTwistStamped, _1, &vel_publisher, &linear_viz_publisher, vehicle_info)); } else { vel_subcscriber = nh.subscribe<vehicle_socket::CanInfo>( "can_info", 10, boost::bind(vel_pose_mux::callbackFromCanInfoAndPublishAsTwistStamped, _1, &vel_publisher, &linear_viz_publisher)); } break; } default: break; } } ros::spin(); return 0; } <commit_msg>Make code format better<commit_after>/* * Copyright (c) 2015, Nagoya University * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of Autoware 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. */ // ROS includes #include <ros/ros.h> #include <geometry_msgs/TwistStamped.h> #include <geometry_msgs/PoseStamped.h> #include <std_msgs/Float32.h> #include "vehicle_socket/CanInfo.h" namespace vel_pose_mux { struct VehicleInfo { double wheel_base; double minimum_turning_radius; double maximum_steering_angle; }; inline double kmph2mps(double velocity_kmph) { return (velocity_kmph * 1000) / (60 * 60); } inline double mps2kmph(double velocity_mps) { return (velocity_mps * 60 * 60) / 1000; } // convert degree to radian inline double deg2rad(double deg) { return deg * M_PI / 180; } // convert degree to radian inline double rad2deg(double rad) { return rad * 180 / M_PI; } void callbackFromCanInfoAndPublishAsTwistStamped(const vehicle_socket::CanInfoConstPtr &msg, ros::Publisher *pub_twist_stamped, ros::Publisher *pub_float, const VehicleInfo &vehicle_info) { geometry_msgs::TwistStamped tw; tw.header = msg->header; // linear velocity tw.twist.linear.x = kmph2mps(msg->speed); // km/h -> m/s // angular velocity double maximum_tire_angle = rad2deg(asin(vehicle_info.wheel_base / vehicle_info.minimum_turning_radius)); //[degree] double current_tire_angle = msg->angle * maximum_tire_angle / vehicle_info.maximum_steering_angle; // steering [degree] -> tire [degree] tw.twist.angular.z = sin(deg2rad(current_tire_angle)) * kmph2mps(msg->speed) / vehicle_info.wheel_base; pub_twist_stamped->publish(tw); std_msgs::Float32 fl; fl.data = msg->speed; pub_float->publish(fl); } void callbackFromCanInfoAndPublishAsTwistStamped(const vehicle_socket::CanInfoConstPtr &msg, ros::Publisher *pub_twist_stamped, ros::Publisher *pub_float) { geometry_msgs::TwistStamped tw; tw.header = msg->header; // linear velocity tw.twist.linear.x = kmph2mps(msg->speed); // km/h -> m/s pub_twist_stamped->publish(tw); std_msgs::Float32 fl; fl.data = msg->speed; pub_float->publish(fl); } void callbackFromPoseStampedAndPublish(const geometry_msgs::PoseStampedConstPtr &msg, ros::Publisher *pub_message) { pub_message->publish(*msg); } void callbackFromTwistStampedAndPublish(const geometry_msgs::TwistStampedConstPtr &msg, ros::Publisher *pub_twist_stamped, ros::Publisher *pub_float) { pub_twist_stamped->publish(*msg); std_msgs::Float32 fl; fl.data = mps2kmph(msg->twist.linear.x); pub_float->publish(fl); } } // namespace int main(int argc, char **argv) { // set up ros ros::init(argc, argv, "vel_pose_mux"); ros::NodeHandle nh; ros::NodeHandle private_nh("~"); int32_t pose_mux_select, vel_mux_select; bool sim_mode; // setting params private_nh.param<int32_t>("pose_mux_select", pose_mux_select, int32_t(0)); // ROS_INFO_STREAM("pose_mux_select : " << pose_mux_select); private_nh.param<int32_t>("vel_mux_select", vel_mux_select, int32_t(1)); // ROS_INFO_STREAM("vel_mux_select : " << vel_mux_select); private_nh.param<bool>("sim_mode", sim_mode, false); // ROS_INFO_STREAM("sim_mode : " << sim_mode); bool vehicle_info_flag = false; vel_pose_mux::VehicleInfo vehicle_info; if (!nh.hasParam("/vehicle_info/wheel_base") || !nh.hasParam("/vehicle_info/minimum_turning_radius") || !nh.hasParam("/vehicle_info/maximum_steering_angle")) { ROS_INFO("vehicle_info is not set"); } else { private_nh.getParam("/vehicle_info/wheel_base", vehicle_info.wheel_base); // ROS_INFO_STREAM("wheel_base : " << wheel_base); private_nh.getParam("/vehicle_info/minimum_turning_radius", vehicle_info.minimum_turning_radius); // ROS_INFO_STREAM("minimum_turning_radius : " << minimum_turning_radius); private_nh.getParam("/vehicle_info/maximum_steering_angle", vehicle_info.maximum_steering_angle); //[degree: // ROS_INFO_STREAM("maximum_steering_angle : " << maximum_steering_angle); vehicle_info_flag = true; } // publish topic ros::Publisher vel_publisher = nh.advertise<geometry_msgs::TwistStamped>("current_velocity", 10); ros::Publisher pose_publisher = nh.advertise<geometry_msgs::PoseStamped>("current_pose", 10); ros::Publisher linear_viz_publisher = nh.advertise<std_msgs::Float32>("linear_velocity_viz", 10); // subscribe topic ros::Subscriber pose_subcscriber; ros::Subscriber vel_subcscriber; if (sim_mode) { vel_subcscriber = nh.subscribe<geometry_msgs::TwistStamped>( "sim_velocity", 10, boost::bind(vel_pose_mux::callbackFromTwistStampedAndPublish, _1, &vel_publisher, &linear_viz_publisher)); pose_subcscriber = nh.subscribe<geometry_msgs::PoseStamped>( "sim_pose", 10, boost::bind(vel_pose_mux::callbackFromPoseStampedAndPublish, _1, &pose_publisher)); } else { // pose switch (pose_mux_select) { case 0: // ndt_localizer { pose_subcscriber = nh.subscribe<geometry_msgs::PoseStamped>( "ndt_pose", 10, boost::bind(vel_pose_mux::callbackFromPoseStampedAndPublish, _1, &pose_publisher)); break; } case 1: // gnss { pose_subcscriber = nh.subscribe<geometry_msgs::PoseStamped>( "gnss_pose", 10, boost::bind(vel_pose_mux::callbackFromPoseStampedAndPublish, _1, &pose_publisher)); break; } default: break; } // velocity switch (vel_mux_select) { case 0: // ndt_localizer { vel_subcscriber = nh.subscribe<geometry_msgs::TwistStamped>( "estimate_twist", 10, boost::bind(vel_pose_mux::callbackFromTwistStampedAndPublish, _1, &vel_publisher, &linear_viz_publisher)); break; } case 1: // CAN { if (vehicle_info_flag) // has vehicle info { vel_subcscriber = nh.subscribe<vehicle_socket::CanInfo>( "can_info", 10, boost::bind(vel_pose_mux::callbackFromCanInfoAndPublishAsTwistStamped, _1, &vel_publisher, &linear_viz_publisher, vehicle_info)); } else { vel_subcscriber = nh.subscribe<vehicle_socket::CanInfo>( "can_info", 10, boost::bind(vel_pose_mux::callbackFromCanInfoAndPublishAsTwistStamped, _1, &vel_publisher, &linear_viz_publisher)); } break; } default: break; } } ros::spin(); return 0; } <|endoftext|>
<commit_before>/****************************************************************************** * Controls.cpp * * Contains the yaw_controller() and depth_controller functions ******************************************************************************/ #include "Mapper.h" /****************************************************************************** * float yaw_controller() * * Takes in readings from the IMU and returns a value between -1 and 1 (-100% - * +100%) that the port and starboard thrusters should run at ******************************************************************************/ float yaw_controller(bno055_t bno055, pid_data_t yaw_pid) { // control output // if( bno055.yaw < 180 ) // AUV is pointed right { // u[2] is negative motor_percent = yaw_pid.kp*(yaw_pid.err) + yaw_pid.kd*(bno055.r)+ yaw_pid.ki*yaw_pid.i_err; // yaw controller } else // AUV is pointed left { // u[2] is positive motor_percent = yaw_pid.kp*(yaw_pid.err) + yaw_pid.kd*(bno055.r) + yaw_pid.ki*yaw_pid.i_err; // yaw controller } // saturate yaw controller // if( motor_percent > YAW_SAT ) { motor_percent=YAW_SAT; } else if( motor_percent < -YAW_SAT ) { motor_percent = -YAW_SAT; } yaw_pid.i_err += yaw_pid.err*DT; // set current yaw to be the old yaw // yaw_pid.oldyaw = bno055.yaw; return motor_percent; } /****************************************************************************** * float depth_controller(float range) * * Takes a range-from-bottom reading from the laser range-finder code and * returns a value between -1 and 1 (-100% - +100%) that the vertical thruster * should run at ******************************************************************************/ /* float depth_controller(float range) { float vert_percent; // vertical thruster output in a percentage float depth_sum_error = 0; // accumulated range error for integral control float range_current; float range_old; float // accumulated range error for integral control // depth_sum_error += range - depth_pid.setpoint; if( range > depth_pid.setpoint ) { vert_percent = depth_pid.kp*(range-depth_pid.setpoint) + depth_pid.ki*(depth_sum_error) + depth_pid.kd*((range_current-range_old)/DT); } else { // shut off vertical thruster // vert_percent = 0; } // saturate depth controller // if( vert_percent > DEPTH_SAT ) { vert_percent = DEPTH_SAT; } else if( vert_percent < -DEPTH_SAT ) { vert_percent = -DEPTH_SAT; } // set current depth to be the old depth // depth_pid.old = depth_pid.current; return vert_percent; } */ <commit_msg>Declared variables in yaw_controller<commit_after>/****************************************************************************** * Controls.cpp * * Contains the yaw_controller() and depth_controller functions ******************************************************************************/ #include "Mapper.h" /****************************************************************************** * float yaw_controller() * * Takes in readings from the IMU and returns a value between -1 and 1 (-100% - * +100%) that the port and starboard thrusters should run at ******************************************************************************/ float yaw_controller(bno055_t bno055, pid_data_t yaw_pid) { float motor_percent; float DT; float YAW_SAT; // control output // if( bno055.yaw < 180 ) // AUV is pointed right { // u[2] is negative motor_percent = yaw_pid.kp*(yaw_pid.err) + yaw_pid.kd*(bno055.r)+ yaw_pid.ki*yaw_pid.i_err; // yaw controller } else // AUV is pointed left { // u[2] is positive motor_percent = yaw_pid.kp*(yaw_pid.err) + yaw_pid.kd*(bno055.r) + yaw_pid.ki*yaw_pid.i_err; // yaw controller } // saturate yaw controller // if( motor_percent > YAW_SAT ) { motor_percent=YAW_SAT; } else if( motor_percent < -YAW_SAT ) { motor_percent = -YAW_SAT; } yaw_pid.i_err += yaw_pid.err*DT; // set current yaw to be the old yaw // yaw_pid.oldyaw = bno055.yaw; return motor_percent; } /****************************************************************************** * float depth_controller(float range) * * Takes a range-from-bottom reading from the laser range-finder code and * returns a value between -1 and 1 (-100% - +100%) that the vertical thruster * should run at ******************************************************************************/ /* float depth_controller(float range) { float vert_percent; // vertical thruster output in a percentage float depth_sum_error = 0; // accumulated range error for integral control float range_current; float range_old; float // accumulated range error for integral control // depth_sum_error += range - depth_pid.setpoint; if( range > depth_pid.setpoint ) { vert_percent = depth_pid.kp*(range-depth_pid.setpoint) + depth_pid.ki*(depth_sum_error) + depth_pid.kd*((range_current-range_old)/DT); } else { // shut off vertical thruster // vert_percent = 0; } // saturate depth controller // if( vert_percent > DEPTH_SAT ) { vert_percent = DEPTH_SAT; } else if( vert_percent < -DEPTH_SAT ) { vert_percent = -DEPTH_SAT; } // set current depth to be the old depth // depth_pid.old = depth_pid.current; return vert_percent; } */ <|endoftext|>
<commit_before>// This file is part of the GLERI project // // Copyright (c) 2012 by Mike Sharov <msharov@users.sourceforge.net> // This file is free software, distributed under the MIT License. #include "cmd.h" //---------------------------------------------------------------------- const char* CCmdBuf::nextname (const char* n, size_type& sz) noexcept // static { #if __x86__ asm("repnz\tscasb\n\trepnz\tscasb":"+D"(n),"+c"(sz):"a"(0):"memory"); return n; #else const char* nn = n; nn += strlen(nn)+1; nn += strlen(nn)+1; sz -= nn - n; return nn; #endif } bool CCmdBuf::namecmp (const void* s1, const void* s2, size_type n) noexcept // static { #if __x86__ asm("repz\tcmpsb":"+D"(s1),"+S"(s2),"+c"(n)); return !n; #else return !memcmp (s1,s2,n); #endif } const char* CCmdBuf::LookupCmdName (unsigned cmd, size_type& sz, const char* cmdnames, size_type cleft) noexcept // static { unsigned ci = InvalidCmd+1; for (const char *ns, *s = cmdnames; cleft; ++ci, s = ns) { ns = nextname(s,cleft); if (cmd == ci) { sz = ns-s; return s; } } sz = 0; assert (!"You have defined an ECmd enum, but not the command signature"); exit (EXIT_FAILURE); } unsigned CCmdBuf::LookupCmd (const char* name, size_type bleft, const char* cmdnames, size_type cleft) noexcept // static { unsigned ci = InvalidCmd+1, namesz = nextname(name,bleft)-name; for (const char* s = cmdnames; cleft; ++ci) { const char* ns = nextname(s,cleft); if (ns-s == namesz && namecmp(s,name,namesz)) return ci; s = ns; } return InvalidCmd; } CCmdBuf::size_type CCmdBuf::nextcapacity (size_type v) const noexcept { #if __x86__ asm("bsr\t%0, %0":"+r"(v)); return 1<<(1+v); #else size_type r = 64; while (r <= v) r *= 2; // Next power of 2 return r; #endif } CCmdBuf::pointer CCmdBuf::addspace (size_type need) noexcept { need += size(); if (_sz < need) { auto nsz = nextcapacity (need); _buf = (pointer) realloc (_buf, nsz); memset (_buf+_sz, 0, nsz-_sz); _sz = nsz; } return end(); } bstro CCmdBuf::CreateCmd (uint32_t o, const char* m, size_type msz, size_type sz, size_type unwritten) noexcept { assert (!unwritten || sz-unwritten == Align(sz-unwritten,c_MsgAlignment)); SMsgHeader h = { Align(sz,c_MsgAlignment), _iid, (uint8_t) (m[msz-2] == 'h' ? sz-sizeof(int) : UINT8_MAX), (uint8_t) Align(sizeof(SMsgHeader)+msz,c_MsgAlignment), o }; const size_type cmdsz = h.hsz+Align(sz-unwritten,c_MsgAlignment); pointer pip = addspace (cmdsz); bstro os (pip,cmdsz); os << h; os.write (m, msz); os.align (c_MsgAlignment); _used += cmdsz; return os; } void CCmdBuf::EndRead (bstri::const_pointer p) noexcept { assert (p >= _buf && p <= _buf+_used && "EndRead must be given pointer returned by BeginRead"); size_type br = p-_buf; memcpy (_buf, p, _used-=br); } void CCmdBuf::ReadCmds (void) { if (!_outf.IsOpen()) return; size_t br; do { pointer pip = addspace (256); br = CanPassFd() ? _outf.ReadWithFdPass(pip, remaining()) : _outf.Read(pip, remaining()); _used += br; } while (br); } void CCmdBuf::WriteCmds (void) { if (!_outf.IsOpen()) return; bstri is (BeginRead()); _outf.Write (is.ipos(), is.remaining()); is.skip (is.remaining()); EndRead (is); } void CCmdBuf::SendFile (CFile& f, uint32_t fsz) { WriteCmds(); if (CanPassFd()) _outf.SendFd (f); else { _outf.Write (&fsz, sizeof(fsz)); f.SendfileTo (_outf, fsz); uint64_t zeropad = 0; uint32_t alignedSize = Align(sizeof(fsz)+fsz, c_MsgAlignment); _outf.Write (&zeropad, alignedSize-(sizeof(fsz)+fsz)); } } //---------------------------------------------------------------------- // COM object interface #define N(n,s) #n "\0" #s "\0" const char CCmdBuf::_cmdNames[] = N(Error,s) N(Export,s) N(Delete,) ; #undef N const char* CCmdBuf::LookupCmdName (ECmd cmd, size_type& sz) noexcept // static { return CCmdBuf::LookupCmdName((unsigned)cmd,sz,ArrayBlock(_cmdNames)-1); } CCmdBuf::ECmd CCmdBuf::LookupCmd (const char* name, size_type bleft) noexcept // static { return ECmd(CCmdBuf::LookupCmd(name,bleft,ArrayBlock(_cmdNames)-1)); } bstro CCmdBuf::CreateCmd (ECmd cmd, size_type sz, size_type unwritten) noexcept { size_type msz; const char* m = LookupCmdName (cmd, msz); return CCmdBuf::CreateCmd (c_ObjectName, m, msz, sz, unwritten); } <commit_msg>Lowercase COM method names to match casycom spec<commit_after>// This file is part of the GLERI project // // Copyright (c) 2012 by Mike Sharov <msharov@users.sourceforge.net> // This file is free software, distributed under the MIT License. #include "cmd.h" //---------------------------------------------------------------------- const char* CCmdBuf::nextname (const char* n, size_type& sz) noexcept // static { #if __x86__ asm("repnz\tscasb\n\trepnz\tscasb":"+D"(n),"+c"(sz):"a"(0):"memory"); return n; #else const char* nn = n; nn += strlen(nn)+1; nn += strlen(nn)+1; sz -= nn - n; return nn; #endif } bool CCmdBuf::namecmp (const void* s1, const void* s2, size_type n) noexcept // static { #if __x86__ asm("repz\tcmpsb":"+D"(s1),"+S"(s2),"+c"(n)); return !n; #else return !memcmp (s1,s2,n); #endif } const char* CCmdBuf::LookupCmdName (unsigned cmd, size_type& sz, const char* cmdnames, size_type cleft) noexcept // static { unsigned ci = InvalidCmd+1; for (const char *ns, *s = cmdnames; cleft; ++ci, s = ns) { ns = nextname(s,cleft); if (cmd == ci) { sz = ns-s; return s; } } sz = 0; assert (!"You have defined an ECmd enum, but not the command signature"); exit (EXIT_FAILURE); } unsigned CCmdBuf::LookupCmd (const char* name, size_type bleft, const char* cmdnames, size_type cleft) noexcept // static { unsigned ci = InvalidCmd+1, namesz = nextname(name,bleft)-name; for (const char* s = cmdnames; cleft; ++ci) { const char* ns = nextname(s,cleft); if (ns-s == namesz && namecmp(s,name,namesz)) return ci; s = ns; } return InvalidCmd; } CCmdBuf::size_type CCmdBuf::nextcapacity (size_type v) const noexcept { #if __x86__ asm("bsr\t%0, %0":"+r"(v)); return 1<<(1+v); #else size_type r = 64; while (r <= v) r *= 2; // Next power of 2 return r; #endif } CCmdBuf::pointer CCmdBuf::addspace (size_type need) noexcept { need += size(); if (_sz < need) { auto nsz = nextcapacity (need); _buf = (pointer) realloc (_buf, nsz); memset (_buf+_sz, 0, nsz-_sz); _sz = nsz; } return end(); } bstro CCmdBuf::CreateCmd (uint32_t o, const char* m, size_type msz, size_type sz, size_type unwritten) noexcept { assert (!unwritten || sz-unwritten == Align(sz-unwritten,c_MsgAlignment)); SMsgHeader h = { Align(sz,c_MsgAlignment), _iid, (uint8_t) (m[msz-2] == 'h' ? sz-sizeof(int) : UINT8_MAX), (uint8_t) Align(sizeof(SMsgHeader)+msz,c_MsgAlignment), o }; const size_type cmdsz = h.hsz+Align(sz-unwritten,c_MsgAlignment); pointer pip = addspace (cmdsz); bstro os (pip,cmdsz); os << h; os.write (m, msz); os.align (c_MsgAlignment); _used += cmdsz; return os; } void CCmdBuf::EndRead (bstri::const_pointer p) noexcept { assert (p >= _buf && p <= _buf+_used && "EndRead must be given pointer returned by BeginRead"); size_type br = p-_buf; memcpy (_buf, p, _used-=br); } void CCmdBuf::ReadCmds (void) { if (!_outf.IsOpen()) return; size_t br; do { pointer pip = addspace (256); br = CanPassFd() ? _outf.ReadWithFdPass(pip, remaining()) : _outf.Read(pip, remaining()); _used += br; } while (br); } void CCmdBuf::WriteCmds (void) { if (!_outf.IsOpen()) return; bstri is (BeginRead()); _outf.Write (is.ipos(), is.remaining()); is.skip (is.remaining()); EndRead (is); } void CCmdBuf::SendFile (CFile& f, uint32_t fsz) { WriteCmds(); if (CanPassFd()) _outf.SendFd (f); else { _outf.Write (&fsz, sizeof(fsz)); f.SendfileTo (_outf, fsz); uint64_t zeropad = 0; uint32_t alignedSize = Align(sizeof(fsz)+fsz, c_MsgAlignment); _outf.Write (&zeropad, alignedSize-(sizeof(fsz)+fsz)); } } //---------------------------------------------------------------------- // COM object interface #define N(n,s) #n "\0" #s "\0" const char CCmdBuf::_cmdNames[] = N(error,s) N(export,s) N(delete,) ; #undef N const char* CCmdBuf::LookupCmdName (ECmd cmd, size_type& sz) noexcept // static { return CCmdBuf::LookupCmdName((unsigned)cmd,sz,ArrayBlock(_cmdNames)-1); } CCmdBuf::ECmd CCmdBuf::LookupCmd (const char* name, size_type bleft) noexcept // static { return ECmd(CCmdBuf::LookupCmd(name,bleft,ArrayBlock(_cmdNames)-1)); } bstro CCmdBuf::CreateCmd (ECmd cmd, size_type sz, size_type unwritten) noexcept { size_type msz; const char* m = LookupCmdName (cmd, msz); return CCmdBuf::CreateCmd (c_ObjectName, m, msz, sz, unwritten); } <|endoftext|>
<commit_before>// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include <vespa/vespalib/testkit/testapp.h> #include <vespa/searchcore/proton/documentmetastore/i_store.h> #include <vespa/searchcore/proton/documentmetastore/lidreusedelayer.h> #include <vespa/searchcore/proton/server/executorthreadingservice.h> #include <vespa/searchcore/proton/test/thread_utils.h> #include <vespa/searchcore/proton/test/threading_service_observer.h> #include <vespa/vespalib/util/lambdatask.h> #include <vespa/log/log.h> LOG_SETUP("lidreusedelayer_test"); using vespalib::makeLambdaTask; namespace proton { namespace { bool assertThreadObserver(uint32_t masterExecuteCnt, uint32_t indexExecuteCnt, uint32_t summaryExecuteCnt, const test::ThreadingServiceObserver &observer) { if (!EXPECT_EQUAL(masterExecuteCnt, observer.masterObserver().getExecuteCnt())) { return false; } if (!EXPECT_EQUAL(summaryExecuteCnt, observer.summaryObserver().getExecuteCnt())) { return false; } if (!EXPECT_EQUAL(indexExecuteCnt, observer.indexObserver().getExecuteCnt())) { return false; } return true; } } class MyMetaStore : public documentmetastore::IStore { public: bool _freeListActive; uint32_t _removes_complete_count; uint32_t _removes_complete_lids; MyMetaStore() : _freeListActive(false), _removes_complete_count(0), _removes_complete_lids(0) { } ~MyMetaStore() override = default; Result inspectExisting(const GlobalId &, uint64_t) override { return Result(); } Result inspect(const GlobalId &, uint64_t) override { return Result(); } Result put(const GlobalId &, const BucketId &, const Timestamp &, uint32_t, DocId, uint64_t) override { return Result(); } bool updateMetaData(DocId, const BucketId &, const Timestamp &) override { return true; } bool remove(DocId, uint64_t) override { return true; } void removes_complete(const std::vector<DocId>& lids) override{ ++_removes_complete_count; _removes_complete_lids += lids.size(); } void move(DocId, DocId, uint64_t) override { } bool validLid(DocId) const override { return true; } void removeBatch(const std::vector<DocId> &, const DocId) override {} const RawDocumentMetaData &getRawMetaData(DocId) const override { LOG_ABORT("should not be reached"); } bool getFreeListActive() const override { return _freeListActive; } bool assertWork(uint32_t exp_removes_complete_count, uint32_t exp_removes_complete_lids) const { if (!EXPECT_EQUAL(exp_removes_complete_count, _removes_complete_count)) { return false; } if (!EXPECT_EQUAL(exp_removes_complete_lids, _removes_complete_lids)) { return false; } return true; } }; class Fixture { public: using LidReuseDelayer = documentmetastore::LidReuseDelayer; vespalib::ThreadStackExecutor _sharedExecutor; ExecutorThreadingService _writeServiceReal; test::ThreadingServiceObserver _writeService; MyMetaStore _store; std::unique_ptr<LidReuseDelayer> _lidReuseDelayer; Fixture() : _sharedExecutor(1, 0x10000), _writeServiceReal(_sharedExecutor), _writeService(_writeServiceReal), _store(), _lidReuseDelayer(std::make_unique<LidReuseDelayer>(_writeService, _store)) { } ~Fixture() { commit(); } template <typename FunctionType> void runInMasterAndSync(FunctionType func) { test::runInMasterAndSync(_writeService, func); } void cycledLids(const std::vector<uint32_t> &lids) { _store.removes_complete(lids); } void performCycleLids(const std::vector<uint32_t> &lids) { _writeService.master().execute(makeLambdaTask([this, lids]() { cycledLids(lids);})); } void cycleLids(const std::vector<uint32_t> &lids) { if (lids.empty()) return; _writeService.index().execute(makeLambdaTask([this, lids]() { performCycleLids(lids);})); } void delayReuse(uint32_t lid) { runInMasterAndSync([&]() { _lidReuseDelayer->delayReuse(lid); }); } void delayReuse(const std::vector<uint32_t> &lids) { runInMasterAndSync([&]() { _lidReuseDelayer->delayReuse(lids); }); } void commit() { runInMasterAndSync([&]() { cycleLids(_lidReuseDelayer->getReuseLids()); }); } }; TEST_F("require that nothing happens before free list is active", Fixture) { f.delayReuse(4); f.delayReuse({ 5, 6}); EXPECT_TRUE(f._store.assertWork(0, 0)); EXPECT_TRUE(assertThreadObserver(2, 0, 0, f._writeService)); } TEST_F("require that reuse can be batched", Fixture) { f._store._freeListActive = true; f.delayReuse(4); f.delayReuse({ 5, 6, 7}); EXPECT_TRUE(f._store.assertWork(0, 0)); EXPECT_TRUE(assertThreadObserver(2, 0, 0, f._writeService)); f.commit(); EXPECT_TRUE(f._store.assertWork(1, 4)); EXPECT_TRUE(assertThreadObserver(4, 1, 0, f._writeService)); f.delayReuse(8); f.delayReuse({ 9, 10}); EXPECT_TRUE(f._store.assertWork(1, 4)); EXPECT_TRUE(assertThreadObserver(6, 1, 0, f._writeService)); } } TEST_MAIN() { TEST_RUN_ALL(); } <commit_msg>commit requires full sync.<commit_after>// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include <vespa/vespalib/testkit/testapp.h> #include <vespa/searchcore/proton/documentmetastore/i_store.h> #include <vespa/searchcore/proton/documentmetastore/lidreusedelayer.h> #include <vespa/searchcore/proton/server/executorthreadingservice.h> #include <vespa/searchcore/proton/test/thread_utils.h> #include <vespa/searchcore/proton/test/threading_service_observer.h> #include <vespa/vespalib/util/lambdatask.h> #include <vespa/log/log.h> LOG_SETUP("lidreusedelayer_test"); using vespalib::makeLambdaTask; namespace proton { namespace { bool assertThreadObserver(uint32_t masterExecuteCnt, uint32_t indexExecuteCnt, uint32_t summaryExecuteCnt, const test::ThreadingServiceObserver &observer) { if (!EXPECT_EQUAL(masterExecuteCnt, observer.masterObserver().getExecuteCnt())) { return false; } if (!EXPECT_EQUAL(summaryExecuteCnt, observer.summaryObserver().getExecuteCnt())) { return false; } if (!EXPECT_EQUAL(indexExecuteCnt, observer.indexObserver().getExecuteCnt())) { return false; } return true; } } class MyMetaStore : public documentmetastore::IStore { public: bool _freeListActive; uint32_t _removes_complete_count; uint32_t _removes_complete_lids; MyMetaStore() : _freeListActive(false), _removes_complete_count(0), _removes_complete_lids(0) { } ~MyMetaStore() override = default; Result inspectExisting(const GlobalId &, uint64_t) override { return Result(); } Result inspect(const GlobalId &, uint64_t) override { return Result(); } Result put(const GlobalId &, const BucketId &, const Timestamp &, uint32_t, DocId, uint64_t) override { return Result(); } bool updateMetaData(DocId, const BucketId &, const Timestamp &) override { return true; } bool remove(DocId, uint64_t) override { return true; } void removes_complete(const std::vector<DocId>& lids) override{ ++_removes_complete_count; _removes_complete_lids += lids.size(); } void move(DocId, DocId, uint64_t) override { } bool validLid(DocId) const override { return true; } void removeBatch(const std::vector<DocId> &, const DocId) override {} const RawDocumentMetaData &getRawMetaData(DocId) const override { LOG_ABORT("should not be reached"); } bool getFreeListActive() const override { return _freeListActive; } bool assertWork(uint32_t exp_removes_complete_count, uint32_t exp_removes_complete_lids) const { if (!EXPECT_EQUAL(exp_removes_complete_count, _removes_complete_count)) { return false; } if (!EXPECT_EQUAL(exp_removes_complete_lids, _removes_complete_lids)) { return false; } return true; } }; class Fixture { public: using LidReuseDelayer = documentmetastore::LidReuseDelayer; vespalib::ThreadStackExecutor _sharedExecutor; ExecutorThreadingService _writeServiceReal; test::ThreadingServiceObserver _writeService; MyMetaStore _store; std::unique_ptr<LidReuseDelayer> _lidReuseDelayer; Fixture() : _sharedExecutor(1, 0x10000), _writeServiceReal(_sharedExecutor), _writeService(_writeServiceReal), _store(), _lidReuseDelayer(std::make_unique<LidReuseDelayer>(_writeService, _store)) { } ~Fixture() { commit(); } template <typename FunctionType> void runInMasterAndSyncAll(FunctionType func) { test::runInMasterAndSyncAll(_writeService, func); } template <typename FunctionType> void runInMasterAndSync(FunctionType func) { test::runInMasterAndSync(_writeService, func); } void cycledLids(const std::vector<uint32_t> &lids) { _store.removes_complete(lids); } void performCycleLids(const std::vector<uint32_t> &lids) { _writeService.master().execute(makeLambdaTask([this, lids]() { cycledLids(lids);})); } void cycleLids(const std::vector<uint32_t> &lids) { if (lids.empty()) return; _writeService.index().execute(makeLambdaTask([this, lids]() { performCycleLids(lids);})); } void delayReuse(uint32_t lid) { runInMasterAndSync([&]() { _lidReuseDelayer->delayReuse(lid); }); } void delayReuse(const std::vector<uint32_t> &lids) { runInMasterAndSync([&]() { _lidReuseDelayer->delayReuse(lids); }); } void commit() { runInMasterAndSyncAll([&]() { cycleLids(_lidReuseDelayer->getReuseLids()); }); } }; TEST_F("require that nothing happens before free list is active", Fixture) { f.delayReuse(4); f.delayReuse({ 5, 6}); EXPECT_TRUE(f._store.assertWork(0, 0)); EXPECT_TRUE(assertThreadObserver(2, 0, 0, f._writeService)); } TEST_F("require that reuse can be batched", Fixture) { f._store._freeListActive = true; f.delayReuse(4); f.delayReuse({ 5, 6, 7}); EXPECT_TRUE(f._store.assertWork(0, 0)); EXPECT_TRUE(assertThreadObserver(2, 0, 0, f._writeService)); f.commit(); EXPECT_TRUE(f._store.assertWork(1, 4)); EXPECT_TRUE(assertThreadObserver(4, 1, 0, f._writeService)); f.delayReuse(8); f.delayReuse({ 9, 10}); EXPECT_TRUE(f._store.assertWork(1, 4)); EXPECT_TRUE(assertThreadObserver(6, 1, 0, f._writeService)); } } TEST_MAIN() { TEST_RUN_ALL(); } <|endoftext|>
<commit_before>#include <boost/filesystem.hpp> #include "rect.h" #include "annotation_widget.h" #include "video_annotation.h" #include "test_video_annotation.h" #ifdef _WIN32 Q_IMPORT_PLUGIN(QWindowsIntegrationPlugin) #endif namespace fa = fish_annotator; namespace va = fish_annotator::video_annotator; void TestVideoAnnotation::testSerialize() { va::VideoAnnotation ann; ann.insert(std::make_shared<va::TrackAnnotation>( ann.nextId(), "ahasdjk", "ahashdjkl", 4, va::kEntering)); ann.insert(std::make_shared<va::TrackAnnotation>( ann.nextId(), "iopjdfg", "ghjasdf aga", 2, va::kIgnore)); ann.insert(std::make_shared<va::TrackAnnotation>( ann.nextId(), "abghj", "iuohysdfg", 3, va::kExiting)); ann.insert(std::make_shared<va::DetectionAnnotation>( 1231, 1, fish_annotator::Rect(1, 2, 3, 4), fa::kBox, QColor(255,0,0))); ann.insert(std::make_shared<va::DetectionAnnotation>( 918, 1, fish_annotator::Rect(1, 2, 3, 4), fa::kBox, QColor(255,0,0))); ann.insert(std::make_shared<va::DetectionAnnotation>( 1031, 1, fish_annotator::Rect(1, 2, 3, 4), fa::kBox, QColor(255,0,0))); ann.insert(std::make_shared<va::DetectionAnnotation>( 1151, 1, fish_annotator::Rect(5, 2, 34, 2), fa::kBox, QColor(255,0,0))); ann.insert(std::make_shared<va::DetectionAnnotation>( 1151, 1, fish_annotator::Rect(15, 12, 3, 5), fa::kBox, QColor(255,0,0))); ann.insert(std::make_shared<va::DetectionAnnotation>( 1151, 3, fish_annotator::Rect(5, 2, 34, 2), fa::kBox, QColor(255,0,0))); ann.insert(std::make_shared<va::DetectionAnnotation>( 718, 1, fish_annotator::Rect(1, 2, 3, 4), fa::kBox, QColor(255,0,0))); QVERIFY(ann.getAllSpecies().size() == 3); QVERIFY(ann.detections_by_id_.left.count(1) == 5); QVERIFY(ann.detections_by_id_.left.count(2) == 0); QVERIFY(ann.detections_by_id_.left.count(3) == 1); QVERIFY(ann.detections_by_frame_.left.count(1231) == 1); QVERIFY(ann.detections_by_frame_.left.count(1151) == 2); QVERIFY(ann.detections_by_frame_.left.count(1031) == 1); QVERIFY(ann.detections_by_frame_.left.count(918) == 1); QVERIFY(ann.detections_by_frame_.left.count(718) == 1); boost::filesystem::path csv_path("vid_ann.csv"); ann.write(csv_path,"15", "23", "Joe Mango", "Open", 24.0); va::VideoAnnotation deser_ann; deser_ann.read(csv_path); QVERIFY(ann == deser_ann); ann.remove(1151, 1); ann.write(csv_path,"15", "23", "Joe Mango", "Open", 24.0); va::VideoAnnotation deser_ann_1; deser_ann_1.read(csv_path); QVERIFY(ann == deser_ann_1); QVERIFY(ann.detections_by_id_.left.count(1) == 4); ann.remove(1); ann.write(csv_path, "15", "23", "Joe Mango", "Open", 24.0); va::VideoAnnotation deser_ann_2; deser_ann_2.read(csv_path); QVERIFY(ann == deser_ann_2); QVERIFY(ann.detections_by_id_.left.count(1) == 0); } QTEST_MAIN(TestVideoAnnotation) #include "test_video_annotation.moc" <commit_msg>Fix compilation of unit tests<commit_after>#include <boost/filesystem.hpp> #include "rect.h" #include "annotation_widget.h" #include "video_annotation.h" #include "test_video_annotation.h" #ifdef _WIN32 Q_IMPORT_PLUGIN(QWindowsIntegrationPlugin) #endif namespace fa = fish_annotator; namespace va = fish_annotator::video_annotator; void TestVideoAnnotation::testSerialize() { va::VideoAnnotation ann; ann.insert(std::make_shared<va::TrackAnnotation>( ann.nextId(), "ahasdjk", "ahashdjkl", 4, va::kEntering)); ann.insert(std::make_shared<va::TrackAnnotation>( ann.nextId(), "iopjdfg", "ghjasdf aga", 2, va::kIgnore)); ann.insert(std::make_shared<va::TrackAnnotation>( ann.nextId(), "abghj", "iuohysdfg", 3, va::kExiting)); ann.insert(std::make_shared<va::DetectionAnnotation>( 1231, 1, fish_annotator::Rect(1, 2, 3, 4), fa::kBox, "asdf", 0.1)); ann.insert(std::make_shared<va::DetectionAnnotation>( 918, 1, fish_annotator::Rect(1, 2, 3, 4), fa::kBox, "asdf", 0.2)); ann.insert(std::make_shared<va::DetectionAnnotation>( 1031, 1, fish_annotator::Rect(1, 2, 3, 4), fa::kBox, "fda", 0.3)); ann.insert(std::make_shared<va::DetectionAnnotation>( 1151, 1, fish_annotator::Rect(5, 2, 34, 2), fa::kBox, "fda", 0.4)); ann.insert(std::make_shared<va::DetectionAnnotation>( 1151, 1, fish_annotator::Rect(15, 12, 3, 5), fa::kBox, "fda", 0.5)); ann.insert(std::make_shared<va::DetectionAnnotation>( 1151, 3, fish_annotator::Rect(5, 2, 34, 2), fa::kBox, "jhlk", 0.6)); ann.insert(std::make_shared<va::DetectionAnnotation>( 718, 1, fish_annotator::Rect(1, 2, 3, 4), fa::kBox, "lhlgl", 0.7)); QVERIFY(ann.getAllSpecies().size() == 3); QVERIFY(ann.detections_by_id_.left.count(1) == 5); QVERIFY(ann.detections_by_id_.left.count(2) == 0); QVERIFY(ann.detections_by_id_.left.count(3) == 1); QVERIFY(ann.detections_by_frame_.left.count(1231) == 1); QVERIFY(ann.detections_by_frame_.left.count(1151) == 2); QVERIFY(ann.detections_by_frame_.left.count(1031) == 1); QVERIFY(ann.detections_by_frame_.left.count(918) == 1); QVERIFY(ann.detections_by_frame_.left.count(718) == 1); boost::filesystem::path json_path("vid_ann.json"); ann.write(json_path,"15", "23", "Joe Mango", "Open", 24.0, true); va::VideoAnnotation deser_ann; deser_ann.read(json_path); QVERIFY(ann == deser_ann); ann.remove(1151, 1); ann.write(json_path,"15", "23", "Joe Mango", "Open", 24.0, true); va::VideoAnnotation deser_ann_1; deser_ann_1.read(json_path); QVERIFY(ann == deser_ann_1); QVERIFY(ann.detections_by_id_.left.count(1) == 4); ann.remove(1); ann.write(json_path, "15", "23", "Joe Mango", "Open", 24.0, true); va::VideoAnnotation deser_ann_2; deser_ann_2.read(json_path); QVERIFY(ann == deser_ann_2); QVERIFY(ann.detections_by_id_.left.count(1) == 0); } QTEST_MAIN(TestVideoAnnotation) #include "test_video_annotation.moc" <|endoftext|>
<commit_before>/////////////////////////////////////////////// // Simple event display for channel spectra // Input file should be raw DATE root tree file /////////////////////////////////////////////// // for the readout const int NFEC = 36; // Max 36 FrontEndCard per SM const int NCHIP = 4; // 4 ALTROs per FEC const int NCHAN = 16; // Channels per ALTRO const int TOTCHAN = NFEC * NCHIP * NCHAN; // Max uses ALTRO channels const int NCOLS = 48; // per SM const int NROWS = 24; const int NMINI = 3; // number of ministrips, or T-cards, per strip // gamma2 fit function double fitfun(double *x, double *par) { double Amp = par[0]; double Tmax = par[1]; double Tau = par[2]; double Ped = par[3]; double gammaN = par[4]; double t = 0; if(Tau) t = (x[0] - Tmax + Tau)/Tau; if(t<0) t = 0; // Since we have now set gammaN to 2, we replace the pow(t, 2) call in // double f = Amp * pow(t,gammaN) * exp(gammaN*(1-t)) + Ped; // with just t*t double f = Amp * t*t * exp(gammaN*(1-t)) + Ped; return f; } // main method void RAW_evtdis(const int runno = 615, const int gainv = 1, /*0=low, 1=high*/ const int evtnum= 1, const int strip = 0, int ymax=200, // set the scale of plots const int delay = 1) // -1=no delay, wait for input, X>=0 => sleep aprox. X sec. after making plot { // set ranges to plot const int col_f = strip*2; const int col_l = col_f + 1; const int row_f = 0; const int row_l = NROWS - 1; const int nsamples = 65; // number of ADC time samples per channel and event const int saveplot = 0; const int numbering = 1; // 0: no numbering, 1: nubering on each plot const int dofit = 0; // 0: no fit, 1: try to fit the spectra (not debugged) const int debug = 0; const float gammaN = 2; // end of setup // Assume we are just interested in the 1st segment, _0.root below for fname* Char_t fname[256]; sprintf(fname, "/local/data/Run_%09d.Seq_1A.Stream_0.root",runno); // set up a raw reader of the data AliRawReader *rawReader = NULL; rawReader = new AliRawReaderRoot(fname); AliCaloRawStream *in = NULL; in = new AliCaloRawStream(rawReader,"EMCAL"); // set up histograms TH1F *hfit[TOTCHAN]; TF1 *f1[TOTCHAN]; char ch_label[TOTCHAN][100]; char buff1[100]; char name[80]; for(int i=0; i<TOTCHAN; i++) { sprintf(buff1,"hfit_%d",i); hfit[i] = new TH1F(buff1,"hfit", nsamples , -0.5, nsamples - 0.5); hfit[i]->SetDirectory(0); sprintf(name,"f1_%d",i); f1[i] = new TF1(name,fitfun,0,70,5); f1[i]->SetLineWidth(2); f1[i]->SetLineColor(2); // int idx = arow * NCOLS + acol + NCOLS*NROWS * gain; // encoding used later int gain = i / (NCOLS*NROWS); int row = (i % (NCOLS*NROWS))/NCOLS; int col = i % NCOLS; sprintf(ch_label[i], "Col%02d Row%02d", col, row); } int numcol = col_l-col_f+1; int numrow = row_l-row_f+1; TCanvas *cc[NMINI]; for (int ic=0; ic<NMINI; ic++) { sprintf(buff1, "cc%d", ic); // use the usual StripX CY, X=0..23, Y=0..2 notation for T-cards (mini-strips) sprintf(name,"Strip %d MiniStrip(T-card) C%d", strip, ic); cc[ic] = new TCanvas(buff1,name, 400*ic, 10, 400,800); cc[ic]->Divide(numcol, numrow/NMINI); cc[ic]->SetTitle(name); } TText *t = new TText; t->SetTextSize(0.17); int clr[2] = {4,2}; // colors // figure out which events we should look at int firstevent = evtnum; int lastevent = evtnum; if (evtnum < 0) { // get a bunch of events firstevent = 0; lastevent = - evtnum; } if (evtnum == 0) { // get all events firstevent = 0; lastevent = 1000000; } Int_t iev =0; AliRawEventHeaderBase *aliHeader=NULL; while ( rawReader->NextEvent() && iev < firstevent) { aliHeader = (AliRawEventHeaderBase*) rawReader->GetEventHeader(); iev++; } // loop over selected events while ( rawReader->NextEvent() && iev <= lastevent) { aliHeader = (AliRawEventHeaderBase*) rawReader->GetEventHeader(); int runNumber = aliHeader->Get("RunNb"); cout << "Found run number " << runNumber << endl; // reset histograms for(int i=0; i<TOTCHAN; i++) { hfit[i]->Reset(); } // get events (the "1" ensures that we actually select all events for now) if ( 1 || aliHeader->Get("Type") == AliRawEventHeaderBase::kPhysicsEvent ) { const UInt_t * evtId = aliHeader->GetP("Id"); int evno_raw = (int) evtId[0]; int timestamp = aliHeader->Get("Timestamp"); cout << " evno " << evno_raw << " size " << aliHeader->GetEventSize() << " type " << aliHeader->Get("Type") << " type name " << aliHeader->GetTypeName() << " timestamp " << timestamp << endl; /// process_event stream while ( in->Next() ) { int acol = in->GetColumn(); int arow = in->GetRow(); int gain = in->GetCaloFlag(); int idx = arow * NCOLS + acol + NCOLS*NROWS * gain; //cout << "hist idx " << idx << endl; if (idx < 0 || idx > TOTCHAN) { cout << "Hist idx out of range: " << idx << endl; } else { // reasonable range of idx (removes TRU and LEDMon data also) hfit[idx]->SetBinContent(in->GetTime(), in->GetSignal()); } } // Raw data read // Next: let's actually plot the data.. int nrow_mini = NROWS/NMINI; // number of rows per T-card or mini-strip for (Int_t arow = row_f; arow <= row_l; arow++) { for (Int_t acol = col_f; acol <= col_l; acol++) { int idx = arow * NCOLS + acol + NCOLS*NROWS * gainv; // which T-card does the tower belong to? int mini = arow / (nrow_mini); // on which pad should we plot it? int pad_id = ((row_l-arow)%nrow_mini) *(col_l-col_f+1) + acol - col_f + 1; cout << "row="<< arow << ", col=" << acol << ", C" << mini << ", pad=" << pad_id << endl; cc[mini]->cd(pad_id); hfit[idx]->SetTitle(""); hfit[idx]->SetFillColor(5); hfit[idx]->SetMaximum(ymax); hfit[idx]->SetMinimum(0); // we may or may not decide to fit the data if (dofit) { hfit[idx]->Fit(f1[i]); } hfit[idx]->Draw(); if( numbering ) { t->SetTextColor(clr[gainv]); t->DrawTextNDC(0.45,0.45,ch_label[idx]); } } } // add some extra text on the canvases for (int ic=0; ic<NMINI; ic++) { // print a box showing run #, evt #, and timestamp cc[ic]->cd(); // first draw transparent pad TPad *trans = new TPad("trans","",0,0,1,1); trans->SetFillStyle(4000); trans->Draw(); trans->cd(); // then draw text TPaveText *label = new TPaveText(.2,.11,.8,.14,"NDC"); // label->Clear(); label->SetBorderSize(1); label->SetFillColor(0); label->SetLineColor(clr[gainv]); label->SetTextColor(clr[gainv]); //label->SetFillStyle(0); TDatime d; d.Set(timestamp); sprintf(name,"Run %d, Event %d, Hist Max %d, %s",runno,iev,ymax,d.AsString()); label->AddText(name); label->Draw(); cc[ic]->Update(); cout << "Done" << endl; } // some shenanigans to hold the plotting, if requested if (firstevent != lastevent) { if (delay == -1) { // wait for character input before proceeding cout << " enter y to proceed " << endl; char dummy[2]; cin >> dummy; cout << " read " << dummy << endl; if (strcmp(dummy, "y")==0) { cout << " ok, continuing with event " << iev+1 << endl; } else { cout << " ok, exiting " << endl; //exit(1); } } else { cout << "Sleeping for " << delay * 500 << endl; gSystem->Sleep(delay * 500); } } } // event selection iev ++; } // event loop // save plot, if setup/requested to do so char plotname[100]; if (saveplot==1) { for (int ic=0; ic<NMINI; ic++) { sprintf(plotname,"Run_%d_Ev%d_Strip%d_C%d_Gain%d_MaxHist%d.gif", runno,iev,strip,ic,gainv,ymax); cout <<"SAVING plot:"<< plotname << endl; cc[ic]->SaveAs(plotname); } } } <commit_msg>belated update for newer decoder<commit_after>/////////////////////////////////////////////// // Simple event display for channel spectra // Input file should be raw DATE root tree file /////////////////////////////////////////////// // for the readout const int NFEC = 36; // Max 36 FrontEndCard per SM const int NCHIP = 4; // 4 ALTROs per FEC const int NCHAN = 16; // Channels per ALTRO const int TOTCHAN = NFEC * NCHIP * NCHAN; // Max uses ALTRO channels const int NCOLS = 48; // per SM const int NROWS = 24; const int NMINI = 3; // number of ministrips, or T-cards, per strip // gamma2 fit function double fitfun(double *x, double *par) { double Amp = par[0]; double Tmax = par[1]; double Tau = par[2]; double Ped = par[3]; double gammaN = par[4]; double t = 0; if(Tau) t = (x[0] - Tmax + Tau)/Tau; if(t<0) t = 0; // Since we have now set gammaN to 2, we replace the pow(t, 2) call in // double f = Amp * pow(t,gammaN) * exp(gammaN*(1-t)) + Ped; // with just t*t double f = Amp * t*t * exp(gammaN*(1-t)) + Ped; return f; } // main method void RAW_evtdis(const int year=12, const int runno = 191741, const int streamno=8, const int segno=10, const int gainv = 1, /*0=low, 1=high*/ const int evtnum= 1, const int module = 0, const int strip = 0, int ymax=200, // set the scale of plots const int delay = 1) // -1=no delay, wait for input, X>=0 => sleep aprox. X sec. after making plot { // set ranges to plot const int col_f = strip*2; const int col_l = col_f + 1; const int row_f = 0; const int row_l = NROWS - 1; const int nsamples = 15; // number of ADC time samples per channel and event const int saveplot = 0; const int numbering = 1; // 0: no numbering, 1: numbering on each plot const int dofit = 0; // 0: no fit, 1: try to fit the spectra (not debugged) const int debug = 0; const float gammaN = 2; // end of setup // Assume we are just interested in the 1st segment, _0.root below for fname* Char_t fname[256]; sprintf(fname, "%02d%09d0%02d.%d.root", year, runno, streamno, segno); // set up a raw reader of the data AliRawReader *rawReader = NULL; rawReader = new AliRawReaderRoot(fname); AliCaloRawStreamV3 *in = NULL; in = new AliCaloRawStreamV3(rawReader,"EMCAL"); rawReader->Select("EMCAL", 0, AliEMCALGeoParams::fgkLastAltroDDL) ; //select EMCAL DDL range // set up histograms TH1F *hfit[TOTCHAN]; TF1 *f1[TOTCHAN]; char ch_label[TOTCHAN][100]; char buff1[100]; char name[80]; for(int i=0; i<TOTCHAN; i++) { sprintf(buff1,"hfit_%d",i); hfit[i] = new TH1F(buff1,"hfit", nsamples , -0.5, nsamples - 0.5); hfit[i]->SetDirectory(0); sprintf(name,"f1_%d",i); f1[i] = new TF1(name,fitfun,0,70,5); f1[i]->SetLineWidth(2); f1[i]->SetLineColor(2); // int idx = arow * NCOLS + acol + NCOLS*NROWS * gain; // encoding used later int gain = i / (NCOLS*NROWS); int row = (i % (NCOLS*NROWS))/NCOLS; int col = i % NCOLS; sprintf(ch_label[i], "Col%02d Row%02d", col, row); } int numcol = col_l-col_f+1; int numrow = row_l-row_f+1; TCanvas *cc[NMINI]; for (int ic=0; ic<NMINI; ic++) { sprintf(buff1, "cc%d", ic); // use the usual StripX CY, X=0..23, Y=0..2 notation for T-cards (mini-strips) sprintf(name,"Strip %d MiniStrip(T-card) C%d", strip, ic); cc[ic] = new TCanvas(buff1,name, 400*ic, 10, 400,800); cc[ic]->Divide(numcol, numrow/NMINI); cc[ic]->SetTitle(name); } TText *t = new TText; t->SetTextSize(0.17); int clr[2] = {4,2}; // colors // figure out which events we should look at int firstevent = evtnum; int lastevent = evtnum; if (evtnum < 0) { // get a bunch of events firstevent = 0; lastevent = - evtnum; } if (evtnum == 0) { // get all events firstevent = 0; lastevent = 1000000; } Int_t iev =0; AliRawEventHeaderBase *aliHeader=NULL; while ( rawReader->NextEvent() && iev < firstevent) { aliHeader = (AliRawEventHeaderBase*) rawReader->GetEventHeader(); iev++; } // loop over selected events while ( rawReader->NextEvent() && iev <= lastevent) { aliHeader = (AliRawEventHeaderBase*) rawReader->GetEventHeader(); int runNumber = aliHeader->Get("RunNb"); cout << "Found run number " << runNumber << endl; // reset histograms for(int i=0; i<TOTCHAN; i++) { hfit[i]->Reset(); } // get events (the "1" ensures that we actually select all events for now) if ( 1 || aliHeader->Get("Type") == AliRawEventHeaderBase::kPhysicsEvent ) { const UInt_t * evtId = aliHeader->GetP("Id"); int evno_raw = (int) evtId[0]; int timestamp = aliHeader->Get("Timestamp"); cout << " evno " << evno_raw << " size " << aliHeader->GetEventSize() << " type " << aliHeader->Get("Type") << " type name " << aliHeader->GetTypeName() << " timestamp " << timestamp << endl; int sample = 0; int time = 0; /// process_event stream while (in->NextDDL()) { // if (module == in->GetModule()) { if (1) { while (in->NextChannel()) { int acol = in->GetColumn(); int arow = in->GetRow(); int gain = in->GetCaloFlag(); int idx = arow * NCOLS + acol + NCOLS*NROWS * gain; //cout << "module " << in->GetModule() << endl; if (gain>1 || module!=in->GetModule()) { // TRU or LEDMon } else if (idx < 0 || idx > TOTCHAN) { cout << "Hist idx out of range: " << idx << endl; } else { // reasonable range of idx (removes TRU and LEDMon data also) //cout << "hist idx " << idx << endl; while (in->NextBunch()) { const UShort_t *sig = in->GetSignals(); int startBin = in->GetStartTimeBin(); for (Int_t i = 0; i < in->GetBunchLength(); i++) { sample = sig[i]; time = startBin--; if (debug>2) { cout << " hw address " << in->GetHWAddress() << " time " << time << " sample " << sample << endl; } // debug if (idx >= 0 && idx < TOTCHAN) { hfit[idx]->SetBinContent(time, sample); } } } } } } } // Raw data read // Next: let's actually plot the data.. int nrow_mini = NROWS/NMINI; // number of rows per T-card or mini-strip for (Int_t arow = row_f; arow <= row_l; arow++) { for (Int_t acol = col_f; acol <= col_l; acol++) { int idx = arow * NCOLS + acol + NCOLS*NROWS * gainv; // which T-card does the tower belong to? int mini = arow / (nrow_mini); // on which pad should we plot it? int pad_id = ((row_l-arow)%nrow_mini) *(col_l-col_f+1) + acol - col_f + 1; cout << "row="<< arow << ", col=" << acol << ", C" << mini << ", pad=" << pad_id << endl; cc[mini]->cd(pad_id); hfit[idx]->SetTitle(""); hfit[idx]->SetFillColor(5); hfit[idx]->SetMaximum(ymax); hfit[idx]->SetMinimum(0); // we may or may not decide to fit the data if (dofit) { hfit[idx]->Fit(f1[i]); } hfit[idx]->Draw(); if( numbering ) { t->SetTextColor(clr[gainv]); t->DrawTextNDC(0.45,0.45,ch_label[idx]); } } } // add some extra text on the canvases for (int ic=0; ic<NMINI; ic++) { // print a box showing run #, evt #, and timestamp cc[ic]->cd(); // first draw transparent pad TPad *trans = new TPad("trans","",0,0,1,1); trans->SetFillStyle(4000); trans->Draw(); trans->cd(); // then draw text TPaveText *label = new TPaveText(.2,.11,.8,.14,"NDC"); // label->Clear(); label->SetBorderSize(1); label->SetFillColor(0); label->SetLineColor(clr[gainv]); label->SetTextColor(clr[gainv]); //label->SetFillStyle(0); TDatime d; d.Set(timestamp); sprintf(name,"Run %d, Event %d, Hist Max %d, %s",runno,iev,ymax,d.AsString()); label->AddText(name); label->Draw(); cc[ic]->Update(); cout << "Done" << endl; } // some shenanigans to hold the plotting, if requested if (firstevent != lastevent) { if (delay == -1) { // wait for character input before proceeding cout << " enter y to proceed " << endl; char dummy[2]; cin >> dummy; cout << " read " << dummy << endl; if (strcmp(dummy, "y")==0) { cout << " ok, continuing with event " << iev+1 << endl; } else { cout << " ok, exiting " << endl; //exit(1); } } else { cout << "Sleeping for " << delay * 500 << endl; gSystem->Sleep(delay * 500); } } } // event selection iev ++; } // event loop // save plot, if setup/requested to do so char plotname[100]; if (saveplot==1) { for (int ic=0; ic<NMINI; ic++) { sprintf(plotname,"Run_%d_Ev%d_Strip%d_C%d_Gain%d_MaxHist%d.gif", runno,iev,strip,ic,gainv,ymax); cout <<"SAVING plot:"<< plotname << endl; cc[ic]->SaveAs(plotname); } } } <|endoftext|>
<commit_before>// $Id $ // // Tests that each form of 4-vector has all the properties that stem from // owning and forwarding to a 4D coordinates instance // // 6/28/05 m fischler // from contents of test_coordinates.h by L. Moneta. // // ================================================================= #include "Math/GenVector/DisplacementVector3D.h" #include "Math/GenVector/PositionVector3D.h" #include "Math/GenVector/Cartesian3D.h" #include "Math/GenVector/Polar3D.h" #include "Math/GenVector/CylindricalEta3D.h" #include "Math/GenVector/etaMax.h" #include "Math/GenVector/PxPyPzE4D.h" #include "Math/GenVector/PxPyPzM4D.h" #include "Math/GenVector/PtEtaPhiE4D.h" #include "Math/GenVector/PtEtaPhiM4D.h" #include "Math/GenVector/LorentzVector.h" #include "Math/Vector4Dfwd.h" // for typedefs definitions #include "CoordinateTraits.h" #include <iostream> #include <limits> #include <cmath> #include <vector> //#define TRACE1 #define DEBUG using namespace ROOT::Math; template <typename T1, typename T2 > struct Precision { enum { result = std::numeric_limits<T1>::digits <= std::numeric_limits<T2>::digits }; }; template <typename T1, typename T2, bool> struct LessPreciseType { typedef T1 type; }; template <typename T1, typename T2> struct LessPreciseType<T1, T2, false> { typedef T2 type; }; template <typename Scalar1, typename Scalar2> int closeEnough ( Scalar1 s1, Scalar2 s2, std::string const & coord, double ticks ) { int ret = 0; Scalar1 eps1 = std::numeric_limits<Scalar1>::epsilon(); Scalar2 eps2 = std::numeric_limits<Scalar2>::epsilon(); typedef typename LessPreciseType<Scalar1, Scalar2,Precision<Scalar1,Scalar2>::result>::type Scalar; Scalar epsilon = (eps1 >= eps2) ? eps1 : eps2; int pr = std::cout.precision(18); Scalar ss1 (s1); Scalar ss2 (s2); Scalar diff = ss1 - ss2; if (diff < 0) diff = -diff; if (ss1 == 0 || ss2 == 0) { // TODO - the ss2==0 makes a big change?? if ( diff > ticks*epsilon ) { ret=3; std::cout << "\nAbsolute discrepancy in " << coord << "(): " << ss1 << " != " << ss2 << "\n" << " (Allowed discrepancy is " << ticks*epsilon << ")\nDifference is " << diff/epsilon << " ticks\n"; } std::cout.precision (pr); return ret; } // infinity dicrepancy musy be checked with max precision long double sd1(ss1); long double sd2(ss2); if ( (sd1 + sd2 == sd1) != (sd1 + sd2 == sd2) ) { ret=5; std::cout << "\nInfinity discrepancy in " << coord << "(): " << sd1 << " != " << sd2 << "\n"; std::cout.precision (pr); return ret; } Scalar denom = ss1 > 0 ? ss1 : -ss1; if ((diff/denom > ticks*epsilon) && (diff > ticks*epsilon)) { ret=9; std::cout << "\nDiscrepancy in " << coord << "(): " << ss1 << " != " << ss2 << "\n" << " (Allowed discrepancy is " << ticks*epsilon*ss1 << ")\nDifference is " << (diff/denom)/epsilon << " ticks\n"; } std::cout.precision (pr); return ret; } template <class V1, class V2> int compare4D (const V1 & v1, const V2 & v2, double ticks) { int ret =0; typedef typename V1::CoordinateType CoordType1; typedef typename V2::CoordinateType CoordType2; ret |= closeEnough ( v1.x(), v2.x(), "x" ,ticks); ret |= closeEnough ( v1.y(), v2.y(), "y" ,ticks); ret |= closeEnough ( v1.z(), v2.z(), "z" ,ticks); ret |= closeEnough ( v1.t(), v2.t(), "t" ,ticks); ret |= closeEnough ( v1.rho(), v2.rho(), "rho" ,ticks); ret |= closeEnough ( v1.phi(), v2.phi(), "phi" ,ticks); ret |= closeEnough ( v1.P(), v2.P(), "p" ,ticks); ret |= closeEnough ( v1.theta(), v2.theta(), "theta" ,ticks); ret |= closeEnough ( v1.perp2(), v2.perp2(), "perp2" ,ticks); ret |= closeEnough ( v1.M2(), v2.M2(), "m2" ,ticks); ret |= closeEnough ( v1.M(), v2.M(), "m" ,ticks); ret |= closeEnough ( v1.Mt(), v2.Mt(), "mt" ,ticks); ret |= closeEnough ( v1.Et(), v2.Et(), "et" ,ticks); if ( v1.rho() > 0 && v2.rho() > 0 ) { // eta can legitimately vary if rho == 0 ret |= closeEnough ( v1.eta(), v2.eta(), "eta" ,ticks); } if (ret != 0) { std::cout << "Discrepancy detected (see above) is between:\n " << CoordinateTraits<CoordType1>::name() << " and\n " << CoordinateTraits<CoordType2>::name() << "\n" << "with v = (" << v1.x() << ", " << v1.y() << ", " << v1.z() << ", " << v1.t() << ")\n"; } else { std::cout << "."; } return ret; } template <class C> int test4D ( const LorentzVector<C> & v, double ticks ) { #ifdef DEBUG std::cout <<"\n>>>>> Testing LorentzVector from " << XYZTVector(v) << " ticks = " << ticks << "\t: "; #endif int ret = 0; LorentzVector< PxPyPzE4D<double> > vxyzt_d (v.x(), v.y(), v.z(), v.t()); //double m = std::sqrt ( v.t()*v.t() - v.x()*v.x() - v.y()*v.y() - v.z()*v.z()); //double r = std::sqrt (v.x()*v.x() + v.y()*v.y() + v.z()*v.z()); double rho = std::sqrt (v.x()*v.x() + v.y()*v.y()); double theta = std::atan2( rho, v.z() ); // better tahn using acos //double theta = r>0 ? std::acos ( v.z()/r ) : 0; double phi = rho>0 ? std::atan2 (v.y(), v.x()) : 0; double eta; if (rho != 0) { eta = -std::log(std::tan(theta/2)); #ifdef TRACE1 std::cout << ":::: rho != 0\n" << ":::: theta = " << theta <<"/n:::: tan(theta/2) = " << std::tan(theta/2) <<"\n:::: eta = " << eta << "\n"; #endif } else if (v.z() == 0) { eta = 0; #ifdef TRACE1 std::cout << ":::: v.z() == 0\n" <<"\n:::: eta = " << eta << "\n"; #endif } else if (v.z() > 0) { eta = v.z() + etaMax<long double>(); #ifdef TRACE1 std::cout << ":::: v.z() > 0\n" << ":::: etaMax = " << etaMax<long double>() <<"\n:::: eta = " << eta << "\n"; #endif } else { eta = v.z() - etaMax<long double>(); #ifdef TRACE1 std::cout << ":::: v.z() < 0\n" << ":::: etaMax = " << etaMax<long double>() <<"\n:::: eta = " << eta << "\n"; #endif } LorentzVector< PtEtaPhiE4D<double> > vrep_d ( rho, eta, phi, v.t() ); ret |= compare4D( vxyzt_d, vrep_d, ticks); LorentzVector< PtEtaPhiM4D<double> > vrepm_d ( rho, eta, phi, v.M() ); ret |= compare4D( vxyzt_d, vrepm_d, ticks); LorentzVector< PxPyPzM4D <double> > vxyzm_d ( v.x(), v.y(), v.z(), v.M() ); ret |= compare4D( vrep_d, vxyzm_d, ticks); LorentzVector< PxPyPzE4D<float> > vxyzt_f (v.x(), v.y(), v.z(), v.t()); ret |= compare4D( vxyzt_d, vxyzt_f, ticks); LorentzVector< PtEtaPhiE4D<float> > vrep_f ( rho, eta, phi, v.t() ); ret |= compare4D( vxyzt_f, vrep_f, ticks); LorentzVector< PtEtaPhiM4D<float> > vrepm_f ( rho, eta, phi, v.M() ); ret |= compare4D( vxyzt_f, vrepm_f, ticks); LorentzVector< PxPyPzM4D<float> > vxyzm_f (v.x(), v.y(), v.z(), v.M()); ret |= compare4D( vrep_f, vxyzm_f, ticks); if (ret == 0) std::cout << "\t OK\n"; else { std::cout << "\t FAIL\n"; std::cerr << "\n>>>>> Testing LorentzVector from " << XYZTVector(v) << " ticks = " << ticks << "\t:\t FAILED\n"; } return ret; } int coordinates4D (bool testAll = false) { int ret = 0; ret |= test4D (XYZTVector ( 0.0, 0.0, 0.0, 0.0 ) , 1 ); ret |= test4D (XYZTVector ( 1.0, 2.0, 3.0, 4.0 ) ,10 ); ret |= test4D (XYZTVector ( -1.0, -2.0, 3.0, 4.0 ) ,10 ); // test for large eta values (which was giving inf before Jun 07) ret |= test4D (XYZTVector ( 1.E-8, 1.E-8, 10.0, 100.0 ) ,10 ); // for z < 0 precision in eta is worse since theta is close to Pi ret |= test4D (XYZTVector ( 1.E-8, 1.E-8, -10.0, 100.0 ) ,1000000000 ); // test cases with zero mass // tick should be p /sqrt(eps) ~ 4 /sqrt(eps) ret |= test4D (PxPyPzMVector ( 1., 2., 3., 0.) , 4./std::sqrt(std::numeric_limits<double>::epsilon()) ); // this test fails in some machines (skip by default) if (!testAll) return ret; // take a factor 1.5 in ticks to be conservative ret |= test4D (PxPyPzMVector ( 1., 1., 100., 0.) , 150./std::sqrt(std::numeric_limits<double>::epsilon()) ); // need a larger a factor here ret |= test4D (PxPyPzMVector ( 1.E8, 1.E8, 1.E8, 0.) , 1.E9/std::sqrt(std::numeric_limits<double>::epsilon()) ); // if use 1 here fails ret |= test4D (PxPyPzMVector ( 1.E-8, 1.E-8, 1.E-8, 0.) , 2.E-8/std::sqrt(std::numeric_limits<double>::epsilon()) ); return ret; } int main() { int ret = coordinates4D(); if (ret) std::cerr << "test FAILED !!! " << std::endl; else std::cout << "test OK " << std::endl; return ret; } <commit_msg>Attempt to fix roottest_root_math_genvector_coordinates4D on ARM64.<commit_after>// $Id $ // // Tests that each form of 4-vector has all the properties that stem from // owning and forwarding to a 4D coordinates instance // // 6/28/05 m fischler // from contents of test_coordinates.h by L. Moneta. // // ================================================================= #include "Math/GenVector/DisplacementVector3D.h" #include "Math/GenVector/PositionVector3D.h" #include "Math/GenVector/Cartesian3D.h" #include "Math/GenVector/Polar3D.h" #include "Math/GenVector/CylindricalEta3D.h" #include "Math/GenVector/etaMax.h" #include "Math/GenVector/PxPyPzE4D.h" #include "Math/GenVector/PxPyPzM4D.h" #include "Math/GenVector/PtEtaPhiE4D.h" #include "Math/GenVector/PtEtaPhiM4D.h" #include "Math/GenVector/LorentzVector.h" #include "Math/Vector4Dfwd.h" // for typedefs definitions #include "CoordinateTraits.h" #include <iostream> #include <limits> #include <cmath> #include <vector> //#define TRACE1 #define DEBUG using namespace ROOT::Math; template <typename T1, typename T2 > struct Precision { enum { result = std::numeric_limits<T1>::digits <= std::numeric_limits<T2>::digits }; }; template <typename T1, typename T2, bool> struct LessPreciseType { typedef T1 type; }; template <typename T1, typename T2> struct LessPreciseType<T1, T2, false> { typedef T2 type; }; template <typename Scalar1, typename Scalar2> int closeEnough ( Scalar1 s1, Scalar2 s2, std::string const & coord, double ticks ) { int ret = 0; Scalar1 eps1 = std::numeric_limits<Scalar1>::epsilon(); Scalar2 eps2 = std::numeric_limits<Scalar2>::epsilon(); typedef typename LessPreciseType<Scalar1, Scalar2,Precision<Scalar1,Scalar2>::result>::type Scalar; Scalar epsilon = (eps1 >= eps2) ? eps1 : eps2; int pr = std::cout.precision(18); Scalar ss1 (s1); Scalar ss2 (s2); Scalar diff = ss1 - ss2; if (diff < 0) diff = -diff; if (ss1 == 0 || ss2 == 0) { // TODO - the ss2==0 makes a big change?? if ( diff > ticks*epsilon ) { ret=3; std::cout << "\nAbsolute discrepancy in " << coord << "(): " << ss1 << " != " << ss2 << "\n" << " (Allowed discrepancy is " << ticks*epsilon << ")\nDifference is " << diff/epsilon << " ticks\n"; } std::cout.precision (pr); return ret; } // infinity dicrepancy musy be checked with max precision long double sd1(ss1); long double sd2(ss2); if ( (sd1 + sd2 == sd1) != (sd1 + sd2 == sd2) ) { ret=5; std::cout << "\nInfinity discrepancy in " << coord << "(): " << sd1 << " != " << sd2 << "\n"; std::cout.precision (pr); return ret; } Scalar denom = ss1 > 0 ? ss1 : -ss1; if ((diff/denom > ticks*epsilon) && (diff > ticks*epsilon)) { ret=9; std::cout << "\nDiscrepancy in " << coord << "(): " << ss1 << " != " << ss2 << "\n" << " (Allowed discrepancy is " << ticks*epsilon*ss1 << ")\nDifference is " << (diff/denom)/epsilon << " ticks\n"; } std::cout.precision (pr); return ret; } template <class V1, class V2> int compare4D (const V1 & v1, const V2 & v2, double ticks) { int ret =0; typedef typename V1::CoordinateType CoordType1; typedef typename V2::CoordinateType CoordType2; ret |= closeEnough ( v1.x(), v2.x(), "x" ,ticks); ret |= closeEnough ( v1.y(), v2.y(), "y" ,ticks); ret |= closeEnough ( v1.z(), v2.z(), "z" ,ticks); ret |= closeEnough ( v1.t(), v2.t(), "t" ,ticks); ret |= closeEnough ( v1.rho(), v2.rho(), "rho" ,ticks); ret |= closeEnough ( v1.phi(), v2.phi(), "phi" ,ticks); ret |= closeEnough ( v1.P(), v2.P(), "p" ,ticks); ret |= closeEnough ( v1.theta(), v2.theta(), "theta" ,ticks); ret |= closeEnough ( v1.perp2(), v2.perp2(), "perp2" ,ticks); ret |= closeEnough ( v1.M2(), v2.M2(), "m2" ,ticks); ret |= closeEnough ( v1.M(), v2.M(), "m" ,ticks); ret |= closeEnough ( v1.Mt(), v2.Mt(), "mt" ,ticks); ret |= closeEnough ( v1.Et(), v2.Et(), "et" ,ticks); if ( v1.rho() > 0 && v2.rho() > 0 ) { // eta can legitimately vary if rho == 0 ret |= closeEnough ( v1.eta(), v2.eta(), "eta" ,ticks); } if (ret != 0) { std::cout << "Discrepancy detected (see above) is between:\n " << CoordinateTraits<CoordType1>::name() << " and\n " << CoordinateTraits<CoordType2>::name() << "\n" << "with v = (" << v1.x() << ", " << v1.y() << ", " << v1.z() << ", " << v1.t() << ")\n"; } else { std::cout << "."; } return ret; } template <class C> int test4D ( const LorentzVector<C> & v, double ticks ) { #ifdef DEBUG std::cout <<"\n>>>>> Testing LorentzVector from " << XYZTVector(v) << " ticks = " << ticks << "\t: "; #endif int ret = 0; LorentzVector< PxPyPzE4D<double> > vxyzt_d (v.x(), v.y(), v.z(), v.t()); //double m = std::sqrt ( v.t()*v.t() - v.x()*v.x() - v.y()*v.y() - v.z()*v.z()); //double r = std::sqrt (v.x()*v.x() + v.y()*v.y() + v.z()*v.z()); double rho = std::sqrt (v.x()*v.x() + v.y()*v.y()); double theta = std::atan2( rho, v.z() ); // better tahn using acos //double theta = r>0 ? std::acos ( v.z()/r ) : 0; double phi = rho>0 ? std::atan2 (v.y(), v.x()) : 0; double eta; if (rho != 0) { eta = -std::log(std::tan(theta/2)); #ifdef TRACE1 std::cout << ":::: rho != 0\n" << ":::: theta = " << theta <<"/n:::: tan(theta/2) = " << std::tan(theta/2) <<"\n:::: eta = " << eta << "\n"; #endif } else if (v.z() == 0) { eta = 0; #ifdef TRACE1 std::cout << ":::: v.z() == 0\n" <<"\n:::: eta = " << eta << "\n"; #endif } else if (v.z() > 0) { eta = v.z() + etaMax<long double>(); #ifdef TRACE1 std::cout << ":::: v.z() > 0\n" << ":::: etaMax = " << etaMax<long double>() <<"\n:::: eta = " << eta << "\n"; #endif } else { eta = v.z() - etaMax<long double>(); #ifdef TRACE1 std::cout << ":::: v.z() < 0\n" << ":::: etaMax = " << etaMax<long double>() <<"\n:::: eta = " << eta << "\n"; #endif } LorentzVector< PtEtaPhiE4D<double> > vrep_d ( rho, eta, phi, v.t() ); ret |= compare4D( vxyzt_d, vrep_d, ticks); LorentzVector< PtEtaPhiM4D<double> > vrepm_d ( rho, eta, phi, v.M() ); ret |= compare4D( vxyzt_d, vrepm_d, ticks); LorentzVector< PxPyPzM4D <double> > vxyzm_d ( v.x(), v.y(), v.z(), v.M() ); ret |= compare4D( vrep_d, vxyzm_d, ticks); LorentzVector< PxPyPzE4D<float> > vxyzt_f (v.x(), v.y(), v.z(), v.t()); ret |= compare4D( vxyzt_d, vxyzt_f, ticks); LorentzVector< PtEtaPhiE4D<float> > vrep_f ( rho, eta, phi, v.t() ); ret |= compare4D( vxyzt_f, vrep_f, ticks); LorentzVector< PtEtaPhiM4D<float> > vrepm_f ( rho, eta, phi, v.M() ); ret |= compare4D( vxyzt_f, vrepm_f, ticks); LorentzVector< PxPyPzM4D<float> > vxyzm_f (v.x(), v.y(), v.z(), v.M()); ret |= compare4D( vrep_f, vxyzm_f, ticks); if (ret == 0) std::cout << "\t OK\n"; else { std::cout << "\t FAIL\n"; std::cerr << "\n>>>>> Testing LorentzVector from " << XYZTVector(v) << " ticks = " << ticks << "\t:\t FAILED\n"; } return ret; } int coordinates4D (bool testAll = false) { int ret = 0; ret |= test4D (XYZTVector ( 0.0, 0.0, 0.0, 0.0 ) , 1 ); ret |= test4D (XYZTVector ( 1.0, 2.0, 3.0, 4.0 ) ,10 ); ret |= test4D (XYZTVector ( -1.0, -2.0, 3.0, 4.0 ) ,10 ); // test for large eta values (which was giving inf before Jun 07) ret |= test4D (XYZTVector ( 1.E-8, 1.E-8, 10.0, 100.0 ) ,10 ); // for z < 0 precision in eta is worse since theta is close to Pi ret |= test4D (XYZTVector ( 1.E-8, 1.E-8, -10.0, 100.0 ) ,1000000000 ); // test cases with zero mass // tick should be p /sqrt(eps) ~ 4 /sqrt(eps) // take a factor 1.5 in ticks to be conservative ret |= test4D (PxPyPzMVector ( 1., 2., 3., 0.) , 1.5 * 4./std::sqrt(std::numeric_limits<double>::epsilon()) ); // this test fails in some machines (skip by default) if (!testAll) return ret; // take a factor 1.5 in ticks to be conservative ret |= test4D (PxPyPzMVector ( 1., 1., 100., 0.) , 150./std::sqrt(std::numeric_limits<double>::epsilon()) ); // need a larger a factor here ret |= test4D (PxPyPzMVector ( 1.E8, 1.E8, 1.E8, 0.) , 1.E9/std::sqrt(std::numeric_limits<double>::epsilon()) ); // if use 1 here fails ret |= test4D (PxPyPzMVector ( 1.E-8, 1.E-8, 1.E-8, 0.) , 2.E-8/std::sqrt(std::numeric_limits<double>::epsilon()) ); return ret; } int main() { int ret = coordinates4D(); if (ret) std::cerr << "test FAILED !!! " << std::endl; else std::cout << "test OK " << std::endl; return ret; } <|endoftext|>
<commit_before>#include "platform/tizen/TizenApplication.h" using namespace Tizen::Graphics::Opengl; namespace lime { int gFixedOrientation = -1; //double mAccelX; //double mAccelY; //double mAccelZ; int mSingleTouchID; FrameCreationCallback sgCallback; unsigned int sgFlags; int sgHeight; const char *sgTitle; TizenFrame *sgTizenFrame; int sgWidth; enum { NO_TOUCH = -1 }; void CreateMainFrame (FrameCreationCallback inOnFrame, int inWidth, int inHeight, unsigned int inFlags, const char *inTitle, Surface *inIcon) { sgCallback = inOnFrame; sgWidth = inWidth; sgHeight = inHeight; sgFlags = inFlags; sgTitle = inTitle; mSingleTouchID = NO_TOUCH; //if (sgWidth == 0 && sgHeight == 0) { // Hard-code screen size for now sgWidth = 720; sgHeight = 1280; //} // For now, swap the width/height for proper EGL initialization, when landscape if (gFixedOrientation == 3 || gFixedOrientation == 4) { int temp = sgWidth; sgWidth = sgHeight; sgHeight = temp; } Tizen::Base::Collection::ArrayList args (Tizen::Base::Collection::SingleObjectDeleter); args.Construct (); result r = Tizen::App::Application::Execute (TizenApplication::CreateInstance, &args); } void StartAnimation () {} void PauseAnimation () {} void ResumeAnimation () {} void StopAnimation () {} TizenApplication::TizenApplication (void) { //mAccelX = 0; //mAccelY = 0; //mAccelZ = 0; mEGLDisplay = EGL_NO_DISPLAY; mEGLSurface = EGL_NO_SURFACE; mEGLConfig = null; mEGLContext = EGL_NO_CONTEXT; mForm = null; mTimer = null; } TizenApplication::~TizenApplication (void) {} void TizenApplication::Cleanup (void) { if (mTimer != null) { mTimer->Cancel (); delete mTimer; mTimer = null; } /*if (mSensorManager) { mSensorManager->RemoveSensorListener (*this); delete mSensorManager; mSensorManager = null; }*/ Event close (etQuit); sgTizenFrame->HandleEvent (close); Event lostFocus (etLostInputFocus); sgTizenFrame->HandleEvent (lostFocus); Event deactivate (etDeactivate); sgTizenFrame->HandleEvent (deactivate); Event kill (etDestroyHandler); sgTizenFrame->HandleEvent (kill); } Tizen::App::Application* TizenApplication::CreateInstance (void) { return new (std::nothrow) TizenApplication (); } bool TizenApplication::OnAppInitializing (Tizen::App::AppRegistry& appRegistry) { Tizen::Ui::Controls::Frame* appFrame = new (std::nothrow) Tizen::Ui::Controls::Frame (); appFrame->Construct (); this->AddFrame (*appFrame); mForm = new (std::nothrow) TizenForm (this); mForm->Construct (Tizen::Ui::Controls::FORM_STYLE_NORMAL); if (gFixedOrientation == 3 || gFixedOrientation == 4) { mForm->SetOrientation (Tizen::Ui::ORIENTATION_LANDSCAPE); } GetAppFrame ()->GetFrame ()->AddControl (mForm); mForm->AddKeyEventListener (*this); mForm->AddTouchEventListener (*this); mForm->SetMultipointTouchEnabled (true); /*long interval = 0L; mSensorManager = new Tizen::Uix::Sensor::SensorManager (); mSensorManager->Construct (); mSensorManager->GetMinInterval (Tizen::Uix::Sensor::SENSOR_TYPE_ACCELERATION, interval); if (interval < 50) { interval = 50; } mSensorManager->AddSensorListener (*this, Tizen::Uix::Sensor::SENSOR_TYPE_ACCELERATION, interval, true);*/ bool ok = limeEGLCreate (mForm, sgWidth, sgHeight, 1, (sgFlags & wfDepthBuffer) ? 16 : 0, (sgFlags & wfStencilBuffer) ? 8 : 0, 0); mTimer = new (std::nothrow) Tizen::Base::Runtime::Timer; mTimer->Construct (*this); Tizen::System::PowerManager::AddScreenEventListener (*this); sgTizenFrame = new TizenFrame (sgWidth, sgHeight); sgCallback (sgTizenFrame); return true; } bool TizenApplication::OnAppTerminating (Tizen::App::AppRegistry& appRegistry, bool forcedTermination) { Cleanup (); return true; } void TizenApplication::OnBackground (void) { if (mTimer != null) { mTimer->Cancel (); } Event lostFocus (etLostInputFocus); sgTizenFrame->HandleEvent (lostFocus); Event deactivate (etDeactivate); sgTizenFrame->HandleEvent (deactivate); } void TizenApplication::OnBatteryLevelChanged (Tizen::System::BatteryLevel batteryLevel) {} //void OnDataReceived (Tizen::Uix::Sensor::SensorType sensorType, Tizen::Uix::Sensor::SensorData& sensorData, result r) { //Tizen::Uix::Sensor::AccelerationSensorData& data = static_cast<Tizen::Uix::Sensor::AccelerationSensorData&>(sensorData); //mAccelX = -data.x; //mAccelY = -data.y; //mAccelZ = -data.z; //} void TizenApplication::OnForeground (void) { Event activate (etActivate); sgTizenFrame->HandleEvent (activate); Event gotFocus (etGotInputFocus); sgTizenFrame->HandleEvent (gotFocus); Event poll (etPoll); sgTizenFrame->HandleEvent (poll); double next = sgTizenFrame->GetStage ()->GetNextWake () - GetTimeStamp (); if (mTimer != null) { if (next > 0.001) { mTimer->Start (next * 1000.0); } else { mTimer->Start (1); } } } void TizenApplication::OnKeyLongPressed (const Tizen::Ui::Control& source, Tizen::Ui::KeyCode keyCode) {} void TizenApplication::OnKeyPressed (const Tizen::Ui::Control& source, Tizen::Ui::KeyCode keyCode) { } void TizenApplication::OnKeyReleased (const Tizen::Ui::Control& source, Tizen::Ui::KeyCode keyCode) { if (keyCode == Tizen::Ui::KEY_BACK || keyCode == Tizen::Ui::KEY_ESC) { Terminate (); } } void TizenApplication::OnLowMemory (void) {} void TizenApplication::OnScreenOn (void) {} void TizenApplication::OnScreenOff (void) {} void TizenApplication::OnTimerExpired (Tizen::Base::Runtime::Timer& timer) { if (mTimer == null) { return; } double next = sgTizenFrame->GetStage ()->GetNextWake () - GetTimeStamp (); if (next > 0.001) { mTimer->Start (next * 1000.0); } else { mTimer->Start (1); } Event poll (etPoll); sgTizenFrame->HandleEvent (poll); } void TizenApplication::OnTouchCanceled (const Tizen::Ui::Control &source, const Tizen::Graphics::Point &currentPosition, const Tizen::Ui::TouchEventInfo &touchInfo) {} void TizenApplication::OnTouchFocusIn (const Tizen::Ui::Control &source, const Tizen::Graphics::Point &currentPosition, const Tizen::Ui::TouchEventInfo &touchInfo) {} void TizenApplication::OnTouchFocusOut (const Tizen::Ui::Control &source, const Tizen::Graphics::Point &currentPosition, const Tizen::Ui::TouchEventInfo &touchInfo) {} void TizenApplication::OnTouchMoved (const Tizen::Ui::Control &source, const Tizen::Graphics::Point &currentPosition, const Tizen::Ui::TouchEventInfo &touchInfo) { Event mouse (etTouchMove, currentPosition.x, currentPosition.y); mouse.value = touchInfo.GetPointId (); if (mSingleTouchID == NO_TOUCH || mouse.value == mSingleTouchID) { mouse.flags |= efPrimaryTouch; } sgTizenFrame->HandleEvent (mouse); } void TizenApplication::OnTouchPressed (const Tizen::Ui::Control &source, const Tizen::Graphics::Point &currentPosition, const Tizen::Ui::TouchEventInfo &touchInfo) { Event mouse (etTouchBegin, currentPosition.x, currentPosition.y); mouse.value = touchInfo.GetPointId (); if (mSingleTouchID == NO_TOUCH || mouse.value == mSingleTouchID) { mouse.flags |= efPrimaryTouch; } sgTizenFrame->HandleEvent (mouse); } void TizenApplication::OnTouchReleased (const Tizen::Ui::Control &source, const Tizen::Graphics::Point &currentPosition, const Tizen::Ui::TouchEventInfo &touchInfo) { Event mouse (etTouchEnd, currentPosition.x, currentPosition.y); mouse.value = touchInfo.GetPointId (); if (mSingleTouchID == NO_TOUCH || mouse.value == mSingleTouchID) { mouse.flags |= efPrimaryTouch; } if (mSingleTouchID == mouse.value) { mSingleTouchID = NO_TOUCH; } sgTizenFrame->HandleEvent (mouse); } bool ClearUserPreference (const char *inId) { result r = E_SUCCESS; Tizen::App::AppRegistry* appRegistry = Tizen::App::AppRegistry::GetInstance (); r = appRegistry->Remove (inId); return (r == E_SUCCESS); } bool GetAcceleration (double &outX, double &outY, double &outZ) { //if (gFixedOrientation == 3 || gFixedOrientation == 4) { //outX = mAccelX; //outY = mAccelY; //outZ = mAccelZ; outX = 0; outY = 0; outZ = 1; return true; //} /*int result = accelerometer_read_forces (&outX, &outY, &outZ); if (getenv ("FORCE_PORTRAIT") != NULL) { int cache = outX; outX = outY; outY = -cache; } outZ = -outZ;*/ } std::string GetUserPreference (const char *inId) { Tizen::Base::String value; result r = E_SUCCESS; Tizen::App::AppRegistry* appRegistry = Tizen::App::AppRegistry::GetInstance (); r = appRegistry->Get (inId, value); if (r == E_SUCCESS) { std::wstring dir = std::wstring (value.GetPointer ()); return std::string (dir.begin (), dir.end ()); } return ""; } bool LaunchBrowser (const char *inUtf8URL) { Tizen::Base::String uri = Tizen::Base::String(inUtf8URL); Tizen::App::AppControl* pAc = Tizen::App::AppManager::FindAppControlN (L"tizen.internet", L"http://tizen.org/appcontrol/operation/view"); if (pAc) { pAc->Start (&uri, null, null, null); delete pAc; } return true; } bool SetUserPreference (const char *inId, const char *inPreference) { result r = E_SUCCESS; Tizen::App::AppRegistry* appRegistry = Tizen::App::AppRegistry::GetInstance (); r = appRegistry->Set (inId, inPreference); if (r != E_SUCCESS) { r = appRegistry->Add (inId, inPreference); } return (r == E_SUCCESS); } } <commit_msg>Accelerometer still crashing on Tizen, use better dummy value<commit_after>#include "platform/tizen/TizenApplication.h" using namespace Tizen::Graphics::Opengl; namespace lime { int gFixedOrientation = -1; //double mAccelX; //double mAccelY; //double mAccelZ; int mSingleTouchID; FrameCreationCallback sgCallback; unsigned int sgFlags; int sgHeight; const char *sgTitle; TizenFrame *sgTizenFrame; int sgWidth; enum { NO_TOUCH = -1 }; void CreateMainFrame (FrameCreationCallback inOnFrame, int inWidth, int inHeight, unsigned int inFlags, const char *inTitle, Surface *inIcon) { sgCallback = inOnFrame; sgWidth = inWidth; sgHeight = inHeight; sgFlags = inFlags; sgTitle = inTitle; mSingleTouchID = NO_TOUCH; //if (sgWidth == 0 && sgHeight == 0) { // Hard-code screen size for now sgWidth = 720; sgHeight = 1280; //} // For now, swap the width/height for proper EGL initialization, when landscape if (gFixedOrientation == 3 || gFixedOrientation == 4) { int temp = sgWidth; sgWidth = sgHeight; sgHeight = temp; } Tizen::Base::Collection::ArrayList args (Tizen::Base::Collection::SingleObjectDeleter); args.Construct (); result r = Tizen::App::Application::Execute (TizenApplication::CreateInstance, &args); } void StartAnimation () {} void PauseAnimation () {} void ResumeAnimation () {} void StopAnimation () {} TizenApplication::TizenApplication (void) { //mAccelX = 0; //mAccelY = 0; //mAccelZ = 0; mEGLDisplay = EGL_NO_DISPLAY; mEGLSurface = EGL_NO_SURFACE; mEGLConfig = null; mEGLContext = EGL_NO_CONTEXT; mForm = null; mTimer = null; } TizenApplication::~TizenApplication (void) {} void TizenApplication::Cleanup (void) { if (mTimer != null) { mTimer->Cancel (); delete mTimer; mTimer = null; } /*if (mSensorManager) { mSensorManager->RemoveSensorListener (*this); delete mSensorManager; mSensorManager = null; }*/ Event close (etQuit); sgTizenFrame->HandleEvent (close); Event lostFocus (etLostInputFocus); sgTizenFrame->HandleEvent (lostFocus); Event deactivate (etDeactivate); sgTizenFrame->HandleEvent (deactivate); Event kill (etDestroyHandler); sgTizenFrame->HandleEvent (kill); } Tizen::App::Application* TizenApplication::CreateInstance (void) { return new (std::nothrow) TizenApplication (); } bool TizenApplication::OnAppInitializing (Tizen::App::AppRegistry& appRegistry) { Tizen::Ui::Controls::Frame* appFrame = new (std::nothrow) Tizen::Ui::Controls::Frame (); appFrame->Construct (); this->AddFrame (*appFrame); mForm = new (std::nothrow) TizenForm (this); mForm->Construct (Tizen::Ui::Controls::FORM_STYLE_NORMAL); if (gFixedOrientation == 3 || gFixedOrientation == 4) { mForm->SetOrientation (Tizen::Ui::ORIENTATION_LANDSCAPE); } GetAppFrame ()->GetFrame ()->AddControl (mForm); mForm->AddKeyEventListener (*this); mForm->AddTouchEventListener (*this); mForm->SetMultipointTouchEnabled (true); /*long interval = 0L; mSensorManager = new Tizen::Uix::Sensor::SensorManager (); mSensorManager->Construct (); mSensorManager->GetMinInterval (Tizen::Uix::Sensor::SENSOR_TYPE_ACCELERATION, interval); if (interval < 50) { interval = 50; } mSensorManager->AddSensorListener (*this, Tizen::Uix::Sensor::SENSOR_TYPE_ACCELERATION, interval, true);*/ bool ok = limeEGLCreate (mForm, sgWidth, sgHeight, 1, (sgFlags & wfDepthBuffer) ? 16 : 0, (sgFlags & wfStencilBuffer) ? 8 : 0, 0); mTimer = new (std::nothrow) Tizen::Base::Runtime::Timer; mTimer->Construct (*this); Tizen::System::PowerManager::AddScreenEventListener (*this); sgTizenFrame = new TizenFrame (sgWidth, sgHeight); sgCallback (sgTizenFrame); return true; } bool TizenApplication::OnAppTerminating (Tizen::App::AppRegistry& appRegistry, bool forcedTermination) { Cleanup (); return true; } void TizenApplication::OnBackground (void) { if (mTimer != null) { mTimer->Cancel (); } Event lostFocus (etLostInputFocus); sgTizenFrame->HandleEvent (lostFocus); Event deactivate (etDeactivate); sgTizenFrame->HandleEvent (deactivate); } void TizenApplication::OnBatteryLevelChanged (Tizen::System::BatteryLevel batteryLevel) {} //void OnDataReceived (Tizen::Uix::Sensor::SensorType sensorType, Tizen::Uix::Sensor::SensorData& sensorData, result r) { //Tizen::Uix::Sensor::AccelerationSensorData& data = static_cast<Tizen::Uix::Sensor::AccelerationSensorData&>(sensorData); //mAccelX = -data.x; //mAccelY = -data.y; //mAccelZ = -data.z; //} void TizenApplication::OnForeground (void) { Event activate (etActivate); sgTizenFrame->HandleEvent (activate); Event gotFocus (etGotInputFocus); sgTizenFrame->HandleEvent (gotFocus); Event poll (etPoll); sgTizenFrame->HandleEvent (poll); double next = sgTizenFrame->GetStage ()->GetNextWake () - GetTimeStamp (); if (mTimer != null) { if (next > 0.001) { mTimer->Start (next * 1000.0); } else { mTimer->Start (1); } } } void TizenApplication::OnKeyLongPressed (const Tizen::Ui::Control& source, Tizen::Ui::KeyCode keyCode) {} void TizenApplication::OnKeyPressed (const Tizen::Ui::Control& source, Tizen::Ui::KeyCode keyCode) { } void TizenApplication::OnKeyReleased (const Tizen::Ui::Control& source, Tizen::Ui::KeyCode keyCode) { if (keyCode == Tizen::Ui::KEY_BACK || keyCode == Tizen::Ui::KEY_ESC) { Terminate (); } } void TizenApplication::OnLowMemory (void) {} void TizenApplication::OnScreenOn (void) {} void TizenApplication::OnScreenOff (void) {} void TizenApplication::OnTimerExpired (Tizen::Base::Runtime::Timer& timer) { if (mTimer == null) { return; } double next = sgTizenFrame->GetStage ()->GetNextWake () - GetTimeStamp (); if (next > 0.001) { mTimer->Start (next * 1000.0); } else { mTimer->Start (1); } Event poll (etPoll); sgTizenFrame->HandleEvent (poll); } void TizenApplication::OnTouchCanceled (const Tizen::Ui::Control &source, const Tizen::Graphics::Point &currentPosition, const Tizen::Ui::TouchEventInfo &touchInfo) {} void TizenApplication::OnTouchFocusIn (const Tizen::Ui::Control &source, const Tizen::Graphics::Point &currentPosition, const Tizen::Ui::TouchEventInfo &touchInfo) {} void TizenApplication::OnTouchFocusOut (const Tizen::Ui::Control &source, const Tizen::Graphics::Point &currentPosition, const Tizen::Ui::TouchEventInfo &touchInfo) {} void TizenApplication::OnTouchMoved (const Tizen::Ui::Control &source, const Tizen::Graphics::Point &currentPosition, const Tizen::Ui::TouchEventInfo &touchInfo) { Event mouse (etTouchMove, currentPosition.x, currentPosition.y); mouse.value = touchInfo.GetPointId (); if (mSingleTouchID == NO_TOUCH || mouse.value == mSingleTouchID) { mouse.flags |= efPrimaryTouch; } sgTizenFrame->HandleEvent (mouse); } void TizenApplication::OnTouchPressed (const Tizen::Ui::Control &source, const Tizen::Graphics::Point &currentPosition, const Tizen::Ui::TouchEventInfo &touchInfo) { Event mouse (etTouchBegin, currentPosition.x, currentPosition.y); mouse.value = touchInfo.GetPointId (); if (mSingleTouchID == NO_TOUCH || mouse.value == mSingleTouchID) { mouse.flags |= efPrimaryTouch; } sgTizenFrame->HandleEvent (mouse); } void TizenApplication::OnTouchReleased (const Tizen::Ui::Control &source, const Tizen::Graphics::Point &currentPosition, const Tizen::Ui::TouchEventInfo &touchInfo) { Event mouse (etTouchEnd, currentPosition.x, currentPosition.y); mouse.value = touchInfo.GetPointId (); if (mSingleTouchID == NO_TOUCH || mouse.value == mSingleTouchID) { mouse.flags |= efPrimaryTouch; } if (mSingleTouchID == mouse.value) { mSingleTouchID = NO_TOUCH; } sgTizenFrame->HandleEvent (mouse); } bool ClearUserPreference (const char *inId) { result r = E_SUCCESS; Tizen::App::AppRegistry* appRegistry = Tizen::App::AppRegistry::GetInstance (); r = appRegistry->Remove (inId); return (r == E_SUCCESS); } bool GetAcceleration (double &outX, double &outY, double &outZ) { //if (gFixedOrientation == 3 || gFixedOrientation == 4) { //outX = mAccelX; //outY = mAccelY; //outZ = mAccelZ; outX = 0; outY = 0; outZ = -1; return true; //} /*int result = accelerometer_read_forces (&outX, &outY, &outZ); if (getenv ("FORCE_PORTRAIT") != NULL) { int cache = outX; outX = outY; outY = -cache; } outZ = -outZ;*/ } std::string GetUserPreference (const char *inId) { Tizen::Base::String value; result r = E_SUCCESS; Tizen::App::AppRegistry* appRegistry = Tizen::App::AppRegistry::GetInstance (); r = appRegistry->Get (inId, value); if (r == E_SUCCESS) { std::wstring dir = std::wstring (value.GetPointer ()); return std::string (dir.begin (), dir.end ()); } return ""; } bool LaunchBrowser (const char *inUtf8URL) { Tizen::Base::String uri = Tizen::Base::String(inUtf8URL); Tizen::App::AppControl* pAc = Tizen::App::AppManager::FindAppControlN (L"tizen.internet", L"http://tizen.org/appcontrol/operation/view"); if (pAc) { pAc->Start (&uri, null, null, null); delete pAc; } return true; } bool SetUserPreference (const char *inId, const char *inPreference) { result r = E_SUCCESS; Tizen::App::AppRegistry* appRegistry = Tizen::App::AppRegistry::GetInstance (); r = appRegistry->Set (inId, inPreference); if (r != E_SUCCESS) { r = appRegistry->Add (inId, inPreference); } return (r == E_SUCCESS); } } <|endoftext|>
<commit_before>// 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 "media/blink/video_frame_compositor.h" #include "base/bind.h" #include "base/message_loop/message_loop.h" #include "base/time/default_tick_clock.h" #include "base/trace_event/trace_event.h" #include "media/base/video_frame.h" namespace media { // Amount of time to wait between UpdateCurrentFrame() callbacks before starting // background rendering to keep the Render() callbacks moving. const int kBackgroundRenderingTimeoutMs = 250; // Returns true if the format has no Alpha channel (hence is always opaque). static bool IsOpaque(const scoped_refptr<VideoFrame>& frame) { switch (frame->format()) { case PIXEL_FORMAT_UNKNOWN: case PIXEL_FORMAT_YV12: case PIXEL_FORMAT_I420: case PIXEL_FORMAT_YV16: case PIXEL_FORMAT_YV24: case PIXEL_FORMAT_NV12: case PIXEL_FORMAT_XRGB: return true; case PIXEL_FORMAT_YV12A: case PIXEL_FORMAT_ARGB: break; } return false; } VideoFrameCompositor::VideoFrameCompositor( const scoped_refptr<base::SingleThreadTaskRunner>& compositor_task_runner, const base::Callback<void(gfx::Size)>& natural_size_changed_cb, const base::Callback<void(bool)>& opacity_changed_cb) : compositor_task_runner_(compositor_task_runner), tick_clock_(new base::DefaultTickClock()), natural_size_changed_cb_(natural_size_changed_cb), opacity_changed_cb_(opacity_changed_cb), background_rendering_enabled_(true), background_rendering_timer_( FROM_HERE, base::TimeDelta::FromMilliseconds(kBackgroundRenderingTimeoutMs), base::Bind(&VideoFrameCompositor::BackgroundRender, base::Unretained(this)), // Task is not repeating, CallRender() will reset the task as needed. false), client_(nullptr), rendering_(false), rendered_last_frame_(false), is_background_rendering_(false), new_background_frame_(false), // Assume 60Hz before the first UpdateCurrentFrame() call. last_interval_(base::TimeDelta::FromSecondsD(1.0 / 60)), callback_(nullptr) { background_rendering_timer_.SetTaskRunner(compositor_task_runner_); } VideoFrameCompositor::~VideoFrameCompositor() { DCHECK(compositor_task_runner_->BelongsToCurrentThread()); DCHECK(!callback_); DCHECK(!rendering_); if (client_) client_->StopUsingProvider(); } void VideoFrameCompositor::OnRendererStateUpdate(bool new_state) { DCHECK(compositor_task_runner_->BelongsToCurrentThread()); DCHECK_NE(rendering_, new_state); rendering_ = new_state; if (rendering_) { // Always start playback in background rendering mode, if |client_| kicks // in right away it's okay. BackgroundRender(); } else if (background_rendering_enabled_) { background_rendering_timer_.Stop(); } else { DCHECK(!background_rendering_timer_.IsRunning()); } if (!client_) return; if (rendering_) client_->StartRendering(); else client_->StopRendering(); } void VideoFrameCompositor::SetVideoFrameProviderClient( cc::VideoFrameProvider::Client* client) { DCHECK(compositor_task_runner_->BelongsToCurrentThread()); if (client_) client_->StopUsingProvider(); client_ = client; // |client_| may now be null, so verify before calling it. if (rendering_ && client_) client_->StartRendering(); } scoped_refptr<VideoFrame> VideoFrameCompositor::GetCurrentFrame() { DCHECK(compositor_task_runner_->BelongsToCurrentThread()); return current_frame_; } void VideoFrameCompositor::PutCurrentFrame() { DCHECK(compositor_task_runner_->BelongsToCurrentThread()); rendered_last_frame_ = true; } bool VideoFrameCompositor::UpdateCurrentFrame(base::TimeTicks deadline_min, base::TimeTicks deadline_max) { DCHECK(compositor_task_runner_->BelongsToCurrentThread()); return CallRender(deadline_min, deadline_max, false); } bool VideoFrameCompositor::HasCurrentFrame() { DCHECK(compositor_task_runner_->BelongsToCurrentThread()); return current_frame_; } void VideoFrameCompositor::Start(RenderCallback* callback) { TRACE_EVENT0("media", "VideoFrameCompositor::Start"); // Called from the media thread, so acquire the callback under lock before // returning in case a Stop() call comes in before the PostTask is processed. base::AutoLock lock(lock_); DCHECK(!callback_); callback_ = callback; compositor_task_runner_->PostTask( FROM_HERE, base::Bind(&VideoFrameCompositor::OnRendererStateUpdate, base::Unretained(this), true)); } void VideoFrameCompositor::Stop() { TRACE_EVENT0("media", "VideoFrameCompositor::Stop"); // Called from the media thread, so release the callback under lock before // returning to avoid a pending UpdateCurrentFrame() call occurring before // the PostTask is processed. base::AutoLock lock(lock_); DCHECK(callback_); callback_ = nullptr; compositor_task_runner_->PostTask( FROM_HERE, base::Bind(&VideoFrameCompositor::OnRendererStateUpdate, base::Unretained(this), false)); } void VideoFrameCompositor::PaintFrameUsingOldRenderingPath( const scoped_refptr<VideoFrame>& frame) { if (!compositor_task_runner_->BelongsToCurrentThread()) { compositor_task_runner_->PostTask( FROM_HERE, base::Bind(&VideoFrameCompositor::PaintFrameUsingOldRenderingPath, base::Unretained(this), frame)); return; } if (ProcessNewFrame(frame) && client_) client_->DidReceiveFrame(); } scoped_refptr<VideoFrame> VideoFrameCompositor::GetCurrentFrameAndUpdateIfStale() { DCHECK(compositor_task_runner_->BelongsToCurrentThread()); if (client_ || !rendering_ || !is_background_rendering_) return current_frame_; DCHECK(!last_background_render_.is_null()); const base::TimeTicks now = tick_clock_->NowTicks(); const base::TimeDelta interval = now - last_background_render_; // Cap updates to 250Hz which should be more than enough for everyone. if (interval < base::TimeDelta::FromMilliseconds(4)) return current_frame_; // Update the interval based on the time between calls and call background // render which will give this information to the client. last_interval_ = interval; BackgroundRender(); return current_frame_; } bool VideoFrameCompositor::ProcessNewFrame( const scoped_refptr<VideoFrame>& frame) { DCHECK(compositor_task_runner_->BelongsToCurrentThread()); if (frame == current_frame_) return false; // Set the flag indicating that the current frame is unrendered, if we get a // subsequent PutCurrentFrame() call it will mark it as rendered. rendered_last_frame_ = false; if (current_frame_ && current_frame_->natural_size() != frame->natural_size()) { natural_size_changed_cb_.Run(frame->natural_size()); } if (!current_frame_ || IsOpaque(current_frame_) != IsOpaque(frame)) opacity_changed_cb_.Run(IsOpaque(frame)); current_frame_ = frame; return true; } void VideoFrameCompositor::BackgroundRender() { DCHECK(compositor_task_runner_->BelongsToCurrentThread()); const base::TimeTicks now = tick_clock_->NowTicks(); last_background_render_ = now; CallRender(now, now + last_interval_, true); } bool VideoFrameCompositor::CallRender(base::TimeTicks deadline_min, base::TimeTicks deadline_max, bool background_rendering) { DCHECK(compositor_task_runner_->BelongsToCurrentThread()); base::AutoLock lock(lock_); if (!callback_) { // Even if we no longer have a callback, return true if we have a frame // which |client_| hasn't seen before. return !rendered_last_frame_ && current_frame_; } DCHECK(rendering_); // If the previous frame was never rendered and we're not in background // rendering mode (nor have just exited it), let the client know. if (!rendered_last_frame_ && current_frame_ && !background_rendering && !is_background_rendering_) { callback_->OnFrameDropped(); } const bool new_frame = ProcessNewFrame( callback_->Render(deadline_min, deadline_max, background_rendering)); // We may create a new frame here with background rendering, but the provider // has no way of knowing that a new frame had been processed, so keep track of // the new frame, and return true on the next call to |CallRender|. const bool had_new_background_frame = new_background_frame_; new_background_frame_ = background_rendering && new_frame; is_background_rendering_ = background_rendering; last_interval_ = deadline_max - deadline_min; // Restart the background rendering timer whether we're background rendering // or not; in either case we should wait for |kBackgroundRenderingTimeoutMs|. if (background_rendering_enabled_) background_rendering_timer_.Reset(); return new_frame || had_new_background_frame; } } // namespace media <commit_msg>Call VideoFrameProviderImpl::DidReceiveFrame when background render completes.<commit_after>// 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 "media/blink/video_frame_compositor.h" #include "base/bind.h" #include "base/message_loop/message_loop.h" #include "base/time/default_tick_clock.h" #include "base/trace_event/trace_event.h" #include "media/base/video_frame.h" namespace media { // Amount of time to wait between UpdateCurrentFrame() callbacks before starting // background rendering to keep the Render() callbacks moving. const int kBackgroundRenderingTimeoutMs = 250; // Returns true if the format has no Alpha channel (hence is always opaque). static bool IsOpaque(const scoped_refptr<VideoFrame>& frame) { switch (frame->format()) { case PIXEL_FORMAT_UNKNOWN: case PIXEL_FORMAT_YV12: case PIXEL_FORMAT_I420: case PIXEL_FORMAT_YV16: case PIXEL_FORMAT_YV24: case PIXEL_FORMAT_NV12: case PIXEL_FORMAT_XRGB: return true; case PIXEL_FORMAT_YV12A: case PIXEL_FORMAT_ARGB: break; } return false; } VideoFrameCompositor::VideoFrameCompositor( const scoped_refptr<base::SingleThreadTaskRunner>& compositor_task_runner, const base::Callback<void(gfx::Size)>& natural_size_changed_cb, const base::Callback<void(bool)>& opacity_changed_cb) : compositor_task_runner_(compositor_task_runner), tick_clock_(new base::DefaultTickClock()), natural_size_changed_cb_(natural_size_changed_cb), opacity_changed_cb_(opacity_changed_cb), background_rendering_enabled_(true), background_rendering_timer_( FROM_HERE, base::TimeDelta::FromMilliseconds(kBackgroundRenderingTimeoutMs), base::Bind(&VideoFrameCompositor::BackgroundRender, base::Unretained(this)), // Task is not repeating, CallRender() will reset the task as needed. false), client_(nullptr), rendering_(false), rendered_last_frame_(false), is_background_rendering_(false), new_background_frame_(false), // Assume 60Hz before the first UpdateCurrentFrame() call. last_interval_(base::TimeDelta::FromSecondsD(1.0 / 60)), callback_(nullptr) { background_rendering_timer_.SetTaskRunner(compositor_task_runner_); } VideoFrameCompositor::~VideoFrameCompositor() { DCHECK(compositor_task_runner_->BelongsToCurrentThread()); DCHECK(!callback_); DCHECK(!rendering_); if (client_) client_->StopUsingProvider(); } void VideoFrameCompositor::OnRendererStateUpdate(bool new_state) { DCHECK(compositor_task_runner_->BelongsToCurrentThread()); DCHECK_NE(rendering_, new_state); rendering_ = new_state; if (rendering_) { // Always start playback in background rendering mode, if |client_| kicks // in right away it's okay. BackgroundRender(); } else if (background_rendering_enabled_) { background_rendering_timer_.Stop(); } else { DCHECK(!background_rendering_timer_.IsRunning()); } if (!client_) return; if (rendering_) client_->StartRendering(); else client_->StopRendering(); } void VideoFrameCompositor::SetVideoFrameProviderClient( cc::VideoFrameProvider::Client* client) { DCHECK(compositor_task_runner_->BelongsToCurrentThread()); if (client_) client_->StopUsingProvider(); client_ = client; // |client_| may now be null, so verify before calling it. if (rendering_ && client_) client_->StartRendering(); } scoped_refptr<VideoFrame> VideoFrameCompositor::GetCurrentFrame() { DCHECK(compositor_task_runner_->BelongsToCurrentThread()); return current_frame_; } void VideoFrameCompositor::PutCurrentFrame() { DCHECK(compositor_task_runner_->BelongsToCurrentThread()); rendered_last_frame_ = true; } bool VideoFrameCompositor::UpdateCurrentFrame(base::TimeTicks deadline_min, base::TimeTicks deadline_max) { DCHECK(compositor_task_runner_->BelongsToCurrentThread()); return CallRender(deadline_min, deadline_max, false); } bool VideoFrameCompositor::HasCurrentFrame() { DCHECK(compositor_task_runner_->BelongsToCurrentThread()); return current_frame_; } void VideoFrameCompositor::Start(RenderCallback* callback) { TRACE_EVENT0("media", "VideoFrameCompositor::Start"); // Called from the media thread, so acquire the callback under lock before // returning in case a Stop() call comes in before the PostTask is processed. base::AutoLock lock(lock_); DCHECK(!callback_); callback_ = callback; compositor_task_runner_->PostTask( FROM_HERE, base::Bind(&VideoFrameCompositor::OnRendererStateUpdate, base::Unretained(this), true)); } void VideoFrameCompositor::Stop() { TRACE_EVENT0("media", "VideoFrameCompositor::Stop"); // Called from the media thread, so release the callback under lock before // returning to avoid a pending UpdateCurrentFrame() call occurring before // the PostTask is processed. base::AutoLock lock(lock_); DCHECK(callback_); callback_ = nullptr; compositor_task_runner_->PostTask( FROM_HERE, base::Bind(&VideoFrameCompositor::OnRendererStateUpdate, base::Unretained(this), false)); } void VideoFrameCompositor::PaintFrameUsingOldRenderingPath( const scoped_refptr<VideoFrame>& frame) { if (!compositor_task_runner_->BelongsToCurrentThread()) { compositor_task_runner_->PostTask( FROM_HERE, base::Bind(&VideoFrameCompositor::PaintFrameUsingOldRenderingPath, base::Unretained(this), frame)); return; } if (ProcessNewFrame(frame) && client_) client_->DidReceiveFrame(); } scoped_refptr<VideoFrame> VideoFrameCompositor::GetCurrentFrameAndUpdateIfStale() { DCHECK(compositor_task_runner_->BelongsToCurrentThread()); if (client_ || !rendering_ || !is_background_rendering_) return current_frame_; DCHECK(!last_background_render_.is_null()); const base::TimeTicks now = tick_clock_->NowTicks(); const base::TimeDelta interval = now - last_background_render_; // Cap updates to 250Hz which should be more than enough for everyone. if (interval < base::TimeDelta::FromMilliseconds(4)) return current_frame_; // Update the interval based on the time between calls and call background // render which will give this information to the client. last_interval_ = interval; BackgroundRender(); return current_frame_; } bool VideoFrameCompositor::ProcessNewFrame( const scoped_refptr<VideoFrame>& frame) { DCHECK(compositor_task_runner_->BelongsToCurrentThread()); if (frame == current_frame_) return false; // Set the flag indicating that the current frame is unrendered, if we get a // subsequent PutCurrentFrame() call it will mark it as rendered. rendered_last_frame_ = false; if (current_frame_ && current_frame_->natural_size() != frame->natural_size()) { natural_size_changed_cb_.Run(frame->natural_size()); } if (!current_frame_ || IsOpaque(current_frame_) != IsOpaque(frame)) opacity_changed_cb_.Run(IsOpaque(frame)); current_frame_ = frame; return true; } void VideoFrameCompositor::BackgroundRender() { DCHECK(compositor_task_runner_->BelongsToCurrentThread()); const base::TimeTicks now = tick_clock_->NowTicks(); last_background_render_ = now; bool new_frame = CallRender(now, now + last_interval_, true); if (new_frame && client_) client_->DidReceiveFrame(); } bool VideoFrameCompositor::CallRender(base::TimeTicks deadline_min, base::TimeTicks deadline_max, bool background_rendering) { DCHECK(compositor_task_runner_->BelongsToCurrentThread()); base::AutoLock lock(lock_); if (!callback_) { // Even if we no longer have a callback, return true if we have a frame // which |client_| hasn't seen before. return !rendered_last_frame_ && current_frame_; } DCHECK(rendering_); // If the previous frame was never rendered and we're not in background // rendering mode (nor have just exited it), let the client know. if (!rendered_last_frame_ && current_frame_ && !background_rendering && !is_background_rendering_) { callback_->OnFrameDropped(); } const bool new_frame = ProcessNewFrame( callback_->Render(deadline_min, deadline_max, background_rendering)); // We may create a new frame here with background rendering, but the provider // has no way of knowing that a new frame had been processed, so keep track of // the new frame, and return true on the next call to |CallRender|. const bool had_new_background_frame = new_background_frame_; new_background_frame_ = background_rendering && new_frame; is_background_rendering_ = background_rendering; last_interval_ = deadline_max - deadline_min; // Restart the background rendering timer whether we're background rendering // or not; in either case we should wait for |kBackgroundRenderingTimeoutMs|. if (background_rendering_enabled_) background_rendering_timer_.Reset(); return new_frame || had_new_background_frame; } } // namespace media <|endoftext|>
<commit_before>#include "localserver.h" namespace rclog { LocalServer::LocalServer(boost::asio::io_service &io_service, std::string socket_path) :socket_(io_service, datagram_protocol::endpoint(socket_path)) { do_receive(); } void LocalServer::do_receive() { socket_.async_receive_from(boost::asio::buffer(data_, max_length), sender_endpoint_, boost::bind(&LocalServer::handle_message, this, _1, _2)); } void LocalServer::do_send(std::size_t length) { std::cout << "EP: " << sender_endpoint_ << std::endl; socket_.async_send_to( boost::asio::buffer(data_, length), sender_endpoint_, [this](boost::system::error_code /*ec*/, std::size_t /*bytes_sent*/) { do_receive(); }); } void LocalServer::handle_message(boost::system::error_code ec, std::size_t bytes_recvd) { if (!ec && bytes_recvd > 0) { std::cout << "Got: '"; std::cout.write(data_, bytes_recvd); std::cout << "'" << std::endl; do_send(bytes_recvd); } else do_receive(); } } <commit_msg>Add message_size error handle to rclogd<commit_after>#include "localserver.h" namespace rclog { LocalServer::LocalServer(boost::asio::io_service &io_service, std::string socket_path) :socket_(io_service, datagram_protocol::endpoint(socket_path)) { do_receive(); } void LocalServer::do_receive() { socket_.async_receive_from(boost::asio::buffer(data_, max_length), sender_endpoint_, boost::bind(&LocalServer::handle_message, this, _1, _2)); } void LocalServer::do_send(std::size_t length) { std::cout << "EP: " << sender_endpoint_ << std::endl; socket_.async_send_to( boost::asio::buffer(data_, length), sender_endpoint_, [this](boost::system::error_code /*ec*/, std::size_t /*bytes_sent*/) { do_receive(); }); } void LocalServer::handle_message(boost::system::error_code ec, std::size_t bytes_recvd) { if (!ec && bytes_recvd > 0) { std::cout << "Got: '"; std::cout.write(data_, bytes_recvd); std::cout << "'" << std::endl; do_send(bytes_recvd); return; } if (ec == boost::asio::error::message_size) std::cerr << "Error: got message greater then buffer size"; // TODO: send error do_receive(); } } <|endoftext|>
<commit_before>#include "asocket.h" // C++ #include <cassert> #include <cstring> #include <cstdint> // STL #include <iostream> // PDTK #include <cxxutils/error_helpers.h> #include <cxxutils/streamcolors.h> #ifndef CMSG_LEN #define CMSG_ALIGN(len) (((len) + sizeof(size_t) - 1) & (size_t) ~ (sizeof(size_t) - 1)) #define CMSG_SPACE(len) (CMSG_ALIGN (len) + CMSG_ALIGN (sizeof (struct cmsghdr))) #define CMSG_LEN(len) (CMSG_ALIGN (sizeof (struct cmsghdr)) + (len)) #endif static_assert(sizeof(uint8_t) == sizeof(char), "size mismatch!"); namespace LocalCommand { static const uint64_t write = 1; static const uint64_t update = 2; static const uint64_t exit = 3; } namespace posix { inline bool getpeercred(fd_t sockfd, proccred_t& cred) noexcept { return ::getpeercred(sockfd, cred) == posix::success_response; } } AsyncSocket::AsyncSocket(EDomain domain, EType type, EProtocol protocol, int flags) noexcept : AsyncSocket(posix::socket(domain, type, protocol, flags)) { } AsyncSocket::AsyncSocket(posix::fd_t socket) noexcept : m_socket(socket), m_bound(false) { posix::fd_t cmdio[2]; assert(::pipe(cmdio) != posix::error_response); m_read_command = cmdio[0]; m_write_command = cmdio[1]; EventBackend::watch(m_read_command, EventFlags_e::Read); EventBackend::watch(m_socket, EventFlags_e::Read); } AsyncSocket::~AsyncSocket(void) noexcept { posix::write(m_write_command, &LocalCommand::exit, sizeof(uint64_t)); m_iothread.join(); // wait for thread to exit if(m_socket != posix::invalid_descriptor) posix::close(m_socket); if(m_selfaddr != EDomain::unspec) ::unlink(m_selfaddr.sun_path); } bool AsyncSocket::bind(const char *socket_path, int socket_backlog) noexcept { if(!has_socket()) return false; assert(std::strlen(socket_path) < sizeof(sockaddr_un::sun_path)); m_selfaddr = socket_path; m_selfaddr = EDomain::unix; return m_bound = posix::bind(m_socket, m_selfaddr, m_selfaddr.size()) && posix::listen(m_socket, socket_backlog) && async_spawn(); } bool AsyncSocket::connect(const char *socket_path) noexcept { if(!has_socket()) return false; assert(std::strlen(socket_path) < sizeof(sockaddr_un::sun_path)); posix::sockaddr_t peeraddr; proccred_t peercred; peeraddr = socket_path; peeraddr = EDomain::unix; m_selfaddr = EDomain::unspec; return posix::connect(m_socket, peeraddr, peeraddr.size()) && posix::getpeercred(m_socket, peercred) && async_spawn() && Object::enqueue(connectedToPeer, m_socket, peeraddr, peercred); } bool AsyncSocket::async_spawn(void) noexcept { if(m_iothread.joinable()) // if thread already active return posix::write(m_write_command, &LocalCommand::update, sizeof(uint64_t)) != posix::error_response; // notify thread of an update m_iothread = std::thread(&AsyncSocket::async_io , this); // create a new thread return m_iothread.joinable(); // if thread creation succeeded } void AsyncSocket::async_io(void) noexcept // runs as it's own thread { msghdr msg = {}; iovec iov = {}; char aux_buffer[CMSG_SPACE(sizeof(int))] = { 0 }; uint64_t command_buffer = 0; ssize_t byte_count = 0; msg.msg_iov = &iov; msg.msg_iovlen = 1; msg.msg_control = aux_buffer; for(;;) { if(EventBackend::invoke()) { for(const auto& pos : EventBackend::results()) { if(pos.first == m_read_command && (pos.second & EventFlags_e::Read)) { command_buffer = 0; byte_count = posix::read(pos.first, &command_buffer, sizeof(uint64_t)); if(byte_count == posix::error_response) continue; switch(command_buffer) { case LocalCommand::update: continue; // EventBackend::m_queue size changed case LocalCommand::exit: std::cout << "thread exiting!" << std::endl << std::flush; return; // thread exit case LocalCommand::write: // m_messages isn't empty { for(auto& msg_pos : m_messages) { msg.msg_iov = &iov; msg.msg_iovlen = 1; msg.msg_control = aux_buffer; iov.iov_base = msg_pos.buffer.begin(); iov.iov_len = msg_pos.buffer.size(); msg.msg_controllen = 0; if(msg_pos.fd_buffer != posix::invalid_descriptor) // if a file descriptor needs to be sent { msg.msg_controllen = CMSG_SPACE(sizeof(int)); cmsghdr* cmsg = CMSG_FIRSTHDR(&msg); cmsg->cmsg_level = SOL_SOCKET; cmsg->cmsg_type = SCM_RIGHTS; cmsg->cmsg_len = CMSG_LEN(sizeof(int)); *reinterpret_cast<int*>(CMSG_DATA(cmsg)) = msg_pos.fd_buffer; } byte_count = posix::sendmsg(msg_pos.socket, &msg, 0); if(byte_count == posix::error_response) // error std::cout << std::flush << std::endl << std::red << "sendmsg error: " << std::strerror(errno) << std::none << std::endl << std::flush; else Object::enqueue(writeFinished, msg_pos.socket, byte_count); } m_messages.clear(); } } } else if(m_bound && // if in server mode pos.first == m_socket && // and this is a primary socket pos.second & EventFlags_e::Read) // and it's a read event { proccred_t peercred; posix::sockaddr_t peeraddr; socklen_t addrlen = 0; posix::fd_t fd = posix::accept(m_socket, peeraddr, &addrlen); // accept a new socket connection if(fd == posix::error_response) std::cout << "accept error: " << std::strerror(errno) << std::endl << std::flush; else { if(!EventBackend::watch(fd, EventFlags_e::Read)) // monitor new socket connection std::cout << "watch failure: " << std::strerror(errno) << std::endl << std::flush; if(!posix::getpeercred(fd, peercred)) // get creditials of connected peer process std::cout << "peercred failure: " << std::strerror(errno) << std::endl << std::flush; Object::enqueue(connectedToPeer, fd, peeraddr, peercred); } } else { if(pos.second & (EventFlags_e::Disconnect | EventFlags_e::Error)) // connection severed or connection error { EventBackend::remove(pos.first); // stop watching for events posix::close(pos.first); // close connection if open } else if(pos.second & EventFlags_e::Read) // read { m_incomming.socket = m_bound ? m_socket : m_read_command; // select proper output socket m_incomming.buffer.allocate(); // allocate 64KB buffer iov.iov_base = m_incomming.buffer.data(); iov.iov_len = m_incomming.buffer.capacity(); msg.msg_controllen = sizeof(aux_buffer); byte_count = posix::recvmsg(pos.first, &msg, 0); if(byte_count == posix::error_response) std::cout << std::red << "recvmsg error: " << std::strerror(errno) << std::none << std::endl << std::flush; else if(!byte_count) { EventBackend::remove(pos.first); // stop watching for events posix::close(pos.first); // connection severed! } else if(m_incomming.buffer.expand(byte_count)) { m_incomming.fd_buffer = posix::invalid_descriptor; if(msg.msg_controllen == CMSG_SPACE(sizeof(int))) { cmsghdr* cmsg = CMSG_FIRSTHDR(&msg); if(cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS && cmsg->cmsg_len == CMSG_LEN(sizeof(int))) m_incomming.fd_buffer = *reinterpret_cast<int*>(CMSG_DATA(cmsg)); } else if(msg.msg_flags) std::cout << std::red << "error, message flags: " << std::hex << msg.msg_flags << std::dec << std::none << std::endl << std::flush; Object::enqueue(readFinished, m_incomming.socket, m_incomming); } } else if(pos.second) { std::cout << "unknown event at: " << pos.first << " value: " << std::hex << (int)pos.second << std::dec << std::endl << std::flush; } } } } } } bool AsyncSocket::write(message_t msg) noexcept { if(!is_connected(msg.socket)) return false; m_messages.push_back(msg); posix::write(m_write_command, &LocalCommand::write, sizeof(uint64_t)); return true; } <commit_msg>important commentary<commit_after>#include "asocket.h" // C++ #include <cassert> #include <cstring> #include <cstdint> // STL #include <iostream> // PDTK #include <cxxutils/error_helpers.h> #include <cxxutils/streamcolors.h> #ifndef CMSG_LEN #define CMSG_ALIGN(len) (((len) + sizeof(size_t) - 1) & (size_t) ~ (sizeof(size_t) - 1)) #define CMSG_SPACE(len) (CMSG_ALIGN (len) + CMSG_ALIGN (sizeof (struct cmsghdr))) #define CMSG_LEN(len) (CMSG_ALIGN (sizeof (struct cmsghdr)) + (len)) #endif static_assert(sizeof(uint8_t) == sizeof(char), "size mismatch!"); // NOTE: this is not an enumeration so that each value can be referenced namespace LocalCommand { static const uint64_t write = 1; static const uint64_t update = 2; static const uint64_t exit = 3; } namespace posix { inline bool getpeercred(fd_t sockfd, proccred_t& cred) noexcept { return ::getpeercred(sockfd, cred) == posix::success_response; } } AsyncSocket::AsyncSocket(EDomain domain, EType type, EProtocol protocol, int flags) noexcept : AsyncSocket(posix::socket(domain, type, protocol, flags)) { } AsyncSocket::AsyncSocket(posix::fd_t socket) noexcept : m_socket(socket), m_bound(false) { posix::fd_t cmdio[2]; assert(::pipe(cmdio) != posix::error_response); m_read_command = cmdio[0]; m_write_command = cmdio[1]; EventBackend::watch(m_read_command, EventFlags_e::Read); EventBackend::watch(m_socket, EventFlags_e::Read); } AsyncSocket::~AsyncSocket(void) noexcept { posix::write(m_write_command, &LocalCommand::exit, sizeof(uint64_t)); m_iothread.join(); // wait for thread to exit if(m_socket != posix::invalid_descriptor) posix::close(m_socket); if(m_selfaddr != EDomain::unspec) ::unlink(m_selfaddr.sun_path); } bool AsyncSocket::bind(const char *socket_path, int socket_backlog) noexcept { if(!has_socket()) return false; assert(std::strlen(socket_path) < sizeof(sockaddr_un::sun_path)); m_selfaddr = socket_path; m_selfaddr = EDomain::unix; return m_bound = posix::bind(m_socket, m_selfaddr, m_selfaddr.size()) && posix::listen(m_socket, socket_backlog) && async_spawn(); } bool AsyncSocket::connect(const char *socket_path) noexcept { if(!has_socket()) return false; assert(std::strlen(socket_path) < sizeof(sockaddr_un::sun_path)); posix::sockaddr_t peeraddr; proccred_t peercred; peeraddr = socket_path; peeraddr = EDomain::unix; m_selfaddr = EDomain::unspec; return posix::connect(m_socket, peeraddr, peeraddr.size()) && posix::getpeercred(m_socket, peercred) && async_spawn() && Object::enqueue(connectedToPeer, m_socket, peeraddr, peercred); } bool AsyncSocket::async_spawn(void) noexcept { if(m_iothread.joinable()) // if thread already active return posix::write(m_write_command, &LocalCommand::update, sizeof(uint64_t)) != posix::error_response; // notify thread of an update m_iothread = std::thread(&AsyncSocket::async_io , this); // create a new thread return m_iothread.joinable(); // if thread creation succeeded } void AsyncSocket::async_io(void) noexcept // runs as it's own thread { msghdr msg = {}; iovec iov = {}; char aux_buffer[CMSG_SPACE(sizeof(int))] = { 0 }; uint64_t command_buffer = 0; ssize_t byte_count = 0; msg.msg_iov = &iov; msg.msg_iovlen = 1; msg.msg_control = aux_buffer; for(;;) { if(EventBackend::invoke()) { for(const auto& pos : EventBackend::results()) { if(pos.first == m_read_command && (pos.second & EventFlags_e::Read)) { command_buffer = 0; byte_count = posix::read(pos.first, &command_buffer, sizeof(uint64_t)); if(byte_count == posix::error_response) continue; switch(command_buffer) { case LocalCommand::update: continue; // EventBackend::m_queue size changed case LocalCommand::exit: std::cout << "thread exiting!" << std::endl << std::flush; return; // thread exit case LocalCommand::write: // m_messages isn't empty { for(auto& msg_pos : m_messages) { msg.msg_iov = &iov; msg.msg_iovlen = 1; msg.msg_control = aux_buffer; iov.iov_base = msg_pos.buffer.begin(); iov.iov_len = msg_pos.buffer.size(); msg.msg_controllen = 0; if(msg_pos.fd_buffer != posix::invalid_descriptor) // if a file descriptor needs to be sent { msg.msg_controllen = CMSG_SPACE(sizeof(int)); cmsghdr* cmsg = CMSG_FIRSTHDR(&msg); cmsg->cmsg_level = SOL_SOCKET; cmsg->cmsg_type = SCM_RIGHTS; cmsg->cmsg_len = CMSG_LEN(sizeof(int)); *reinterpret_cast<int*>(CMSG_DATA(cmsg)) = msg_pos.fd_buffer; } byte_count = posix::sendmsg(msg_pos.socket, &msg, 0); if(byte_count == posix::error_response) // error std::cout << std::flush << std::endl << std::red << "sendmsg error: " << std::strerror(errno) << std::none << std::endl << std::flush; else Object::enqueue(writeFinished, msg_pos.socket, byte_count); } m_messages.clear(); } } } else if(m_bound && // if in server mode pos.first == m_socket && // and this is a primary socket pos.second & EventFlags_e::Read) // and it's a read event { proccred_t peercred; posix::sockaddr_t peeraddr; socklen_t addrlen = 0; posix::fd_t fd = posix::accept(m_socket, peeraddr, &addrlen); // accept a new socket connection if(fd == posix::error_response) std::cout << "accept error: " << std::strerror(errno) << std::endl << std::flush; else { if(!EventBackend::watch(fd, EventFlags_e::Read)) // monitor new socket connection std::cout << "watch failure: " << std::strerror(errno) << std::endl << std::flush; if(!posix::getpeercred(fd, peercred)) // get creditials of connected peer process std::cout << "peercred failure: " << std::strerror(errno) << std::endl << std::flush; Object::enqueue(connectedToPeer, fd, peeraddr, peercred); } } else { if(pos.second & (EventFlags_e::Disconnect | EventFlags_e::Error)) // connection severed or connection error { EventBackend::remove(pos.first); // stop watching for events posix::close(pos.first); // close connection if open } else if(pos.second & EventFlags_e::Read) // read { m_incomming.socket = m_bound ? m_socket : m_read_command; // select proper output socket m_incomming.buffer.allocate(); // allocate 64KB buffer iov.iov_base = m_incomming.buffer.data(); iov.iov_len = m_incomming.buffer.capacity(); msg.msg_controllen = sizeof(aux_buffer); byte_count = posix::recvmsg(pos.first, &msg, 0); if(byte_count == posix::error_response) std::cout << std::red << "recvmsg error: " << std::strerror(errno) << std::none << std::endl << std::flush; else if(!byte_count) { EventBackend::remove(pos.first); // stop watching for events posix::close(pos.first); // connection severed! } else if(m_incomming.buffer.expand(byte_count)) { m_incomming.fd_buffer = posix::invalid_descriptor; if(msg.msg_controllen == CMSG_SPACE(sizeof(int))) { cmsghdr* cmsg = CMSG_FIRSTHDR(&msg); if(cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS && cmsg->cmsg_len == CMSG_LEN(sizeof(int))) m_incomming.fd_buffer = *reinterpret_cast<int*>(CMSG_DATA(cmsg)); } else if(msg.msg_flags) std::cout << std::red << "error, message flags: " << std::hex << msg.msg_flags << std::dec << std::none << std::endl << std::flush; Object::enqueue(readFinished, m_incomming.socket, m_incomming); } } else if(pos.second) { std::cout << "unknown event at: " << pos.first << " value: " << std::hex << (int)pos.second << std::dec << std::endl << std::flush; } } } } } } bool AsyncSocket::write(message_t msg) noexcept { if(!is_connected(msg.socket)) return false; m_messages.push_back(msg); posix::write(m_write_command, &LocalCommand::write, sizeof(uint64_t)); return true; } <|endoftext|>
<commit_before>// Copyright 2015 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 <stddef.h> #include <stdint.h> #include <string> #include "flatbuffers/flexbuffers.h" extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { std::vector<bool> reuse_tracker; flexbuffers::VerifyBuffer(data, size, &reuse_tracker); return 0; } <commit_msg>Updated FlexBuffers fuzzer<commit_after>// Copyright 2015 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 <stddef.h> #include <stdint.h> #include <string> #include "flatbuffers/flexbuffers.h" extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { std::vector<uint8_t> reuse_tracker; // Check both with and without reuse tracker paths. flexbuffers::VerifyBuffer(data, size, &reuse_tracker); flexbuffers::VerifyBuffer(data, size, nullptr); return 0; } <|endoftext|>
<commit_before>/** * Copyright (c) 2016-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ #include "utils.h" #include <cmath> #include <ios> namespace utils { real* t_sigmoid; real* t_log; real log(real x) { if (x > 1.0) { return 0.0; } int i = int(x * LOG_TABLE_SIZE); return t_log[i]; } real sigmoid(real x) { if (x < -MAX_SIGMOID) { return 0.0; } else if (x > MAX_SIGMOID) { return 1.0; } else { int i = int((x + MAX_SIGMOID) * SIGMOID_TABLE_SIZE / MAX_SIGMOID / 2); return t_sigmoid[i]; } } void initTables() { initSigmoid(); initLog(); } void initSigmoid() { t_sigmoid = new real[SIGMOID_TABLE_SIZE + 1]; for (int i = 0; i < SIGMOID_TABLE_SIZE + 1; i++) { real x = real(i * 2 * MAX_SIGMOID) / SIGMOID_TABLE_SIZE - MAX_SIGMOID; t_sigmoid[i] = 1.0 / (1.0 + std::exp(-x)); } } void initLog() { t_log = new real[LOG_TABLE_SIZE + 1]; for (int i = 0; i < LOG_TABLE_SIZE + 1; i++) { real x = (real(i) + 1e-5) / LOG_TABLE_SIZE; t_log[i] = std::log(x); } } void freeTables() { delete[] t_sigmoid; delete[] t_log; t_sigmoid = nullptr; t_log = nullptr; } int64_t size(std::ifstream& ifs) { ifs.seekg(std::streamoff(0), std::ios::end); return ifs.tellg(); } void seek(std::ifstream& ifs, int64_t pos) { char c; ifs.clear(); ifs.seekg(std::streampos(pos)); } } <commit_msg>Remove unused variable<commit_after>/** * Copyright (c) 2016-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ #include "utils.h" #include <cmath> #include <ios> namespace utils { real* t_sigmoid; real* t_log; real log(real x) { if (x > 1.0) { return 0.0; } int i = int(x * LOG_TABLE_SIZE); return t_log[i]; } real sigmoid(real x) { if (x < -MAX_SIGMOID) { return 0.0; } else if (x > MAX_SIGMOID) { return 1.0; } else { int i = int((x + MAX_SIGMOID) * SIGMOID_TABLE_SIZE / MAX_SIGMOID / 2); return t_sigmoid[i]; } } void initTables() { initSigmoid(); initLog(); } void initSigmoid() { t_sigmoid = new real[SIGMOID_TABLE_SIZE + 1]; for (int i = 0; i < SIGMOID_TABLE_SIZE + 1; i++) { real x = real(i * 2 * MAX_SIGMOID) / SIGMOID_TABLE_SIZE - MAX_SIGMOID; t_sigmoid[i] = 1.0 / (1.0 + std::exp(-x)); } } void initLog() { t_log = new real[LOG_TABLE_SIZE + 1]; for (int i = 0; i < LOG_TABLE_SIZE + 1; i++) { real x = (real(i) + 1e-5) / LOG_TABLE_SIZE; t_log[i] = std::log(x); } } void freeTables() { delete[] t_sigmoid; delete[] t_log; t_sigmoid = nullptr; t_log = nullptr; } int64_t size(std::ifstream& ifs) { ifs.seekg(std::streamoff(0), std::ios::end); return ifs.tellg(); } void seek(std::ifstream& ifs, int64_t pos) { ifs.clear(); ifs.seekg(std::streampos(pos)); } } <|endoftext|>
<commit_before>#ifndef utils_hh_INCLUDED #define utils_hh_INCLUDED #include "exception.hh" #include "assert.hh" #include <memory> #include <algorithm> namespace Kakoune { // *** Singleton *** // // Singleton helper class, every singleton type T should inherit // from Singleton<T> to provide a consistent interface. template<typename T> class Singleton { public: Singleton(const Singleton&) = delete; Singleton& operator=(const Singleton&) = delete; static T& instance() { assert (ms_instance); return *ms_instance; } static void delete_instance() { delete ms_instance; ms_instance = nullptr; } protected: Singleton() { assert(not ms_instance); ms_instance = static_cast<T*>(this); } ~Singleton() { assert(ms_instance == this); ms_instance = nullptr; } private: static T* ms_instance; }; template<typename T> T* Singleton<T>::ms_instance = nullptr; // *** Containers helpers *** template<typename Container> struct ReversedContainer { ReversedContainer(Container& container) : container(container) {} Container& container; decltype(container.rbegin()) begin() { return container.rbegin(); } decltype(container.rend()) end() { return container.rend(); } }; template<typename Container> ReversedContainer<Container> reversed(Container& container) { return ReversedContainer<Container>(container); } template<typename Container, typename T> auto find(Container& container, const T& value) -> decltype(container.begin()) { return std::find(container.begin(), container.end(), value); } template<typename Container, typename T> bool contains(const Container& container, const T& value) { return find(container, value) != container.end(); } // *** On scope end *** // // on_scope_end provides a way to register some code to be // executed when current scope closes. // // usage: // auto cleaner = on_scope_end([]() { ... }); // // This permits to cleanup c-style resources without implementing // a wrapping class template<typename T> class OnScopeEnd { public: OnScopeEnd(T func) : m_func(func) {} ~OnScopeEnd() { m_func(); } private: T m_func; }; template<typename T> OnScopeEnd<T> on_scope_end(T t) { return OnScopeEnd<T>(t); } // *** Misc helper functions *** template<typename T> bool operator== (const std::unique_ptr<T>& lhs, T* rhs) { return lhs.get() == rhs; } } #endif // utils_hh_INCLUDED <commit_msg>Add SafeCountable and safe_ptr classes<commit_after>#ifndef utils_hh_INCLUDED #define utils_hh_INCLUDED #include "exception.hh" #include "assert.hh" #include <memory> #include <algorithm> namespace Kakoune { // *** Singleton *** // // Singleton helper class, every singleton type T should inherit // from Singleton<T> to provide a consistent interface. template<typename T> class Singleton { public: Singleton(const Singleton&) = delete; Singleton& operator=(const Singleton&) = delete; static T& instance() { assert (ms_instance); return *ms_instance; } static void delete_instance() { delete ms_instance; ms_instance = nullptr; } protected: Singleton() { assert(not ms_instance); ms_instance = static_cast<T*>(this); } ~Singleton() { assert(ms_instance == this); ms_instance = nullptr; } private: static T* ms_instance; }; template<typename T> T* Singleton<T>::ms_instance = nullptr; // *** safe_ptr: objects that assert nobody references them when they die *** typedef void* (*unspecified_bool_type)(); template<typename T> class safe_ptr { public: safe_ptr() : m_ptr(nullptr) {} explicit safe_ptr(T* ptr) : m_ptr(ptr) { if (ptr) ptr->inc_safe_count(); } safe_ptr(const safe_ptr& other) : safe_ptr(other.m_ptr) {} safe_ptr(safe_ptr&& other) : m_ptr(other.m_ptr) { other.m_ptr = nullptr; } ~safe_ptr() { if (m_ptr) m_ptr->dec_safe_count(); } safe_ptr& operator=(const safe_ptr& other) { if (m_ptr != other.m_ptr) { if (m_ptr) m_ptr->dec_safe_count(); m_ptr = other.m_ptr; if (m_ptr) m_ptr->inc_safe_count(); } return *this; } bool operator== (const safe_ptr& other) const { return m_ptr == other.m_ptr; } bool operator!= (const safe_ptr& other) const { return m_ptr != other.m_ptr; } bool operator== (T* ptr) const { return m_ptr == ptr; } bool operator!= (T* ptr) const { return m_ptr != ptr; } T& operator* () const { return *m_ptr; } T* operator-> () const { return m_ptr; } T* get() const { return m_ptr; } operator unspecified_bool_type() const { return (unspecified_bool_type)(m_ptr); } private: T* m_ptr; }; class SafeCountable { public: SafeCountable() : m_count(0) {} ~SafeCountable() { assert(m_count == 0); } void inc_safe_count() { ++m_count; } void dec_safe_count() { --m_count; assert(m_count >= 0); } private: int m_count; }; // *** Containers helpers *** template<typename Container> struct ReversedContainer { ReversedContainer(Container& container) : container(container) {} Container& container; decltype(container.rbegin()) begin() { return container.rbegin(); } decltype(container.rend()) end() { return container.rend(); } }; template<typename Container> ReversedContainer<Container> reversed(Container& container) { return ReversedContainer<Container>(container); } template<typename Container, typename T> auto find(Container& container, const T& value) -> decltype(container.begin()) { return std::find(container.begin(), container.end(), value); } template<typename Container, typename T> bool contains(const Container& container, const T& value) { return find(container, value) != container.end(); } // *** On scope end *** // // on_scope_end provides a way to register some code to be // executed when current scope closes. // // usage: // auto cleaner = on_scope_end([]() { ... }); // // This permits to cleanup c-style resources without implementing // a wrapping class template<typename T> class OnScopeEnd { public: OnScopeEnd(T func) : m_func(func) {} ~OnScopeEnd() { m_func(); } private: T m_func; }; template<typename T> OnScopeEnd<T> on_scope_end(T t) { return OnScopeEnd<T>(t); } // *** Misc helper functions *** template<typename T> bool operator== (const std::unique_ptr<T>& lhs, T* rhs) { return lhs.get() == rhs; } } #endif // utils_hh_INCLUDED <|endoftext|>