commit
stringlengths
40
40
old_file
stringlengths
2
205
new_file
stringlengths
2
205
old_contents
stringlengths
0
32.9k
new_contents
stringlengths
1
38.9k
subject
stringlengths
3
9.4k
message
stringlengths
6
9.84k
lang
stringlengths
3
13
license
stringclasses
13 values
repos
stringlengths
6
115k
0a85184cb7629532b469cb407b9f34e0992cf17f
OpenSim/Common/Test/testStorage.cpp
OpenSim/Common/Test/testStorage.cpp
/* -------------------------------------------------------------------------- * * OpenSim: testStorage.cpp * * -------------------------------------------------------------------------- * * The OpenSim API is a toolkit for musculoskeletal modeling and simulation. * * See http://opensim.stanford.edu and the NOTICE file for more information. * * OpenSim is developed at Stanford University and supported by the US * * National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA * * through the Warrior Web program. * * * * Copyright (c) 2005-2017 Stanford University and the Authors * * * * Licensed under the Apache License, Version 2.0 (the "License"); you may * * not use this file except in compliance with the License. You may obtain a * * copy of the License at http://www.apache.org/licenses/LICENSE-2.0. * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * * -------------------------------------------------------------------------- */ #include <fstream> #include <OpenSim/Common/Storage.h> #include <OpenSim/Auxiliary/auxiliaryTestFunctions.h> using namespace OpenSim; using namespace std; void testStorageLoadingFromFile(const std::string& fileName, const int ncols); void testStorageLegacy() { // Create a storage from a std file "std_storage.sto" //ofstream checkRunDirFile("rundir.txt"); //checkRunDirFile << "Run from here:\n\n"; //checkRunDirFile.close(); string stdLabels[] = { "time", "v1", "v2" }; std::unique_ptr<Storage> st(new Storage("test.sto")); // time[\t]v1[\t]v2 // 1.[\t] 10.0[Space]20 // 2.[\t\t] 20.0[\t]40 ASSERT(st->getSize() == 2); const Array<std::string> &lbls = st->getColumnLabels(); ASSERT(lbls.getSize() == 3); int i = 0; for (i = 0; i<lbls.getSize(); i++) { ASSERT(lbls[i] == stdLabels[i]); } double val; for (i = 0; i<st->getSize(); i++) { StateVector& row = (*st->getStateVector(i)); ASSERT(row.getTime() == i + 1); ASSERT(row.getData()[0] == row.getTime()*10.0); row.getDataValue(0, val); ASSERT(val == row.getTime()*10.0); ASSERT(row.getData()[0] == row.getTime()*10.0); ASSERT(row.getData()[1] == row.getTime()*20.0); } int ncol = st->getSmallestNumberOfStates(); ASSERT(ncol == 2); Array<double> col(SimTK::CNT<SimTK::Real>::getNaN(), 4); st->getDataColumn(1, col); ASSERT(col[0] == 20.); ASSERT(col[1] == 40.0); ASSERT(st->getStateIndex("v2") == 1); Storage st2("testDiff.sto"); // Test Comparison double diff = st->compareColumn(st2, stdLabels[1], 0.); ASSERT(fabs(diff) < 1E-7); diff = st->compareColumn(st2, stdLabels[2], 0.); ASSERT(fabs(diff) < 1E-7); // Loading version 2 storage file with Storage class. auto table = st->exportToTable(); STOFileAdapter::write(table, "testStorage_version2.sto"); { // Now read using Storage() constructor. Storage stVersion2("testStorage_version2.sto"); // Compare with st. SimTK_TEST_EQ(table.getMatrix(), stVersion2.exportToTable().getMatrix()); } // The version 2 storage file does not require nRows and nColumns // metadata (Issue #2120). { table.removeTableMetaDataKey("nRows"); table.removeTableMetaDataKey("nColumns"); STOFileAdapter::write(table, "testStorage_version2_short_header.sto"); Storage stVersion2("testStorage_version2_short_header.sto"); SimTK_TEST_EQ(table.getMatrix(), stVersion2.exportToTable().getMatrix()); } } int main() { SimTK_START_TEST("testStorage"); // Verify the loading scalar Outputs (2) from ..sto into a Storage SimTK_SUBTEST2(testStorageLoadingFromFile, "sampleOutputs.sto", 2+1); // Verify the loading Vec3 Outputs (2) from .sto into a Storage SimTK_SUBTEST2(testStorageLoadingFromFile, "sampleOutputsVec3.sto", 2*3+1); // Verify the loading SpatialVec Outputs (2) from .sto into a Storage SimTK_SUBTEST2(testStorageLoadingFromFile, "sampleOutputsSpatialVec.sto", 2*6+1); // Verify the loading of marker data (14) from .trc into a Storage SimTK_SUBTEST2(testStorageLoadingFromFile, "TRCFileWithNANs.trc", 43); // Verify the loading of forces from .c3d into a Storage. Includes 2 // force-plates with force, point, moment vectors (Vec3 flattened) SimTK_SUBTEST2(testStorageLoadingFromFile, "walking2.c3d", 3*6+1); SimTK_SUBTEST(testStorageLegacy); SimTK_END_TEST(); } void testStorageLoadingFromFile(const std::string& fileName, const int numCols) { Storage storage{ fileName}; // remove extension auto ix = fileName.rfind("."); if (ix == std::string::npos) { throw Exception("File name for Storage loading '" + fileName + "' must have a valid extension."); } std::string name = fileName.substr(0, ix-1); Array<std::string> labels = storage.getColumnLabels(); storage.print("test_" + name + ".sto"); ASSERT(numCols == labels.size()); }
/* -------------------------------------------------------------------------- * * OpenSim: testStorage.cpp * * -------------------------------------------------------------------------- * * The OpenSim API is a toolkit for musculoskeletal modeling and simulation. * * See http://opensim.stanford.edu and the NOTICE file for more information. * * OpenSim is developed at Stanford University and supported by the US * * National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA * * through the Warrior Web program. * * * * Copyright (c) 2005-2017 Stanford University and the Authors * * * * Licensed under the Apache License, Version 2.0 (the "License"); you may * * not use this file except in compliance with the License. You may obtain a * * copy of the License at http://www.apache.org/licenses/LICENSE-2.0. * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * * -------------------------------------------------------------------------- */ #include <fstream> #include <OpenSim/Common/Storage.h> #include <OpenSim/Auxiliary/auxiliaryTestFunctions.h> using namespace OpenSim; using namespace std; void testStorageLoadingFromFile(const std::string& fileName, const int ncols); void testStorageLegacy() { // Create a storage from a std file "std_storage.sto" //ofstream checkRunDirFile("rundir.txt"); //checkRunDirFile << "Run from here:\n\n"; //checkRunDirFile.close(); string stdLabels[] = { "time", "v1", "v2" }; std::unique_ptr<Storage> st(new Storage("test.sto")); // time[\t]v1[\t]v2 // 1.[\t] 10.0[Space]20 // 2.[\t\t] 20.0[\t]40 ASSERT(st->getSize() == 2); const Array<std::string> &lbls = st->getColumnLabels(); ASSERT(lbls.getSize() == 3); int i = 0; for (i = 0; i<lbls.getSize(); i++) { ASSERT(lbls[i] == stdLabels[i]); } double val; for (i = 0; i<st->getSize(); i++) { StateVector& row = (*st->getStateVector(i)); ASSERT(row.getTime() == i + 1); ASSERT(row.getData()[0] == row.getTime()*10.0); row.getDataValue(0, val); ASSERT(val == row.getTime()*10.0); ASSERT(row.getData()[0] == row.getTime()*10.0); ASSERT(row.getData()[1] == row.getTime()*20.0); } int ncol = st->getSmallestNumberOfStates(); ASSERT(ncol == 2); Array<double> col(SimTK::CNT<SimTK::Real>::getNaN(), 4); st->getDataColumn(1, col); ASSERT(col[0] == 20.); ASSERT(col[1] == 40.0); ASSERT(st->getStateIndex("v2") == 1); Storage st2("testDiff.sto"); // Test Comparison double diff = st->compareColumn(st2, stdLabels[1], 0.); ASSERT(fabs(diff) < 1E-7); diff = st->compareColumn(st2, stdLabels[2], 0.); ASSERT(fabs(diff) < 1E-7); // Loading version 2 storage file with Storage class. auto table = st->exportToTable(); STOFileAdapter::write(table, "testStorage_version2.sto"); { // Now read using Storage() constructor. Storage stVersion2("testStorage_version2.sto"); // Compare with st. SimTK_TEST_EQ(table.getMatrix(), stVersion2.exportToTable().getMatrix()); } // The version 2 storage file does not require nRows and nColumns // metadata (Issue #2120). { table.removeTableMetaDataKey("nRows"); table.removeTableMetaDataKey("nColumns"); STOFileAdapter::write(table, "testStorage_version2_short_header.sto"); Storage stVersion2("testStorage_version2_short_header.sto"); SimTK_TEST_EQ(table.getMatrix(), stVersion2.exportToTable().getMatrix()); } } int main() { SimTK_START_TEST("testStorage"); // Verify loading of scalar Outputs (there are 2) from .sto into a Storage SimTK_SUBTEST2(testStorageLoadingFromFile, "sampleOutputs.sto", 2+1); // Verify loading of Vec3 Outputs (2) from .sto into a Storage SimTK_SUBTEST2(testStorageLoadingFromFile, "sampleOutputsVec3.sto", 2*3+1); // Verify loading of SpatialVec Outputs (2) from .sto into a Storage SimTK_SUBTEST2(testStorageLoadingFromFile, "sampleOutputsSpatialVec.sto", 2*6+1); // Verify the loading of marker data (14 markers) from .trc into a Storage SimTK_SUBTEST2(testStorageLoadingFromFile, "TRCFileWithNANs.trc", 43); // Verify the loading of forces from .c3d into a Storage. Includes 2 // force-plates with force, point, moment vectors (Vec3 flattened) SimTK_SUBTEST2(testStorageLoadingFromFile, "walking2.c3d", 3*6+1); SimTK_SUBTEST(testStorageLegacy); SimTK_END_TEST(); } void testStorageLoadingFromFile(const std::string& fileName, const int numCols) { Storage storage{ fileName}; // remove extension auto ix = fileName.rfind("."); if (ix == std::string::npos) { throw Exception("File name for Storage loading '" + fileName + "' must have a valid extension."); } std::string name = fileName.substr(0, ix-1); Array<std::string> labels = storage.getColumnLabels(); storage.print("test_" + name + ".sto"); ASSERT(numCols == labels.size()); }
Update test case comments
Update test case comments [ci skip] [appveyor skip]
C++
apache-2.0
opensim-org/opensim-core,opensim-org/opensim-core,opensim-org/opensim-core,opensim-org/opensim-core,opensim-org/opensim-core,opensim-org/opensim-core,opensim-org/opensim-core
6ac00a982914c709f38f36c91a32a185147379f5
source/qcan/qcan_defs.hpp
source/qcan/qcan_defs.hpp
//============================================================================// // File: qcan_defs.hpp // // Description: QCAN classes - Definitions // // // // Copyright 2017 MicroControl GmbH & Co. KG // // 53844 Troisdorf - Germany // // www.microcontrol.net // // // //----------------------------------------------------------------------------// // Redistribution and use in source and binary forms, with or without // // modification, are permitted provided that the following conditions // // are met: // // 1. Redistributions of source code must retain the above copyright // // notice, this list of conditions, the following disclaimer and // // the referenced file 'LICENSE'. // // 2. Redistributions in binary form must reproduce the above copyright // // notice, this list of conditions and the following disclaimer in the // // documentation and/or other materials provided with the distribution. // // 3. Neither the name of MicroControl nor the names of its contributors // // may be used to endorse or promote products derived from this software // // without specific prior written permission. // // // // Licensed under the Apache License, Version 2.0 (the "License"); // // you may not use this file except in compliance with the License. // // You may obtain a copy of the License at // // // // http://www.apache.org/licenses/LICENSE-2.0 // // // // Unless required by applicable law or agreed to in writing, software // // distributed under the License is distributed on an "AS IS" BASIS, // // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // // limitations under the License. // //============================================================================// #ifndef QCAN_DEFS_HPP_ #define QCAN_DEFS_HPP_ //----------------------------------------------------------------------------- /*! ** \file qcan_defs.hpp ** \brief Global QCan definitions ** ** This file holds global definitions for the QCanServer and QCanInterface ** classes. ** */ /*----------------------------------------------------------------------------*\ ** Definitions ** ** ** \*----------------------------------------------------------------------------*/ //------------------------------------------------------------------- /*! ** \defgroup QCAN_NW QCan network definitions ** ** */ //------------------------------------------------------------------- /*! ** \def QCAN_TCP_DEFAULT_PORT ** \ingroup QCAN_NW ** \brief Default port for TCP server ** ** This symbol defines the default TCP port for the server. */ #define QCAN_TCP_DEFAULT_PORT 55660 //------------------------------------------------------------------- /*! ** \def QCAN_TCP_SOCKET_MAX ** \ingroup QCAN_NW ** \brief Maximum number of TCP sockets ** ** This symbol defines the maximum number of sockets connected to ** the TCP server. */ #define QCAN_TCP_SOCKET_MAX 16 //------------------------------------------------------------------- /*! ** \def QCAN_NETWORK_MAX ** \ingroup QCAN_NW ** \brief Maximum number of networks ** ** This symbol defines the maximum number of networks. */ #define QCAN_NETWORK_MAX 8 //------------------------------------------------------------------- /*! ** \defgroup QCAN_IF QCan interface definitions ** ** The QCan interface definitions are used by the method ** QCanInterface::supportedFeatures(). */ //------------------------------------------------------------------- /*! ** \def QCAN_IF_SUPPORT_ERROR_FRAMES ** \ingroup QCAN_IF ** \brief Support error frames ** ** The bit-mask value defines if error frames are supported by ** a CAN interface. */ #define QCAN_IF_SUPPORT_ERROR_FRAMES ((uint32_t) (0x00000001)) //------------------------------------------------------------------- /*! ** \def QCAN_IF_SUPPORT_LISTEN_ONLY ** \ingroup QCAN_IF ** \brief Support listen-only mode ** ** The bit-mask value defines if the listen-only mode is supported by ** a CAN interface. */ #define QCAN_IF_SUPPORT_LISTEN_ONLY ((uint32_t) (0x00000002)) //------------------------------------------------------------------- /*! ** \def QCAN_IF_SUPPORT_CAN_FD ** \ingroup QCAN_IF ** \brief Support CAN FD ** ** The bit-mask value defines if CAN FD is supported by ** a CAN interface. */ #define QCAN_IF_SUPPORT_CAN_FD ((uint32_t) (0x00000004)) #endif // QCAN_DEFS_HPP_
//============================================================================// // File: qcan_defs.hpp // // Description: QCAN classes - Definitions // // // // Copyright 2017 MicroControl GmbH & Co. KG // // 53844 Troisdorf - Germany // // www.microcontrol.net // // // //----------------------------------------------------------------------------// // Redistribution and use in source and binary forms, with or without // // modification, are permitted provided that the following conditions // // are met: // // 1. Redistributions of source code must retain the above copyright // // notice, this list of conditions, the following disclaimer and // // the referenced file 'LICENSE'. // // 2. Redistributions in binary form must reproduce the above copyright // // notice, this list of conditions and the following disclaimer in the // // documentation and/or other materials provided with the distribution. // // 3. Neither the name of MicroControl nor the names of its contributors // // may be used to endorse or promote products derived from this software // // without specific prior written permission. // // // // Licensed under the Apache License, Version 2.0 (the "License"); // // you may not use this file except in compliance with the License. // // You may obtain a copy of the License at // // // // http://www.apache.org/licenses/LICENSE-2.0 // // // // Unless required by applicable law or agreed to in writing, software // // distributed under the License is distributed on an "AS IS" BASIS, // // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // // limitations under the License. // //============================================================================// #ifndef QCAN_DEFS_HPP_ #define QCAN_DEFS_HPP_ //----------------------------------------------------------------------------- /*! ** \file qcan_defs.hpp ** \brief Global QCan definitions ** ** This file holds global definitions for the QCanServer and QCanInterface ** classes. ** */ /*----------------------------------------------------------------------------*\ ** Definitions ** ** ** \*----------------------------------------------------------------------------*/ //------------------------------------------------------------------- /*! ** \defgroup QCAN_NW QCan network definitions ** ** */ //------------------------------------------------------------------- /*! ** \def QCAN_TCP_DEFAULT_PORT ** \ingroup QCAN_NW ** \brief Default port for TCP server ** ** This symbol defines the default TCP port for the server. */ #define QCAN_TCP_DEFAULT_PORT 55660 //------------------------------------------------------------------- /*! ** \def QCAN_TCP_SOCKET_MAX ** \ingroup QCAN_NW ** \brief Maximum number of TCP sockets ** ** This symbol defines the maximum number of sockets connected to ** the TCP server. */ #define QCAN_TCP_SOCKET_MAX 16 #define QCAN_LOCAL_SOCKET_MAX 16 //------------------------------------------------------------------- /*! ** \def QCAN_NETWORK_MAX ** \ingroup QCAN_NW ** \brief Maximum number of networks ** ** This symbol defines the maximum number of networks. */ #define QCAN_NETWORK_MAX 8 //------------------------------------------------------------------- /*! ** \defgroup QCAN_IF QCan interface definitions ** ** The QCan interface definitions are used by the method ** QCanInterface::supportedFeatures(). */ //------------------------------------------------------------------- /*! ** \def QCAN_IF_SUPPORT_ERROR_FRAMES ** \ingroup QCAN_IF ** \brief Support error frames ** ** The bit-mask value defines if error frames are supported by ** a CAN interface. */ #define QCAN_IF_SUPPORT_ERROR_FRAMES ((uint32_t) (0x00000001)) //------------------------------------------------------------------- /*! ** \def QCAN_IF_SUPPORT_LISTEN_ONLY ** \ingroup QCAN_IF ** \brief Support listen-only mode ** ** The bit-mask value defines if the listen-only mode is supported by ** a CAN interface. */ #define QCAN_IF_SUPPORT_LISTEN_ONLY ((uint32_t) (0x00000002)) //------------------------------------------------------------------- /*! ** \def QCAN_IF_SUPPORT_CAN_FD ** \ingroup QCAN_IF ** \brief Support CAN FD ** ** The bit-mask value defines if CAN FD is supported by ** a CAN interface. */ #define QCAN_IF_SUPPORT_CAN_FD ((uint32_t) (0x00000004)) //------------------------------------------------------------------- /*! ** \def QCAN_IF_SUPPORT_SPECIFIC_CONFIG ** \ingroup QCAN_IF ** \brief Support device specific configuration ** ** The bit-mask value defines if CAN interface supports ** device specific configuration. */ #define QCAN_IF_SUPPORT_SPECIFIC_CONFIG ((uint32_t) (0x00000008)) #endif // QCAN_DEFS_HPP_
Introduce symbols QCAN_LOCAL_SOCKET_MAX and QCAN_IF_SUPPORT_SPECIFIC_CONFIG
Introduce symbols QCAN_LOCAL_SOCKET_MAX and QCAN_IF_SUPPORT_SPECIFIC_CONFIG
C++
apache-2.0
canpie/CANpie,canpie/CANpie,JoTid/CANpie,JoTid/CANpie,canpie/CANpie,JoTid/CANpie
19c43416e3c488d84fa45a39a63c3af61be5ca6d
Charts/vtkOpenGLContextDevice3D.cxx
Charts/vtkOpenGLContextDevice3D.cxx
/*========================================================================= Program: Visualization Toolkit Module: vtkOpenGLContextDevice3D.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkOpenGLContextDevice3D.h" #include "vtkBrush.h" #include "vtkPen.h" #include "vtkMatrix4x4.h" #include "vtkOpenGLRenderer.h" #include "vtkOpenGLRenderWindow.h" #include "vtkOpenGLExtensionManager.h" #include "vtkgl.h" #include "vtkObjectFactory.h" class vtkOpenGLContextDevice3D::Private { public: Private() { this->SavedLighting = GL_TRUE; this->SavedDepthTest = GL_TRUE; } ~Private() { } void SaveGLState() { this->SavedLighting = glIsEnabled(GL_LIGHTING); this->SavedDepthTest = glIsEnabled(GL_DEPTH_TEST); this->SavedBlending = glIsEnabled(GL_BLEND); } void RestoreGLState() { this->SetGLCapability(GL_LIGHTING, this->SavedLighting); this->SetGLCapability(GL_DEPTH_TEST, this->SavedDepthTest); this->SetGLCapability(GL_BLEND, this->SavedBlending); } void SetGLCapability(GLenum capability, GLboolean state) { if (state) { glEnable(capability); } else { glDisable(capability); } } void Transpose(double *in, double *transposed) { transposed[0] = in[0]; transposed[1] = in[4]; transposed[2] = in[8]; transposed[3] = in[12]; transposed[4] = in[1]; transposed[5] = in[5]; transposed[6] = in[9]; transposed[7] = in[13]; transposed[8] = in[2]; transposed[9] = in[6]; transposed[10] = in[10]; transposed[11] = in[14]; transposed[12] = in[3]; transposed[13] = in[7]; transposed[14] = in[11]; transposed[15] = in[15]; } void SetLineType(int type) { if (type == vtkPen::SOLID_LINE) { glDisable(GL_LINE_STIPPLE); } else { glEnable(GL_LINE_STIPPLE); } GLushort pattern = 0x0000; switch (type) { case vtkPen::NO_PEN: pattern = 0x0000; break; case vtkPen::DASH_LINE: pattern = 0x00FF; break; case vtkPen::DOT_LINE: pattern = 0x0101; break; case vtkPen::DASH_DOT_LINE: pattern = 0x0C0F; break; case vtkPen::DASH_DOT_DOT_LINE: pattern = 0x1C47; break; default: pattern = 0x0000; } glLineStipple(1, pattern); } // Store the previous GL state so that we can restore it when complete GLboolean SavedLighting; GLboolean SavedDepthTest; GLboolean SavedBlending; vtkVector2i Dim; vtkVector2i Offset; }; vtkStandardNewMacro(vtkOpenGLContextDevice3D) vtkOpenGLContextDevice3D::vtkOpenGLContextDevice3D() : Storage(new Private) { } vtkOpenGLContextDevice3D::~vtkOpenGLContextDevice3D() { delete Storage; } void vtkOpenGLContextDevice3D::DrawPoly(const float *verts, int n, const unsigned char *colors, int nc) { assert("verts must be non-null" && verts != NULL); assert("n must be greater than 0" && n > 0); this->Storage->SetLineType(this->Pen->GetLineType()); glLineWidth(this->Pen->GetWidth()); if (colors) { glEnableClientState(GL_COLOR_ARRAY); glColorPointer(nc, GL_UNSIGNED_BYTE, 0, colors); } else { glColor4ubv(this->Pen->GetColor()); } glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(3, GL_FLOAT, 0, verts); glDrawArrays(GL_LINE_STRIP, 0, n); glDisableClientState(GL_VERTEX_ARRAY); if (colors) { glDisableClientState(GL_COLOR_ARRAY); } } void vtkOpenGLContextDevice3D::DrawPoints(const float *verts, int n, const unsigned char *colors, int nc) { assert("verts must be non-null" && verts != NULL); assert("n must be greater than 0" && n > 0); glPointSize(this->Pen->GetWidth()); glEnableClientState(GL_VERTEX_ARRAY); if (colors && nc) { glEnableClientState(GL_COLOR_ARRAY); glColorPointer(nc, GL_UNSIGNED_BYTE, 0, colors); } else { glColor4ubv(this->Pen->GetColor()); } glVertexPointer(3, GL_FLOAT, 0, verts); glDrawArrays(GL_POINTS, 0, n); glDisableClientState(GL_VERTEX_ARRAY); if (colors && nc) { glDisableClientState(GL_COLOR_ARRAY); } } void vtkOpenGLContextDevice3D::ApplyPen(vtkPen *pen) { this->Pen->DeepCopy(pen); } void vtkOpenGLContextDevice3D::ApplyBrush(vtkBrush *brush) { this->Brush->DeepCopy(brush); } void vtkOpenGLContextDevice3D::SetMatrix(vtkMatrix4x4 *m) { double matrix[16]; double *M = m->Element[0]; this->Storage->Transpose(M, matrix); glLoadMatrixd(matrix); } void vtkOpenGLContextDevice3D::GetMatrix(vtkMatrix4x4 *m) { double *M = m->Element[0]; m->Transpose(); double matrix[16]; glGetDoublev(GL_MODELVIEW_MATRIX, matrix); this->Storage->Transpose(M, matrix); } void vtkOpenGLContextDevice3D::MultiplyMatrix(vtkMatrix4x4 *m) { double matrix[16]; double *M = m->Element[0]; this->Storage->Transpose(M, matrix); glMultMatrixd(matrix); } void vtkOpenGLContextDevice3D::PushMatrix() { glMatrixMode(GL_MODELVIEW); glPushMatrix(); } void vtkOpenGLContextDevice3D::PopMatrix() { glMatrixMode(GL_MODELVIEW); glPopMatrix(); } void vtkOpenGLContextDevice3D::SetClipping(const vtkRecti &rect) { // Check the bounds, and clamp if necessary GLint vp[4] = { this->Storage->Offset.GetX(), this->Storage->Offset.GetY(), this->Storage->Dim.GetX(), this->Storage->Dim.GetY()}; if (rect.X() > 0 && rect.X() < vp[2] ) { vp[0] += rect.X(); } if (rect.Y() > 0 && rect.Y() < vp[3]) { vp[1] += rect.Y(); } if (rect.Width() > 0 && rect.Width() < vp[2]) { vp[2] = rect.Width(); } if (rect.Height() > 0 && rect.Height() < vp[3]) { vp[3] = rect.Height(); } glScissor(vp[0], vp[1], vp[2], vp[3]); } void vtkOpenGLContextDevice3D::EnableClipping(bool enable) { if (enable) { glEnable(GL_SCISSOR_TEST); } else { glDisable(GL_SCISSOR_TEST); } } void vtkOpenGLContextDevice3D::Begin(vtkViewport* viewport) { // Need the actual pixel size of the viewport - ask OpenGL. GLint vp[4]; glGetIntegerv(GL_VIEWPORT, vp); this->Storage->Offset.Set(static_cast<int>(vp[0]), static_cast<int>(vp[1])); this->Storage->Dim.Set(static_cast<int>(vp[2]), static_cast<int>(vp[3])); // push a 2D matrix on the stack glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); float offset = 0.5; glOrtho(offset, vp[2]+offset-1.0, offset, vp[3]+offset-1.0, -1000, 1000); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); // Store the previous state before changing it this->Storage->SaveGLState(); glDisable(GL_LIGHTING); glDisable(GL_DEPTH_TEST); glEnable(GL_BLEND); this->Renderer = vtkRenderer::SafeDownCast(viewport); this->InRender = true; } void vtkOpenGLContextDevice3D::End() { if (!this->InRender) { return; } // push a 2D matrix on the stack glMatrixMode(GL_PROJECTION); glPopMatrix(); glMatrixMode(GL_MODELVIEW); glPopMatrix(); // Restore the GL state that we changed this->Storage->RestoreGLState(); this->InRender = false; } void vtkOpenGLContextDevice3D::PrintSelf(ostream &os, vtkIndent indent) { Superclass::PrintSelf(os, indent); }
/*========================================================================= Program: Visualization Toolkit Module: vtkOpenGLContextDevice3D.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkOpenGLContextDevice3D.h" #include "vtkBrush.h" #include "vtkPen.h" #include "vtkMatrix4x4.h" #include "vtkOpenGLRenderer.h" #include "vtkOpenGLRenderWindow.h" #include "vtkOpenGLExtensionManager.h" #include "vtkgl.h" #include "vtkObjectFactory.h" class vtkOpenGLContextDevice3D::Private { public: Private() { this->SavedLighting = GL_TRUE; this->SavedDepthTest = GL_TRUE; } ~Private() { } void SaveGLState() { this->SavedLighting = glIsEnabled(GL_LIGHTING); this->SavedDepthTest = glIsEnabled(GL_DEPTH_TEST); this->SavedBlending = glIsEnabled(GL_BLEND); } void RestoreGLState() { this->SetGLCapability(GL_LIGHTING, this->SavedLighting); this->SetGLCapability(GL_DEPTH_TEST, this->SavedDepthTest); this->SetGLCapability(GL_BLEND, this->SavedBlending); } void SetGLCapability(GLenum capability, GLboolean state) { if (state) { glEnable(capability); } else { glDisable(capability); } } void Transpose(double *in, double *transposed) { transposed[0] = in[0]; transposed[1] = in[4]; transposed[2] = in[8]; transposed[3] = in[12]; transposed[4] = in[1]; transposed[5] = in[5]; transposed[6] = in[9]; transposed[7] = in[13]; transposed[8] = in[2]; transposed[9] = in[6]; transposed[10] = in[10]; transposed[11] = in[14]; transposed[12] = in[3]; transposed[13] = in[7]; transposed[14] = in[11]; transposed[15] = in[15]; } void SetLineType(int type) { if (type == vtkPen::SOLID_LINE) { glDisable(GL_LINE_STIPPLE); } else { glEnable(GL_LINE_STIPPLE); } GLushort pattern = 0x0000; switch (type) { case vtkPen::NO_PEN: pattern = 0x0000; break; case vtkPen::DASH_LINE: pattern = 0x00FF; break; case vtkPen::DOT_LINE: pattern = 0x0101; break; case vtkPen::DASH_DOT_LINE: pattern = 0x0C0F; break; case vtkPen::DASH_DOT_DOT_LINE: pattern = 0x1C47; break; default: pattern = 0x0000; } glLineStipple(1, pattern); } // Store the previous GL state so that we can restore it when complete GLboolean SavedLighting; GLboolean SavedDepthTest; GLboolean SavedBlending; vtkVector2i Dim; vtkVector2i Offset; }; vtkStandardNewMacro(vtkOpenGLContextDevice3D) vtkOpenGLContextDevice3D::vtkOpenGLContextDevice3D() : Storage(new Private) { this->InRender = false; } vtkOpenGLContextDevice3D::~vtkOpenGLContextDevice3D() { delete Storage; } void vtkOpenGLContextDevice3D::DrawPoly(const float *verts, int n, const unsigned char *colors, int nc) { assert("verts must be non-null" && verts != NULL); assert("n must be greater than 0" && n > 0); this->Storage->SetLineType(this->Pen->GetLineType()); glLineWidth(this->Pen->GetWidth()); if (colors) { glEnableClientState(GL_COLOR_ARRAY); glColorPointer(nc, GL_UNSIGNED_BYTE, 0, colors); } else { glColor4ubv(this->Pen->GetColor()); } glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(3, GL_FLOAT, 0, verts); glDrawArrays(GL_LINE_STRIP, 0, n); glDisableClientState(GL_VERTEX_ARRAY); if (colors) { glDisableClientState(GL_COLOR_ARRAY); } } void vtkOpenGLContextDevice3D::DrawPoints(const float *verts, int n, const unsigned char *colors, int nc) { assert("verts must be non-null" && verts != NULL); assert("n must be greater than 0" && n > 0); glPointSize(this->Pen->GetWidth()); glEnableClientState(GL_VERTEX_ARRAY); if (colors && nc) { glEnableClientState(GL_COLOR_ARRAY); glColorPointer(nc, GL_UNSIGNED_BYTE, 0, colors); } else { glColor4ubv(this->Pen->GetColor()); } glVertexPointer(3, GL_FLOAT, 0, verts); glDrawArrays(GL_POINTS, 0, n); glDisableClientState(GL_VERTEX_ARRAY); if (colors && nc) { glDisableClientState(GL_COLOR_ARRAY); } } void vtkOpenGLContextDevice3D::ApplyPen(vtkPen *pen) { this->Pen->DeepCopy(pen); } void vtkOpenGLContextDevice3D::ApplyBrush(vtkBrush *brush) { this->Brush->DeepCopy(brush); } void vtkOpenGLContextDevice3D::SetMatrix(vtkMatrix4x4 *m) { double matrix[16]; double *M = m->Element[0]; this->Storage->Transpose(M, matrix); glLoadMatrixd(matrix); } void vtkOpenGLContextDevice3D::GetMatrix(vtkMatrix4x4 *m) { double *M = m->Element[0]; m->Transpose(); double matrix[16]; glGetDoublev(GL_MODELVIEW_MATRIX, matrix); this->Storage->Transpose(M, matrix); } void vtkOpenGLContextDevice3D::MultiplyMatrix(vtkMatrix4x4 *m) { double matrix[16]; double *M = m->Element[0]; this->Storage->Transpose(M, matrix); glMultMatrixd(matrix); } void vtkOpenGLContextDevice3D::PushMatrix() { glMatrixMode(GL_MODELVIEW); glPushMatrix(); } void vtkOpenGLContextDevice3D::PopMatrix() { glMatrixMode(GL_MODELVIEW); glPopMatrix(); } void vtkOpenGLContextDevice3D::SetClipping(const vtkRecti &rect) { // Check the bounds, and clamp if necessary GLint vp[4] = { this->Storage->Offset.GetX(), this->Storage->Offset.GetY(), this->Storage->Dim.GetX(), this->Storage->Dim.GetY()}; if (rect.X() > 0 && rect.X() < vp[2] ) { vp[0] += rect.X(); } if (rect.Y() > 0 && rect.Y() < vp[3]) { vp[1] += rect.Y(); } if (rect.Width() > 0 && rect.Width() < vp[2]) { vp[2] = rect.Width(); } if (rect.Height() > 0 && rect.Height() < vp[3]) { vp[3] = rect.Height(); } glScissor(vp[0], vp[1], vp[2], vp[3]); } void vtkOpenGLContextDevice3D::EnableClipping(bool enable) { if (enable) { glEnable(GL_SCISSOR_TEST); } else { glDisable(GL_SCISSOR_TEST); } } void vtkOpenGLContextDevice3D::Begin(vtkViewport* viewport) { // Need the actual pixel size of the viewport - ask OpenGL. GLint vp[4]; glGetIntegerv(GL_VIEWPORT, vp); this->Storage->Offset.Set(static_cast<int>(vp[0]), static_cast<int>(vp[1])); this->Storage->Dim.Set(static_cast<int>(vp[2]), static_cast<int>(vp[3])); // push a 2D matrix on the stack glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); float offset = 0.5; glOrtho(offset, vp[2]+offset-1.0, offset, vp[3]+offset-1.0, -1000, 1000); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); // Store the previous state before changing it this->Storage->SaveGLState(); glDisable(GL_LIGHTING); glDisable(GL_DEPTH_TEST); glEnable(GL_BLEND); this->Renderer = vtkRenderer::SafeDownCast(viewport); this->InRender = true; } void vtkOpenGLContextDevice3D::End() { if (!this->InRender) { return; } // push a 2D matrix on the stack glMatrixMode(GL_PROJECTION); glPopMatrix(); glMatrixMode(GL_MODELVIEW); glPopMatrix(); // Restore the GL state that we changed this->Storage->RestoreGLState(); this->InRender = false; } void vtkOpenGLContextDevice3D::PrintSelf(ostream &os, vtkIndent indent) { Superclass::PrintSelf(os, indent); }
Fix valgrind error for unitialized ivar.
COMP: Fix valgrind error for unitialized ivar. Change-Id: Ic7a0459513258ab8c04786c33d7518a8e69b4cb8
C++
bsd-3-clause
msmolens/VTK,gram526/VTK,aashish24/VTK-old,biddisco/VTK,johnkit/vtk-dev,SimVascular/VTK,mspark93/VTK,demarle/VTK,aashish24/VTK-old,demarle/VTK,SimVascular/VTK,collects/VTK,SimVascular/VTK,demarle/VTK,keithroe/vtkoptix,jmerkow/VTK,SimVascular/VTK,candy7393/VTK,gram526/VTK,demarle/VTK,keithroe/vtkoptix,johnkit/vtk-dev,biddisco/VTK,mspark93/VTK,gram526/VTK,sankhesh/VTK,hendradarwin/VTK,ashray/VTK-EVM,ashray/VTK-EVM,ashray/VTK-EVM,sankhesh/VTK,demarle/VTK,jmerkow/VTK,hendradarwin/VTK,sankhesh/VTK,biddisco/VTK,candy7393/VTK,keithroe/vtkoptix,keithroe/vtkoptix,msmolens/VTK,gram526/VTK,demarle/VTK,berendkleinhaneveld/VTK,jmerkow/VTK,johnkit/vtk-dev,berendkleinhaneveld/VTK,collects/VTK,mspark93/VTK,msmolens/VTK,SimVascular/VTK,sankhesh/VTK,candy7393/VTK,berendkleinhaneveld/VTK,johnkit/vtk-dev,candy7393/VTK,msmolens/VTK,hendradarwin/VTK,gram526/VTK,SimVascular/VTK,sankhesh/VTK,jmerkow/VTK,candy7393/VTK,sankhesh/VTK,SimVascular/VTK,msmolens/VTK,cjh1/VTK,jmerkow/VTK,msmolens/VTK,sankhesh/VTK,keithroe/vtkoptix,cjh1/VTK,msmolens/VTK,gram526/VTK,candy7393/VTK,aashish24/VTK-old,collects/VTK,berendkleinhaneveld/VTK,sumedhasingla/VTK,cjh1/VTK,aashish24/VTK-old,SimVascular/VTK,keithroe/vtkoptix,hendradarwin/VTK,hendradarwin/VTK,cjh1/VTK,berendkleinhaneveld/VTK,mspark93/VTK,collects/VTK,aashish24/VTK-old,sumedhasingla/VTK,ashray/VTK-EVM,sumedhasingla/VTK,sumedhasingla/VTK,cjh1/VTK,cjh1/VTK,keithroe/vtkoptix,collects/VTK,jmerkow/VTK,mspark93/VTK,candy7393/VTK,mspark93/VTK,jmerkow/VTK,sumedhasingla/VTK,biddisco/VTK,johnkit/vtk-dev,sumedhasingla/VTK,candy7393/VTK,biddisco/VTK,keithroe/vtkoptix,hendradarwin/VTK,gram526/VTK,berendkleinhaneveld/VTK,collects/VTK,johnkit/vtk-dev,ashray/VTK-EVM,sumedhasingla/VTK,mspark93/VTK,msmolens/VTK,biddisco/VTK,demarle/VTK,berendkleinhaneveld/VTK,jmerkow/VTK,sankhesh/VTK,ashray/VTK-EVM,hendradarwin/VTK,johnkit/vtk-dev,ashray/VTK-EVM,sumedhasingla/VTK,mspark93/VTK,aashish24/VTK-old,gram526/VTK,biddisco/VTK,ashray/VTK-EVM,demarle/VTK
6052af05556e2f7ee6b8310abf8911dfc1d0b7ea
source/symbols/Symbol.cpp
source/symbols/Symbol.cpp
//------------------------------------------------------------------------------ // Symbol.h // Symbols for semantic analysis. // // File is under the MIT license; see LICENSE for details. //------------------------------------------------------------------------------ #include "slang/symbols/Symbol.h" #include <nlohmann/json.hpp> #include "slang/compilation/Compilation.h" #include "slang/symbols/ASTVisitor.h" #include "slang/symbols/CompilationUnitSymbols.h" #include "slang/symbols/MemberSymbols.h" #include "slang/symbols/Type.h" #include "slang/syntax/AllSyntax.h" #include "slang/text/SourceManager.h" #include "slang/util/StackContainer.h" namespace { using namespace slang; struct AsScopeVisitor { template<typename T> const Scope* visit(const T& symbol) { if constexpr (std::is_base_of_v<Scope, T>) { return static_cast<const Scope*>(&symbol); } else { (void)symbol; return nullptr; } } }; struct ToJsonVisitor { template<typename T> void visit(const T& symbol, json& j) { if constexpr (std::is_base_of_v<Type, T> && !std::is_same_v<TypeAliasType, T>) { j = symbol.toString(); } else { j["name"] = std::string(symbol.name); j["kind"] = toString(symbol.kind); j["addr"] = uintptr_t(&symbol); auto scope = symbol.getParentScope(); if (scope) { for (auto attr : scope->getCompilation().getAttributes(symbol)) j["attributes"].push_back(*attr); } if constexpr (std::is_base_of_v<ValueSymbol, T>) { j["type"] = symbol.getType(); auto& value = symbol.getConstantValue(); if (value) j["value"] = value; if (auto init = symbol.getInitializer()) j["initializer"] = *init; } if constexpr (std::is_base_of_v<Scope, T>) { for (const auto& member : symbol.members()) j["members"].push_back(member); } if constexpr (!std::is_same_v<Symbol, T>) { symbol.toJson(j); } } } }; } // namespace namespace slang { bool Symbol::isType() const { return Type::isKind(kind); } bool Symbol::isValue() const { return ValueSymbol::isKind(kind); } bool Symbol::isInstance() const { return InstanceSymbol::isKind(kind); } const Scope* Symbol::getLexicalScope() const { if (InstanceSymbol::isKind(kind)) return as<InstanceSymbol>().definition.getParentScope(); else return getParentScope(); } const DeclaredType* Symbol::getDeclaredType() const { switch (kind) { case SymbolKind::TypeAlias: return &as<TypeAliasType>().targetType; case SymbolKind::Subroutine: return &as<SubroutineSymbol>().declaredReturnType; case SymbolKind::NetType: return &as<NetType>().declaredType; case SymbolKind::TypeParameter: return &as<TypeParameterSymbol>().targetType; default: if (isValue()) return as<ValueSymbol>().getDeclaredType(); return nullptr; } } static void getHierarchicalPathImpl(const Symbol& symbol, std::string& buffer) { if (symbol.getParentScope()) { auto& parent = symbol.getParentScope()->asSymbol(); if (parent.kind != SymbolKind::Root && parent.kind != SymbolKind::CompilationUnit) { getHierarchicalPathImpl(parent, buffer); if (!symbol.name.empty()) { if (parent.kind == SymbolKind::Package || parent.kind == SymbolKind::ClassType) buffer.append("::"); else buffer.append("."); } } } if (!symbol.name.empty()) buffer.append(symbol.name); } void Symbol::getHierarchicalPath(std::string& buffer) const { size_t sz = buffer.size(); getHierarchicalPathImpl(*this, buffer); if (sz == buffer.size()) buffer.append("$unit"); } optional<bool> Symbol::isDeclaredBefore(const Symbol& target) const { return isDeclaredBefore(LookupLocation::beforeLexical(target)); } optional<bool> Symbol::isDeclaredBefore(LookupLocation ll) const { if (!ll.getScope()) return LookupLocation::before(*this) < ll; // Find a common parent scope for the two symbols. Start with our parent and // walk upwards until we find `target`s scope or run into a compilation unit. SmallMap<const Scope*, LookupLocation, 8> locMap; const Symbol* sym = this; const Scope* scope; while ((scope = sym->getLexicalScope()) != nullptr && sym->kind != SymbolKind::CompilationUnit && scope != ll.getScope()) { locMap[scope] = LookupLocation::beforeLexical(*sym); sym = &scope->asSymbol(); } if (scope == ll.getScope()) return LookupLocation::beforeLexical(*sym) < ll; // If ll wasn't in a direct scope of any of our own parents, // repeat the process walking up ll's scopes. sym = &ll.getScope()->asSymbol(); while ((scope = sym->getLexicalScope()) != nullptr && sym->kind != SymbolKind::CompilationUnit) { if (auto it = locMap.find(scope); it != locMap.end()) return it->second < LookupLocation::beforeLexical(*sym); sym = &scope->asSymbol(); } return std::nullopt; } void Symbol::setAttributes(const Scope& scope, span<const AttributeInstanceSyntax* const> syntax) { if (syntax.empty()) return; scope.getCompilation().setAttributes(*this, AttributeSymbol::fromSyntax(syntax, scope, *this)); } const Scope* Symbol::scopeOrNull() const { AsScopeVisitor visitor; return visit(visitor); } std::string Symbol::jsonLink(const Symbol& target) { return std::to_string(uintptr_t(&target)) + " " + (target.isType() ? target.as<Type>().toString() : std::string(target.name)); } ValueSymbol::ValueSymbol(SymbolKind kind, string_view name, SourceLocation location, bitmask<DeclaredTypeFlags> flags) : Symbol(kind, name, location), declaredType(*this, flags) { } void ValueSymbol::setFromDeclarator(const DeclaratorSyntax& decl) { declaredType.setFromDeclarator(decl); setSyntax(decl); } bool ValueSymbol::isKind(SymbolKind kind) { switch (kind) { case SymbolKind::Net: case SymbolKind::EnumValue: case SymbolKind::Parameter: case SymbolKind::Port: return true; default: return VariableSymbol::isKind(kind); } } void to_json(json& j, const Symbol& symbol) { ToJsonVisitor visitor; symbol.visit(visitor, j); } } // namespace slang
//------------------------------------------------------------------------------ // Symbol.h // Symbols for semantic analysis. // // File is under the MIT license; see LICENSE for details. //------------------------------------------------------------------------------ #include "slang/symbols/Symbol.h" #include <nlohmann/json.hpp> #include "slang/compilation/Compilation.h" #include "slang/symbols/ASTVisitor.h" #include "slang/symbols/CompilationUnitSymbols.h" #include "slang/symbols/MemberSymbols.h" #include "slang/symbols/Type.h" #include "slang/syntax/AllSyntax.h" #include "slang/text/SourceManager.h" #include "slang/util/StackContainer.h" namespace { using namespace slang; struct AsScopeVisitor { template<typename T> const Scope* visit(const T& symbol) { if constexpr (std::is_base_of_v<Scope, T>) { return static_cast<const Scope*>(&symbol); } else { (void)symbol; return nullptr; } } }; struct ToJsonVisitor { template<typename T> void visit(const T& symbol, json& j) { if constexpr (std::is_base_of_v<Type, T> && !std::is_same_v<TypeAliasType, T>) { j = symbol.toString(); } else { j["name"] = std::string(symbol.name); j["kind"] = toString(symbol.kind); j["addr"] = uintptr_t(&symbol); auto scope = symbol.getParentScope(); if (scope) { for (auto attr : scope->getCompilation().getAttributes(symbol)) j["attributes"].push_back(*attr); } if constexpr (std::is_base_of_v<ValueSymbol, T>) { j["type"] = symbol.getType(); auto& value = symbol.getConstantValue(); if (value) j["value"] = value; if (auto init = symbol.getInitializer()) j["initializer"] = *init; } if constexpr (std::is_base_of_v<Scope, T>) { for (const auto& member : symbol.members()) j["members"].push_back(member); } if constexpr (!std::is_same_v<Symbol, T>) { symbol.toJson(j); } } } }; } // namespace namespace slang { bool Symbol::isType() const { return Type::isKind(kind); } bool Symbol::isValue() const { return ValueSymbol::isKind(kind); } bool Symbol::isInstance() const { return InstanceSymbol::isKind(kind); } const Scope* Symbol::getLexicalScope() const { if (InstanceSymbol::isKind(kind)) return as<InstanceSymbol>().definition.getParentScope(); else return getParentScope(); } const DeclaredType* Symbol::getDeclaredType() const { switch (kind) { case SymbolKind::TypeAlias: return &as<TypeAliasType>().targetType; case SymbolKind::Subroutine: return &as<SubroutineSymbol>().declaredReturnType; case SymbolKind::NetType: return &as<NetType>().declaredType; case SymbolKind::TypeParameter: return &as<TypeParameterSymbol>().targetType; default: if (isValue()) return as<ValueSymbol>().getDeclaredType(); return nullptr; } } static void getHierarchicalPathImpl(const Symbol& symbol, std::string& buffer) { if (symbol.getParentScope()) { auto& parent = symbol.getParentScope()->asSymbol(); if (parent.kind != SymbolKind::Root && parent.kind != SymbolKind::CompilationUnit) { getHierarchicalPathImpl(parent, buffer); if (!symbol.name.empty()) { if (parent.kind == SymbolKind::Package || parent.kind == SymbolKind::ClassType) buffer.append("::"); else buffer.append("."); } } } if (!symbol.name.empty()) buffer.append(symbol.name); } void Symbol::getHierarchicalPath(std::string& buffer) const { size_t sz = buffer.size(); getHierarchicalPathImpl(*this, buffer); if (sz == buffer.size()) buffer.append("$unit"); } optional<bool> Symbol::isDeclaredBefore(const Symbol& target) const { return isDeclaredBefore(LookupLocation::beforeLexical(target)); } optional<bool> Symbol::isDeclaredBefore(LookupLocation target) const { LookupLocation ll = LookupLocation::before(*this); if (!target.getScope()) return ll < target; // Find a common parent scope for the two symbols. Start with our parent and // walk upwards until we find `target`s scope or run into a compilation unit. SmallMap<const Scope*, LookupLocation, 8> locMap; const Symbol* sym = this; const Scope* scope = ll.getScope(); while (sym->kind != SymbolKind::CompilationUnit && scope && scope != target.getScope()) { locMap[scope] = ll; sym = &scope->asSymbol(); ll = LookupLocation::beforeLexical(*sym); scope = ll.getScope(); } if (scope == target.getScope()) return ll < target; // If target wasn't in a direct scope of any of our own parents, // repeat the process walking up target's scopes. sym = &target.getScope()->asSymbol(); ll = LookupLocation::beforeLexical(*sym); while ((scope = ll.getScope()) != nullptr && sym->kind != SymbolKind::CompilationUnit) { if (auto it = locMap.find(scope); it != locMap.end()) return it->second < ll; sym = &scope->asSymbol(); ll = LookupLocation::beforeLexical(*sym); } return std::nullopt; } void Symbol::setAttributes(const Scope& scope, span<const AttributeInstanceSyntax* const> syntax) { if (syntax.empty()) return; scope.getCompilation().setAttributes(*this, AttributeSymbol::fromSyntax(syntax, scope, *this)); } const Scope* Symbol::scopeOrNull() const { AsScopeVisitor visitor; return visit(visitor); } std::string Symbol::jsonLink(const Symbol& target) { return std::to_string(uintptr_t(&target)) + " " + (target.isType() ? target.as<Type>().toString() : std::string(target.name)); } ValueSymbol::ValueSymbol(SymbolKind kind, string_view name, SourceLocation location, bitmask<DeclaredTypeFlags> flags) : Symbol(kind, name, location), declaredType(*this, flags) { } void ValueSymbol::setFromDeclarator(const DeclaratorSyntax& decl) { declaredType.setFromDeclarator(decl); setSyntax(decl); } bool ValueSymbol::isKind(SymbolKind kind) { switch (kind) { case SymbolKind::Net: case SymbolKind::EnumValue: case SymbolKind::Parameter: case SymbolKind::Port: return true; default: return VariableSymbol::isKind(kind); } } void to_json(json& j, const Symbol& symbol) { ToJsonVisitor visitor; symbol.visit(visitor, j); } } // namespace slang
Fix Symbol::isDeclaredBefore when called on an instance symbol
Fix Symbol::isDeclaredBefore when called on an instance symbol
C++
mit
MikePopoloski/slang,MikePopoloski/slang
3e26756f1dfe1ddd1d7f5e458771c9bf79acb09a
src/base/types.hh
src/base/types.hh
/* * Copyright (c) 2003-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: Nathan Binkert */ /** * @file * Defines global host-dependent types: * Counter, Tick, and (indirectly) {int,uint}{8,16,32,64}_t. */ #ifndef __BASE_TYPES_HH__ #define __BASE_TYPES_HH__ #include <inttypes.h> #include <cassert> #include <memory> #include <ostream> #include "base/refcnt.hh" /** uint64_t constant */ #define ULL(N) ((uint64_t)N##ULL) /** int64_t constant */ #define LL(N) ((int64_t)N##LL) /** Statistics counter type. Not much excuse for not using a 64-bit * integer here, but if you're desperate and only run short * simulations you could make this 32 bits. */ typedef int64_t Counter; /** * Tick count type. */ typedef uint64_t Tick; const Tick MaxTick = ULL(0xffffffffffffffff); /** * Cycles is a wrapper class for representing cycle counts, i.e. a * relative difference between two points in time, expressed in a * number of clock cycles. * * The Cycles wrapper class is a type-safe alternative to a * typedef, aiming to avoid unintentional mixing of cycles and ticks * in the code base. * * Operators are defined inside an ifndef block to avoid swig touching * them. Note that there is no overloading of the bool operator as the * compiler is allowed to turn booleans into integers and this causes * a whole range of issues in a handful locations. The solution to * this problem would be to use the safe bool idiom, but for now we * make do without the test and use the more elaborate comparison > * Cycles(0). */ class Cycles { private: /** Member holding the actual value. */ uint64_t c; public: /** Explicit constructor assigning a value. */ explicit Cycles(uint64_t _c) : c(_c) { } /** Default constructor for parameter classes. */ Cycles() : c(0) { } #ifndef SWIG // keep the operators away from SWIG /** Converting back to the value type. */ operator uint64_t() const { return c; } /** Prefix increment operator. */ Cycles& operator++() { ++c; return *this; } /** Prefix decrement operator. Is only temporarily used in the O3 CPU. */ Cycles& operator--() { assert(c != 0); --c; return *this; } /** In-place addition of cycles. */ const Cycles& operator+=(const Cycles& cc) { c += cc.c; return *this; } /** Greater than comparison used for > Cycles(0). */ bool operator>(const Cycles& cc) const { return c > cc.c; } const Cycles operator +(const Cycles& b) const { return Cycles(c + b.c); } const Cycles operator -(const Cycles& b) const { assert(c >= b.c); return Cycles(c - b.c); } const Cycles operator <<(const int32_t shift) { return Cycles(c << shift); } const Cycles operator >>(const int32_t shift) { return Cycles(c >> shift); } friend std::ostream& operator<<(std::ostream &out, const Cycles & cycles); #endif // SWIG not touching operators }; /** * Address type * This will probably be moved somewhere else in the near future. * This should be at least as big as the biggest address width in use * in the system, which will probably be 64 bits. */ typedef uint64_t Addr; typedef uint16_t MicroPC; static const MicroPC MicroPCRomBit = 1 << (sizeof(MicroPC) * 8 - 1); static inline MicroPC romMicroPC(MicroPC upc) { return upc | MicroPCRomBit; } static inline MicroPC normalMicroPC(MicroPC upc) { return upc & ~MicroPCRomBit; } static inline bool isRomMicroPC(MicroPC upc) { return MicroPCRomBit & upc; } const Addr MaxAddr = (Addr)-1; /** * Thread index/ID type */ typedef int16_t ThreadID; const ThreadID InvalidThreadID = (ThreadID)-1; /** * Port index/ID type, and a symbolic name for an invalid port id. */ typedef int16_t PortID; const PortID InvalidPortID = (PortID)-1; class FaultBase; typedef std::shared_ptr<FaultBase> Fault; #ifndef SWIG // Swig gets really confused by decltype // Rather than creating a shared_ptr instance and assigning it nullptr, // we just create an alias. constexpr decltype(nullptr) NoFault = nullptr; #endif enum ByteOrder { BigEndianByteOrder, LittleEndianByteOrder }; #endif // __BASE_TYPES_HH__
/* * Copyright (c) 2003-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: Nathan Binkert */ /** * @file * Defines global host-dependent types: * Counter, Tick, and (indirectly) {int,uint}{8,16,32,64}_t. */ #ifndef __BASE_TYPES_HH__ #define __BASE_TYPES_HH__ #include <inttypes.h> #include <cassert> #include <memory> #include <ostream> #include <stdexcept> #include "base/refcnt.hh" /** uint64_t constant */ #define ULL(N) ((uint64_t)N##ULL) /** int64_t constant */ #define LL(N) ((int64_t)N##LL) /** Statistics counter type. Not much excuse for not using a 64-bit * integer here, but if you're desperate and only run short * simulations you could make this 32 bits. */ typedef int64_t Counter; /** * Tick count type. */ typedef uint64_t Tick; const Tick MaxTick = ULL(0xffffffffffffffff); /** * Cycles is a wrapper class for representing cycle counts, i.e. a * relative difference between two points in time, expressed in a * number of clock cycles. * * The Cycles wrapper class is a type-safe alternative to a * typedef, aiming to avoid unintentional mixing of cycles and ticks * in the code base. * * Operators are defined inside an ifndef block to avoid swig touching * them. Note that there is no overloading of the bool operator as the * compiler is allowed to turn booleans into integers and this causes * a whole range of issues in a handful locations. The solution to * this problem would be to use the safe bool idiom, but for now we * make do without the test and use the more elaborate comparison > * Cycles(0). */ class Cycles { private: /** Member holding the actual value. */ uint64_t c; public: #ifndef SWIG // SWIG gets confused by constexpr /** Explicit constructor assigning a value. */ explicit constexpr Cycles(uint64_t _c) : c(_c) { } #else explicit Cycles(uint64_t _c) : c(_c) { } #endif /** Default constructor for parameter classes. */ Cycles() : c(0) { } #ifndef SWIG // keep the operators away from SWIG /** Converting back to the value type. */ constexpr operator uint64_t() const { return c; } /** Prefix increment operator. */ Cycles& operator++() { ++c; return *this; } /** Prefix decrement operator. Is only temporarily used in the O3 CPU. */ Cycles& operator--() { assert(c != 0); --c; return *this; } /** In-place addition of cycles. */ Cycles& operator+=(const Cycles& cc) { c += cc.c; return *this; } /** Greater than comparison used for > Cycles(0). */ constexpr bool operator>(const Cycles& cc) const { return c > cc.c; } constexpr Cycles operator +(const Cycles& b) const { return Cycles(c + b.c); } constexpr Cycles operator -(const Cycles& b) const { return c >= b.c ? Cycles(c - b.c) : throw std::invalid_argument("RHS cycle value larger than LHS"); } constexpr Cycles operator <<(const int32_t shift) const { return Cycles(c << shift); } constexpr Cycles operator >>(const int32_t shift) const { return Cycles(c >> shift); } friend std::ostream& operator<<(std::ostream &out, const Cycles & cycles); #endif // SWIG not touching operators }; /** * Address type * This will probably be moved somewhere else in the near future. * This should be at least as big as the biggest address width in use * in the system, which will probably be 64 bits. */ typedef uint64_t Addr; typedef uint16_t MicroPC; static const MicroPC MicroPCRomBit = 1 << (sizeof(MicroPC) * 8 - 1); static inline MicroPC romMicroPC(MicroPC upc) { return upc | MicroPCRomBit; } static inline MicroPC normalMicroPC(MicroPC upc) { return upc & ~MicroPCRomBit; } static inline bool isRomMicroPC(MicroPC upc) { return MicroPCRomBit & upc; } const Addr MaxAddr = (Addr)-1; /** * Thread index/ID type */ typedef int16_t ThreadID; const ThreadID InvalidThreadID = (ThreadID)-1; /** * Port index/ID type, and a symbolic name for an invalid port id. */ typedef int16_t PortID; const PortID InvalidPortID = (PortID)-1; class FaultBase; typedef std::shared_ptr<FaultBase> Fault; #ifndef SWIG // Swig gets really confused by decltype // Rather than creating a shared_ptr instance and assigning it nullptr, // we just create an alias. constexpr decltype(nullptr) NoFault = nullptr; #endif enum ByteOrder { BigEndianByteOrder, LittleEndianByteOrder }; #endif // __BASE_TYPES_HH__
Use constexpr in Cycles
base: Use constexpr in Cycles Declare the constructor and all of the operators that don't change the state of a Cycles instance as constexpr. This makes it possible to use Cycles as a static constant and allows the compiler to evaulate simple expressions at compile time. An unfortunate side-effect of this is that we cannot use assertions since C++11 doesn't support them in constexpr functions. As a workaround, we throw an invalid_argument exception when the assert would have triggered. A nice side-effect of this is that the compiler will evaluate the "assertion" at compile time when an expression involving Cycles can be statically evaluated.
C++
bsd-3-clause
rallylee/gem5,SanchayanMaity/gem5,qizenguf/MLC-STT,KuroeKurose/gem5,powerjg/gem5-ci-test,gem5/gem5,rjschof/gem5,rallylee/gem5,sobercoder/gem5,briancoutinho0905/2dsampling,cancro7/gem5,Weil0ng/gem5,TUD-OS/gem5-dtu,rjschof/gem5,rallylee/gem5,SanchayanMaity/gem5,briancoutinho0905/2dsampling,TUD-OS/gem5-dtu,TUD-OS/gem5-dtu,TUD-OS/gem5-dtu,KuroeKurose/gem5,rjschof/gem5,KuroeKurose/gem5,qizenguf/MLC-STT,cancro7/gem5,rjschof/gem5,HwisooSo/gemV-update,Weil0ng/gem5,aclifton/cpeg853-gem5,rjschof/gem5,HwisooSo/gemV-update,powerjg/gem5-ci-test,HwisooSo/gemV-update,gem5/gem5,gedare/gem5,cancro7/gem5,aclifton/cpeg853-gem5,rjschof/gem5,gedare/gem5,aclifton/cpeg853-gem5,qizenguf/MLC-STT,Weil0ng/gem5,powerjg/gem5-ci-test,cancro7/gem5,HwisooSo/gemV-update,aclifton/cpeg853-gem5,SanchayanMaity/gem5,sobercoder/gem5,aclifton/cpeg853-gem5,KuroeKurose/gem5,gedare/gem5,briancoutinho0905/2dsampling,rjschof/gem5,TUD-OS/gem5-dtu,powerjg/gem5-ci-test,aclifton/cpeg853-gem5,sobercoder/gem5,briancoutinho0905/2dsampling,TUD-OS/gem5-dtu,gedare/gem5,Weil0ng/gem5,gem5/gem5,qizenguf/MLC-STT,powerjg/gem5-ci-test,rallylee/gem5,gem5/gem5,SanchayanMaity/gem5,briancoutinho0905/2dsampling,cancro7/gem5,gedare/gem5,HwisooSo/gemV-update,gem5/gem5,SanchayanMaity/gem5,gedare/gem5,SanchayanMaity/gem5,Weil0ng/gem5,sobercoder/gem5,qizenguf/MLC-STT,rallylee/gem5,TUD-OS/gem5-dtu,sobercoder/gem5,KuroeKurose/gem5,cancro7/gem5,gem5/gem5,Weil0ng/gem5,gedare/gem5,rallylee/gem5,sobercoder/gem5,sobercoder/gem5,HwisooSo/gemV-update,powerjg/gem5-ci-test,aclifton/cpeg853-gem5,qizenguf/MLC-STT,powerjg/gem5-ci-test,Weil0ng/gem5,briancoutinho0905/2dsampling,HwisooSo/gemV-update,gem5/gem5,KuroeKurose/gem5,qizenguf/MLC-STT,SanchayanMaity/gem5,briancoutinho0905/2dsampling,KuroeKurose/gem5,cancro7/gem5,rallylee/gem5
7cb694bc2e443a817779b8363c187cf21b207e75
src/appleseed/renderer/kernel/rendering/localsampleaccumulationbuffer.cpp
src/appleseed/renderer/kernel/rendering/localsampleaccumulationbuffer.cpp
// // This source file is part of appleseed. // Visit http://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited // Copyright (c) 2014-2016 Francois Beaune, The appleseedhq Organization // // 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. // // Interface header. #include "localsampleaccumulationbuffer.h" // appleseed.renderer headers. #include "renderer/kernel/rendering/sample.h" #include "renderer/kernel/aov/imagestack.h" #include "renderer/kernel/aov/tilestack.h" #include "renderer/modeling/frame/frame.h" // appleseed.foundation headers. #include "foundation/image/canvasproperties.h" #include "foundation/image/color.h" #include "foundation/image/filteredtile.h" #include "foundation/image/image.h" #include "foundation/image/pixel.h" #include "foundation/image/tile.h" #include "foundation/math/aabb.h" #include "foundation/math/scalar.h" #include "foundation/platform/timers.h" #include "foundation/utility/job/iabortswitch.h" #include "foundation/utility/stopwatch.h" // Boost headers. #include "boost/chrono/duration.hpp" // Standard headers. #include <algorithm> #include <cassert> using namespace boost; using namespace foundation; using namespace std; namespace renderer { // // LocalSampleAccumulationBuffer class implementation. // // The algorithm for progressive display deserves some explanations. Here is how it works: // // When the accumulation buffer is constructed, we create a stack of framebuffers of // decreasing resolution, much like a mipmap pyramid: each level of this pyramid is a // quarter of the resolution of the previous one (half the resolution in each dimension). // We don't actually go down all the way to the 1x1 level; instead we stop when we reach // a resolution that we consider provides a good balance between speed and usefulness. // // At render-time, the store_samples() method pushes the individual samples through this // pyramid. Samples are stored starting at the highest resolution level and up to what // we call the "active level", that is, the coarsest level of the pyramid that we're still // pushing samples to and the level that is displayed. As soon as a level contains enough // samples, it becomes the new active level. // //#define PRINT_DETAILED_PERF_REPORTS LocalSampleAccumulationBuffer::LocalSampleAccumulationBuffer( const size_t width, const size_t height, const Filter2f& filter) { const size_t MinSize = 32; size_t level_width = width; size_t level_height = height; while (true) { m_levels.push_back( new FilteredTile( level_width, level_height, 5, filter)); if (level_width < MinSize * 2 || level_height < MinSize * 2) break; if (level_width > MinSize) level_width = max(level_width / 2, MinSize); if (level_height > MinSize) level_height = max(level_height / 2, MinSize); } m_remaining_pixels = new atomic<int32>[m_levels.size()]; clear(); } LocalSampleAccumulationBuffer::~LocalSampleAccumulationBuffer() { delete[] m_remaining_pixels; for (size_t i = 0, e = m_levels.size(); i < e; ++i) delete m_levels[i]; } void LocalSampleAccumulationBuffer::clear() { #ifdef PRINT_DETAILED_PERF_REPORTS Stopwatch<DefaultWallclockTimer> sw(0); sw.start(); #endif // Request exclusive access. unique_lock<shared_mutex> lock(m_mutex); #ifdef PRINT_DETAILED_PERF_REPORTS sw.measure(); RENDERER_LOG_DEBUG("clear: acquiring lock: %f", sw.get_seconds() * 1000.0); #endif m_sample_count = 0; for (size_t i = 0, e = m_levels.size(); i < e; ++i) { m_levels[i]->clear(); m_remaining_pixels[i] = static_cast<int32>(m_levels[i]->get_pixel_count()); } m_active_level = static_cast<uint32>(m_levels.size() - 1); } void LocalSampleAccumulationBuffer::store_samples( const size_t sample_count, const Sample samples[], IAbortSwitch& abort_switch) { #ifdef PRINT_DETAILED_PERF_REPORTS Stopwatch<DefaultWallclockTimer> sw(0); sw.start(); #endif { // Request non-exclusive access. shared_lock<shared_mutex> lock(m_mutex, defer_lock); while (true) { if (abort_switch.is_aborted()) return; if (lock.try_lock_for(chrono::milliseconds(5))) break; } #ifdef PRINT_DETAILED_PERF_REPORTS sw.measure(); RENDERER_LOG_DEBUG("store_samples: acquiring lock: %f", sw.get_seconds() * 1000.0); #endif // Store samples at every level, starting with the highest resolution level up to the active level. size_t counter = 0; for (uint32 i = 0, e = m_active_level; i <= e; ++i) { FilteredTile* level = m_levels[i]; const float level_width = static_cast<float>(level->get_width()); const float level_height = static_cast<float>(level->get_height()); const Sample* sample_end = samples + sample_count; for (const Sample* s = samples; s < sample_end; ++s) { if ((counter++ & 4096) == 0 && abort_switch.is_aborted()) return; const float fx = s->m_position.x * level_width; const float fy = s->m_position.y * level_height; level->add(fx, fy, s->m_values); } } } m_sample_count += sample_count; #ifdef PRINT_DETAILED_PERF_REPORTS sw.measure(); RENDERER_LOG_DEBUG("store_samples: " FMT_SIZE_T " -> %f", sample_count, sw.get_seconds() * 1000.0); #endif // Potentially update the new active level if we're not already at the highest resolution level. if (m_active_level > 0) { // Update pixel counters for all levels up to the active level. const int32 n = static_cast<int32>(sample_count); for (uint32 i = 0, e = m_active_level; i <= e; ++i) m_remaining_pixels[i].fetch_sub(n); // Find the new active level. uint32 cur_active_level = m_active_level; uint32 new_active_level = cur_active_level; for (uint32 i = 0, e = cur_active_level; i < e; ++i) { if (m_remaining_pixels[i] <= 0) { new_active_level = i; break; } } // Attempt to update the active level. It's OK if we fail, another thread will succeed. if (new_active_level < cur_active_level) m_active_level.compare_exchange_strong(cur_active_level, new_active_level); } } namespace { void develop_to_tile( Tile& color_tile, Tile& depth_tile, const size_t image_width, const size_t image_height, const FilteredTile& level, const size_t origin_x, const size_t origin_y, const AABB2u& crop_window, const bool undo_premultiplied_alpha) { const AABB2u r = AABB2u::intersect( AABB2u( Vector2u(origin_x, origin_y), Vector2u(origin_x + color_tile.get_width() - 1, origin_y + color_tile.get_height() - 1)), crop_window); if (undo_premultiplied_alpha) { for (size_t iy = r.min.y; iy <= r.max.y; ++iy) { const size_t level_width = level.get_width(); const size_t src_y = (iy * level.get_height() / image_height) * level_width; const size_t dest_y = (iy - origin_y) * color_tile.get_width() - origin_x; for (size_t ix = r.min.x; ix <= r.max.x; ++ix) { Color<float, 5> values; level.get_pixel( src_y + ix * level_width / image_width, &values[0]); const float rcp_alpha = values[3] == 0.0f ? 0.0f : 1.0f / values[3]; values[0] *= rcp_alpha; values[1] *= rcp_alpha; values[2] *= rcp_alpha; color_tile.set_pixel<float>(dest_y + ix, &values[0]); depth_tile.set_component(dest_y + ix, 0, values[4]); } } } else { for (size_t iy = r.min.y; iy <= r.max.y; ++iy) { const size_t level_width = level.get_width(); const size_t src_y = (iy * level.get_height() / image_height) * level_width; const size_t dest_y = (iy - origin_y) * color_tile.get_width() - origin_x; for (size_t ix = r.min.x; ix <= r.max.x; ++ix) { Color<float, 5> values; level.get_pixel( src_y + ix * level_width / image_width, &values[0]); color_tile.set_pixel<float>(dest_y + ix, &values[0]); depth_tile.set_component(dest_y + ix, 0, values[4]); } } } } } void LocalSampleAccumulationBuffer::develop_to_frame( Frame& frame, IAbortSwitch& abort_switch) { #ifdef PRINT_DETAILED_PERF_REPORTS Stopwatch<DefaultWallclockTimer> sw(0); sw.start(); #endif // Request exclusive access. unique_lock<shared_mutex> lock(m_mutex, defer_lock); while (true) { if (abort_switch.is_aborted()) return; if (lock.try_lock_for(chrono::milliseconds(5))) break; } #ifdef PRINT_DETAILED_PERF_REPORTS sw.measure(); const double t1 = sw.get_seconds(); RENDERER_LOG_DEBUG("develop_to_frame: acquiring lock: %f", t1 * 1000.0); #endif Image& color_image = frame.image(); Image& depth_image = frame.aov_images().get_image(0); const CanvasProperties& frame_props = color_image.properties(); assert(frame_props.m_canvas_width == m_levels[0]->get_width()); assert(frame_props.m_canvas_height == m_levels[0]->get_height()); assert(frame_props.m_channel_count == 4); const AABB2u& crop_window = frame.get_crop_window(); const bool undo_premultiplied_alpha = !frame.is_premultiplied_alpha(); const FilteredTile& level = *m_levels[m_active_level]; for (size_t ty = 0; ty < frame_props.m_tile_count_y; ++ty) { for (size_t tx = 0; tx < frame_props.m_tile_count_x; ++tx) { if (abort_switch.is_aborted()) return; const size_t origin_x = tx * frame_props.m_tile_width; const size_t origin_y = ty * frame_props.m_tile_height; Tile& color_tile = color_image.tile(tx, ty); Tile& depth_tile = depth_image.tile(tx, ty); develop_to_tile( color_tile, depth_tile, frame_props.m_canvas_width, frame_props.m_canvas_height, level, origin_x, origin_y, crop_window, undo_premultiplied_alpha); } } #ifdef PRINT_DETAILED_PERF_REPORTS sw.measure(); const double t2 = sw.get_seconds(); RENDERER_LOG_DEBUG("develop_to_frame: %f", (t2 - t1) * 1000.0); #endif } } // namespace renderer
// // This source file is part of appleseed. // Visit http://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited // Copyright (c) 2014-2016 Francois Beaune, The appleseedhq Organization // // 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. // // Interface header. #include "localsampleaccumulationbuffer.h" // appleseed.renderer headers. #include "renderer/kernel/rendering/sample.h" #include "renderer/kernel/aov/imagestack.h" #include "renderer/kernel/aov/tilestack.h" #include "renderer/modeling/frame/frame.h" // appleseed.foundation headers. #include "foundation/image/canvasproperties.h" #include "foundation/image/color.h" #include "foundation/image/filteredtile.h" #include "foundation/image/image.h" #include "foundation/image/pixel.h" #include "foundation/image/tile.h" #include "foundation/math/aabb.h" #include "foundation/math/scalar.h" #include "foundation/platform/timers.h" #include "foundation/utility/job/iabortswitch.h" #include "foundation/utility/stopwatch.h" // Boost headers. #include "boost/chrono/duration.hpp" // Standard headers. #include <algorithm> #include <cassert> using namespace boost; using namespace foundation; using namespace std; namespace renderer { // // LocalSampleAccumulationBuffer class implementation. // // The algorithm for progressive display deserves some explanations. Here is how it works: // // When the accumulation buffer is constructed, we create a stack of framebuffers of // decreasing resolution, much like a mipmap pyramid: each level of this pyramid is a // quarter of the resolution of the previous one (half the resolution in each dimension). // We don't actually go down all the way to the 1x1 level; instead we stop when we reach // a resolution that we consider provides a good balance between speed and usefulness. // // At render-time, the store_samples() method pushes the individual samples through this // pyramid. Samples are stored starting at the highest resolution level and up to what // we call the "active level", that is, the coarsest level of the pyramid that we're still // pushing samples to and the level that is displayed. As soon as a level contains enough // samples, it becomes the new active level. // //#define PRINT_DETAILED_PERF_REPORTS LocalSampleAccumulationBuffer::LocalSampleAccumulationBuffer( const size_t width, const size_t height, const Filter2f& filter) { const size_t MinSize = 32; size_t level_width = width; size_t level_height = height; while (true) { m_levels.push_back(new FilteredTile(level_width, level_height, 5, filter)); if (level_width <= MinSize && level_height <= MinSize) break; level_width = max(level_width / 2, MinSize); level_height = max(level_height / 2, MinSize); } m_remaining_pixels = new atomic<int32>[m_levels.size()]; clear(); } LocalSampleAccumulationBuffer::~LocalSampleAccumulationBuffer() { delete[] m_remaining_pixels; for (size_t i = 0, e = m_levels.size(); i < e; ++i) delete m_levels[i]; } void LocalSampleAccumulationBuffer::clear() { #ifdef PRINT_DETAILED_PERF_REPORTS Stopwatch<DefaultWallclockTimer> sw(0); sw.start(); #endif // Request exclusive access. unique_lock<shared_mutex> lock(m_mutex); #ifdef PRINT_DETAILED_PERF_REPORTS sw.measure(); RENDERER_LOG_DEBUG("clear: acquiring lock: %f", sw.get_seconds() * 1000.0); #endif m_sample_count = 0; for (size_t i = 0, e = m_levels.size(); i < e; ++i) { m_levels[i]->clear(); m_remaining_pixels[i] = static_cast<int32>(m_levels[i]->get_pixel_count()); } m_active_level = static_cast<uint32>(m_levels.size() - 1); } void LocalSampleAccumulationBuffer::store_samples( const size_t sample_count, const Sample samples[], IAbortSwitch& abort_switch) { #ifdef PRINT_DETAILED_PERF_REPORTS Stopwatch<DefaultWallclockTimer> sw(0); sw.start(); #endif { // Request non-exclusive access. shared_lock<shared_mutex> lock(m_mutex, defer_lock); while (true) { if (abort_switch.is_aborted()) return; if (lock.try_lock_for(chrono::milliseconds(5))) break; } #ifdef PRINT_DETAILED_PERF_REPORTS sw.measure(); RENDERER_LOG_DEBUG("store_samples: acquiring lock: %f", sw.get_seconds() * 1000.0); #endif // Store samples at every level, starting with the highest resolution level up to the active level. size_t counter = 0; for (uint32 i = 0, e = m_active_level; i <= e; ++i) { FilteredTile* level = m_levels[i]; const float level_width = static_cast<float>(level->get_width()); const float level_height = static_cast<float>(level->get_height()); const Sample* sample_end = samples + sample_count; for (const Sample* s = samples; s < sample_end; ++s) { if ((counter++ & 4096) == 0 && abort_switch.is_aborted()) return; const float fx = s->m_position.x * level_width; const float fy = s->m_position.y * level_height; level->add(fx, fy, s->m_values); } } } m_sample_count += sample_count; #ifdef PRINT_DETAILED_PERF_REPORTS sw.measure(); RENDERER_LOG_DEBUG("store_samples: " FMT_SIZE_T " -> %f", sample_count, sw.get_seconds() * 1000.0); #endif // Potentially update the new active level if we're not already at the highest resolution level. if (m_active_level > 0) { // Update pixel counters for all levels up to the active level. const int32 n = static_cast<int32>(sample_count); for (uint32 i = 0, e = m_active_level; i <= e; ++i) m_remaining_pixels[i].fetch_sub(n); // Find the new active level. uint32 cur_active_level = m_active_level; uint32 new_active_level = cur_active_level; for (uint32 i = 0, e = cur_active_level; i < e; ++i) { if (m_remaining_pixels[i] <= 0) { new_active_level = i; break; } } // Attempt to update the active level. It's OK if we fail, another thread will succeed. if (new_active_level < cur_active_level) m_active_level.compare_exchange_strong(cur_active_level, new_active_level); } } namespace { void develop_to_tile( Tile& color_tile, Tile& depth_tile, const size_t image_width, const size_t image_height, const FilteredTile& level, const size_t origin_x, const size_t origin_y, const AABB2u& crop_window, const bool undo_premultiplied_alpha) { const AABB2u r = AABB2u::intersect( AABB2u( Vector2u(origin_x, origin_y), Vector2u(origin_x + color_tile.get_width() - 1, origin_y + color_tile.get_height() - 1)), crop_window); if (undo_premultiplied_alpha) { for (size_t iy = r.min.y; iy <= r.max.y; ++iy) { const size_t level_width = level.get_width(); const size_t src_y = (iy * level.get_height() / image_height) * level_width; const size_t dest_y = (iy - origin_y) * color_tile.get_width() - origin_x; for (size_t ix = r.min.x; ix <= r.max.x; ++ix) { Color<float, 5> values; level.get_pixel( src_y + ix * level_width / image_width, &values[0]); const float rcp_alpha = values[3] == 0.0f ? 0.0f : 1.0f / values[3]; values[0] *= rcp_alpha; values[1] *= rcp_alpha; values[2] *= rcp_alpha; color_tile.set_pixel<float>(dest_y + ix, &values[0]); depth_tile.set_component(dest_y + ix, 0, values[4]); } } } else { for (size_t iy = r.min.y; iy <= r.max.y; ++iy) { const size_t level_width = level.get_width(); const size_t src_y = (iy * level.get_height() / image_height) * level_width; const size_t dest_y = (iy - origin_y) * color_tile.get_width() - origin_x; for (size_t ix = r.min.x; ix <= r.max.x; ++ix) { Color<float, 5> values; level.get_pixel( src_y + ix * level_width / image_width, &values[0]); color_tile.set_pixel<float>(dest_y + ix, &values[0]); depth_tile.set_component(dest_y + ix, 0, values[4]); } } } } } void LocalSampleAccumulationBuffer::develop_to_frame( Frame& frame, IAbortSwitch& abort_switch) { #ifdef PRINT_DETAILED_PERF_REPORTS Stopwatch<DefaultWallclockTimer> sw(0); sw.start(); #endif // Request exclusive access. unique_lock<shared_mutex> lock(m_mutex, defer_lock); while (true) { if (abort_switch.is_aborted()) return; if (lock.try_lock_for(chrono::milliseconds(5))) break; } #ifdef PRINT_DETAILED_PERF_REPORTS sw.measure(); const double t1 = sw.get_seconds(); RENDERER_LOG_DEBUG("develop_to_frame: acquiring lock: %f", t1 * 1000.0); #endif Image& color_image = frame.image(); Image& depth_image = frame.aov_images().get_image(0); const CanvasProperties& frame_props = color_image.properties(); assert(frame_props.m_canvas_width == m_levels[0]->get_width()); assert(frame_props.m_canvas_height == m_levels[0]->get_height()); assert(frame_props.m_channel_count == 4); const AABB2u& crop_window = frame.get_crop_window(); const bool undo_premultiplied_alpha = !frame.is_premultiplied_alpha(); const FilteredTile& level = *m_levels[m_active_level]; for (size_t ty = 0; ty < frame_props.m_tile_count_y; ++ty) { for (size_t tx = 0; tx < frame_props.m_tile_count_x; ++tx) { if (abort_switch.is_aborted()) return; const size_t origin_x = tx * frame_props.m_tile_width; const size_t origin_y = ty * frame_props.m_tile_height; Tile& color_tile = color_image.tile(tx, ty); Tile& depth_tile = depth_image.tile(tx, ty); develop_to_tile( color_tile, depth_tile, frame_props.m_canvas_width, frame_props.m_canvas_height, level, origin_x, origin_y, crop_window, undo_premultiplied_alpha); } } #ifdef PRINT_DETAILED_PERF_REPORTS sw.measure(); const double t2 = sw.get_seconds(); RENDERER_LOG_DEBUG("develop_to_frame: %f", (t2 - t1) * 1000.0); #endif } } // namespace renderer
Improve pyramid construction in sample accumulation buffer
Improve pyramid construction in sample accumulation buffer
C++
mit
pjessesco/appleseed,Vertexwahn/appleseed,aiivashchenko/appleseed,dictoon/appleseed,pjessesco/appleseed,dictoon/appleseed,Vertexwahn/appleseed,aytekaman/appleseed,Biart95/appleseed,pjessesco/appleseed,gospodnetic/appleseed,Aakash1312/appleseed,luisbarrancos/appleseed,Aakash1312/appleseed,est77/appleseed,est77/appleseed,dictoon/appleseed,Biart95/appleseed,aiivashchenko/appleseed,luisbarrancos/appleseed,dictoon/appleseed,luisbarrancos/appleseed,appleseedhq/appleseed,Biart95/appleseed,Aakash1312/appleseed,Vertexwahn/appleseed,appleseedhq/appleseed,Biart95/appleseed,glebmish/appleseed,gospodnetic/appleseed,glebmish/appleseed,pjessesco/appleseed,luisbarrancos/appleseed,Biart95/appleseed,Vertexwahn/appleseed,aytekaman/appleseed,aytekaman/appleseed,pjessesco/appleseed,Aakash1312/appleseed,est77/appleseed,aytekaman/appleseed,est77/appleseed,gospodnetic/appleseed,appleseedhq/appleseed,Aakash1312/appleseed,Vertexwahn/appleseed,glebmish/appleseed,aiivashchenko/appleseed,aiivashchenko/appleseed,dictoon/appleseed,appleseedhq/appleseed,gospodnetic/appleseed,aytekaman/appleseed,glebmish/appleseed,luisbarrancos/appleseed,gospodnetic/appleseed,appleseedhq/appleseed,est77/appleseed,glebmish/appleseed,aiivashchenko/appleseed
9fea039054ba3e1992e9f1f9bce45b4ef9fa2608
NaoTHSoccer/Source/Motion/Engine/InverseKinematicsMotion/Motions/IKParameters.cpp
NaoTHSoccer/Source/Motion/Engine/InverseKinematicsMotion/Motions/IKParameters.cpp
/** * @file IKParameters.cpp * * @author <a href="mailto:[email protected]">Xu, Yuan</a> * Implement of parameters for IK motion */ #include "IKParameters.h" IKParameters::IKParameters() :ParameterList("IKParameters") { PARAMETER_REGISTER(footOffsetY) = 0; // stand parameter PARAMETER_REGISTER(stand.speed) = 0.04; PARAMETER_REGISTER(stand.enableStabilization) = true; PARAMETER_REGISTER(stand.enableStabilizationRC16) = false; PARAMETER_REGISTER(stand.stiffness) = 0.7; PARAMETER_ANGLE_REGISTER(stand.bodyPitchOffset) = 0.2; PARAMETER_REGISTER(stand.hipOffsetX) = 15; // relax PARAMETER_REGISTER(stand.relax.enable) = true; PARAMETER_REGISTER(stand.relax.allowedDeviation) = 5; // [mm] PARAMETER_ANGLE_REGISTER(stand.relax.allowedRotationDeviation) = 5; // [rad] PARAMETER_REGISTER(stand.relax.timeBonusForCorrection) = 1000; // [ms] PARAMETER_REGISTER(stand.relax.jointOffsetTuning.enable) = true; PARAMETER_REGISTER(stand.relax.jointOffsetTuning.deadTime) = 1000; // [ms] PARAMETER_REGISTER(stand.relax.jointOffsetTuning.currentThreshold) = 0.3; // [A] PARAMETER_REGISTER(stand.relax.jointOffsetTuning.minimalJointStep) = 0.0013962634; // [rad] PARAMETER_REGISTER(stand.relax.stiffnessControl.enable) = true; PARAMETER_REGISTER(stand.relax.stiffnessControl.deadTime) = 100; // [ms] PARAMETER_REGISTER(stand.relax.stiffnessControl.minAngle) = 0.08; // [°] PARAMETER_REGISTER(stand.relax.stiffnessControl.maxAngle) = 2; // [°] PARAMETER_REGISTER(stand.relax.stiffnessControl.minStiffness) = 0.3; PARAMETER_REGISTER(stand.relax.stiffnessControl.maxStiffness) = 1.0; // walk parameter: // General PARAMETER_ANGLE_REGISTER(walk.general.bodyPitchOffset) = 0.2; PARAMETER_REGISTER(walk.general.hipOffsetX) = 15; PARAMETER_REGISTER(walk.general.stiffness) = 0.7; PARAMETER_REGISTER(walk.general.stiffnessArms) = 0.7; PARAMETER_REGISTER(walk.general.useArm) = false; PARAMETER_REGISTER(walk.general.hipRollSingleSupFactorLeft) = 0.4; PARAMETER_REGISTER(walk.general.hipRollSingleSupFactorRight) = 0.4; // hip trajectory geometry PARAMETER_REGISTER(walk.hip.comHeight) = 260; PARAMETER_REGISTER(walk.hip.comHeightOffset) = 0.18; PARAMETER_REGISTER(walk.hip.comStepOffsetY) = 0; PARAMETER_REGISTER(walk.hip.ZMPOffsetY) = 5; PARAMETER_REGISTER(walk.hip.ZMPOffsetYByCharacter) = 0; // experimental: new ZMP PARAMETER_REGISTER(walk.hip.newZMP_ON) = false; PARAMETER_REGISTER(walk.hip.newZMP_offset) = 0.8; PARAMETER_REGISTER(walk.hip.newZMP_width) = 0.4; PARAMETER_REGISTER(walk.zmp.bezier.transitionScaling) = 0.6; PARAMETER_REGISTER(walk.zmp.bezier.inFootScalingY) = 1; PARAMETER_REGISTER(walk.zmp.bezier.inFootSpacing) = 10; PARAMETER_REGISTER(walk.zmp.bezier.offsetX) = 15; PARAMETER_REGISTER(walk.zmp.bezier.offsetY) = 0; PARAMETER_REGISTER(walk.zmp.bezier.offsetYForKicks) = 0; PARAMETER_REGISTER(walk.zmp.bezier2.offsetY) = 0; PARAMETER_REGISTER(walk.zmp.bezier2.offsetT) = 0; // step geometry PARAMETER_REGISTER(walk.step.duration) = 300; PARAMETER_REGISTER(walk.step.doubleSupportTime) = 40; PARAMETER_REGISTER(walk.step.stepHeight) = 15; PARAMETER_REGISTER(walk.step.splineFootTrajectory) = true; // kick PARAMETER_REGISTER(walk.kick.stepHeight) = 20; PARAMETER_REGISTER(walk.kick.ZMPOffsetY) = 0; // step limits PARAMETER_REGISTER(walk.limits.maxTurnInner) = 10; PARAMETER_REGISTER(walk.limits.maxStepTurn) = 30; PARAMETER_REGISTER(walk.limits.maxStepLength) = 50; PARAMETER_REGISTER(walk.limits.maxStepLengthBack) = 50; PARAMETER_REGISTER(walk.limits.maxStepWidth) = 50; PARAMETER_REGISTER(walk.limits.maxStepChange) = 0.5; // step control PARAMETER_REGISTER(walk.limits.maxCtrlTurn) = 30; PARAMETER_REGISTER(walk.limits.maxCtrlLength) = 80; PARAMETER_REGISTER(walk.limits.maxCtrlWidth) = 50; // Stabilization //PARAMETER_REGISTER(walk.stabilization.enableFSRProtection) = true; //PARAMETER_REGISTER(walk.stabilization.enableWaitLanding) = false; //PARAMETER_REGISTER(walk.stabilization.minFSRProtectionCount) = 0; //PARAMETER_REGISTER(walk.stabilization.maxUnsupportedCount) = 0; //PARAMETER_REGISTER(walk.stabilization.maxWaitLandingCount) = 20; PARAMETER_REGISTER(walk.stabilization.emergencyStopError) = 500; PARAMETER_REGISTER(walk.stabilization.rotationStabilize) = true; PARAMETER_REGISTER(walk.stabilization.rotationStabilizeRC16) = false; PARAMETER_REGISTER(walk.stabilization.rotationStabilizeNewIMU) = false; PARAMETER_REGISTER(walk.stabilization.rotationP.x) = 0; PARAMETER_REGISTER(walk.stabilization.rotationP.y) = 0; PARAMETER_REGISTER(walk.stabilization.rotationVelocityP.x) = 0; PARAMETER_REGISTER(walk.stabilization.rotationVelocityP.y) = 0; PARAMETER_REGISTER(walk.stabilization.rotationD.x) = 0; PARAMETER_REGISTER(walk.stabilization.rotationD.y) = 0; PARAMETER_REGISTER(walk.stabilization.stabilizeFeet) = true; PARAMETER_REGISTER(walk.stabilization.stabilizeFeetP.x) = 0.04; PARAMETER_REGISTER(walk.stabilization.stabilizeFeetP.y) = 0.035; PARAMETER_REGISTER(walk.stabilization.stabilizeFeetD.x) = -0.4; PARAMETER_REGISTER(walk.stabilization.stabilizeFeetD.y) = -0.3; PARAMETER_REGISTER(walk.stabilization.dynamicStepsize) = true; PARAMETER_REGISTER(walk.stabilization.dynamicStepsizeP) = -1; PARAMETER_REGISTER(walk.stabilization.dynamicStepsizeD) = 0.5; // rotation stabilize parameter PARAMETER_REGISTER(rotationStabilize.k.x) = -0.5; PARAMETER_REGISTER(rotationStabilize.k.y) = -0.2; PARAMETER_REGISTER(rotationStabilize.threshold.x) = 2; PARAMETER_REGISTER(rotationStabilize.threshold.y) = 3; // arm parameter PARAMETER_REGISTER(arm.inertialModelBasedMovement.shoulderPitchInterialSensorRate) = -10; PARAMETER_REGISTER(arm.inertialModelBasedMovement.shoulderRollInterialSensorRate) = -10; PARAMETER_REGISTER(arm.synchronisedWithWalk.shoulderPitchRate) = 0.5; PARAMETER_REGISTER(arm.synchronisedWithWalk.shoulderRollRate) = 0.5; PARAMETER_REGISTER(arm.synchronisedWithWalk.elbowRollRate) = 0.5; PARAMETER_REGISTER(arm.maxSpeed) = 60; PARAMETER_REGISTER(balanceCoM.kP) = 0; PARAMETER_REGISTER(balanceCoM.kI) = 0; PARAMETER_REGISTER(balanceCoM.kD) = 0; PARAMETER_REGISTER(balanceCoM.threshold) = 10; syncWithConfig(); } IKParameters::~IKParameters() { }
/** * @file IKParameters.cpp * * @author <a href="mailto:[email protected]">Xu, Yuan</a> * Implement of parameters for IK motion */ #include "IKParameters.h" IKParameters::IKParameters() :ParameterList("IKParameters") { PARAMETER_REGISTER(footOffsetY) = 0; // stand parameter PARAMETER_REGISTER(stand.speed) = 0.04; PARAMETER_REGISTER(stand.enableStabilization) = true; PARAMETER_REGISTER(stand.enableStabilizationRC16) = false; PARAMETER_REGISTER(stand.stiffness) = 0.7; PARAMETER_ANGLE_REGISTER(stand.bodyPitchOffset) = 0.2; PARAMETER_REGISTER(stand.hipOffsetX) = 15; // relax PARAMETER_REGISTER(stand.relax.enable) = true; PARAMETER_REGISTER(stand.relax.allowedDeviation) = 5; // [mm] PARAMETER_ANGLE_REGISTER(stand.relax.allowedRotationDeviation) = 5; // [rad] PARAMETER_REGISTER(stand.relax.timeBonusForCorrection) = 1000; // [ms] PARAMETER_REGISTER(stand.relax.jointOffsetTuning.enable) = true; PARAMETER_REGISTER(stand.relax.jointOffsetTuning.deadTime) = 1000; // [ms] PARAMETER_REGISTER(stand.relax.jointOffsetTuning.currentThreshold) = 0.3; // [A] PARAMETER_REGISTER(stand.relax.jointOffsetTuning.minimalJointStep) = 0.0013962634; // [rad] PARAMETER_REGISTER(stand.relax.stiffnessControl.enable) = true; PARAMETER_REGISTER(stand.relax.stiffnessControl.deadTime) = 100; // [ms] PARAMETER_REGISTER(stand.relax.stiffnessControl.minAngle) = 0.08; // [°] PARAMETER_REGISTER(stand.relax.stiffnessControl.maxAngle) = 2; // [°] PARAMETER_REGISTER(stand.relax.stiffnessControl.minStiffness) = 0.3; PARAMETER_REGISTER(stand.relax.stiffnessControl.maxStiffness) = 1.0; // walk parameter: // General PARAMETER_ANGLE_REGISTER(walk.general.bodyPitchOffset) = 0.2; PARAMETER_REGISTER(walk.general.hipOffsetX) = 15; PARAMETER_REGISTER(walk.general.stiffness) = 0.7; PARAMETER_REGISTER(walk.general.stiffnessArms) = 0.7; PARAMETER_REGISTER(walk.general.useArm) = false; PARAMETER_REGISTER(walk.general.hipRollSingleSupFactorLeft) = 0.4; PARAMETER_REGISTER(walk.general.hipRollSingleSupFactorRight) = 0.4; // hip trajectory geometry PARAMETER_REGISTER(walk.hip.comHeight) = 260; PARAMETER_REGISTER(walk.hip.comHeightOffset) = 0.18; PARAMETER_REGISTER(walk.hip.comStepOffsetY) = 0; PARAMETER_REGISTER(walk.hip.ZMPOffsetY) = 5; PARAMETER_REGISTER(walk.hip.ZMPOffsetYByCharacter) = 0; // experimental: new ZMP PARAMETER_REGISTER(walk.hip.newZMP_ON) = false; PARAMETER_REGISTER(walk.hip.newZMP_offset) = 0.8; PARAMETER_REGISTER(walk.hip.newZMP_width) = 0.4; PARAMETER_REGISTER(walk.zmp.bezier.transitionScaling) = 0.6; PARAMETER_REGISTER(walk.zmp.bezier.inFootScalingY) = 1; PARAMETER_REGISTER(walk.zmp.bezier.inFootSpacing) = 10; PARAMETER_REGISTER(walk.zmp.bezier.offsetX) = 20; PARAMETER_REGISTER(walk.zmp.bezier.offsetY) = 0; PARAMETER_REGISTER(walk.zmp.bezier.offsetYForKicks) = 0; PARAMETER_REGISTER(walk.zmp.bezier2.offsetY) = 0; PARAMETER_REGISTER(walk.zmp.bezier2.offsetT) = 0; // step geometry PARAMETER_REGISTER(walk.step.duration) = 300; PARAMETER_REGISTER(walk.step.doubleSupportTime) = 40; PARAMETER_REGISTER(walk.step.stepHeight) = 15; PARAMETER_REGISTER(walk.step.splineFootTrajectory) = true; // kick PARAMETER_REGISTER(walk.kick.stepHeight) = 20; PARAMETER_REGISTER(walk.kick.ZMPOffsetY) = 0; // step limits PARAMETER_REGISTER(walk.limits.maxTurnInner) = 10; PARAMETER_REGISTER(walk.limits.maxStepTurn) = 30; PARAMETER_REGISTER(walk.limits.maxStepLength) = 50; PARAMETER_REGISTER(walk.limits.maxStepLengthBack) = 50; PARAMETER_REGISTER(walk.limits.maxStepWidth) = 50; PARAMETER_REGISTER(walk.limits.maxStepChange) = 0.5; // step control PARAMETER_REGISTER(walk.limits.maxCtrlTurn) = 30; PARAMETER_REGISTER(walk.limits.maxCtrlLength) = 80; PARAMETER_REGISTER(walk.limits.maxCtrlWidth) = 50; // Stabilization //PARAMETER_REGISTER(walk.stabilization.enableFSRProtection) = true; //PARAMETER_REGISTER(walk.stabilization.enableWaitLanding) = false; //PARAMETER_REGISTER(walk.stabilization.minFSRProtectionCount) = 0; //PARAMETER_REGISTER(walk.stabilization.maxUnsupportedCount) = 0; //PARAMETER_REGISTER(walk.stabilization.maxWaitLandingCount) = 20; PARAMETER_REGISTER(walk.stabilization.emergencyStopError) = 500; PARAMETER_REGISTER(walk.stabilization.rotationStabilize) = true; PARAMETER_REGISTER(walk.stabilization.rotationStabilizeRC16) = false; PARAMETER_REGISTER(walk.stabilization.rotationStabilizeNewIMU) = false; PARAMETER_REGISTER(walk.stabilization.rotationP.x) = 0; PARAMETER_REGISTER(walk.stabilization.rotationP.y) = 0; PARAMETER_REGISTER(walk.stabilization.rotationVelocityP.x) = 0; PARAMETER_REGISTER(walk.stabilization.rotationVelocityP.y) = 0; PARAMETER_REGISTER(walk.stabilization.rotationD.x) = 0; PARAMETER_REGISTER(walk.stabilization.rotationD.y) = 0; PARAMETER_REGISTER(walk.stabilization.stabilizeFeet) = true; PARAMETER_REGISTER(walk.stabilization.stabilizeFeetP.x) = 0.04; PARAMETER_REGISTER(walk.stabilization.stabilizeFeetP.y) = 0.035; PARAMETER_REGISTER(walk.stabilization.stabilizeFeetD.x) = -0.4; PARAMETER_REGISTER(walk.stabilization.stabilizeFeetD.y) = -0.3; PARAMETER_REGISTER(walk.stabilization.dynamicStepsize) = true; PARAMETER_REGISTER(walk.stabilization.dynamicStepsizeP) = -1; PARAMETER_REGISTER(walk.stabilization.dynamicStepsizeD) = 0.5; // rotation stabilize parameter PARAMETER_REGISTER(rotationStabilize.k.x) = -0.5; PARAMETER_REGISTER(rotationStabilize.k.y) = -0.2; PARAMETER_REGISTER(rotationStabilize.threshold.x) = 2; PARAMETER_REGISTER(rotationStabilize.threshold.y) = 3; // arm parameter PARAMETER_REGISTER(arm.inertialModelBasedMovement.shoulderPitchInterialSensorRate) = -10; PARAMETER_REGISTER(arm.inertialModelBasedMovement.shoulderRollInterialSensorRate) = -10; PARAMETER_REGISTER(arm.synchronisedWithWalk.shoulderPitchRate) = 0.5; PARAMETER_REGISTER(arm.synchronisedWithWalk.shoulderRollRate) = 0.5; PARAMETER_REGISTER(arm.synchronisedWithWalk.elbowRollRate) = 0.5; PARAMETER_REGISTER(arm.maxSpeed) = 60; PARAMETER_REGISTER(balanceCoM.kP) = 0; PARAMETER_REGISTER(balanceCoM.kI) = 0; PARAMETER_REGISTER(balanceCoM.kD) = 0; PARAMETER_REGISTER(balanceCoM.threshold) = 10; syncWithConfig(); } IKParameters::~IKParameters() { }
increase offsetX
increase offsetX
C++
apache-2.0
BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH
d4b90aab7da51287276c4ba8cc57586e03ee143a
Code/IO/src/sitkImageFileReader.cxx
Code/IO/src/sitkImageFileReader.cxx
/*========================================================================= * * Copyright Insight Software Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #ifdef _MFC_VER #pragma warning(disable:4996) #endif #include "sitkImageFileReader.h" #include <itkImageFileReader.h> #include "sitkMetaDataDictionaryCustomCast.hxx" namespace itk { namespace simple { Image ReadImage ( const std::string &filename, PixelIDValueEnum outputPixelType ) { ImageFileReader reader; return reader.SetFileName ( filename ).SetOutputPixelType(outputPixelType).Execute(); } ImageFileReader::ImageFileReader() : m_PixelType(sitkUnknown), m_Dimension(0), m_NumberOfComponents(0) { // list of pixel types supported typedef NonLabelPixelIDTypeList PixelIDTypeList; this->m_MemberFactory.reset( new detail::MemberFunctionFactory<MemberFunctionType>( this ) ); this->m_MemberFactory->RegisterMemberFunctions< PixelIDTypeList, 4 > (); this->m_MemberFactory->RegisterMemberFunctions< PixelIDTypeList, 3 > (); this->m_MemberFactory->RegisterMemberFunctions< PixelIDTypeList, 2 > (); } std::string ImageFileReader::ToString() const { std::ostringstream out; out << "itk::simple::ImageFileReader"; out << std::endl; out << " FileName: \""; this->ToStringHelper(out, this->m_FileName) << "\"" << std::endl; out << " Image Information:" << " PixelType: "; this->ToStringHelper(out, this->m_PixelType) << std::endl; out << " Dimension: " << this->m_Dimension << std::endl; out << " NumberOfComponents: " << this->m_NumberOfComponents << std::endl; out << " Direction: " << this->m_Direction << std::endl; out << " Origin: " << this->m_Origin << std::endl; out << " Spacing: " << this->m_Spacing << std::endl; out << " Size: " << this->m_Size << std::endl; out << ImageReaderBase::ToString(); return out.str(); } ImageFileReader& ImageFileReader::SetFileName ( const std::string &fn ) { this->m_FileName = fn; return *this; } std::string ImageFileReader::GetFileName() const { return this->m_FileName; } void ImageFileReader ::UpdateImageInformationFromImageIO(const itk::ImageIOBase* iobase) { PixelIDValueType pixelType; this->GetPixelIDFromImageIO(iobase, pixelType, m_Dimension); std::vector<double> direction; direction.reserve(m_Dimension*m_Dimension); std::vector<double> origin(m_Dimension); std::vector<double> spacing(m_Dimension); std::vector<uint64_t> size(m_Dimension); for( unsigned int i = 0; i < m_Dimension; ++i) { origin[i] = iobase->GetOrigin(i); spacing[i] = iobase->GetSpacing(i); size[i] = iobase->GetDimensions(i); const std::vector< double > temp_direction = iobase->GetDirection(i); direction.insert(direction.end(), temp_direction.begin(), temp_direction.end()); } // release functions bound to old meta data dictionary if (m_MetaDataDictionary.get()) { this->m_pfGetMetaDataKeys = SITK_NULLPTR; this->m_pfHasMetaDataKey = SITK_NULLPTR; this->m_pfGetMetaData = SITK_NULLPTR; } this->m_MetaDataDictionary.reset(new MetaDataDictionary(iobase->GetMetaDataDictionary())); m_PixelType = static_cast<PixelIDValueEnum>(pixelType); // Should this be as reported by ImageIO, or as reported by sitk::Image? m_NumberOfComponents = iobase->GetNumberOfComponents(); using std::swap; swap(direction, m_Direction); swap(origin, m_Origin); swap(spacing, m_Spacing); swap(size, m_Size); this->m_pfGetMetaDataKeys = nsstd::bind(&MetaDataDictionary::GetKeys, this->m_MetaDataDictionary.get()); this->m_pfHasMetaDataKey = nsstd::bind(&MetaDataDictionary::HasKey, this->m_MetaDataDictionary.get(), nsstd::placeholders::_1); this->m_pfGetMetaData = nsstd::bind(&GetMetaDataDictionaryCustomCast::CustomCast, this->m_MetaDataDictionary.get(), nsstd::placeholders::_1); } PixelIDValueEnum ImageFileReader ::GetPixelID( void ) const { return this->m_PixelType; } PixelIDValueType ImageFileReader ::GetPixelIDValue( void ) const { return this->m_PixelType; } unsigned int ImageFileReader ::GetDimension( void ) const { return this->m_Dimension; } unsigned int ImageFileReader ::GetNumberOfComponents( void ) const { return this->m_NumberOfComponents; } const std::vector<double> & ImageFileReader ::GetOrigin( void ) const { return this->m_Origin; } const std::vector<double> & ImageFileReader ::GetSpacing( void ) const { return this->m_Spacing; } const std::vector<double> & ImageFileReader ::GetDirection() const { return this->m_Direction; } const std::vector<uint64_t> & ImageFileReader ::GetSize( void ) const { return this->m_Size; } void ImageFileReader ::ReadImageInformation( void ) { itk::ImageIOBase::Pointer imageio = this->GetImageIOBase( this->m_FileName ); this->UpdateImageInformationFromImageIO(imageio); } std::vector<std::string> ImageFileReader ::GetMetaDataKeys( void ) const { return this->m_pfGetMetaDataKeys(); } bool ImageFileReader ::HasMetaDataKey( const std::string &key ) const { return this->m_pfHasMetaDataKey(key); } std::string ImageFileReader ::GetMetaData( const std::string &key ) const { return this->m_pfGetMetaData(key); } Image ImageFileReader::Execute () { PixelIDValueType type = this->GetOutputPixelType(); unsigned int dimension = 0; itk::ImageIOBase::Pointer imageio = this->GetImageIOBase( this->m_FileName ); if (type == sitkUnknown) { this->GetPixelIDFromImageIO( imageio, type, dimension ); } else { PixelIDValueType unused; this->GetPixelIDFromImageIO( imageio, unused, dimension ); } #ifdef SITK_4D_IMAGES if ( dimension != 2 && dimension != 3 && dimension != 4 ) #else if ( dimension != 2 && dimension != 3 ) #endif { sitkExceptionMacro( "The file has unsupported " << dimension << " dimensions." ); } if ( !this->m_MemberFactory->HasMemberFunction( type, dimension ) ) { sitkExceptionMacro( << "PixelType is not supported!" << std::endl << "Pixel Type: " << GetPixelIDValueAsString( type ) << std::endl << "Refusing to load! " << std::endl ); } return this->m_MemberFactory->GetMemberFunction( type, dimension )(imageio.GetPointer()); } template <class TImageType> Image ImageFileReader::ExecuteInternal( itk::ImageIOBase *imageio ) { typedef TImageType ImageType; typedef itk::ImageFileReader<ImageType> Reader; // if the InstantiatedToken is correctly implemented this should // not occur assert( ImageTypeToPixelIDValue<ImageType>::Result != (int)sitkUnknown ); assert( imageio != SITK_NULLPTR ); typename Reader::Pointer reader = Reader::New(); reader->SetImageIO( imageio ); reader->SetFileName( this->m_FileName.c_str() ); this->PreUpdate( reader.GetPointer() ); reader->Update(); return Image( reader->GetOutput() ); } } }
/*========================================================================= * * Copyright Insight Software Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #ifdef _MFC_VER #pragma warning(disable:4996) #endif #include "sitkImageFileReader.h" #include <itkImageFileReader.h> #include "sitkMetaDataDictionaryCustomCast.hxx" namespace itk { namespace simple { Image ReadImage ( const std::string &filename, PixelIDValueEnum outputPixelType ) { ImageFileReader reader; return reader.SetFileName ( filename ).SetOutputPixelType(outputPixelType).Execute(); } ImageFileReader::ImageFileReader() : m_PixelType(sitkUnknown), m_Dimension(0), m_NumberOfComponents(0) { // list of pixel types supported typedef NonLabelPixelIDTypeList PixelIDTypeList; this->m_MemberFactory.reset( new detail::MemberFunctionFactory<MemberFunctionType>( this ) ); this->m_MemberFactory->RegisterMemberFunctions< PixelIDTypeList, 4 > (); this->m_MemberFactory->RegisterMemberFunctions< PixelIDTypeList, 3 > (); this->m_MemberFactory->RegisterMemberFunctions< PixelIDTypeList, 2 > (); } std::string ImageFileReader::ToString() const { std::ostringstream out; out << "itk::simple::ImageFileReader"; out << std::endl; out << " FileName: \""; this->ToStringHelper(out, this->m_FileName) << "\"" << std::endl; out << " Image Information:" << " PixelType: "; this->ToStringHelper(out, this->m_PixelType) << std::endl; out << " Dimension: " << this->m_Dimension << std::endl; out << " NumberOfComponents: " << this->m_NumberOfComponents << std::endl; out << " Direction: " << this->m_Direction << std::endl; out << " Origin: " << this->m_Origin << std::endl; out << " Spacing: " << this->m_Spacing << std::endl; out << " Size: " << this->m_Size << std::endl; out << ImageReaderBase::ToString(); return out.str(); } ImageFileReader& ImageFileReader::SetFileName ( const std::string &fn ) { this->m_FileName = fn; return *this; } std::string ImageFileReader::GetFileName() const { return this->m_FileName; } void ImageFileReader ::UpdateImageInformationFromImageIO(const itk::ImageIOBase* iobase) { PixelIDValueType pixelType; this->GetPixelIDFromImageIO(iobase, pixelType, m_Dimension); std::vector<double> direction; direction.reserve(m_Dimension*m_Dimension); std::vector<double> origin(m_Dimension); std::vector<double> spacing(m_Dimension); std::vector<uint64_t> size(m_Dimension); for( unsigned int i = 0; i < m_Dimension; ++i) { origin[i] = iobase->GetOrigin(i); spacing[i] = iobase->GetSpacing(i); size[i] = iobase->GetDimensions(i); const std::vector< double > temp_direction = iobase->GetDirection(i); direction.insert(direction.end(), temp_direction.begin(), temp_direction.end()); } // release functions bound to old meta data dictionary if (m_MetaDataDictionary.get()) { this->m_pfGetMetaDataKeys = SITK_NULLPTR; this->m_pfHasMetaDataKey = SITK_NULLPTR; this->m_pfGetMetaData = SITK_NULLPTR; } this->m_MetaDataDictionary.reset(new MetaDataDictionary(iobase->GetMetaDataDictionary())); m_PixelType = static_cast<PixelIDValueEnum>(pixelType); // Should this be as reported by ImageIO, or as reported by sitk::Image? m_NumberOfComponents = iobase->GetNumberOfComponents(); using std::swap; swap(direction, m_Direction); swap(origin, m_Origin); swap(spacing, m_Spacing); swap(size, m_Size); this->m_pfGetMetaDataKeys = nsstd::bind(&MetaDataDictionary::GetKeys, this->m_MetaDataDictionary.get()); this->m_pfHasMetaDataKey = nsstd::bind(&MetaDataDictionary::HasKey, this->m_MetaDataDictionary.get(), nsstd::placeholders::_1); this->m_pfGetMetaData = nsstd::bind(&GetMetaDataDictionaryCustomCast::CustomCast, this->m_MetaDataDictionary.get(), nsstd::placeholders::_1); } PixelIDValueEnum ImageFileReader ::GetPixelID( void ) const { return this->m_PixelType; } PixelIDValueType ImageFileReader ::GetPixelIDValue( void ) const { return this->m_PixelType; } unsigned int ImageFileReader ::GetDimension( void ) const { return this->m_Dimension; } unsigned int ImageFileReader ::GetNumberOfComponents( void ) const { return this->m_NumberOfComponents; } const std::vector<double> & ImageFileReader ::GetOrigin( void ) const { return this->m_Origin; } const std::vector<double> & ImageFileReader ::GetSpacing( void ) const { return this->m_Spacing; } const std::vector<double> & ImageFileReader ::GetDirection() const { return this->m_Direction; } const std::vector<uint64_t> & ImageFileReader ::GetSize( void ) const { return this->m_Size; } void ImageFileReader ::ReadImageInformation( void ) { itk::ImageIOBase::Pointer imageio = this->GetImageIOBase( this->m_FileName ); this->UpdateImageInformationFromImageIO(imageio); } std::vector<std::string> ImageFileReader ::GetMetaDataKeys( void ) const { return this->m_pfGetMetaDataKeys(); } bool ImageFileReader ::HasMetaDataKey( const std::string &key ) const { return this->m_pfHasMetaDataKey(key); } std::string ImageFileReader ::GetMetaData( const std::string &key ) const { return this->m_pfGetMetaData(key); } Image ImageFileReader::Execute () { PixelIDValueType type = this->GetOutputPixelType(); itk::ImageIOBase::Pointer imageio = this->GetImageIOBase( this->m_FileName ); this->UpdateImageInformationFromImageIO(imageio); const unsigned int dimension = this->GetDimension(); if (type == sitkUnknown) { type = this->GetPixelIDValue(); } #ifdef SITK_4D_IMAGES if ( dimension != 2 && dimension != 3 && dimension != 4 ) #else if ( dimension != 2 && dimension != 3 ) #endif { sitkExceptionMacro( "The file has unsupported " << dimension << " dimensions." ); } if ( !this->m_MemberFactory->HasMemberFunction( type, dimension ) ) { sitkExceptionMacro( << "PixelType is not supported!" << std::endl << "Pixel Type: " << GetPixelIDValueAsString( type ) << std::endl << "Refusing to load! " << std::endl ); } return this->m_MemberFactory->GetMemberFunction( type, dimension )(imageio.GetPointer()); } template <class TImageType> Image ImageFileReader::ExecuteInternal( itk::ImageIOBase *imageio ) { typedef TImageType ImageType; typedef itk::ImageFileReader<ImageType> Reader; // if the InstantiatedToken is correctly implemented this should // not occur assert( ImageTypeToPixelIDValue<ImageType>::Result != (int)sitkUnknown ); assert( imageio != SITK_NULLPTR ); typename Reader::Pointer reader = Reader::New(); reader->SetImageIO( imageio ); reader->SetFileName( this->m_FileName.c_str() ); this->PreUpdate( reader.GetPointer() ); reader->Update(); return Image( reader->GetOutput() ); } } }
Update the full image information for every execute of the reader
Update the full image information for every execute of the reader The downside to this is that the extra copies will still occur with the procedural interface even though the copied data can not be used.
C++
apache-2.0
SimpleITK/SimpleITK,InsightSoftwareConsortium/SimpleITK,kaspermarstal/SimpleElastix,SimpleITK/SimpleITK,blowekamp/SimpleITK,InsightSoftwareConsortium/SimpleITK,SimpleITK/SimpleITK,richardbeare/SimpleITK,richardbeare/SimpleITK,kaspermarstal/SimpleElastix,kaspermarstal/SimpleElastix,blowekamp/SimpleITK,blowekamp/SimpleITK,blowekamp/SimpleITK,blowekamp/SimpleITK,blowekamp/SimpleITK,richardbeare/SimpleITK,InsightSoftwareConsortium/SimpleITK,SimpleITK/SimpleITK,InsightSoftwareConsortium/SimpleITK,SimpleITK/SimpleITK,richardbeare/SimpleITK,InsightSoftwareConsortium/SimpleITK,SimpleITK/SimpleITK,kaspermarstal/SimpleElastix,kaspermarstal/SimpleElastix,richardbeare/SimpleITK,richardbeare/SimpleITK,InsightSoftwareConsortium/SimpleITK,InsightSoftwareConsortium/SimpleITK,blowekamp/SimpleITK,kaspermarstal/SimpleElastix,SimpleITK/SimpleITK,kaspermarstal/SimpleElastix,SimpleITK/SimpleITK,InsightSoftwareConsortium/SimpleITK,richardbeare/SimpleITK,richardbeare/SimpleITK,blowekamp/SimpleITK
bfd21e3f90079542e86596da2469871d47753aaa
ykman-gui/main.cpp
ykman-gui/main.cpp
#include <QApplication> #include <QQmlApplicationEngine> #include <QQmlContext> #include <stdlib.h> #include <QtGlobal> #include <QtWidgets> int main(int argc, char *argv[]) { // Global menubar is broken for qt5 apps in Ubuntu Unity, see: // https://bugs.launchpad.net/ubuntu/+source/appmenu-qt5/+bug/1323853 // This workaround enables a local menubar. qputenv("UBUNTU_MENUPROXY","0"); // Don't write .pyc files. qputenv("PYTHONDONTWRITEBYTECODE", "1"); QApplication app(argc, argv); QString app_dir = app.applicationDirPath(); QString main_qml = "/qml/main.qml"; QString path_prefix; QString url_prefix; app.setApplicationName("YubiKey Manager"); app.setApplicationVersion(APP_VERSION); app.setOrganizationName("Yubico"); app.setOrganizationDomain("com.yubico"); QCommandLineParser cliParser; cliParser.setApplicationDescription("Cross-platform application for YubiKey configuration"); cliParser.addHelpOption(); cliParser.addVersionOption(); cliParser.addOptions({ {"log-level", QCoreApplication::translate("main", "Enable logging at verbosity <LEVEL>: DEBUG, INFO, WARNING, ERROR, CRITICAL"), QCoreApplication::translate("main", "LEVEL")}, {"log-file", QCoreApplication::translate("main", "Print logs to <FILE> instead of standard output; ignored without --log-level"), QCoreApplication::translate("main", "FILE")}, }); cliParser.process(app); // A lock file is used, to ensure only one running instance at the time. QString tmpDir = QDir::tempPath(); QLockFile lockFile(tmpDir + "/ykman-gui.lock"); if(!lockFile.tryLock(100)) { QMessageBox msgBox; msgBox.setIcon(QMessageBox::Warning); msgBox.setText("YubiKey Manager is already running."); msgBox.exec(); return 1; } if (QFileInfo::exists(":" + main_qml)) { // Embedded resources path_prefix = ":"; url_prefix = "qrc://"; } else if (QFileInfo::exists(app_dir + main_qml)) { // Try relative to executable path_prefix = app_dir; url_prefix = app_dir; } else { //Assume qml/main.qml in cwd. app_dir = "."; path_prefix = "."; url_prefix = "."; } app.setWindowIcon(QIcon(path_prefix + "/images/windowicon.png")); QQmlApplicationEngine engine; engine.rootContext()->setContextProperty("appDir", app_dir); engine.rootContext()->setContextProperty("urlPrefix", url_prefix); engine.rootContext()->setContextProperty("appVersion", APP_VERSION); engine.load(QUrl(url_prefix + main_qml)); if (cliParser.isSet("log-level")) { if (cliParser.isSet("log-file")) { QMetaObject::invokeMethod(engine.rootObjects().first(), "enableLoggingToFile", Q_ARG(QVariant, cliParser.value("log-level")), Q_ARG(QVariant, cliParser.value("log-file"))); } else { QMetaObject::invokeMethod(engine.rootObjects().first(), "enableLogging", Q_ARG(QVariant, cliParser.value("log-level"))); } } else { QMetaObject::invokeMethod(engine.rootObjects().first(), "disableLogging"); } return app.exec(); }
#include <QApplication> #include <QQmlApplicationEngine> #include <QQmlContext> #include <stdlib.h> #include <QtGlobal> #include <QtWidgets> int main(int argc, char *argv[]) { // Global menubar is broken for qt5 apps in Ubuntu Unity, see: // https://bugs.launchpad.net/ubuntu/+source/appmenu-qt5/+bug/1323853 // This workaround enables a local menubar. qputenv("UBUNTU_MENUPROXY","0"); // Don't write .pyc files. qputenv("PYTHONDONTWRITEBYTECODE", "1"); QApplication app(argc, argv); QString app_dir = app.applicationDirPath(); QString main_qml = "/qml/main.qml"; QString path_prefix; QString url_prefix; app.setApplicationName("YubiKey Manager"); app.setApplicationVersion(APP_VERSION); app.setOrganizationName("Yubico"); app.setOrganizationDomain("com.yubico"); QCommandLineParser cliParser; cliParser.setApplicationDescription("Configure your YubiKey using a graphical application."); cliParser.addHelpOption(); cliParser.addVersionOption(); cliParser.addOptions({ {"log-level", QCoreApplication::translate("main", "Enable logging at verbosity <LEVEL>: DEBUG, INFO, WARNING, ERROR, CRITICAL"), QCoreApplication::translate("main", "LEVEL")}, {"log-file", QCoreApplication::translate("main", "Print logs to <FILE> instead of standard output; ignored without --log-level"), QCoreApplication::translate("main", "FILE")}, }); cliParser.process(app); // A lock file is used, to ensure only one running instance at the time. QString tmpDir = QDir::tempPath(); QLockFile lockFile(tmpDir + "/ykman-gui.lock"); if(!lockFile.tryLock(100)) { QMessageBox msgBox; msgBox.setIcon(QMessageBox::Warning); msgBox.setText("YubiKey Manager is already running."); msgBox.exec(); return 1; } if (QFileInfo::exists(":" + main_qml)) { // Embedded resources path_prefix = ":"; url_prefix = "qrc://"; } else if (QFileInfo::exists(app_dir + main_qml)) { // Try relative to executable path_prefix = app_dir; url_prefix = app_dir; } else { //Assume qml/main.qml in cwd. app_dir = "."; path_prefix = "."; url_prefix = "."; } app.setWindowIcon(QIcon(path_prefix + "/images/windowicon.png")); QQmlApplicationEngine engine; engine.rootContext()->setContextProperty("appDir", app_dir); engine.rootContext()->setContextProperty("urlPrefix", url_prefix); engine.rootContext()->setContextProperty("appVersion", APP_VERSION); engine.load(QUrl(url_prefix + main_qml)); if (cliParser.isSet("log-level")) { if (cliParser.isSet("log-file")) { QMetaObject::invokeMethod(engine.rootObjects().first(), "enableLoggingToFile", Q_ARG(QVariant, cliParser.value("log-level")), Q_ARG(QVariant, cliParser.value("log-file"))); } else { QMetaObject::invokeMethod(engine.rootObjects().first(), "enableLogging", Q_ARG(QVariant, cliParser.value("log-level"))); } } else { QMetaObject::invokeMethod(engine.rootObjects().first(), "disableLogging"); } return app.exec(); }
Rewrite --help description to an imperative sentence
Rewrite --help description to an imperative sentence
C++
bsd-2-clause
Yubico/yubikey-manager-qt,Yubico/yubikey-manager-qt,Yubico/yubikey-manager-qt,Yubico/yubikey-manager-qt
15434d897fbd4991a862e431e9b4bbf1b7cab726
service/notification-manager/SampleApp/linux/sampleConsumer/SampleConsumer.cpp
service/notification-manager/SampleApp/linux/sampleConsumer/SampleConsumer.cpp
//****************************************************************** // // Copyright 2015 Samsung Electronics All Rights Reserved. // //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // OCClient.cpp : Defines the entry point for the console application. // #include <string> #include <cstdlib> #include <pthread.h> #include "OCPlatform.h" #include "OCApi.h" #include <mutex> using namespace OC; const int SUCCESS_RESPONSE = OC_STACK_OK; #define OC_WELL_KNOWN_COORDINATING_QUERY "coap://224.0.1.187:5683/oc/core?rt=Resource.Hosting" #define OBSERVE 1 #define GET 2 #define PUT 3 #define DELETE 4 std::shared_ptr< OCResource > g_curResource; std::mutex curResourceLock; OCStackResult nmfindResource(const std::string &host , const std::string &resourceName); void onObserve(const HeaderOptions &headerOption , const OCRepresentation &rep , const int &eCode, const int &sequenceNumber); void onPut(const HeaderOptions &headerOption, const OCRepresentation &rep, const int eCode); void onGet(const HeaderOptions &headerOption , const OCRepresentation &rep , const int eCode); void onDelete(const HeaderOptions &headerOption , const int eCode); void findResourceCandidate() { try { nmfindResource("" , OC_WELL_KNOWN_COORDINATING_QUERY); std::cout << "Finding Resource... " << std::endl; } catch (OCException &e) { } } void startObserve(std::shared_ptr< OCResource > resource) { if (resource == NULL) { std::cout << "startObserve() error : resource == null" << std::endl; return; } QueryParamsMap test; if (OC_STACK_OK != resource->observe(ObserveType::Observe , test , &onObserve)) std::cout << "To Fail resource observe() process" << std::endl; } void startGet(std::shared_ptr< OCResource > resource) { if (resource == NULL) { std::cout << "startObserve() error : resource == null" << std::endl; return; } QueryParamsMap test; std::cout << "URI :" << resource->uri() << std::endl; if (OC_STACK_OK != resource->get(test, &onGet)) std::cout << "To Fail resource get() process" << std::endl; } void startPut(std::shared_ptr< OCResource > resource) { if (resource == NULL) { std::cout << "startObserve() error : resource == null" << std::endl; return; } g_curResource = resource; OCRepresentation rep; rep.setValue("temperature", 25); rep.setValue("humidity", 10); QueryParamsMap test; if (OC_STACK_OK != resource->put(rep, test, &onPut)) std::cout << "To Fail resource put() process" << std::endl; } void startDelete(std::shared_ptr< OCResource > resource) { if (resource == NULL) { std::cout << "startObserve() error : resource == null" << std::endl; return; } g_curResource = resource; if (OC_STACK_OK != resource->deleteResource(&onDelete)) std::cout << "To Fail resource delete() process" << std::endl; } int observe_count() { static int oc = 0; return ++oc; } void onObserve(const HeaderOptions &headerOption , const OCRepresentation &rep , const int &eCode, const int &sequenceNumber) { std::cout << "onObserve" << std::endl; if (eCode <= OC_STACK_OK) { std::cout << std::endl; std::cout << "========================================================" << std::endl; std::cout << "Receive OBSERVE RESULT:" << std::endl; std::cout << "\tUri: " << rep.getUri() << std::endl; std::cout << "\tSequenceNumber: " << sequenceNumber << std::endl; std::cout << "\tTemperature : " << rep.getValue<int>("temperature") << std::endl; std::cout << "\tHumidity : " << rep.getValue<int>("humidity") << std::endl; if (observe_count() > 30) { std::cout << "Cancelling Observe..." << std::endl; OCStackResult result = g_curResource->cancelObserve(); std::cout << "Cancel result: " << result << std::endl; sleep(10); std::cout << "DONE" << std::endl; std::exit(0); } } else { std::cout << "onObserve Response error: " << eCode << std::endl; std::exit(-1); } } void foundResource(std::shared_ptr< OCResource > resource) { std::string resourceURI; std::string hostAddress; std::cout << "foundResource" << std::endl; try { std::cout << "mutex lock passed" << std::endl; if (resource) { std::cout << resource->uri() << std::endl; if (resource->uri() == "/a/TempHumSensor") { std::cout << std::endl; std::cout << "========================================================" << std::endl; std::cout << "DISCOVERED Resource(Consumer):" << std::endl; resourceURI = resource->uri(); std::cout << "\tURI of the resource: " << resourceURI << std::endl; hostAddress = resource->host(); std::cout << "\tHost address of the resource: " << hostAddress << std::endl; g_curResource = resource; } } else { std::cout << "Resource is invalid" << std::endl; } } catch (std::exception &e) { } } OCStackResult nmfindResource(const std::string &host , const std::string &resourceName) { return OCPlatform::findResource(host , resourceName , OC_ETHERNET, &foundResource); } void getRepresentation(std::shared_ptr< OCResource > resource) { if (resource) { std::cout << "Getting Light Representation..." << std::endl; } } void onPut(const HeaderOptions &headerOption, const OCRepresentation &rep, const int eCode) { try { if (eCode == OC_STACK_OK) { std::cout << "PUT request was successful" << std::endl; int humidity; int temperature; rep.getValue("temperature", temperature); rep.getValue("humidity", humidity); std::cout << "\t temperature: " << temperature << std::endl; std::cout << "\t humidity: " << humidity << std::endl; } else { std::cout << "onPut Response error: " << eCode << std::endl; std::exit(-1); } } catch (std::exception &e) { std::cout << "Exception: " << e.what() << " in onPut" << std::endl; } } //callback hadnler on DELETE request void onDelete(const HeaderOptions &headerOption , const int eCode) { try { if (eCode == OC_STACK_RESOURCE_DELETED) { std::cout << "DELETE request was successful" << std::endl; } else { std::cout << "onDelete Response error: " << eCode << std::endl; std::exit(-1); } } catch (std::exception &e) { std::cout << "Exception: " << e.what() << " in onDelete" << std::endl; } } // callback handler on GET request void onGet(const HeaderOptions &headerOption , const OCRepresentation &rep , const int eCode) { std::cout << "GET request was successful1" << std::endl; if (eCode == SUCCESS_RESPONSE) { std::cout << "GET request was successful" << std::endl; std::cout << "Resource URI: " << rep.getUri().c_str() << std::endl; std::cout << "\tTemperature : " << rep.getValue<int>("temperature") << std::endl; std::cout << "\tHumidity : " << rep.getValue<int>("humidity") << std::endl; } else { std::cout << "onGET Response error: " << eCode << std::endl; std::exit(-1); } } void getLightRepresentation(std::shared_ptr< OCResource > resource) { if (resource) { std::cout << "Getting Light Representation..." << std::endl; QueryParamsMap test; resource->get(test , &onGet); } } void PrintUsage() { std::cout << std::endl; std::cout << "Usage : simpleclient <ObserveType>" << std::endl; std::cout << " ObserveType : 1 - Observe" << std::endl; std::cout << " ObserveType : 2 - ObserveAll" << std::endl; } void PRINT() { std::cout << std::endl; std::cout << "********************************************" << std::endl; std::cout << "* method Type : 1 - Observe *" << std::endl; std::cout << "* method Type : 2 - Get *" << std::endl; std::cout << "* method Type : 3 - Put *" << std::endl; std::cout << "* method Type : 4 - Delete *" << std::endl; std::cout << "********************************************" << std::endl; std::cout << std::endl; } int main(int argc , char *argv[]) { int in; PlatformConfig cfg; OCPlatform::Configure(cfg); std::cout << "Created Platform..." << std::endl; g_curResource = NULL; findResourceCandidate(); while (1) { sleep(2); if(g_curResource == NULL) { continue; } PRINT(); in = 0; std::cin >> in; if(std::cin.fail()) { std::cin.clear(); std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); std::cout << "Invalid input type, please try again" << std::endl; continue; } switch ((int)in) { case OBSERVE: startObserve(g_curResource); break; case GET: startGet(g_curResource); break; case PUT: startPut(g_curResource); break; case DELETE: startDelete(g_curResource); break; default: std::cout << "Invalid input, please try again" << std::endl; break; } } return 0; }
//****************************************************************** // // Copyright 2015 Samsung Electronics All Rights Reserved. // //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= /** * @file SampleConsumer.cpp * @brief Defines the entry point for the sample consumer application about Resource Hosting. */ #include <string> #include <cstdlib> #include <pthread.h> #include "OCPlatform.h" #include "OCApi.h" #include <mutex> using namespace OC; const int SUCCESS_RESPONSE = OC_STACK_OK; #define OC_WELL_KNOWN_COORDINATING_QUERY "224.0.1.187:5683/oc/core?rt=Resource.Hosting" #define OBSERVE 1 #define GET 2 #define PUT 3 #define DELETE 4 std::shared_ptr< OCResource > g_curResource; std::shared_ptr< OCResource > g_curObserveResource; std::mutex curResourceLock; OCStackResult nmfindResource(const std::string &host , const std::string &resourceName); void onObserve(const HeaderOptions &headerOption , const OCRepresentation &rep , const int &eCode, const int &sequenceNumber); void onPut(const HeaderOptions &headerOption, const OCRepresentation &rep, const int eCode); void onGet(const HeaderOptions &headerOption , const OCRepresentation &rep , const int eCode); void onDelete(const HeaderOptions &headerOption , const int eCode); void findResourceCandidate() { try { nmfindResource("" , OC_WELL_KNOWN_COORDINATING_QUERY); std::cout << "Finding Resource... " << std::endl; } catch (OCException &e) { std::cout << "Exception for find resource : " << e.reason() << std::endl; } } void startObserve(std::shared_ptr< OCResource > resource) { if (resource == NULL) { std::cout << "startObserve() error : resource == null" << std::endl; return; } if(g_curObserveResource == NULL) { g_curObserveResource = resource; std::cout << "request for new observation" << std::endl; } else if(g_curObserveResource == g_curResource) { std::cout << "already registered same observation" << std::endl; return; } else { std::cout << "change observed resource" << std::endl; g_curObserveResource->cancelObserve(); g_curObserveResource = resource; } QueryParamsMap test; if (OC_STACK_OK != resource->observe(ObserveType::Observe , test , &onObserve)) std::cout << "To Fail resource observe() process" << std::endl; } void startGet(std::shared_ptr< OCResource > resource) { if (resource == NULL) { std::cout << "startObserve() error : resource == null" << std::endl; return; } QueryParamsMap test; std::cout << "URI :" << resource->uri() << std::endl; if (OC_STACK_OK != resource->get(test, &onGet)) std::cout << "To Fail resource get() process" << std::endl; } void startPut(std::shared_ptr< OCResource > resource) { if (resource == NULL) { std::cout << "startObserve() error : resource == null" << std::endl; return; } g_curResource = resource; OCRepresentation rep; rep.setValue("temperature", 25); rep.setValue("humidity", 10); QueryParamsMap test; if (OC_STACK_OK != resource->put(rep, test, &onPut)) std::cout << "To Fail resource put() process" << std::endl; } void startDelete(std::shared_ptr< OCResource > resource) { if (resource == NULL) { std::cout << "startObserve() error : resource == null" << std::endl; return; } g_curResource = resource; if (OC_STACK_OK != resource->deleteResource(&onDelete)) std::cout << "To Fail resource delete() process" << std::endl; } int observe_count() { static int oc = 0; return ++oc; } void onObserve(const HeaderOptions &headerOption , const OCRepresentation &rep , const int &eCode, const int &sequenceNumber) { std::cout << "onObserve" << std::endl; if (eCode <= OC_STACK_OK) { std::cout << std::endl; std::cout << "========================================================" << std::endl; std::cout << "Receive OBSERVE RESULT:" << std::endl; std::cout << "\tUri: " << rep.getUri() << std::endl; std::cout << "\tSequenceNumber: " << sequenceNumber << std::endl; std::cout << "\tTemperature : " << rep.getValue<int>("temperature") << std::endl; std::cout << "\tHumidity : " << rep.getValue<int>("humidity") << std::endl; if (observe_count() > 30) { std::cout << "Cancelling Observe..." << std::endl; OCStackResult result = g_curResource->cancelObserve(); std::cout << "Cancel result: " << result << std::endl; sleep(10); std::cout << "DONE" << std::endl; std::exit(0); } } else { std::cout << "onObserve Response error: " << eCode << std::endl; std::exit(-1); } } void foundResource(std::shared_ptr< OCResource > resource) { std::string resourceURI; std::string hostAddress; std::cout << "foundResource" << std::endl; try { std::cout << "mutex lock passed" << std::endl; if (resource) { std::cout << resource->uri() << std::endl; if (resource->uri() == "/a/TempHumSensor") { std::cout << std::endl; std::cout << "========================================================" << std::endl; std::cout << "DISCOVERED Resource(Consumer):" << std::endl; resourceURI = resource->uri(); std::cout << "\tURI of the resource: " << resourceURI << std::endl; hostAddress = resource->host(); std::cout << "\tHost address of the resource: " << hostAddress << std::endl; g_curResource = resource; } } else { std::cout << "Resource is invalid" << std::endl; } } catch (std::exception &e) { } } OCStackResult nmfindResource(const std::string &host , const std::string &resourceName) { return OCPlatform::findResource(host , resourceName , OC_ETHERNET, &foundResource); } void getRepresentation(std::shared_ptr< OCResource > resource) { if (resource) { std::cout << "Getting Light Representation..." << std::endl; } } void onPut(const HeaderOptions &headerOption, const OCRepresentation &rep, const int eCode) { try { if (eCode == OC_STACK_OK) { std::cout << "PUT request was successful" << std::endl; int humidity; int temperature; rep.getValue("temperature", temperature); rep.getValue("humidity", humidity); std::cout << "\t temperature: " << temperature << std::endl; std::cout << "\t humidity: " << humidity << std::endl; } else { std::cout << "onPut Response error: " << eCode << std::endl; std::exit(-1); } } catch (std::exception &e) { std::cout << "Exception: " << e.what() << " in onPut" << std::endl; } } //callback hadnler on DELETE request void onDelete(const HeaderOptions &headerOption , const int eCode) { try { if (eCode == OC_STACK_RESOURCE_DELETED) { std::cout << "DELETE request was successful" << std::endl; } else { std::cout << "onDelete Response error: " << eCode << std::endl; std::exit(-1); } } catch (std::exception &e) { std::cout << "Exception: " << e.what() << " in onDelete" << std::endl; } } // callback handler on GET request void onGet(const HeaderOptions &headerOption , const OCRepresentation &rep , const int eCode) { std::cout << "GET request was successful1" << std::endl; if (eCode == SUCCESS_RESPONSE) { std::cout << "GET request was successful" << std::endl; std::cout << "Resource URI: " << rep.getUri().c_str() << std::endl; std::cout << "\tTemperature : " << rep.getValue<int>("temperature") << std::endl; std::cout << "\tHumidity : " << rep.getValue<int>("humidity") << std::endl; } else { std::cout << "onGET Response error: " << eCode << std::endl; std::exit(-1); } } void getLightRepresentation(std::shared_ptr< OCResource > resource) { if (resource) { std::cout << "Getting Light Representation..." << std::endl; QueryParamsMap test; resource->get(test , &onGet); } } void PrintUsage() { std::cout << std::endl; std::cout << "Usage : simpleclient <ObserveType>" << std::endl; std::cout << " ObserveType : 1 - Observe" << std::endl; std::cout << " ObserveType : 2 - ObserveAll" << std::endl; } void PRINT() { std::cout << std::endl; std::cout << "********************************************" << std::endl; std::cout << "* method Type : 1 - Observe *" << std::endl; std::cout << "* method Type : 2 - Get *" << std::endl; std::cout << "* method Type : 3 - Put *" << std::endl; std::cout << "* method Type : 4 - Delete *" << std::endl; std::cout << "********************************************" << std::endl; std::cout << std::endl; } int main(int argc , char *argv[]) { int in; PlatformConfig cfg; OCPlatform::Configure(cfg); std::cout << "Created Platform..." << std::endl; g_curResource = NULL; g_curObserveResource = NULL; findResourceCandidate(); while (1) { sleep(2); if(g_curResource == NULL) { continue; } PRINT(); in = 0; std::cin >> in; if(std::cin.fail()) { std::cin.clear(); std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); std::cout << "Invalid input type, please try again" << std::endl; continue; } switch ((int)in) { case OBSERVE: startObserve(g_curResource); break; case GET: startGet(g_curResource); break; case PUT: startPut(g_curResource); break; case DELETE: startDelete(g_curResource); break; default: std::cout << "Invalid input, please try again" << std::endl; break; } } return 0; }
Fix exception handling in Notification Manager Sample.
Fix exception handling in Notification Manager Sample. 1. handle exception for resource bind. 2. update multicast-request address. 3. clean up code. Change-Id: I9cf87319cf360aaa8b483b45be34b2d520597abf Signed-off-by: jyong2.kim <[email protected]> Reviewed-on: https://gerrit.iotivity.org/gerrit/852 Reviewed-by: Uze Choi <[email protected]> Tested-by: Uze Choi <[email protected]>
C++
apache-2.0
WojciechLuczkow/iotivity,rzr/iotivity,kartben/iotivity,tienfuc/iotivity-democlient-snap,santais/iotivity,santais/iotivity_1.1,rzr/iotivity,santais/iotivity_1.1.0,WojciechLuczkow/iotivity,santais/iotivity,rzr/iotivity,santais/iotivity_1.1.0,kartben/iotivity,santais/iotivity_1.1,tienfuc/iotivity-democlient-snap,WojciechLuczkow/iotivity,kartben/iotivity,santais/iotivity,santais/iotivity_1.1.0,santais/iotivity,tienfuc/iotivity-democlient-snap,iotivity/iotivity,iotivity/iotivity,iotivity/iotivity,kartben/iotivity,santais/iotivity_1.1.0,santais/iotivity,tienfuc/iotivity-democlient-snap,tienfuc/iotivity-democlient-snap,santais/iotivity_1.1.0,santais/iotivity_1.1.0,iotivity/iotivity,tienfuc/iotivity-democlient-snap,rzr/iotivity,rzr/iotivity,WojciechLuczkow/iotivity,santais/iotivity_1.1,kartben/iotivity,WojciechLuczkow/iotivity,tienfuc/iotivity-democlient-snap,kartben/iotivity,iotivity/iotivity,iotivity/iotivity,WojciechLuczkow/iotivity,WojciechLuczkow/iotivity,rzr/iotivity,tienfuc/iotivity-democlient-snap,santais/iotivity_1.1,tienfuc/iotivity-democlient-snap,kartben/iotivity,iotivity/iotivity,rzr/iotivity,iotivity/iotivity,santais/iotivity_1.1,WojciechLuczkow/iotivity,santais/iotivity_1.1,santais/iotivity_1.1,tienfuc/iotivity-democlient-snap,kartben/iotivity,santais/iotivity,santais/iotivity_1.1,santais/iotivity,santais/iotivity_1.1.0
ef19bf318ff394bc0794206506bfc385c88e866d
C++/remove-invalid-parentheses.cpp
C++/remove-invalid-parentheses.cpp
// DFS solution. class Solution { public: vector<string> removeInvalidParentheses(string s) { // Calculate the minimum left and right parantheses to remove int left_removed = 0, right_removed = 0; for (const auto& c : s) { if (c == '(') { ++left_removed; } else if (c == ')') { if (!left_removed) { ++right_removed; } else { --left_removed; } } } vector<string> res; removeInvalidParentheses(s, 0, left_removed, right_removed, &res); return res; } void removeInvalidParentheses(const string& s, int start, int left_removed, int right_removed, vector<string> *res) { if (left_removed == 0 && right_removed == 0) { if (isValid(s)) { res->emplace_back(s); } return; } for (int i = start; i < s.size(); ++i) { string tmp = s; if (right_removed == 0 && left_removed > 0 && tmp[i] == '(') { if (i == start || tmp[i] != tmp[i - 1]) { // Skip duplicated. tmp.erase(i, 1); removeInvalidParentheses(tmp, i, left_removed - 1, right_removed, res); } } if (right_removed > 0 && tmp[i] == ')') { if (i == start || tmp[i] != tmp[i - 1]) { // Skip duplicated. tmp.erase(i, 1); removeInvalidParentheses(tmp, i, left_removed, right_removed - 1, res); } } } } private: // Check whether s is valid or not. bool isValid(string s) { int sum = 0; for (const auto &c : s) { if (c == '(') { ++sum; } else if (c == ')') { --sum; } if (sum < 0) { return false; } } return sum == 0; } };
// Time: O(n * 2^n) // Space: O(n^2) // DFS solution. class Solution { public: vector<string> removeInvalidParentheses(string s) { // Calculate the minimum left and right parantheses to remove int left_removed = 0, right_removed = 0; for (const auto& c : s) { if (c == '(') { ++left_removed; } else if (c == ')') { if (!left_removed) { ++right_removed; } else { --left_removed; } } } vector<string> res; removeInvalidParentheses(s, 0, left_removed, right_removed, &res); return res; } void removeInvalidParentheses(const string& s, int start, int left_removed, int right_removed, vector<string> *res) { if (left_removed == 0 && right_removed == 0) { if (isValid(s)) { res->emplace_back(s); } return; } for (int i = start; i < s.size(); ++i) { string tmp = s; if (right_removed == 0 && left_removed > 0 && tmp[i] == '(') { if (i == start || tmp[i] != tmp[i - 1]) { // Skip duplicated. tmp.erase(i, 1); removeInvalidParentheses(tmp, i, left_removed - 1, right_removed, res); } } if (right_removed > 0 && tmp[i] == ')') { if (i == start || tmp[i] != tmp[i - 1]) { // Skip duplicated. tmp.erase(i, 1); removeInvalidParentheses(tmp, i, left_removed, right_removed - 1, res); } } } } private: // Check whether s is valid or not. bool isValid(string s) { int sum = 0; for (const auto &c : s) { if (c == '(') { ++sum; } else if (c == ')') { --sum; } if (sum < 0) { return false; } } return sum == 0; } };
Update remove-invalid-parentheses.cpp
Update remove-invalid-parentheses.cpp
C++
mit
kamyu104/LeetCode,yiwen-luo/LeetCode,kamyu104/LeetCode,jaredkoontz/leetcode,tudennis/LeetCode---kamyu104-11-24-2015,tudennis/LeetCode---kamyu104-11-24-2015,jaredkoontz/leetcode,yiwen-luo/LeetCode,tudennis/LeetCode---kamyu104-11-24-2015,yiwen-luo/LeetCode,kamyu104/LeetCode,jaredkoontz/leetcode,tudennis/LeetCode---kamyu104-11-24-2015,yiwen-luo/LeetCode,tudennis/LeetCode---kamyu104-11-24-2015,kamyu104/LeetCode,githubutilities/LeetCode,githubutilities/LeetCode,githubutilities/LeetCode,kamyu104/LeetCode,githubutilities/LeetCode,yiwen-luo/LeetCode,jaredkoontz/leetcode,jaredkoontz/leetcode,githubutilities/LeetCode
908f420abd0719db2c6308840c87fd5983f40cf1
unittests/ExecutionEngine/Orc/RPCUtilsTest.cpp
unittests/ExecutionEngine/Orc/RPCUtilsTest.cpp
//===----------- RPCUtilsTest.cpp - Unit tests the Orc RPC utils ----------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/ExecutionEngine/Orc/RPCChannel.h" #include "llvm/ExecutionEngine/Orc/RPCUtils.h" #include "gtest/gtest.h" #include <queue> using namespace llvm; using namespace llvm::orc; using namespace llvm::orc::remote; class Queue : public std::queue<char> { public: std::mutex &getLock() { return Lock; } private: std::mutex Lock; }; class QueueChannel : public RPCChannel { public: QueueChannel(Queue &InQueue, Queue &OutQueue) : InQueue(InQueue), OutQueue(OutQueue) {} Error readBytes(char *Dst, unsigned Size) override { while (Size != 0) { // If there's nothing to read then yield. while (InQueue.empty()) std::this_thread::yield(); // Lock the channel and read what we can. std::lock_guard<std::mutex> Lock(InQueue.getLock()); while (!InQueue.empty() && Size) { *Dst++ = InQueue.front(); --Size; InQueue.pop(); } } return Error::success(); } Error appendBytes(const char *Src, unsigned Size) override { std::lock_guard<std::mutex> Lock(OutQueue.getLock()); while (Size--) OutQueue.push(*Src++); return Error::success(); } Error send() override { return Error::success(); } private: Queue &InQueue; Queue &OutQueue; }; class DummyRPC : public testing::Test, public RPC<QueueChannel> { public: enum FuncId : uint32_t { VoidBoolId = RPCFunctionIdTraits<FuncId>::FirstValidId, IntIntId, AllTheTypesId }; typedef Function<VoidBoolId, void(bool)> VoidBool; typedef Function<IntIntId, int32_t(int32_t)> IntInt; typedef Function<AllTheTypesId, void(int8_t, uint8_t, int16_t, uint16_t, int32_t, uint32_t, int64_t, uint64_t, bool, std::string, std::vector<int>)> AllTheTypes; }; TEST_F(DummyRPC, TestAsyncVoidBool) { Queue Q1, Q2; QueueChannel C1(Q1, Q2); QueueChannel C2(Q2, Q1); // Make an async call. auto ResOrErr = callAsyncWithSeq<VoidBool>(C1, true); EXPECT_TRUE(!!ResOrErr) << "Simple call over queue failed"; { // Expect a call to Proc1. auto EC = expect<VoidBool>(C2, [&](bool &B) { EXPECT_EQ(B, true) << "Bool serialization broken"; return Error::success(); }); EXPECT_FALSE(EC) << "Simple expect over queue failed"; } { // Wait for the result. auto EC = waitForResult(C1, ResOrErr->second, handleNone); EXPECT_FALSE(EC) << "Could not read result."; } // Verify that the function returned ok. auto Err = ResOrErr->first.get(); EXPECT_TRUE(!!Err) << "Remote void function failed to execute."; } TEST_F(DummyRPC, TestAsyncIntInt) { Queue Q1, Q2; QueueChannel C1(Q1, Q2); QueueChannel C2(Q2, Q1); // Make an async call. auto ResOrErr = callAsyncWithSeq<IntInt>(C1, 21); EXPECT_TRUE(!!ResOrErr) << "Simple call over queue failed"; { // Expect a call to Proc1. auto EC = expect<IntInt>(C2, [&](int32_t I) -> Expected<int32_t> { EXPECT_EQ(I, 21) << "Bool serialization broken"; return 2 * I; }); EXPECT_FALSE(EC) << "Simple expect over queue failed"; } { // Wait for the result. auto EC = waitForResult(C1, ResOrErr->second, handleNone); EXPECT_FALSE(EC) << "Could not read result."; } // Verify that the function returned ok. auto Val = ResOrErr->first.get(); EXPECT_TRUE(!!Val) << "Remote int function failed to execute."; EXPECT_EQ(*Val, 42) << "Remote int function return wrong value."; } TEST_F(DummyRPC, TestSerialization) { Queue Q1, Q2; QueueChannel C1(Q1, Q2); QueueChannel C2(Q2, Q1); // Make a call to Proc1. std::vector<int> v({42, 7}); auto ResOrErr = callAsyncWithSeq<AllTheTypes>( C1, -101, 250, -10000, 10000, -1000000000, 1000000000, -10000000000, 10000000000, true, "foo", v); EXPECT_TRUE(!!ResOrErr) << "Big (serialization test) call over queue failed"; { // Expect a call to Proc1. auto EC = expect<AllTheTypes>( C2, [&](int8_t &s8, uint8_t &u8, int16_t &s16, uint16_t &u16, int32_t &s32, uint32_t &u32, int64_t &s64, uint64_t &u64, bool &b, std::string &s, std::vector<int> &v) { EXPECT_EQ(s8, -101) << "int8_t serialization broken"; EXPECT_EQ(u8, 250) << "uint8_t serialization broken"; EXPECT_EQ(s16, -10000) << "int16_t serialization broken"; EXPECT_EQ(u16, 10000) << "uint16_t serialization broken"; EXPECT_EQ(s32, -1000000000) << "int32_t serialization broken"; EXPECT_EQ(u32, 1000000000ULL) << "uint32_t serialization broken"; EXPECT_EQ(s64, -10000000000) << "int64_t serialization broken"; EXPECT_EQ(u64, 10000000000ULL) << "uint64_t serialization broken"; EXPECT_EQ(b, true) << "bool serialization broken"; EXPECT_EQ(s, "foo") << "std::string serialization broken"; EXPECT_EQ(v, std::vector<int>({42, 7})) << "std::vector serialization broken"; return Error::success(); }); EXPECT_FALSE(EC) << "Big (serialization test) call over queue failed"; } { // Wait for the result. auto EC = waitForResult(C1, ResOrErr->second, handleNone); EXPECT_FALSE(EC) << "Could not read result."; } // Verify that the function returned ok. auto Err = ResOrErr->first.get(); EXPECT_TRUE(!!Err) << "Remote void function failed to execute."; } // Test the synchronous call API. // FIXME: Re-enable once deadlock encountered on S390 has been debugged / fixed, // see http://lab.llvm.org:8011/builders/clang-s390x-linux/builds/3459 // TEST_F(DummyRPC, TestSynchronousCall) { // Queue Q1, Q2; // QueueChannel C1(Q1, Q2); // QueueChannel C2(Q2, Q1); // // auto ServerResult = // std::async(std::launch::async, // [&]() { // return expect<IntInt>(C2, [&](int32_t V) { return V; }); // }); // // auto ValOrErr = callST<IntInt>(C1, 42); // // EXPECT_FALSE(!!ServerResult.get()) // << "Server returned an error."; // EXPECT_TRUE(!!ValOrErr) // << "callST returned an error."; // EXPECT_EQ(*ValOrErr, 42) // << "Incorrect callST<IntInt> result"; // }
//===----------- RPCUtilsTest.cpp - Unit tests the Orc RPC utils ----------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/ExecutionEngine/Orc/RPCChannel.h" #include "llvm/ExecutionEngine/Orc/RPCUtils.h" #include "gtest/gtest.h" #include <queue> using namespace llvm; using namespace llvm::orc; using namespace llvm::orc::remote; class Queue : public std::queue<char> { public: std::mutex &getLock() { return Lock; } private: std::mutex Lock; }; class QueueChannel : public RPCChannel { public: QueueChannel(Queue &InQueue, Queue &OutQueue) : InQueue(InQueue), OutQueue(OutQueue) {} Error readBytes(char *Dst, unsigned Size) override { while (Size != 0) { // If there's nothing to read then yield. while (InQueue.empty()) std::this_thread::yield(); // Lock the channel and read what we can. std::lock_guard<std::mutex> Lock(InQueue.getLock()); while (!InQueue.empty() && Size) { *Dst++ = InQueue.front(); --Size; InQueue.pop(); } } return Error::success(); } Error appendBytes(const char *Src, unsigned Size) override { std::lock_guard<std::mutex> Lock(OutQueue.getLock()); while (Size--) OutQueue.push(*Src++); return Error::success(); } Error send() override { return Error::success(); } private: Queue &InQueue; Queue &OutQueue; }; class DummyRPC : public testing::Test, public RPC<QueueChannel> { public: enum FuncId : uint32_t { VoidBoolId = RPCFunctionIdTraits<FuncId>::FirstValidId, IntIntId, AllTheTypesId }; typedef Function<VoidBoolId, void(bool)> VoidBool; typedef Function<IntIntId, int32_t(int32_t)> IntInt; typedef Function<AllTheTypesId, void(int8_t, uint8_t, int16_t, uint16_t, int32_t, uint32_t, int64_t, uint64_t, bool, std::string, std::vector<int>)> AllTheTypes; }; TEST_F(DummyRPC, TestAsyncVoidBool) { Queue Q1, Q2; QueueChannel C1(Q1, Q2); QueueChannel C2(Q2, Q1); // Make an async call. auto ResOrErr = callAsyncWithSeq<VoidBool>(C1, true); EXPECT_TRUE(!!ResOrErr) << "Simple call over queue failed"; { // Expect a call to Proc1. auto EC = expect<VoidBool>(C2, [&](bool &B) { EXPECT_EQ(B, true) << "Bool serialization broken"; return Error::success(); }); EXPECT_FALSE(EC) << "Simple expect over queue failed"; } { // Wait for the result. auto EC = waitForResult(C1, ResOrErr->second, handleNone); EXPECT_FALSE(EC) << "Could not read result."; } // Verify that the function returned ok. auto Err = ResOrErr->first.get(); EXPECT_FALSE(!!Err) << "Remote void function failed to execute."; } TEST_F(DummyRPC, TestAsyncIntInt) { Queue Q1, Q2; QueueChannel C1(Q1, Q2); QueueChannel C2(Q2, Q1); // Make an async call. auto ResOrErr = callAsyncWithSeq<IntInt>(C1, 21); EXPECT_TRUE(!!ResOrErr) << "Simple call over queue failed"; { // Expect a call to Proc1. auto EC = expect<IntInt>(C2, [&](int32_t I) -> Expected<int32_t> { EXPECT_EQ(I, 21) << "Bool serialization broken"; return 2 * I; }); EXPECT_FALSE(EC) << "Simple expect over queue failed"; } { // Wait for the result. auto EC = waitForResult(C1, ResOrErr->second, handleNone); EXPECT_FALSE(EC) << "Could not read result."; } // Verify that the function returned ok. auto Val = ResOrErr->first.get(); EXPECT_TRUE(!!Val) << "Remote int function failed to execute."; EXPECT_EQ(*Val, 42) << "Remote int function return wrong value."; } TEST_F(DummyRPC, TestSerialization) { Queue Q1, Q2; QueueChannel C1(Q1, Q2); QueueChannel C2(Q2, Q1); // Make a call to Proc1. std::vector<int> v({42, 7}); auto ResOrErr = callAsyncWithSeq<AllTheTypes>( C1, -101, 250, -10000, 10000, -1000000000, 1000000000, -10000000000, 10000000000, true, "foo", v); EXPECT_TRUE(!!ResOrErr) << "Big (serialization test) call over queue failed"; { // Expect a call to Proc1. auto EC = expect<AllTheTypes>( C2, [&](int8_t &s8, uint8_t &u8, int16_t &s16, uint16_t &u16, int32_t &s32, uint32_t &u32, int64_t &s64, uint64_t &u64, bool &b, std::string &s, std::vector<int> &v) { EXPECT_EQ(s8, -101) << "int8_t serialization broken"; EXPECT_EQ(u8, 250) << "uint8_t serialization broken"; EXPECT_EQ(s16, -10000) << "int16_t serialization broken"; EXPECT_EQ(u16, 10000) << "uint16_t serialization broken"; EXPECT_EQ(s32, -1000000000) << "int32_t serialization broken"; EXPECT_EQ(u32, 1000000000ULL) << "uint32_t serialization broken"; EXPECT_EQ(s64, -10000000000) << "int64_t serialization broken"; EXPECT_EQ(u64, 10000000000ULL) << "uint64_t serialization broken"; EXPECT_EQ(b, true) << "bool serialization broken"; EXPECT_EQ(s, "foo") << "std::string serialization broken"; EXPECT_EQ(v, std::vector<int>({42, 7})) << "std::vector serialization broken"; return Error::success(); }); EXPECT_FALSE(EC) << "Big (serialization test) call over queue failed"; } { // Wait for the result. auto EC = waitForResult(C1, ResOrErr->second, handleNone); EXPECT_FALSE(EC) << "Could not read result."; } // Verify that the function returned ok. auto Err = ResOrErr->first.get(); EXPECT_FALSE(!!Err) << "Remote void function failed to execute."; } // Test the synchronous call API. // FIXME: Re-enable once deadlock encountered on S390 has been debugged / fixed, // see http://lab.llvm.org:8011/builders/clang-s390x-linux/builds/3459 // TEST_F(DummyRPC, TestSynchronousCall) { // Queue Q1, Q2; // QueueChannel C1(Q1, Q2); // QueueChannel C2(Q2, Q1); // // auto ServerResult = // std::async(std::launch::async, // [&]() { // return expect<IntInt>(C2, [&](int32_t V) { return V; }); // }); // // auto ValOrErr = callST<IntInt>(C1, 42); // // EXPECT_FALSE(!!ServerResult.get()) // << "Server returned an error."; // EXPECT_TRUE(!!ValOrErr) // << "callST returned an error."; // EXPECT_EQ(*ValOrErr, 42) // << "Incorrect callST<IntInt> result"; // }
Fix unit-test breakage from r280016.
[ORC] Fix unit-test breakage from r280016. Void functions returning error now boolean convert to 'false' if they succeed. Unit tests updated to reflect this. git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@280027 91177308-0d34-0410-b5e6-96231b3b80d8
C++
apache-2.0
GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,apple/swift-llvm,apple/swift-llvm,llvm-mirror/llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,llvm-mirror/llvm,apple/swift-llvm,llvm-mirror/llvm,apple/swift-llvm
ac3030ca63717406f7600efd61b4988b4f6deece
include/eli/geom/surface/piecewise_cubic_spline_skinning_surface_creator.hpp
include/eli/geom/surface/piecewise_cubic_spline_skinning_surface_creator.hpp
/********************************************************************************* * Copyright (c) 2013 David D. Marshall <[email protected]> * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * David D. Marshall - piecewise general surface creator * Rob McDonald - Modified to piecewise cubic spline surface creator ********************************************************************************/ #ifndef eli_geom_surface_piecewise_cubic_spline_skinning_surface_creator_hpp #define eli_geom_surface_piecewise_cubic_spline_skinning_surface_creator_hpp #include <list> #include <vector> #include <iterator> #include "eli/code_eli.hpp" #include "eli/util/tolerance.hpp" #include "eli/geom/curve/bezier.hpp" #include "eli/geom/curve/piecewise.hpp" #include "eli/geom/curve/piecewise_cubic_spline_creator.hpp" #include "eli/geom/surface/piecewise.hpp" #include "eli/geom/surface/bezier.hpp" #include "eli/geom/surface/piecewise_connection_data.hpp" #include "eli/geom/surface/piecewise_creator_base.hpp" namespace eli { namespace geom { namespace surface { template<typename data__, unsigned short dim__, typename tol__> class piecewise_cubic_spline_skinning_surface_creator : public piecewise_creator_base<data__, dim__, tol__> { public: typedef piecewise_creator_base<data__, dim__, tol__> base_class_type; typedef typename base_class_type::data_type data_type; typedef typename base_class_type::point_type point_type; typedef typename base_class_type::index_type index_type; typedef typename base_class_type::tolerance_type tolerance_type; typedef typename base_class_type::piecewise_surface_type piecewise_surface_type; typedef connection_data<data_type, dim__, tolerance_type> rib_data_type; piecewise_cubic_spline_skinning_surface_creator() : piecewise_creator_base<data__, dim__, tol__>(0, 0), ribs(2), max_degree(1), closed(false) { } piecewise_cubic_spline_skinning_surface_creator(const data_type &uu0, const data_type &vv0) : piecewise_creator_base<data__, dim__, tol__>(uu0, vv0), ribs(2), max_degree(1), closed(false) { } piecewise_cubic_spline_skinning_surface_creator(const piecewise_general_skinning_surface_creator<data_type, dim__, tolerance_type> & gs) : piecewise_creator_base<data_type, dim__, tolerance_type>(gs), ribs(gs.ribs), max_degree(gs.max_degree), closed(gs.closed) { } virtual ~piecewise_cubic_spline_skinning_surface_creator() { } void set_closed() {closed=true;} void set_open() {closed=false;} bool is_closed() const {return closed;} bool is_open() const {return !closed;} void set_u0(const data_type &uu0) {this->set_initial_u(uu0);} void set_segment_du(const data_type &duu, const index_type &i) { this->set_du(duu, i); } bool set_conditions(const std::vector<rib_data_type> &rbs, const std::vector<index_type> &maxd, bool cl=false) { index_type i, j, nsegs(static_cast<index_type>(maxd.size())), nribs(rbs.size()); // ensure input vectors are correct size if (!cl && (nribs!=(nsegs+1))) return false; if (cl && (nribs!=nsegs)) return false; // check to make sure have valid end conditions if (!cl) { if (rbs[0].use_left_fp() || rbs[0].use_left_fpp() || rbs[0].get_continuity()!=rib_data_type::C0) { return false; } if (rbs[nsegs].use_right_fp() || rbs[nsegs].use_right_fpp() || rbs[nsegs].get_continuity()!=rib_data_type::C0) { return false; } } // make sure ribs are in valid state data_type v_start(rbs[0].get_t0()), v_end(rbs[0].get_tmax()); tolerance_type tol; for (i=0; i<nribs; ++i) { if (!rbs[i].check_state()) return false; if (!tol.approximately_equal(rbs[i].get_t0(), v_start) || !tol.approximately_equal(rbs[i].get_tmax(), v_end)) return false; } // find all unique v-coordinates on joints for each rib auto comp = [&tol](const data_type &x1, const data_type &x2)->bool { return tol.approximately_less_than(x1, x2); }; std::vector<data_type> joints; data_type t0(rbs[0].get_t0()), tmax(rbs[0].get_tmax()); rbs[0].get_joints(std::back_inserter(joints)); for (i=1; i<nribs; ++i) { // test to make sure this rib's parameterization matches rest if (!tol.approximately_equal(rbs[i].get_t0(), t0) || !tol.approximately_equal(rbs[i].get_tmax(), tmax)) { return false; } // get the joints on the current rib std::vector<data_type> rjoints, jts_out; rbs[i].get_joints(std::back_inserter(rjoints)); // merge these joints with current list of joints std::set_union(joints.begin(), joints.end(), rjoints.begin(), rjoints.end(), std::back_inserter(jts_out), comp); std::swap(joints, jts_out); } // record where the joints need to be for create() index_type njoints(static_cast<index_type>(joints.size())); // set the v-parameterization this->set_number_v_segments(njoints-1); this->set_initial_v(joints[0]); for (j=0; j<(njoints-1); ++j) { this->set_dv(joints[j+1]-joints[j], j); } // reset the number of u-segments this->set_number_u_segments(nsegs); ribs=rbs; max_degree=maxd; closed=cl; return true; } virtual bool create(piecewise_surface_type &ps) const { typedef typename piecewise_surface_type::surface_type surface_type; index_type nribs(this->get_number_u_segments()+1), i, j; std::vector<index_type> seg_degree(nribs-1); std::vector<rib_data_type> rib_states(ribs); tolerance_type tol; // FIX: Should be able to handle closed surfaces assert(!closed); // FIX: Need to be able to handle v-direction discontinuous fu and fuu specifications // reset the incoming piecewise surface ps.clear(); // split ribs so have same number of curves (with same joint parameters) for all ribs and get degree index_type njoints(this->get_number_v_segments()+1); std::vector<data_type> joints(njoints); std::vector<index_type> max_jdegs(njoints-1,0); joints[0]=this->get_v0(); for (j=0; j<(njoints-1); ++j) { joints[j+1]=joints[j]+this->get_segment_dv(j); } for (i=0; i<nribs; ++i) { std::vector<index_type> jdegs; rib_states[i].split(joints.begin(), joints.end(), std::back_inserter(jdegs)); for (j=0; j<(njoints-1); ++j) { if (jdegs[j]>max_jdegs[j]) { max_jdegs[j]=jdegs[j]; } } } // set degree in u-direction for each rib segment strip for (i=0; i<nribs; ++i) { rib_states[i].promote(max_jdegs.begin(), max_jdegs.end()); } // resize the piecewise surface index_type u, v, nu(nribs-1), nv(njoints-1); ps.init_uv(this->du_begin(), this->du_end(), this->dv_begin(), this->dv_end(), this->get_u0(), this->get_v0()); // build segments based on rib information // here should have everything to make an nribs x njoints piecewise surface with all // of the j-degrees matching in the u-direction so that can use general curve creator // techniques to create control points for (v=0; v<nv; ++v) { typedef eli::geom::curve::piecewise_cubic_spline_creator<data_type, dim__, tolerance_type> piecewise_curve_creator_type; typedef eli::geom::curve::piecewise<eli::geom::curve::bezier, data_type, dim__, tolerance_type> piecewise_curve_type; typedef typename piecewise_curve_type::curve_type curve_type; std::vector < point_type > pts( nu+1 ); piecewise_curve_creator_type gc; piecewise_curve_type c; std::vector<surface_type> surfs(nu); for (j=0; j<=max_jdegs[v]; ++j) { // cycle through each rib to set corresponding joint info for (u=0; u<=nu; ++u) { curve_type jcrv; rib_states[u].get_f().get(jcrv, v); pts[u] = jcrv.get_control_point(j); } int nseg( pts.size() - 1 ); if ( closed ) { ++nseg; } gc.set_number_segments( nseg ); // set the parameterizations and create curve gc.set_t0(this->get_u0()); for (u=0; u<nu; ++u) { gc.set_segment_dt(this->get_segment_du(u), u); } if ( closed ) { gc.set_chip( pts.begin(), eli::geom::general::C1 ); } else { gc.set_chip( pts.begin(), eli::geom::general::NOT_CONNECTED ); } bool rtn_flag=gc.create(c); if (!rtn_flag) { return false; } // extract the control points from piecewise curve and set the surface control points for (u=0; u<nu; ++u) { curve_type crv; c.get(crv, u); // resize the temp surface if (j==0) { surfs[u].resize(crv.degree(), max_jdegs[v]); } for (i=0; i<=crv.degree(); ++i) { surfs[u].set_control_point(crv.get_control_point(i), i, j); } } } // put these surfaces into piecewise surface typename piecewise_surface_type::error_code ec; for (u=0; u<nu; ++u) { ec=ps.set(surfs[u], u, v); if (ec!=piecewise_surface_type::NO_ERRORS) { assert(false); return false; } } } return true; } private: std::vector<rib_data_type> ribs; std::vector<index_type> max_degree; bool closed; }; } } } #endif
/********************************************************************************* * Copyright (c) 2013 David D. Marshall <[email protected]> * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * David D. Marshall - piecewise general surface creator * Rob McDonald - Modified to piecewise cubic spline surface creator ********************************************************************************/ #ifndef eli_geom_surface_piecewise_cubic_spline_skinning_surface_creator_hpp #define eli_geom_surface_piecewise_cubic_spline_skinning_surface_creator_hpp #include <list> #include <vector> #include <iterator> #include "eli/code_eli.hpp" #include "eli/util/tolerance.hpp" #include "eli/geom/curve/bezier.hpp" #include "eli/geom/curve/piecewise.hpp" #include "eli/geom/curve/piecewise_cubic_spline_creator.hpp" #include "eli/geom/surface/piecewise.hpp" #include "eli/geom/surface/bezier.hpp" #include "eli/geom/surface/piecewise_connection_data.hpp" #include "eli/geom/surface/piecewise_creator_base.hpp" namespace eli { namespace geom { namespace surface { template<typename data__, unsigned short dim__, typename tol__> class piecewise_cubic_spline_skinning_surface_creator : public piecewise_creator_base<data__, dim__, tol__> { public: typedef piecewise_creator_base<data__, dim__, tol__> base_class_type; typedef typename base_class_type::data_type data_type; typedef typename base_class_type::point_type point_type; typedef typename base_class_type::index_type index_type; typedef typename base_class_type::tolerance_type tolerance_type; typedef typename base_class_type::piecewise_surface_type piecewise_surface_type; typedef connection_data<data_type, dim__, tolerance_type> rib_data_type; piecewise_cubic_spline_skinning_surface_creator() : piecewise_creator_base<data__, dim__, tol__>(0, 0), ribs(2), max_degree(1), closed(false) { } piecewise_cubic_spline_skinning_surface_creator(const data_type &uu0, const data_type &vv0) : piecewise_creator_base<data__, dim__, tol__>(uu0, vv0), ribs(2), max_degree(1), closed(false) { } piecewise_cubic_spline_skinning_surface_creator(const piecewise_general_skinning_surface_creator<data_type, dim__, tolerance_type> & gs) : piecewise_creator_base<data_type, dim__, tolerance_type>(gs), ribs(gs.ribs), max_degree(gs.max_degree), closed(gs.closed) { } virtual ~piecewise_cubic_spline_skinning_surface_creator() { } void set_closed() {closed=true;} void set_open() {closed=false;} bool is_closed() const {return closed;} bool is_open() const {return !closed;} void set_u0(const data_type &uu0) {this->set_initial_u(uu0);} void set_segment_du(const data_type &duu, const index_type &i) { this->set_du(duu, i); } void set_tdisc( const std::vector<data_type> &td ) { tdisc = td; } bool set_conditions(const std::vector<rib_data_type> &rbs, const std::vector<index_type> &maxd, bool cl=false) { index_type i, j, nsegs(static_cast<index_type>(maxd.size())), nribs(rbs.size()); // ensure input vectors are correct size if (!cl && (nribs!=(nsegs+1))) return false; if (cl && (nribs!=nsegs)) return false; // check to make sure have valid end conditions if (!cl) { if (rbs[0].use_left_fp() || rbs[0].use_left_fpp() || rbs[0].get_continuity()!=rib_data_type::C0) { return false; } if (rbs[nsegs].use_right_fp() || rbs[nsegs].use_right_fpp() || rbs[nsegs].get_continuity()!=rib_data_type::C0) { return false; } } // make sure ribs are in valid state data_type v_start(rbs[0].get_t0()), v_end(rbs[0].get_tmax()); tolerance_type tol; for (i=0; i<nribs; ++i) { if (!rbs[i].check_state()) return false; if (!tol.approximately_equal(rbs[i].get_t0(), v_start) || !tol.approximately_equal(rbs[i].get_tmax(), v_end)) return false; } // find all unique v-coordinates on joints for each rib auto comp = [&tol](const data_type &x1, const data_type &x2)->bool { return tol.approximately_less_than(x1, x2); }; std::vector<data_type> joints; data_type t0(rbs[0].get_t0()), tmax(rbs[0].get_tmax()); rbs[0].get_joints(std::back_inserter(joints)); for (i=1; i<nribs; ++i) { // test to make sure this rib's parameterization matches rest if (!tol.approximately_equal(rbs[i].get_t0(), t0) || !tol.approximately_equal(rbs[i].get_tmax(), tmax)) { return false; } // get the joints on the current rib std::vector<data_type> rjoints, jts_out; rbs[i].get_joints(std::back_inserter(rjoints)); // merge these joints with current list of joints std::set_union(joints.begin(), joints.end(), rjoints.begin(), rjoints.end(), std::back_inserter(jts_out), comp); std::swap(joints, jts_out); } // record where the joints need to be for create() index_type njoints(static_cast<index_type>(joints.size())); // set the v-parameterization this->set_number_v_segments(njoints-1); this->set_initial_v(joints[0]); for (j=0; j<(njoints-1); ++j) { this->set_dv(joints[j+1]-joints[j], j); } // reset the number of u-segments this->set_number_u_segments(nsegs); ribs=rbs; max_degree=maxd; closed=cl; return true; } virtual bool create(piecewise_surface_type &ps) const { typedef typename piecewise_surface_type::surface_type surface_type; index_type nribs(this->get_number_u_segments()+1), i, j; std::vector<index_type> seg_degree(nribs-1); std::vector<rib_data_type> rib_states(ribs); tolerance_type tol; // FIX: Should be able to handle closed surfaces assert(!closed); // FIX: Need to be able to handle v-direction discontinuous fu and fuu specifications // reset the incoming piecewise surface ps.clear(); // split ribs so have same number of curves (with same joint parameters) for all ribs and get degree index_type njoints(this->get_number_v_segments()+1); std::vector<data_type> joints(njoints); std::vector<index_type> max_jdegs(njoints-1,0); joints[0]=this->get_v0(); for (j=0; j<(njoints-1); ++j) { joints[j+1]=joints[j]+this->get_segment_dv(j); } for (i=0; i<nribs; ++i) { std::vector<index_type> jdegs; rib_states[i].split(joints.begin(), joints.end(), std::back_inserter(jdegs)); for (j=0; j<(njoints-1); ++j) { if (jdegs[j]>max_jdegs[j]) { max_jdegs[j]=jdegs[j]; } } } // set degree in u-direction for each rib segment strip for (i=0; i<nribs; ++i) { rib_states[i].promote(max_jdegs.begin(), max_jdegs.end()); } // resize the piecewise surface index_type u, v, nu(nribs-1), nv(njoints-1); ps.init_uv(this->du_begin(), this->du_end(), this->dv_begin(), this->dv_end(), this->get_u0(), this->get_v0()); // build segments based on rib information // here should have everything to make an nribs x njoints piecewise surface with all // of the j-degrees matching in the u-direction so that can use general curve creator // techniques to create control points for (v=0; v<nv; ++v) { typedef eli::geom::curve::piecewise_cubic_spline_creator<data_type, dim__, tolerance_type> piecewise_curve_creator_type; typedef eli::geom::curve::piecewise<eli::geom::curve::bezier, data_type, dim__, tolerance_type> piecewise_curve_type; typedef typename piecewise_curve_type::curve_type curve_type; std::vector < point_type > pts( nu+1 ); piecewise_curve_creator_type gc; piecewise_curve_type c; std::vector<surface_type> surfs(nu); for (j=0; j<=max_jdegs[v]; ++j) { // cycle through each rib to set corresponding joint info for (u=0; u<=nu; ++u) { curve_type jcrv; rib_states[u].get_f().get(jcrv, v); pts[u] = jcrv.get_control_point(j); } int nseg( pts.size() - 1 ); if ( closed ) { ++nseg; } gc.set_number_segments( nseg ); // set the parameterizations and create curve gc.set_t0(this->get_u0()); for (u=0; u<nu; ++u) { gc.set_segment_dt(this->get_segment_du(u), u); } if ( closed ) { gc.set_chip( pts.begin(), eli::geom::general::C1 ); } else { gc.set_chip( pts.begin(), eli::geom::general::NOT_CONNECTED ); } bool rtn_flag=gc.create(c); if (!rtn_flag) { return false; } // extract the control points from piecewise curve and set the surface control points for (u=0; u<nu; ++u) { curve_type crv; c.get(crv, u); // resize the temp surface if (j==0) { surfs[u].resize(crv.degree(), max_jdegs[v]); } for (i=0; i<=crv.degree(); ++i) { surfs[u].set_control_point(crv.get_control_point(i), i, j); } } } // put these surfaces into piecewise surface typename piecewise_surface_type::error_code ec; for (u=0; u<nu; ++u) { ec=ps.set(surfs[u], u, v); if (ec!=piecewise_surface_type::NO_ERRORS) { assert(false); return false; } } } return true; } private: std::vector<rib_data_type> ribs; std::vector<index_type> max_degree; std::vector<data_type> tdisc; bool closed; }; } } } #endif
Add tdisc member data to cubic skinner
Add tdisc member data to cubic skinner
C++
epl-1.0
ramcdona/Code-Eli
2a7026b797204e12a2d5316f34f3652cb420068f
Code/Common/mvdI18nApplication.cxx
Code/Common/mvdI18nApplication.cxx
/*========================================================================= Program: Monteverdi2 Language: C++ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See Copyright.txt for details. Monteverdi2 is distributed under the CeCILL licence version 2. See Licence_CeCILL_V2-en.txt or http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt for more details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "mvdI18nApplication.h" // // Qt includes (sorted by alphabetic order) //// Must be included before system/custom includes. // // System includes (sorted by alphabetic order) // // OTB includes (sorted by alphabetic order) // // Monteverdi includes (sorted by alphabetic order) // // Class implementation. namespace mvd { /* TRANSLATOR mvd::I18nApplication Necessary for lupdate to be aware of C++ namespaces. Context comment for translator. */ /*******************************************************************************/ I18nApplication ::I18nApplication( int& argc, char** argv ) : QApplication( argc, argv ), m_IsRunningFromBuildDir( false ) { InitializeLocale(); } /*******************************************************************************/ I18nApplication ::~I18nApplication() { } /*******************************************************************************/ void I18nApplication ::InitializeLocale() { QTextCodec::setCodecForTr( QTextCodec::codecForName( "utf8" ) ); // // 1. default UI language is english (no translation). QLocale sys_lc( QLocale::system() ); if( sys_lc.language()==QLocale::C || ( sys_lc.language()==QLocale::English && sys_lc.country()==QLocale::UnitedStates ) ) { return; } // // 2. Choose i18n path between build dir and install dir. QDir i18n_dir; QDir bin_dir( QDir::cleanPath( QCoreApplication::applicationDirPath() ) ); QDir build_i18n_dir( bin_dir ); // If build dir is identified... if( build_i18n_dir.exists( "../i18n" ) && build_i18n_dir.cd( "../i18n" ) && build_i18n_dir.exists( "../" Monteverdi2_CONFIGURE_FILE ) || build_i18n_dir.exists( "../../i18n" ) && build_i18n_dir.cd( "../../i18n" ) && build_i18n_dir.exists( "../" Monteverdi2_CONFIGURE_FILE ) ) { m_IsRunningFromBuildDir = true; // ...use build dir as prioritary load path for translation. i18n_dir = build_i18n_dir; // TODO: Use log system to trace message. qDebug() << tr( "Running from build directory '%1'." ).arg( bin_dir.path() ); } // Otherwise... else { m_IsRunningFromBuildDir = false; QDir install_i18n_dir( QDir::cleanPath( Monteverdi2_INSTALL_DATA_I18N_DIR ) ); // ...if install data dir is identified if( install_i18n_dir.exists() ) { // ...use install data dir as load path for translation. i18n_dir = install_i18n_dir; // TODO: Use log system to trace message. qDebug() << tr( "Running from install directory '%1'." ).arg( Monteverdi2_INSTALL_BIN_DIR ); } // Otherwise else { QString message( tr( "Failed to access translation-files directory '%1'." ) .arg( install_i18n_dir.path() ) ); // TODO: Use log system to trace error while loading locale translation file. qDebug() << message; // TODO: morph into better HMI design. QMessageBox::critical( NULL, tr( "Critical error!" ), message ); return; } } // // 3.1 Stack Qt translator. LoadAndInstallTranslator( "qt_" + sys_lc.name(), QLibraryInfo::location( QLibraryInfo::TranslationsPath ) ); // // 3.2 Stack Monteverdi2 translator as prioritary over Qt translator. LoadAndInstallTranslator( sys_lc.name(), i18n_dir.path() ); // TODO: Record locale translation filename(s) used in UI component (e.g. // AboutDialog, Settings dialog, Information dialog etc.) } /*******************************************************************************/ bool I18nApplication ::LoadAndInstallTranslator(const QString& filename, const QString& directory, const QString& searchDelimiters, const QString& suffix ) { QString filename_ext( filename + ( suffix.isNull() ? ".qm" : suffix ) ); // (a) Do need to new QTranslator() here! QTranslator* lc_translator = new QTranslator( this ); if( !lc_translator->load( filename, directory, searchDelimiters, suffix ) ) { QString message( tr( "Failed to load '%1' translation file from '%2'." ) .arg( filename_ext ) .arg( directory ) ); // TODO: Use log system to trace error while loading locale translation file. qWarning() << message; // TODO: morph into better HMI design. QMessageBox::warning( NULL, tr( "Warning!" ), message ); return false; } // (a) ...because QTranslator needs to be alive during the whole // lifespan of the application. QCoreApplication::installTranslator( lc_translator ); QString message( tr( "Successfully loaded '%1' translation file from '%2'." ) .arg( filename_ext ) .arg( directory ) ); // TODO: Log locale translation filename used. qDebug() << message; return true; } /*******************************************************************************/ /* SLOTS */ /*******************************************************************************/ } // end namespace 'mvd'
/*========================================================================= Program: Monteverdi2 Language: C++ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See Copyright.txt for details. Monteverdi2 is distributed under the CeCILL licence version 2. See Licence_CeCILL_V2-en.txt or http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt for more details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "mvdI18nApplication.h" // // Qt includes (sorted by alphabetic order) //// Must be included before system/custom includes. // // System includes (sorted by alphabetic order) // // OTB includes (sorted by alphabetic order) // // Monteverdi includes (sorted by alphabetic order) // // Class implementation. namespace mvd { /* TRANSLATOR mvd::I18nApplication Necessary for lupdate to be aware of C++ namespaces. Context comment for translator. */ /*******************************************************************************/ I18nApplication ::I18nApplication( int& argc, char** argv ) : QApplication( argc, argv ), m_IsRunningFromBuildDir( false ) { InitializeLocale(); } /*******************************************************************************/ I18nApplication ::~I18nApplication() { } /*******************************************************************************/ void I18nApplication ::InitializeLocale() { QTextCodec::setCodecForTr( QTextCodec::codecForName( "utf8" ) ); // // 1. default UI language is english (no translation). QLocale sys_lc( QLocale::system() ); if( sys_lc.language() == QLocale::C || ( sys_lc.language() == QLocale::English && sys_lc.country() == QLocale::UnitedStates ) ) { return; } // // 2. Choose i18n path between build dir and install dir. QDir i18n_dir; QDir bin_dir( QDir::cleanPath( QCoreApplication::applicationDirPath() ) ); QDir build_i18n_dir( bin_dir ); // If build dir is identified... if( build_i18n_dir.exists( "../i18n" ) && build_i18n_dir.cd( "../i18n" ) && build_i18n_dir.exists( "../" Monteverdi2_CONFIGURE_FILE ) || build_i18n_dir.exists( "../../i18n" ) && build_i18n_dir.cd( "../../i18n" ) && build_i18n_dir.exists( "../" Monteverdi2_CONFIGURE_FILE ) ) { m_IsRunningFromBuildDir = true; // ...use build dir as prioritary load path for translation. i18n_dir = build_i18n_dir; // TODO: Use log system to trace message. qDebug() << tr( "Running from build directory '%1'." ).arg( bin_dir.path() ); } // Otherwise... else { m_IsRunningFromBuildDir = false; QDir install_i18n_dir( QDir::cleanPath( Monteverdi2_INSTALL_DATA_I18N_DIR ) ); // ...if install data dir is identified if( install_i18n_dir.exists() ) { // ...use install data dir as load path for translation. i18n_dir = install_i18n_dir; // TODO: Use log system to trace message. qDebug() << tr( "Running from install directory '%1'." ).arg( Monteverdi2_INSTALL_BIN_DIR ); } // Otherwise else { QString message( tr( "Failed to access translation-files directory '%1'." ) .arg( install_i18n_dir.path() ) ); // TODO: Use log system to trace error while loading locale translation file. qDebug() << message; // TODO: morph into better HMI design. QMessageBox::critical( NULL, tr( "Critical error!" ), message ); return; } } // // 3.1 Stack Qt translator. LoadAndInstallTranslator( "qt_" + sys_lc.name(), QLibraryInfo::location( QLibraryInfo::TranslationsPath ) ); // // 3.2 Stack Monteverdi2 translator as prioritary over Qt translator. LoadAndInstallTranslator( sys_lc.name(), i18n_dir.path() ); // TODO: Record locale translation filename(s) used in UI component (e.g. // AboutDialog, Settings dialog, Information dialog etc.) } /*******************************************************************************/ bool I18nApplication ::LoadAndInstallTranslator(const QString& filename, const QString& directory, const QString& searchDelimiters, const QString& suffix ) { QString filename_ext( filename + ( suffix.isNull() ? ".qm" : suffix ) ); // (a) Do need to new QTranslator() here! QTranslator* lc_translator = new QTranslator( this ); if( !lc_translator->load( filename, directory, searchDelimiters, suffix ) ) { QString message( tr( "Failed to load '%1' translation file from '%2'." ) .arg( filename_ext ) .arg( directory ) ); // TODO: Use log system to trace error while loading locale translation file. qWarning() << message; // TODO: morph into better HMI design. QMessageBox::warning( NULL, tr( "Warning!" ), message ); return false; } // (a) ...because QTranslator needs to be alive during the whole // lifespan of the application. QCoreApplication::installTranslator( lc_translator ); QString message( tr( "Successfully loaded '%1' translation file from '%2'." ) .arg( filename_ext ) .arg( directory ) ); // TODO: Log locale translation filename used. qDebug() << message; return true; } /*******************************************************************************/ /* SLOTS */ /*******************************************************************************/ } // end namespace 'mvd'
remove tabs
STYLE: remove tabs
C++
apache-2.0
orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB
cc4608744d5c3f932cbb097112e4965b57381e1c
src/MissionManager/ComplexMissionItemTest.cc
src/MissionManager/ComplexMissionItemTest.cc
/**************************************************************************** * * (c) 2009-2016 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org> * * QGroundControl is licensed according to the terms in the file * COPYING.md in the root of the source code directory. * ****************************************************************************/ #include "ComplexMissionItemTest.h" ComplexMissionItemTest::ComplexMissionItemTest(void) { _polyPoints << QGeoCoordinate(47.633550640000003, -122.08982199) << QGeoCoordinate(47.634129020000003, -122.08887249) << QGeoCoordinate(47.633619320000001, -122.08811074) << QGeoCoordinate(47.633189139999999, -122.08900124); } void ComplexMissionItemTest::init(void) { _rgComplexMissionItemSignals[polygonPathChangedIndex] = SIGNAL(polygonPathChanged()); _rgComplexMissionItemSignals[lastSequenceNumberChangedIndex] = SIGNAL(lastSequenceNumberChanged(int)); _rgComplexMissionItemSignals[altitudeChangedIndex] = SIGNAL(altitudeChanged(double)); _rgComplexMissionItemSignals[gridAngleChangedIndex] = SIGNAL(gridAngleChanged(double)); _rgComplexMissionItemSignals[gridPointsChangedIndex] = SIGNAL(gridPointsChanged()); _rgComplexMissionItemSignals[cameraTriggerChangedIndex] = SIGNAL(cameraTriggerChanged(bool)); _rgComplexMissionItemSignals[altDifferenceChangedIndex] = SIGNAL(altDifferenceChanged(double)); _rgComplexMissionItemSignals[altPercentChangedIndex] = SIGNAL(altPercentChanged(double)); _rgComplexMissionItemSignals[azimuthChangedIndex] = SIGNAL(azimuthChanged(double)); _rgComplexMissionItemSignals[commandDescriptionChangedIndex] = SIGNAL(commandDescriptionChanged()); _rgComplexMissionItemSignals[commandNameChangedIndex] = SIGNAL(commandNameChanged()); _rgComplexMissionItemSignals[abbreviationChangedIndex] = SIGNAL(abbreviationChanged()); _rgComplexMissionItemSignals[coordinateChangedIndex] = SIGNAL(coordinateChanged(const QGeoCoordinate&)); _rgComplexMissionItemSignals[exitCoordinateChangedIndex] = SIGNAL(exitCoordinateChanged(const QGeoCoordinate&)); _rgComplexMissionItemSignals[dirtyChangedIndex] = SIGNAL(dirtyChanged(bool)); _rgComplexMissionItemSignals[distanceChangedIndex] = SIGNAL(distanceChanged(double)); _rgComplexMissionItemSignals[isCurrentItemChangedIndex] = SIGNAL(isCurrentItemChanged(bool)); _rgComplexMissionItemSignals[sequenceNumberChangedIndex] = SIGNAL(sequenceNumberChanged(int)); _rgComplexMissionItemSignals[isSimpleItemChangedIndex] = SIGNAL(isSimpleItemChanged(bool)); _rgComplexMissionItemSignals[specifiesCoordinateChangedIndex] = SIGNAL(specifiesCoordinateChanged()); _rgComplexMissionItemSignals[isStandaloneCoordinateChangedIndex] = SIGNAL(isStandaloneCoordinateChanged()); _rgComplexMissionItemSignals[coordinateHasRelativeAltitudeChangedIndex] = SIGNAL(coordinateHasRelativeAltitudeChanged(bool)); _rgComplexMissionItemSignals[exitCoordinateHasRelativeAltitudeChangedIndex] = SIGNAL(exitCoordinateHasRelativeAltitudeChanged(bool)); _rgComplexMissionItemSignals[exitCoordinateSameAsEntryChangedIndex] = SIGNAL(exitCoordinateSameAsEntryChanged(bool)); _complexItem = new SurveyMissionItem(NULL /* Vehicle */, this); // It's important to check that the right signals are emitted at the right time since that drives ui change. // It's also important to check that things are not being over-signalled when they should not be, since that can lead // to incorrect ui or perf impact of uneeded signals propogating ui change. _multiSpy = new MultiSignalSpy(); Q_CHECK_PTR(_multiSpy); QCOMPARE(_multiSpy->init(_complexItem, _rgComplexMissionItemSignals, _cComplexMissionItemSignals), true); } void ComplexMissionItemTest::cleanup(void) { delete _complexItem; delete _multiSpy; } void ComplexMissionItemTest::_testDirty(void) { QVERIFY(!_complexItem->dirty()); _complexItem->setDirty(false); QVERIFY(!_complexItem->dirty()); QVERIFY(_multiSpy->checkNoSignals()); _complexItem->setDirty(true); QVERIFY(_complexItem->dirty()); QVERIFY(_multiSpy->checkOnlySignalByMask(dirtyChangedMask)); QVERIFY(_multiSpy->pullBoolFromSignalIndex(dirtyChangedIndex)); _multiSpy->clearAllSignals(); _complexItem->setDirty(false); QVERIFY(!_complexItem->dirty()); QVERIFY(_multiSpy->checkOnlySignalByMask(dirtyChangedMask)); QVERIFY(!_multiSpy->pullBoolFromSignalIndex(dirtyChangedIndex)); } void ComplexMissionItemTest::_testAddPolygonCoordinate(void) { QCOMPARE(_complexItem->polygonPath().count(), 0); // First call to addPolygonCoordinate should trigger: // polygonPathChanged // dirtyChanged _complexItem->addPolygonCoordinate(_polyPoints[0]); QVERIFY(_multiSpy->checkOnlySignalByMask(polygonPathChangedMask | dirtyChangedMask)); // Validate object data QVariantList polyList = _complexItem->polygonPath(); QCOMPARE(polyList.count(), 1); QCOMPARE(polyList[0].value<QGeoCoordinate>(), _polyPoints[0]); // Reset _complexItem->setDirty(false); _multiSpy->clearAllSignals(); // Second call to addPolygonCoordinate should only trigger: // polygonPathChanged // dirtyChanged _complexItem->addPolygonCoordinate(_polyPoints[1]); QVERIFY(_multiSpy->checkOnlySignalByMask(polygonPathChangedMask | dirtyChangedMask)); polyList = _complexItem->polygonPath(); QCOMPARE(polyList.count(), 2); for (int i=0; i<polyList.count(); i++) { QCOMPARE(polyList[i].value<QGeoCoordinate>(), _polyPoints[i]); } _complexItem->setDirty(false); _multiSpy->clearAllSignals(); // Third call to addPolygonCoordinate should trigger: // polygonPathChanged // dirtyChanged // Grid is generated for the first time on closing of polygon which triggers: // coordinateChanged - grid generates new entry coordinate // exitCoordinateChanged - grid generates new exit coordinate // specifiesCoordinateChanged - once grid entry/exit shows up specifiesCoordinate gets set to true // Grid generation triggers the following signals // lastSequenceNumberChanged - number of internal mission items changes // gridPointsChanged - grid points show up for the first time _complexItem->addPolygonCoordinate(_polyPoints[2]); QVERIFY(_multiSpy->checkOnlySignalByMask(polygonPathChangedMask | lastSequenceNumberChangedMask | gridPointsChangedMask | coordinateChangedMask | exitCoordinateChangedMask | specifiesCoordinateChangedMask | dirtyChangedMask)); int seqNum = _multiSpy->pullIntFromSignalIndex(lastSequenceNumberChangedIndex); QVERIFY(seqNum > 0); polyList = _complexItem->polygonPath(); QCOMPARE(polyList.count(), 3); for (int i=0; i<polyList.count(); i++) { QCOMPARE(polyList[i].value<QGeoCoordinate>(), _polyPoints[i]); } } void ComplexMissionItemTest::_testClearPolygon(void) { for (int i=0; i<3; i++) { _complexItem->addPolygonCoordinate(_polyPoints[i]); } _complexItem->setDirty(false); _multiSpy->clearAllSignals(); // Call to clearPolygon should trigger: // polygonPathChangedMask // dirtyChanged // lastSequenceNumberChangedMask // gridPointsChangedMask // dirtyChangedMask // specifiesCoordinateChangedMask _complexItem->clearPolygon(); QVERIFY(_multiSpy->checkOnlySignalByMask(polygonPathChangedMask | lastSequenceNumberChangedMask | gridPointsChangedMask | dirtyChangedMask | specifiesCoordinateChangedMask)); QVERIFY(!_multiSpy->pullBoolFromSignalIndex(specifiesCoordinateChangedIndex)); QCOMPARE(_multiSpy->pullIntFromSignalIndex(lastSequenceNumberChangedIndex), 0); QCOMPARE(_complexItem->polygonPath().count(), 0); QCOMPARE(_complexItem->gridPoints().count(), 0); _complexItem->setDirty(false); _multiSpy->clearAllSignals(); } void ComplexMissionItemTest::_testCameraTrigger(void) { QVERIFY(!_complexItem->property("cameraTrigger").toBool()); // Turning on/off camera triggering while there is no grid should trigger: // cameraTriggerChanged // dirtyChanged // lastSequenceNumber should not change int lastSeq = _complexItem->lastSequenceNumber(); _complexItem->setProperty("cameraTrigger", true); QVERIFY(_multiSpy->checkOnlySignalByMask(dirtyChangedMask | cameraTriggerChangedMask)); QVERIFY(_multiSpy->pullBoolFromSignalIndex(cameraTriggerChangedIndex)); QCOMPARE(_complexItem->lastSequenceNumber(), lastSeq); _complexItem->setDirty(false); _multiSpy->clearAllSignals(); _complexItem->setProperty("cameraTrigger", false); QVERIFY(_multiSpy->checkOnlySignalByMask(dirtyChangedMask | cameraTriggerChangedMask)); QVERIFY(!_multiSpy->pullBoolFromSignalIndex(cameraTriggerChangedIndex)); QCOMPARE(_complexItem->lastSequenceNumber(), lastSeq); // Set up a grid for (int i=0; i<3; i++) { _complexItem->addPolygonCoordinate(_polyPoints[i]); } _complexItem->setDirty(false); _multiSpy->clearAllSignals(); lastSeq = _complexItem->lastSequenceNumber(); QVERIFY(lastSeq > 0); // Turning on camera triggering should add two more mission items, this should trigger: // lastSequenceNumberChanged // dirtyChanged _complexItem->setProperty("cameraTrigger", true); QVERIFY(_multiSpy->checkOnlySignalByMask(lastSequenceNumberChangedMask | dirtyChangedMask | cameraTriggerChangedMask)); QCOMPARE(_multiSpy->pullIntFromSignalIndex(lastSequenceNumberChangedIndex), lastSeq + 2); _complexItem->setDirty(false); _multiSpy->clearAllSignals(); // Turn off camera triggering and make sure things go back to previous count _complexItem->setProperty("cameraTrigger", false); QVERIFY(_multiSpy->checkOnlySignalByMask(lastSequenceNumberChangedMask | dirtyChangedMask | cameraTriggerChangedMask)); QCOMPARE(_multiSpy->pullIntFromSignalIndex(lastSequenceNumberChangedIndex), lastSeq); }
/**************************************************************************** * * (c) 2009-2016 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org> * * QGroundControl is licensed according to the terms in the file * COPYING.md in the root of the source code directory. * ****************************************************************************/ #include "ComplexMissionItemTest.h" ComplexMissionItemTest::ComplexMissionItemTest(void) { _polyPoints << QGeoCoordinate(47.633550640000003, -122.08982199) << QGeoCoordinate(47.634129020000003, -122.08887249) << QGeoCoordinate(47.633619320000001, -122.08811074) << QGeoCoordinate(47.633189139999999, -122.08900124); } void ComplexMissionItemTest::init(void) { _rgComplexMissionItemSignals[polygonPathChangedIndex] = SIGNAL(polygonPathChanged()); _rgComplexMissionItemSignals[lastSequenceNumberChangedIndex] = SIGNAL(lastSequenceNumberChanged(int)); _rgComplexMissionItemSignals[altitudeChangedIndex] = SIGNAL(altitudeChanged(double)); _rgComplexMissionItemSignals[gridAngleChangedIndex] = SIGNAL(gridAngleChanged(double)); _rgComplexMissionItemSignals[gridPointsChangedIndex] = SIGNAL(gridPointsChanged()); _rgComplexMissionItemSignals[cameraTriggerChangedIndex] = SIGNAL(cameraTriggerChanged(bool)); _rgComplexMissionItemSignals[altDifferenceChangedIndex] = SIGNAL(altDifferenceChanged(double)); _rgComplexMissionItemSignals[altPercentChangedIndex] = SIGNAL(altPercentChanged(double)); _rgComplexMissionItemSignals[azimuthChangedIndex] = SIGNAL(azimuthChanged(double)); _rgComplexMissionItemSignals[commandDescriptionChangedIndex] = SIGNAL(commandDescriptionChanged()); _rgComplexMissionItemSignals[commandNameChangedIndex] = SIGNAL(commandNameChanged()); _rgComplexMissionItemSignals[abbreviationChangedIndex] = SIGNAL(abbreviationChanged()); _rgComplexMissionItemSignals[coordinateChangedIndex] = SIGNAL(coordinateChanged(const QGeoCoordinate&)); _rgComplexMissionItemSignals[exitCoordinateChangedIndex] = SIGNAL(exitCoordinateChanged(const QGeoCoordinate&)); _rgComplexMissionItemSignals[dirtyChangedIndex] = SIGNAL(dirtyChanged(bool)); _rgComplexMissionItemSignals[distanceChangedIndex] = SIGNAL(distanceChanged(double)); _rgComplexMissionItemSignals[isCurrentItemChangedIndex] = SIGNAL(isCurrentItemChanged(bool)); _rgComplexMissionItemSignals[sequenceNumberChangedIndex] = SIGNAL(sequenceNumberChanged(int)); _rgComplexMissionItemSignals[isSimpleItemChangedIndex] = SIGNAL(isSimpleItemChanged(bool)); _rgComplexMissionItemSignals[specifiesCoordinateChangedIndex] = SIGNAL(specifiesCoordinateChanged()); _rgComplexMissionItemSignals[isStandaloneCoordinateChangedIndex] = SIGNAL(isStandaloneCoordinateChanged()); _rgComplexMissionItemSignals[coordinateHasRelativeAltitudeChangedIndex] = SIGNAL(coordinateHasRelativeAltitudeChanged(bool)); _rgComplexMissionItemSignals[exitCoordinateHasRelativeAltitudeChangedIndex] = SIGNAL(exitCoordinateHasRelativeAltitudeChanged(bool)); _rgComplexMissionItemSignals[exitCoordinateSameAsEntryChangedIndex] = SIGNAL(exitCoordinateSameAsEntryChanged(bool)); _complexItem = new SurveyMissionItem(NULL /* Vehicle */, this); // It's important to check that the right signals are emitted at the right time since that drives ui change. // It's also important to check that things are not being over-signalled when they should not be, since that can lead // to incorrect ui or perf impact of uneeded signals propogating ui change. _multiSpy = new MultiSignalSpy(); Q_CHECK_PTR(_multiSpy); QCOMPARE(_multiSpy->init(_complexItem, _rgComplexMissionItemSignals, _cComplexMissionItemSignals), true); } void ComplexMissionItemTest::cleanup(void) { delete _complexItem; delete _multiSpy; } void ComplexMissionItemTest::_testDirty(void) { QVERIFY(!_complexItem->dirty()); _complexItem->setDirty(false); QVERIFY(!_complexItem->dirty()); QVERIFY(_multiSpy->checkNoSignals()); _complexItem->setDirty(true); QVERIFY(_complexItem->dirty()); QVERIFY(_multiSpy->checkOnlySignalByMask(dirtyChangedMask)); QVERIFY(_multiSpy->pullBoolFromSignalIndex(dirtyChangedIndex)); _multiSpy->clearAllSignals(); _complexItem->setDirty(false); QVERIFY(!_complexItem->dirty()); QVERIFY(_multiSpy->checkOnlySignalByMask(dirtyChangedMask)); QVERIFY(!_multiSpy->pullBoolFromSignalIndex(dirtyChangedIndex)); } void ComplexMissionItemTest::_testAddPolygonCoordinate(void) { QCOMPARE(_complexItem->polygonPath().count(), 0); // First call to addPolygonCoordinate should trigger: // polygonPathChanged // dirtyChanged _complexItem->addPolygonCoordinate(_polyPoints[0]); QVERIFY(_multiSpy->checkOnlySignalByMask(polygonPathChangedMask | dirtyChangedMask)); // Validate object data QVariantList polyList = _complexItem->polygonPath(); QCOMPARE(polyList.count(), 1); QCOMPARE(polyList[0].value<QGeoCoordinate>(), _polyPoints[0]); // Reset _complexItem->setDirty(false); _multiSpy->clearAllSignals(); // Second call to addPolygonCoordinate should only trigger: // polygonPathChanged // dirtyChanged _complexItem->addPolygonCoordinate(_polyPoints[1]); QVERIFY(_multiSpy->checkOnlySignalByMask(polygonPathChangedMask | dirtyChangedMask)); polyList = _complexItem->polygonPath(); QCOMPARE(polyList.count(), 2); for (int i=0; i<polyList.count(); i++) { QCOMPARE(polyList[i].value<QGeoCoordinate>(), _polyPoints[i]); } _complexItem->setDirty(false); _multiSpy->clearAllSignals(); // Third call to addPolygonCoordinate should trigger: // polygonPathChanged // dirtyChanged // Grid is generated for the first time on closing of polygon which triggers: // coordinateChanged - grid generates new entry coordinate // exitCoordinateChanged - grid generates new exit coordinate // specifiesCoordinateChanged - once grid entry/exit shows up specifiesCoordinate gets set to true // Grid generation triggers the following signals // lastSequenceNumberChanged - number of internal mission items changes // gridPointsChanged - grid points show up for the first time _complexItem->addPolygonCoordinate(_polyPoints[2]); QVERIFY(_multiSpy->checkOnlySignalByMask(polygonPathChangedMask | lastSequenceNumberChangedMask | gridPointsChangedMask | coordinateChangedMask | exitCoordinateChangedMask | specifiesCoordinateChangedMask | dirtyChangedMask)); int seqNum = _multiSpy->pullIntFromSignalIndex(lastSequenceNumberChangedIndex); QVERIFY(seqNum > 0); polyList = _complexItem->polygonPath(); QCOMPARE(polyList.count(), 3); for (int i=0; i<polyList.count(); i++) { QCOMPARE(polyList[i].value<QGeoCoordinate>(), _polyPoints[i]); } } void ComplexMissionItemTest::_testClearPolygon(void) { for (int i=0; i<3; i++) { _complexItem->addPolygonCoordinate(_polyPoints[i]); } _complexItem->setDirty(false); _multiSpy->clearAllSignals(); // Call to clearPolygon should trigger: // polygonPathChangedMask // dirtyChanged // lastSequenceNumberChangedMask // gridPointsChangedMask // dirtyChangedMask // specifiesCoordinateChangedMask _complexItem->clearPolygon(); QVERIFY(_multiSpy->checkOnlySignalByMask(polygonPathChangedMask | lastSequenceNumberChangedMask | gridPointsChangedMask | dirtyChangedMask | specifiesCoordinateChangedMask)); QVERIFY(!_multiSpy->pullBoolFromSignalIndex(specifiesCoordinateChangedIndex)); QCOMPARE(_multiSpy->pullIntFromSignalIndex(lastSequenceNumberChangedIndex), 0); QCOMPARE(_complexItem->polygonPath().count(), 0); QCOMPARE(_complexItem->gridPoints().count(), 0); _complexItem->setDirty(false); _multiSpy->clearAllSignals(); } void ComplexMissionItemTest::_testCameraTrigger(void) { QCOMPARE(_complexItem->property("cameraTrigger").toBool(), true); // Turning on/off camera triggering while there is no grid should trigger: // cameraTriggerChanged // dirtyChanged // lastSequenceNumber should not change int lastSeq = _complexItem->lastSequenceNumber(); _complexItem->setProperty("cameraTrigger", false); QVERIFY(_multiSpy->checkOnlySignalByMask(dirtyChangedMask | cameraTriggerChangedMask)); QVERIFY(!_multiSpy->pullBoolFromSignalIndex(cameraTriggerChangedIndex)); QCOMPARE(_complexItem->lastSequenceNumber(), lastSeq); _complexItem->setDirty(false); _multiSpy->clearAllSignals(); _complexItem->setProperty("cameraTrigger", true); QVERIFY(_multiSpy->checkOnlySignalByMask(dirtyChangedMask | cameraTriggerChangedMask)); QVERIFY(_multiSpy->pullBoolFromSignalIndex(cameraTriggerChangedIndex)); QCOMPARE(_complexItem->lastSequenceNumber(), lastSeq); // Set up a grid for (int i=0; i<3; i++) { _complexItem->addPolygonCoordinate(_polyPoints[i]); } _complexItem->setDirty(false); _multiSpy->clearAllSignals(); lastSeq = _complexItem->lastSequenceNumber(); QVERIFY(lastSeq > 0); // Turning off camera triggering should remove two camera trigger mission items, this should trigger: // lastSequenceNumberChanged // dirtyChanged _complexItem->setProperty("cameraTrigger", false); QVERIFY(_multiSpy->checkOnlySignalByMask(lastSequenceNumberChangedMask | dirtyChangedMask | cameraTriggerChangedMask)); QCOMPARE(_multiSpy->pullIntFromSignalIndex(lastSequenceNumberChangedIndex), lastSeq - 2); _complexItem->setDirty(false); _multiSpy->clearAllSignals(); // Turn on camera triggering and make sure things go back to previous count _complexItem->setProperty("cameraTrigger", true); QVERIFY(_multiSpy->checkOnlySignalByMask(lastSequenceNumberChangedMask | dirtyChangedMask | cameraTriggerChangedMask)); QCOMPARE(_multiSpy->pullIntFromSignalIndex(lastSequenceNumberChangedIndex), lastSeq); }
Update for cameraTrigger=true default
Update for cameraTrigger=true default
C++
agpl-3.0
kd0aij/qgroundcontrol,kd0aij/qgroundcontrol,kd0aij/qgroundcontrol,ethz-asl/qgc_asl,CornerOfSkyline/qgroundcontrol,Hunter522/qgroundcontrol,RedoXyde/PX4_qGCS,Hunter522/qgroundcontrol,RedoXyde/PX4_qGCS,kd0aij/qgroundcontrol,RedoXyde/PX4_qGCS,RedoXyde/PX4_qGCS,RedoXyde/PX4_qGCS,kd0aij/qgroundcontrol,CornerOfSkyline/qgroundcontrol,ethz-asl/qgc_asl,Hunter522/qgroundcontrol,ethz-asl/qgc_asl,kd0aij/qgroundcontrol,ethz-asl/qgc_asl,Hunter522/qgroundcontrol,CornerOfSkyline/qgroundcontrol,ethz-asl/qgc_asl,Hunter522/qgroundcontrol,Hunter522/qgroundcontrol,RedoXyde/PX4_qGCS,CornerOfSkyline/qgroundcontrol,CornerOfSkyline/qgroundcontrol,CornerOfSkyline/qgroundcontrol
35a9ea50b8b0ca1a45fba15ec5186496c1d49a7a
modules/perception/camera/lib/obstacle/postprocessor/location_refiner/location_refiner_obstacle_postprocessor.cc
modules/perception/camera/lib/obstacle/postprocessor/location_refiner/location_refiner_obstacle_postprocessor.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the License); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an AS IS BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/perception/camera/lib/obstacle/postprocessor/location_refiner/location_refiner_obstacle_postprocessor.h" // NOLINT #include <assert.h> #include <algorithm> #include "cyber/common/log.h" #include "modules/common/util/file.h" #include "modules/perception/camera/common/global_config.h" #include "modules/perception/camera/lib/interface/base_calibration_service.h" #include "modules/perception/lib/io/file_util.h" #include "modules/perception/lib/singleton/singleton.h" // TODO(Xun): code completion namespace apollo { namespace perception { namespace camera { bool LocationRefinerObstaclePostprocessor::Init( const ObstaclePostprocessorInitOptions &options) { std::string postprocessor_config = apollo::common::util::GetAbsolutePath(options.root_dir, options.conf_file); if (!apollo::common::util::GetProtoFromFile <location_refiner::LocationRefinerParam>(postprocessor_config, &location_refiner_param_)) { AERROR << "Read config failed: " << postprocessor_config; return false; } AINFO << "Load postprocessor parameters from " << postprocessor_config << " \nmin_dist_to_camera: " << location_refiner_param_.min_dist_to_camera() << " \nroi_h2bottom_scale: " << location_refiner_param_.roi_h2bottom_scale(); return true; } bool LocationRefinerObstaclePostprocessor::Process( const ObstaclePostprocessorOptions &options, CameraFrame *frame) { if (frame->detected_objects.empty() || frame->calibration_service == nullptr || !options.do_refinement_with_calibration_service) { ADEBUG << "Do not run obstacle postprocessor."; return true; } Eigen::Vector4d plane; if (options.do_refinement_with_calibration_service == true && !frame->calibration_service->QueryGroundPlaneInCameraFrame(&plane) ) { AINFO << "No valid ground plane in the service."; return false; } float query_plane[4] = {static_cast<float>(plane(0)), static_cast<float>(plane(1)), static_cast<float>(plane(2)), static_cast<float>(plane(3))}; const auto &camera_k_matrix = frame->camera_k_matrix; float k_mat[9] = {0}; for (size_t i = 0; i < 3; i++) { size_t i3 = i * 3; for (size_t j = 0; j < 3; j++) { k_mat[i3 + j] = camera_k_matrix(i, j); } } ADEBUG << "Camera k matrix input to obstacle postprocessor: \n" << k_mat[0] << ", " << k_mat[1] << ", " << k_mat[2] << "\n" << k_mat[3] << ", " << k_mat[4] << ", " << k_mat[5] << "\n" << k_mat[6] << ", " << k_mat[7] << ", " << k_mat[8] << "\n"; const int width_image = frame->data_provider->src_width(); const int height_image = frame->data_provider->src_height(); postprocessor_->Init(k_mat, width_image, height_image); ObjPostProcessorOptions obj_postprocessor_options; int nr_valid_obj = 0; for (auto &obj : frame->detected_objects) { ++nr_valid_obj; float object_center[3] = {obj->camera_supplement.local_center(0), obj->camera_supplement.local_center(1), obj->camera_supplement.local_center(2)}; float bbox2d[4] = { obj->camera_supplement.box.xmin, obj->camera_supplement.box.ymin, obj->camera_supplement.box.xmax, obj->camera_supplement.box.ymax}; float bottom_center[2] = {(bbox2d[0] + bbox2d[2]) / 2, bbox2d[3]}; float h_down = (static_cast<float>(height_image) - k_mat[5]) * location_refiner_param_.roi_h2bottom_scale(); bool is_in_rule_roi = is_in_roi(bottom_center, static_cast<float>(width_image), static_cast<float>(height_image), k_mat[5], h_down); float dist2camera = common::ISqrt( common::ISqr(object_center[0]) + common::ISqr(object_center[2])); if (dist2camera > location_refiner_param_.min_dist_to_camera() || !is_in_rule_roi) { ADEBUG << "Pass for obstacle postprocessor."; continue; } float dimension_hwl[3] = {obj->size(2), obj->size(1), obj->size(0)}; float box_cent_x = (bbox2d[0] + bbox2d[2]) / 2; Eigen::Vector3f image_point_low_center(box_cent_x, bbox2d[3], 1); Eigen::Vector3f point_in_camera = camera_k_matrix.inverse() * image_point_low_center; float theta_ray = atan2(point_in_camera.x(), point_in_camera.z()); float rotation_y = theta_ray + obj->camera_supplement.alpha; // enforce the ry to be in the range [-pi, pi) const float PI = common::Constant<float>::PI(); if (rotation_y < -PI) { rotation_y += 2 * PI; } else if (rotation_y >= PI) { rotation_y -= 2 * PI; } // process memcpy(obj_postprocessor_options.bbox, bbox2d, sizeof(float) * 4); obj_postprocessor_options.check_lowerbound = true; camera::LineSegment2D<float> line_seg(bbox2d[0], bbox2d[3], bbox2d[2], bbox2d[3]); obj_postprocessor_options.line_segs.push_back(line_seg); memcpy(obj_postprocessor_options.hwl, dimension_hwl, sizeof(float) * 3); obj_postprocessor_options.ry = rotation_y; // refine with calibration service, support ground plane model currently // {0.0f, cos(tilt), -sin(tilt), -camera_ground_height} memcpy(obj_postprocessor_options.plane, query_plane, sizeof(float) * 4); // changed to touching-ground center object_center[1] += dimension_hwl[0] / 2; postprocessor_->PostProcessObjWithGround(obj_postprocessor_options, object_center, dimension_hwl, &rotation_y); object_center[1] -= dimension_hwl[0] / 2; float z_diff_camera = object_center[2] - obj->camera_supplement.local_center(2); // fill back results obj->camera_supplement.local_center(0) = object_center[0]; obj->camera_supplement.local_center(1) = object_center[1]; obj->camera_supplement.local_center(2) = object_center[2]; obj->center(0) = static_cast<double>(object_center[0]); obj->center(1) = static_cast<double>(object_center[1]); obj->center(2) = static_cast<double>(object_center[2]); obj->center = frame->camera2world_pose * obj->center; AINFO << "diff on camera z: " << z_diff_camera; AINFO << "Obj center from postprocessor: " << obj->center.transpose(); } return true; } std::string LocationRefinerObstaclePostprocessor::Name() const { return "LocationRefinerObstaclePostprocessor"; } // Register plugin. REGISTER_OBSTACLE_POSTPROCESSOR(LocationRefinerObstaclePostprocessor); } // namespace camera } // namespace perception } // namespace apollo
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the License); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an AS IS BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/perception/camera/lib/obstacle/postprocessor/location_refiner/location_refiner_obstacle_postprocessor.h" // NOLINT #include <assert.h> #include <algorithm> #include "cyber/common/log.h" #include "modules/common/util/file.h" #include "modules/perception/camera/common/global_config.h" #include "modules/perception/camera/lib/interface/base_calibration_service.h" #include "modules/perception/lib/io/file_util.h" #include "modules/perception/lib/singleton/singleton.h" // TODO(Xun): code completion namespace apollo { namespace perception { namespace camera { bool LocationRefinerObstaclePostprocessor::Init( const ObstaclePostprocessorInitOptions &options) { std::string postprocessor_config = apollo::common::util::GetAbsolutePath( options.root_dir, options.conf_file); if (!apollo::common::util::GetProtoFromFile <location_refiner::LocationRefinerParam>(postprocessor_config, &location_refiner_param_)) { AERROR << "Read config failed: " << postprocessor_config; return false; } AINFO << "Load postprocessor parameters from " << postprocessor_config << " \nmin_dist_to_camera: " << location_refiner_param_.min_dist_to_camera() << " \nroi_h2bottom_scale: " << location_refiner_param_.roi_h2bottom_scale(); return true; } bool LocationRefinerObstaclePostprocessor::Process( const ObstaclePostprocessorOptions &options, CameraFrame *frame) { if (frame->detected_objects.empty() || frame->calibration_service == nullptr || !options.do_refinement_with_calibration_service) { ADEBUG << "Do not run obstacle postprocessor."; return true; } Eigen::Vector4d plane; if (options.do_refinement_with_calibration_service == true && !frame->calibration_service->QueryGroundPlaneInCameraFrame(&plane) ) { AINFO << "No valid ground plane in the service."; return false; } float query_plane[4] = {static_cast<float>(plane(0)), static_cast<float>(plane(1)), static_cast<float>(plane(2)), static_cast<float>(plane(3))}; const auto &camera_k_matrix = frame->camera_k_matrix; float k_mat[9] = {0}; for (size_t i = 0; i < 3; i++) { size_t i3 = i * 3; for (size_t j = 0; j < 3; j++) { k_mat[i3 + j] = camera_k_matrix(i, j); } } ADEBUG << "Camera k matrix input to obstacle postprocessor: \n" << k_mat[0] << ", " << k_mat[1] << ", " << k_mat[2] << "\n" << k_mat[3] << ", " << k_mat[4] << ", " << k_mat[5] << "\n" << k_mat[6] << ", " << k_mat[7] << ", " << k_mat[8] << "\n"; const int width_image = frame->data_provider->src_width(); const int height_image = frame->data_provider->src_height(); postprocessor_->Init(k_mat, width_image, height_image); ObjPostProcessorOptions obj_postprocessor_options; int nr_valid_obj = 0; for (auto &obj : frame->detected_objects) { ++nr_valid_obj; float object_center[3] = {obj->camera_supplement.local_center(0), obj->camera_supplement.local_center(1), obj->camera_supplement.local_center(2)}; float bbox2d[4] = { obj->camera_supplement.box.xmin, obj->camera_supplement.box.ymin, obj->camera_supplement.box.xmax, obj->camera_supplement.box.ymax}; float bottom_center[2] = {(bbox2d[0] + bbox2d[2]) / 2, bbox2d[3]}; float h_down = (static_cast<float>(height_image) - k_mat[5]) * location_refiner_param_.roi_h2bottom_scale(); bool is_in_rule_roi = is_in_roi(bottom_center, static_cast<float>(width_image), static_cast<float>(height_image), k_mat[5], h_down); float dist2camera = common::ISqrt( common::ISqr(object_center[0]) + common::ISqr(object_center[2])); if (dist2camera > location_refiner_param_.min_dist_to_camera() || !is_in_rule_roi) { ADEBUG << "Pass for obstacle postprocessor."; continue; } float dimension_hwl[3] = {obj->size(2), obj->size(1), obj->size(0)}; float box_cent_x = (bbox2d[0] + bbox2d[2]) / 2; Eigen::Vector3f image_point_low_center(box_cent_x, bbox2d[3], 1); Eigen::Vector3f point_in_camera = camera_k_matrix.inverse() * image_point_low_center; float theta_ray = atan2(point_in_camera.x(), point_in_camera.z()); float rotation_y = theta_ray + obj->camera_supplement.alpha; // enforce the ry to be in the range [-pi, pi) const float PI = common::Constant<float>::PI(); if (rotation_y < -PI) { rotation_y += 2 * PI; } else if (rotation_y >= PI) { rotation_y -= 2 * PI; } // process memcpy(obj_postprocessor_options.bbox, bbox2d, sizeof(float) * 4); obj_postprocessor_options.check_lowerbound = true; camera::LineSegment2D<float> line_seg(bbox2d[0], bbox2d[3], bbox2d[2], bbox2d[3]); obj_postprocessor_options.line_segs.push_back(line_seg); memcpy(obj_postprocessor_options.hwl, dimension_hwl, sizeof(float) * 3); obj_postprocessor_options.ry = rotation_y; // refine with calibration service, support ground plane model currently // {0.0f, cos(tilt), -sin(tilt), -camera_ground_height} memcpy(obj_postprocessor_options.plane, query_plane, sizeof(float) * 4); // changed to touching-ground center object_center[1] += dimension_hwl[0] / 2; postprocessor_->PostProcessObjWithGround(obj_postprocessor_options, object_center, dimension_hwl, &rotation_y); object_center[1] -= dimension_hwl[0] / 2; float z_diff_camera = object_center[2] - obj->camera_supplement.local_center(2); // fill back results obj->camera_supplement.local_center(0) = object_center[0]; obj->camera_supplement.local_center(1) = object_center[1]; obj->camera_supplement.local_center(2) = object_center[2]; obj->center(0) = static_cast<double>(object_center[0]); obj->center(1) = static_cast<double>(object_center[1]); obj->center(2) = static_cast<double>(object_center[2]); obj->center = frame->camera2world_pose * obj->center; AINFO << "diff on camera z: " << z_diff_camera; AINFO << "Obj center from postprocessor: " << obj->center.transpose(); } return true; } std::string LocationRefinerObstaclePostprocessor::Name() const { return "LocationRefinerObstaclePostprocessor"; } // Register plugin. REGISTER_OBSTACLE_POSTPROCESSOR(LocationRefinerObstaclePostprocessor); } // namespace camera } // namespace perception } // namespace apollo
Fix lint
Fix lint
C++
apache-2.0
msbeta/apollo,msbeta/apollo,msbeta/apollo,msbeta/apollo,msbeta/apollo,msbeta/apollo
b061622bf84010f876effd92fd8bb8c3ff3a7e1f
tutorial/example.cpp
tutorial/example.cpp
#include<chrono> #include<iostream> #include<mutex> #include<random> #include<queue> #include<thread> #include"../header/CThreadPool.h" namespace { std::mutex mut; size_t get() { using namespace std; static mt19937 mu{static_cast<mt19937::result_type>(chrono::high_resolution_clock::now().time_since_epoch().count())}; return mu()%4; } std::size_t add_func(const std::size_t i) { using namespace std; const auto sec{get()}; this_thread::sleep_for(chrono::seconds{sec}); lock_guard<mutex> lock{mut}; cout<<"add - thread "<<i<<" wait "<<sec<<" sec"<<endl; return i; } std::size_t add_and_detach_func(const std::size_t i) { using namespace std; const auto sec{get()}; this_thread::sleep_for(chrono::seconds{sec}); lock_guard<mutex> lock{mut}; cout<<"add_and_detach - thread "<<i<<" wait "<<sec<<" sec"<<endl; return i; } } int main() { using namespace std; nThread::CThreadPool tp{4}; queue<nThread::CThreadPool::thread_id> que; cout<<"stage 1"<<endl; for(size_t i{0};i!=tp.count();++i) tp.add_and_detach(add_and_detach_func,i); tp.join_all(); //this will not block, because you use add_and_detach cout<<"stage 2"<<endl; for(size_t i{0};i!=tp.count();++i) que.push(tp.add(add_func,i)); //tp will block here until add_and_detach_func complete for(size_t i{0};i!=tp.count();++i) { tp.join(que.front()); //tp will block here until the i of thread complete que.pop(); } cout<<"stage 3"<<endl; for(size_t i{0};i!=tp.count();++i) tp.add_and_detach(add_and_detach_func,i); tp.wait_until_all_available(); //this will block until all detach threads complete add_and_detach_func cout<<"stage 4"<<endl; for(size_t i{0};i!=tp.count();++i) tp.add(add_func,i); //tp will not block here, because you join all thread tp.join_all(); //tp will block here until add_func complete, it is same as //for(size_t i(0);i!=tp.count();++i) // tp.join(i); cout<<"stage 5"<<endl; for(size_t i{0};i!=tp.count();++i) tp.add(add_func,i); cout<<"thread "<<tp.join_any()<<" complete"<<endl; //join any thread without specify which one tp.join_all(); cout<<"stage 6"<<endl; for(size_t i{0};i!=tp.count();++i) que.push(tp.add(add_func,i)); tp.join(que.front()); tp.join_any(); //calling join prior to join_any is ok //but calling join_any with join (or join_all) is not ok when using multi-thread, such as the code below //here is an incorrect example //for(size_t i(0);i!=tp.count();++i) // tp.add(add_func,i); //thread thr([&]{tp.join(0);}); //tp.join_any(); //please, don't do this // //do not combine these function together in multi-thread // //use join or join_any each time // //otherwise, it will make some threads which are calling join_any cannot get notification //thr.join(); //however, here is an correct example tp.join_any(); tp.join_all(); //because, this is in single thread cout<<"stage 7"<<endl; for(size_t i{0};i!=tp.count();++i) tp.add(add_func,i); thread thr([&]{tp.join_any();}); tp.join_any(); //ok, no problem thr.join(); tp.join_all(); //in short, do not call join_any with join and join_all in 2 (or higher) threads //the user has to guarantee that //every threads' join can be called only once after calling assign cout<<"stage 8"<<endl; for(size_t i{0};i!=tp.count();++i) tp.add(add_func,i); tp.join_any(); //you don't need to call join_all to guarantee all threads are joining //the destructor of CThreadPool will deal with this //something else you have to notice //CThreadPool::join_all will not block CThreadPool::add, and vice versa }
#include<chrono> #include<iostream> #include<mutex> #include<random> #include<queue> #include<thread> #include"../header/CThreadPool.h" namespace { std::mutex mut; size_t get() { using namespace std; static mt19937 mu{static_cast<mt19937::result_type>(chrono::high_resolution_clock::now().time_since_epoch().count())}; return mu()%4; } std::size_t add_func(const std::size_t i) { using namespace std; const auto sec{get()}; this_thread::sleep_for(chrono::seconds{sec}); lock_guard<mutex> lock{mut}; cout<<"add - thread "<<i<<" wait "<<sec<<" sec"<<endl; return i; } std::size_t add_and_detach_func(const std::size_t i) { using namespace std; const auto sec{get()}; this_thread::sleep_for(chrono::seconds{sec}); lock_guard<mutex> lock{mut}; cout<<"add_and_detach - thread "<<i<<" wait "<<sec<<" sec"<<endl; return i; } } int main() { using namespace std; nThread::CThreadPool tp{4}; queue<nThread::CThreadPool::thread_id> que; cout<<"stage 1"<<endl; for(size_t i{0};i!=tp.count();++i) tp.add_and_detach(add_and_detach_func,i); tp.join_all(); //this will not block, because you use add_and_detach cout<<"stage 2"<<endl; for(size_t i{0};i!=tp.count();++i) que.push(tp.add(add_func,i)); //tp will block here until add_and_detach_func complete for(size_t i{0};i!=tp.count();++i) { tp.join(que.front()); //tp will block here until the i of thread complete que.pop(); } cout<<"after for loop of join, "<<tp.available()<<" should equal to "<<tp.count()<<endl; cout<<"stage 3"<<endl; for(size_t i{0};i!=tp.count();++i) tp.add_and_detach(add_and_detach_func,i); tp.wait_until_all_available(); //this will block until all detach threads complete add_and_detach_func cout<<"after wait_until_all_available, "<<tp.available()<<" should equal to "<<tp.count()<<endl; cout<<"stage 4"<<endl; for(size_t i{0};i!=tp.count();++i) tp.add(add_func,i); //tp will not block here, because you join all thread tp.join_all(); //tp will block here until add_func complete, it is same as //for(size_t i(0);i!=tp.count();++i) // tp.join(i); cout<<"after join_all, "<<tp.available()<<" should equal to "<<tp.count()<<endl; cout<<"stage 5"<<endl; for(size_t i{0};i!=tp.count();++i) tp.add(add_func,i); cout<<"thread "<<tp.join_any()<<" complete"<<endl; //join any thread without specify which one tp.join_all(); cout<<"after join_all, "<<tp.available()<<" should equal to "<<tp.count()<<endl; cout<<"stage 6"<<endl; for(size_t i{0};i!=tp.count();++i) que.push(tp.add(add_func,i)); tp.join(que.front()); cout<<"after join, "<<tp.available()<<" should equal to "<<1<<endl; tp.join_any(); //calling join prior to join_any is ok //but calling join_any with join (or join_all) is not ok when using multi-thread, such as the code below cout<<"after join_any, "<<tp.available()<<" should equal to "<<2<<endl; //here is an incorrect example //for(size_t i(0);i!=tp.count();++i) // tp.add(add_func,i); //thread thr([&]{tp.join(0);}); //tp.join_any(); //please, don't do this // //do not combine these function together in multi-thread // //use join or join_any each time // //otherwise, it will make some threads which are calling join_any cannot get notification //thr.join(); //however, here is an correct example tp.join_any(); cout<<"after join_any, "<<tp.available()<<" should equal to "<<3<<endl; tp.join_all(); //because, this is in single thread cout<<"after join_all, "<<tp.available()<<" should equal to "<<tp.count()<<endl; cout<<"stage 7"<<endl; for(size_t i{0};i!=tp.count();++i) tp.add(add_func,i); thread thr([&]{tp.join_any();}); tp.join_any(); //ok, no problem cout<<"after join, "<<tp.available()<<" should equal to "<<1<<endl; thr.join(); tp.join_all(); cout<<"after join_all, "<<tp.available()<<" should equal to "<<tp.count()<<endl; //in short, do not call join_any with join and join_all in 2 (or higher) threads //the user has to guarantee that //every threads' join can be called only once after calling assign cout<<"stage 8"<<endl; for(size_t i{0};i!=tp.count();++i) tp.add(add_func,i); tp.join_any(); cout<<"after join, "<<tp.available()<<" should equal to "<<1<<endl; //you don't need to call join_all to guarantee all threads are joining //the destructor of CThreadPool will deal with this //something else you have to notice //CThreadPool::join_all will not block CThreadPool::add, and vice versa }
add more information
add more information
C++
mit
Fdhvdu/ThreadPool
cf738cb1570f21d8df1272075ef9a6ea58b33c56
SOURCE/C++/Numbers/Calculator.cpp
SOURCE/C++/Numbers/Calculator.cpp
#include <iostream> #include <string> #include <ctype.h> #include <cstdlib> #include <stdexcept> class Calculator { private: std::string source; int pos; public: Calculator(std::string s) { source = s; pos = 0; }; // Utilities char peek() { return source[pos]; }; bool isNumber (char ch) { return isdigit(ch); }; bool eof () { return (unsigned int)pos >= source.length(); }; char consume(char ch) { if (peek() != ch) { throw std::runtime_error("Expected " + ch); } return source[pos++]; }; char consume() { return source[pos++]; }; // Parser float parseAdditive() { float first = parseMultiplicative(), next; char op; while (peek() == '+' || peek() == '-') { op = consume(); next = parseMultiplicative(); if (op == '+') first = first + next; if (op == '-') first = first - next; } return first; }; float parseMultiplicative() { float first = parsePrimary(), next; char op; while (peek() == '*' || peek() == '/') { op = consume(); next = parsePrimary(); if (op == '*') first = first * next; if (op == '/') first = first / next; } return first; }; float parsePrimary() { if (peek() == '(') { consume('('); int expr = parseExpression(); consume(')'); return expr; } else if (isNumber(peek())) { return parseNum(); } else { throw std::runtime_error("Unexpected token."); } return 0; }; float parseNum() { std::string source, dec; float value; while (!eof()) { if (isNumber(peek())) { source += this->source[pos++]; } else { break; } } if (peek() == '.') { source += consume('.'); while (!eof()) { if (isNumber(peek())) { source += this->source[pos++]; } else { break; } } } value = atof(source.c_str()); return value; }; float parseExpression() { return parseAdditive(); }; }; int main() { std::string source; std::cout << "Enter equation:\n"; std::getline(std::cin, source); Calculator calc(source); std::cout << "Result: " << calc.parseExpression(); return 0; };
#include <iostream> #include <string> #include <ctype.h> #include <cstdlib> #include <stdexcept> class Calculator { private: std::string source; int pos; public: Calculator(std::string s) { source = s; pos = 0; }; // Utilities char peek() { return source[pos]; }; bool isNumber (char ch) { return isdigit(ch); }; bool eof () { return (unsigned int)pos >= source.length(); }; char consume(char ch) { if (peek() != ch) { throw std::runtime_error("Expected " + ch); } return source[pos++]; }; char consume() { return source[pos++]; }; // Parser float parseAdditive() { float first = parseMultiplicative(), next; char op; while (peek() == '+' || peek() == '-') { op = consume(); next = parseMultiplicative(); if (op == '+') first = first + next; if (op == '-') first = first - next; } return first; }; float parseMultiplicative() { float first = parsePrimary(), next; char op; while (peek() == '*' || peek() == '/') { op = consume(); next = parsePrimary(); if (op == '*') first = first * next; if (op == '/') first = first / next; } return first; }; float parsePrimary() { if (peek() == '(') { consume('('); int expr = parseExpression(); consume(')'); return expr; } else if (isNumber(peek())) { return parseNum(); } else { throw std::runtime_error("Unexpected token."); } return 0; }; float parseNum() { std::string source, dec; float value; while (!eof()) { if (isNumber(peek())) { source += this->source[pos++]; } else { break; } } if (peek() == '.') { source += consume('.'); while (!eof()) { if (isNumber(peek())) { source += this->source[pos++]; } else { break; } } } value = atof(source.c_str()); return value; }; float parseExpression() { return parseAdditive(); }; }; int main() { std::string source; std::cout << "Enter equation (do not include space):\n"; std::getline(std::cin, source); Calculator calc(source); std::cout << "Result: " << calc.parseExpression(); return 0; };
Update Calculator
Update Calculator
C++
mit
idunnowhy9000/Projects,idunnowhy9000/Projects,idunnowhy9000/Projects
6c4a02479d6ec5f415f414f696626c75f05f9d2c
servers/physics_2d/collision_solver_2d_sw.cpp
servers/physics_2d/collision_solver_2d_sw.cpp
/*************************************************************************/ /* collision_solver_2d_sw.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* 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 "collision_solver_2d_sw.h" #include "collision_solver_2d_sat.h" #define collision_solver sat_2d_calculate_penetration //#define collision_solver gjk_epa_calculate_penetration bool CollisionSolver2DSW::solve_static_line(const Shape2DSW *p_shape_A, const Transform2D &p_transform_A, const Shape2DSW *p_shape_B, const Transform2D &p_transform_B, CallbackResult p_result_callback, void *p_userdata, bool p_swap_result) { const LineShape2DSW *line = static_cast<const LineShape2DSW *>(p_shape_A); if (p_shape_B->get_type() == Physics2DServer::SHAPE_LINE) return false; Vector2 n = p_transform_A.basis_xform(line->get_normal()).normalized(); Vector2 p = p_transform_A.xform(line->get_normal() * line->get_d()); real_t d = n.dot(p); Vector2 supports[2]; int support_count; p_shape_B->get_supports(p_transform_A.affine_inverse().basis_xform(-n).normalized(), supports, support_count); bool found = false; for (int i = 0; i < support_count; i++) { supports[i] = p_transform_B.xform(supports[i]); real_t pd = n.dot(supports[i]); if (pd >= d) continue; found = true; Vector2 support_A = supports[i] - n * (pd - d); if (p_result_callback) { if (p_swap_result) p_result_callback(supports[i], support_A, p_userdata); else p_result_callback(support_A, supports[i], p_userdata); } } return found; } bool CollisionSolver2DSW::solve_raycast(const Shape2DSW *p_shape_A, const Vector2 &p_motion_A, const Transform2D &p_transform_A, const Shape2DSW *p_shape_B, const Transform2D &p_transform_B, CallbackResult p_result_callback, void *p_userdata, bool p_swap_result, Vector2 *sep_axis) { const RayShape2DSW *ray = static_cast<const RayShape2DSW *>(p_shape_A); if (p_shape_B->get_type() == Physics2DServer::SHAPE_RAY) return false; Vector2 from = p_transform_A.get_origin(); Vector2 to = from + p_transform_A[1] * ray->get_length(); if (p_motion_A != Vector2()) { //not the best but should be enough Vector2 normal = (to - from).normalized(); to += normal * MAX(0.0, normal.dot(p_motion_A)); } Vector2 support_A = to; Transform2D invb = p_transform_B.affine_inverse(); from = invb.xform(from); to = invb.xform(to); Vector2 p, n; if (!p_shape_B->intersect_segment(from, to, p, n)) { if (sep_axis) *sep_axis = p_transform_A[1].normalized(); return false; } Vector2 support_B = p_transform_B.xform(p); if (ray->get_slips_on_slope()) { Vector2 global_n = invb.basis_xform_inv(n).normalized(); support_B = support_A + (support_B - support_A).length() * global_n; } if (p_result_callback) { if (p_swap_result) p_result_callback(support_B, support_A, p_userdata); else p_result_callback(support_A, support_B, p_userdata); } return true; } struct _ConcaveCollisionInfo2D { const Transform2D *transform_A; const Shape2DSW *shape_A; const Transform2D *transform_B; Vector2 motion_A; Vector2 motion_B; real_t margin_A; real_t margin_B; CollisionSolver2DSW::CallbackResult result_callback; void *userdata; bool swap_result; bool collided; int aabb_tests; int collisions; Vector2 *sep_axis; }; void CollisionSolver2DSW::concave_callback(void *p_userdata, Shape2DSW *p_convex) { _ConcaveCollisionInfo2D &cinfo = *(_ConcaveCollisionInfo2D *)(p_userdata); cinfo.aabb_tests++; if (!cinfo.result_callback && cinfo.collided) return; //already collided and no contacts requested, don't test anymore bool collided = collision_solver(cinfo.shape_A, *cinfo.transform_A, cinfo.motion_A, p_convex, *cinfo.transform_B, cinfo.motion_B, cinfo.result_callback, cinfo.userdata, cinfo.swap_result, cinfo.sep_axis, cinfo.margin_A, cinfo.margin_B); if (!collided) return; cinfo.collided = true; cinfo.collisions++; } bool CollisionSolver2DSW::solve_concave(const Shape2DSW *p_shape_A, const Transform2D &p_transform_A, const Vector2 &p_motion_A, const Shape2DSW *p_shape_B, const Transform2D &p_transform_B, const Vector2 &p_motion_B, CallbackResult p_result_callback, void *p_userdata, bool p_swap_result, Vector2 *sep_axis, real_t p_margin_A, real_t p_margin_B) { const ConcaveShape2DSW *concave_B = static_cast<const ConcaveShape2DSW *>(p_shape_B); _ConcaveCollisionInfo2D cinfo; cinfo.transform_A = &p_transform_A; cinfo.shape_A = p_shape_A; cinfo.transform_B = &p_transform_B; cinfo.motion_A = p_motion_A; cinfo.result_callback = p_result_callback; cinfo.userdata = p_userdata; cinfo.swap_result = p_swap_result; cinfo.collided = false; cinfo.collisions = 0; cinfo.sep_axis = sep_axis; cinfo.margin_A = p_margin_A; cinfo.margin_B = p_margin_B; cinfo.aabb_tests = 0; Transform2D rel_transform = p_transform_A; rel_transform.elements[2] -= p_transform_B.get_origin(); //quickly compute a local Rect2 Rect2 local_aabb; for (int i = 0; i < 2; i++) { Vector2 axis(p_transform_B.elements[i]); real_t axis_scale = 1.0 / axis.length(); axis *= axis_scale; real_t smin, smax; p_shape_A->project_rangev(axis, rel_transform, smin, smax); smin *= axis_scale; smax *= axis_scale; local_aabb.position[i] = smin; local_aabb.size[i] = smax - smin; } concave_B->cull(local_aabb, concave_callback, &cinfo); return cinfo.collided; } bool CollisionSolver2DSW::solve(const Shape2DSW *p_shape_A, const Transform2D &p_transform_A, const Vector2 &p_motion_A, const Shape2DSW *p_shape_B, const Transform2D &p_transform_B, const Vector2 &p_motion_B, CallbackResult p_result_callback, void *p_userdata, Vector2 *sep_axis, real_t p_margin_A, real_t p_margin_B) { Physics2DServer::ShapeType type_A = p_shape_A->get_type(); Physics2DServer::ShapeType type_B = p_shape_B->get_type(); bool concave_A = p_shape_A->is_concave(); bool concave_B = p_shape_B->is_concave(); real_t margin_A = p_margin_A, margin_B = p_margin_B; bool swap = false; if (type_A > type_B) { SWAP(type_A, type_B); SWAP(concave_A, concave_B); SWAP(margin_A, margin_B); swap = true; } if (type_A == Physics2DServer::SHAPE_LINE) { if (type_B == Physics2DServer::SHAPE_LINE || type_B == Physics2DServer::SHAPE_RAY) { return false; } if (swap) { return solve_static_line(p_shape_B, p_transform_B, p_shape_A, p_transform_A, p_result_callback, p_userdata, true); } else { return solve_static_line(p_shape_A, p_transform_A, p_shape_B, p_transform_B, p_result_callback, p_userdata, false); } } else if (type_A == Physics2DServer::SHAPE_RAY) { if (type_B == Physics2DServer::SHAPE_RAY) { return false; //no ray-ray } if (swap) { return solve_raycast(p_shape_B, p_motion_B, p_transform_B, p_shape_A, p_transform_A, p_result_callback, p_userdata, true, sep_axis); } else { return solve_raycast(p_shape_A, p_motion_A, p_transform_A, p_shape_B, p_transform_B, p_result_callback, p_userdata, false, sep_axis); } } else if (concave_B) { if (concave_A) return false; if (!swap) return solve_concave(p_shape_A, p_transform_A, p_motion_A, p_shape_B, p_transform_B, p_motion_B, p_result_callback, p_userdata, false, sep_axis, margin_A, margin_B); else return solve_concave(p_shape_B, p_transform_B, p_motion_B, p_shape_A, p_transform_A, p_motion_A, p_result_callback, p_userdata, true, sep_axis, margin_A, margin_B); } else { return collision_solver(p_shape_A, p_transform_A, p_motion_A, p_shape_B, p_transform_B, p_motion_B, p_result_callback, p_userdata, false, sep_axis, margin_A, margin_B); } }
/*************************************************************************/ /* collision_solver_2d_sw.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* 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 "collision_solver_2d_sw.h" #include "collision_solver_2d_sat.h" #define collision_solver sat_2d_calculate_penetration //#define collision_solver gjk_epa_calculate_penetration bool CollisionSolver2DSW::solve_static_line(const Shape2DSW *p_shape_A, const Transform2D &p_transform_A, const Shape2DSW *p_shape_B, const Transform2D &p_transform_B, CallbackResult p_result_callback, void *p_userdata, bool p_swap_result) { const LineShape2DSW *line = static_cast<const LineShape2DSW *>(p_shape_A); if (p_shape_B->get_type() == Physics2DServer::SHAPE_LINE) return false; Vector2 n = p_transform_A.basis_xform(line->get_normal()).normalized(); Vector2 p = p_transform_A.xform(line->get_normal() * line->get_d()); real_t d = n.dot(p); Vector2 supports[2]; int support_count; p_shape_B->get_supports(p_transform_B.affine_inverse().basis_xform(-n).normalized(), supports, support_count); bool found = false; for (int i = 0; i < support_count; i++) { supports[i] = p_transform_B.xform(supports[i]); real_t pd = n.dot(supports[i]); if (pd >= d) continue; found = true; Vector2 support_A = supports[i] - n * (pd - d); if (p_result_callback) { if (p_swap_result) p_result_callback(supports[i], support_A, p_userdata); else p_result_callback(support_A, supports[i], p_userdata); } } return found; } bool CollisionSolver2DSW::solve_raycast(const Shape2DSW *p_shape_A, const Vector2 &p_motion_A, const Transform2D &p_transform_A, const Shape2DSW *p_shape_B, const Transform2D &p_transform_B, CallbackResult p_result_callback, void *p_userdata, bool p_swap_result, Vector2 *sep_axis) { const RayShape2DSW *ray = static_cast<const RayShape2DSW *>(p_shape_A); if (p_shape_B->get_type() == Physics2DServer::SHAPE_RAY) return false; Vector2 from = p_transform_A.get_origin(); Vector2 to = from + p_transform_A[1] * ray->get_length(); if (p_motion_A != Vector2()) { //not the best but should be enough Vector2 normal = (to - from).normalized(); to += normal * MAX(0.0, normal.dot(p_motion_A)); } Vector2 support_A = to; Transform2D invb = p_transform_B.affine_inverse(); from = invb.xform(from); to = invb.xform(to); Vector2 p, n; if (!p_shape_B->intersect_segment(from, to, p, n)) { if (sep_axis) *sep_axis = p_transform_A[1].normalized(); return false; } Vector2 support_B = p_transform_B.xform(p); if (ray->get_slips_on_slope()) { Vector2 global_n = invb.basis_xform_inv(n).normalized(); support_B = support_A + (support_B - support_A).length() * global_n; } if (p_result_callback) { if (p_swap_result) p_result_callback(support_B, support_A, p_userdata); else p_result_callback(support_A, support_B, p_userdata); } return true; } struct _ConcaveCollisionInfo2D { const Transform2D *transform_A; const Shape2DSW *shape_A; const Transform2D *transform_B; Vector2 motion_A; Vector2 motion_B; real_t margin_A; real_t margin_B; CollisionSolver2DSW::CallbackResult result_callback; void *userdata; bool swap_result; bool collided; int aabb_tests; int collisions; Vector2 *sep_axis; }; void CollisionSolver2DSW::concave_callback(void *p_userdata, Shape2DSW *p_convex) { _ConcaveCollisionInfo2D &cinfo = *(_ConcaveCollisionInfo2D *)(p_userdata); cinfo.aabb_tests++; if (!cinfo.result_callback && cinfo.collided) return; //already collided and no contacts requested, don't test anymore bool collided = collision_solver(cinfo.shape_A, *cinfo.transform_A, cinfo.motion_A, p_convex, *cinfo.transform_B, cinfo.motion_B, cinfo.result_callback, cinfo.userdata, cinfo.swap_result, cinfo.sep_axis, cinfo.margin_A, cinfo.margin_B); if (!collided) return; cinfo.collided = true; cinfo.collisions++; } bool CollisionSolver2DSW::solve_concave(const Shape2DSW *p_shape_A, const Transform2D &p_transform_A, const Vector2 &p_motion_A, const Shape2DSW *p_shape_B, const Transform2D &p_transform_B, const Vector2 &p_motion_B, CallbackResult p_result_callback, void *p_userdata, bool p_swap_result, Vector2 *sep_axis, real_t p_margin_A, real_t p_margin_B) { const ConcaveShape2DSW *concave_B = static_cast<const ConcaveShape2DSW *>(p_shape_B); _ConcaveCollisionInfo2D cinfo; cinfo.transform_A = &p_transform_A; cinfo.shape_A = p_shape_A; cinfo.transform_B = &p_transform_B; cinfo.motion_A = p_motion_A; cinfo.result_callback = p_result_callback; cinfo.userdata = p_userdata; cinfo.swap_result = p_swap_result; cinfo.collided = false; cinfo.collisions = 0; cinfo.sep_axis = sep_axis; cinfo.margin_A = p_margin_A; cinfo.margin_B = p_margin_B; cinfo.aabb_tests = 0; Transform2D rel_transform = p_transform_A; rel_transform.elements[2] -= p_transform_B.get_origin(); //quickly compute a local Rect2 Rect2 local_aabb; for (int i = 0; i < 2; i++) { Vector2 axis(p_transform_B.elements[i]); real_t axis_scale = 1.0 / axis.length(); axis *= axis_scale; real_t smin, smax; p_shape_A->project_rangev(axis, rel_transform, smin, smax); smin *= axis_scale; smax *= axis_scale; local_aabb.position[i] = smin; local_aabb.size[i] = smax - smin; } concave_B->cull(local_aabb, concave_callback, &cinfo); return cinfo.collided; } bool CollisionSolver2DSW::solve(const Shape2DSW *p_shape_A, const Transform2D &p_transform_A, const Vector2 &p_motion_A, const Shape2DSW *p_shape_B, const Transform2D &p_transform_B, const Vector2 &p_motion_B, CallbackResult p_result_callback, void *p_userdata, Vector2 *sep_axis, real_t p_margin_A, real_t p_margin_B) { Physics2DServer::ShapeType type_A = p_shape_A->get_type(); Physics2DServer::ShapeType type_B = p_shape_B->get_type(); bool concave_A = p_shape_A->is_concave(); bool concave_B = p_shape_B->is_concave(); real_t margin_A = p_margin_A, margin_B = p_margin_B; bool swap = false; if (type_A > type_B) { SWAP(type_A, type_B); SWAP(concave_A, concave_B); SWAP(margin_A, margin_B); swap = true; } if (type_A == Physics2DServer::SHAPE_LINE) { if (type_B == Physics2DServer::SHAPE_LINE || type_B == Physics2DServer::SHAPE_RAY) { return false; } if (swap) { return solve_static_line(p_shape_B, p_transform_B, p_shape_A, p_transform_A, p_result_callback, p_userdata, true); } else { return solve_static_line(p_shape_A, p_transform_A, p_shape_B, p_transform_B, p_result_callback, p_userdata, false); } } else if (type_A == Physics2DServer::SHAPE_RAY) { if (type_B == Physics2DServer::SHAPE_RAY) { return false; //no ray-ray } if (swap) { return solve_raycast(p_shape_B, p_motion_B, p_transform_B, p_shape_A, p_transform_A, p_result_callback, p_userdata, true, sep_axis); } else { return solve_raycast(p_shape_A, p_motion_A, p_transform_A, p_shape_B, p_transform_B, p_result_callback, p_userdata, false, sep_axis); } } else if (concave_B) { if (concave_A) return false; if (!swap) return solve_concave(p_shape_A, p_transform_A, p_motion_A, p_shape_B, p_transform_B, p_motion_B, p_result_callback, p_userdata, false, sep_axis, margin_A, margin_B); else return solve_concave(p_shape_B, p_transform_B, p_motion_B, p_shape_A, p_transform_A, p_motion_A, p_result_callback, p_userdata, true, sep_axis, margin_A, margin_B); } else { return collision_solver(p_shape_A, p_transform_A, p_motion_A, p_shape_B, p_transform_B, p_motion_B, p_result_callback, p_userdata, false, sep_axis, margin_A, margin_B); } }
Fix how Line2D obtains the other object's supports
Fix how Line2D obtains the other object's supports Measure the distance from the line against the rotated object, not the rotated line, when obtaining the object's supports against a line. (cherry picked from commit 7e44682c0382779a6142a3cfa7c712d85d8ec928)
C++
mit
ex/godot,ex/godot,ex/godot,ex/godot,ex/godot,ex/godot,ex/godot,ex/godot
1eceed92f1bd33904963fc812860e4642f5dede3
share/qtcreator/templates/qt4project/main.cpp
share/qtcreator/templates/qt4project/main.cpp
#include <%QAPP_INCLUDE%> #include "%INCLUDE%" int main(int argc, char *argv[]) { QApplication a(argc, argv); %CLASS% w; #if defined(Q_WS_S60) || defined(Q_WS_MAEMO_5) w.showMaximized(); #else w.show(); #endif return a.exec(); }
#include <%QAPP_INCLUDE%> #include "%INCLUDE%" int main(int argc, char *argv[]) { QApplication a(argc, argv); %CLASS% w; #if defined(Q_WS_S60) w.showMaximized(); #else w.show(); #endif return a.exec(); }
Remove special showMaximized case for Maemo 5
Remove special showMaximized case for Maemo 5 The Maemo 5 window manager already makes sure applications always run maximized. Reviewed-by: Robert Griebl
C++
lgpl-2.1
jonnor/qt-creator,duythanhphan/qt-creator,azat/qtcreator,azat/qtcreator,maui-packages/qt-creator,KDE/android-qt-creator,richardmg/qtcreator,darksylinc/qt-creator,danimo/qt-creator,bakaiadam/collaborative_qt_creator,sandsmark/qtcreator-minimap,ostash/qt-creator-i18n-uk,hdweiss/qt-creator-visualizer,syntheticpp/qt-creator,malikcjm/qtcreator,maui-packages/qt-creator,malikcjm/qtcreator,amyvmiwei/qt-creator,renatofilho/QtCreator,martyone/sailfish-qtcreator,martyone/sailfish-qtcreator,ostash/qt-creator-i18n-uk,ostash/qt-creator-i18n-uk,maui-packages/qt-creator,Distrotech/qtcreator,duythanhphan/qt-creator,maui-packages/qt-creator,martyone/sailfish-qtcreator,farseerri/git_code,martyone/sailfish-qtcreator,malikcjm/qtcreator,duythanhphan/qt-creator,darksylinc/qt-creator,bakaiadam/collaborative_qt_creator,dmik/qt-creator-os2,yinyunqiao/qtcreator,danimo/qt-creator,danimo/qt-creator,ostash/qt-creator-i18n-uk,colede/qtcreator,jonnor/qt-creator,yinyunqiao/qtcreator,duythanhphan/qt-creator,danimo/qt-creator,colede/qtcreator,AltarBeastiful/qt-creator,xianian/qt-creator,xianian/qt-creator,omniacreator/qtcreator,darksylinc/qt-creator,KDE/android-qt-creator,martyone/sailfish-qtcreator,xianian/qt-creator,AltarBeastiful/qt-creator,xianian/qt-creator,omniacreator/qtcreator,danimo/qt-creator,KDAB/KDAB-Creator,xianian/qt-creator,Distrotech/qtcreator,dmik/qt-creator-os2,jonnor/qt-creator,syntheticpp/qt-creator,azat/qtcreator,sandsmark/qtcreator-minimap,malikcjm/qtcreator,Distrotech/qtcreator,colede/qtcreator,yinyunqiao/qtcreator,AltarBeastiful/qt-creator,bakaiadam/collaborative_qt_creator,hdweiss/qt-creator-visualizer,sandsmark/qtcreator-minimap,Distrotech/qtcreator,bakaiadam/collaborative_qt_creator,darksylinc/qt-creator,amyvmiwei/qt-creator,farseerri/git_code,KDAB/KDAB-Creator,renatofilho/QtCreator,ostash/qt-creator-i18n-uk,AltarBeastiful/qt-creator,colede/qtcreator,farseerri/git_code,bakaiadam/collaborative_qt_creator,AltarBeastiful/qt-creator,renatofilho/QtCreator,colede/qtcreator,dmik/qt-creator-os2,xianian/qt-creator,martyone/sailfish-qtcreator,farseerri/git_code,richardmg/qtcreator,martyone/sailfish-qtcreator,pcacjr/qt-creator,Distrotech/qtcreator,AltarBeastiful/qt-creator,hdweiss/qt-creator-visualizer,richardmg/qtcreator,jonnor/qt-creator,maui-packages/qt-creator,KDE/android-qt-creator,Distrotech/qtcreator,amyvmiwei/qt-creator,yinyunqiao/qtcreator,pcacjr/qt-creator,richardmg/qtcreator,malikcjm/qtcreator,darksylinc/qt-creator,azat/qtcreator,KDAB/KDAB-Creator,kuba1/qtcreator,maui-packages/qt-creator,malikcjm/qtcreator,syntheticpp/qt-creator,azat/qtcreator,amyvmiwei/qt-creator,pcacjr/qt-creator,yinyunqiao/qtcreator,jonnor/qt-creator,kuba1/qtcreator,yinyunqiao/qtcreator,omniacreator/qtcreator,renatofilho/QtCreator,kuba1/qtcreator,sandsmark/qtcreator-minimap,dmik/qt-creator-os2,kuba1/qtcreator,omniacreator/qtcreator,KDE/android-qt-creator,danimo/qt-creator,syntheticpp/qt-creator,darksylinc/qt-creator,amyvmiwei/qt-creator,AltarBeastiful/qt-creator,omniacreator/qtcreator,yinyunqiao/qtcreator,xianian/qt-creator,Distrotech/qtcreator,danimo/qt-creator,kuba1/qtcreator,jonnor/qt-creator,amyvmiwei/qt-creator,farseerri/git_code,danimo/qt-creator,kuba1/qtcreator,KDE/android-qt-creator,amyvmiwei/qt-creator,danimo/qt-creator,KDAB/KDAB-Creator,hdweiss/qt-creator-visualizer,farseerri/git_code,farseerri/git_code,syntheticpp/qt-creator,bakaiadam/collaborative_qt_creator,duythanhphan/qt-creator,kuba1/qtcreator,ostash/qt-creator-i18n-uk,syntheticpp/qt-creator,KDE/android-qt-creator,azat/qtcreator,duythanhphan/qt-creator,sandsmark/qtcreator-minimap,bakaiadam/collaborative_qt_creator,martyone/sailfish-qtcreator,colede/qtcreator,KDAB/KDAB-Creator,renatofilho/QtCreator,ostash/qt-creator-i18n-uk,sandsmark/qtcreator-minimap,omniacreator/qtcreator,pcacjr/qt-creator,renatofilho/QtCreator,dmik/qt-creator-os2,dmik/qt-creator-os2,maui-packages/qt-creator,pcacjr/qt-creator,malikcjm/qtcreator,syntheticpp/qt-creator,kuba1/qtcreator,xianian/qt-creator,darksylinc/qt-creator,pcacjr/qt-creator,xianian/qt-creator,richardmg/qtcreator,dmik/qt-creator-os2,richardmg/qtcreator,AltarBeastiful/qt-creator,KDE/android-qt-creator,richardmg/qtcreator,colede/qtcreator,KDAB/KDAB-Creator,kuba1/qtcreator,pcacjr/qt-creator,amyvmiwei/qt-creator,hdweiss/qt-creator-visualizer,martyone/sailfish-qtcreator,darksylinc/qt-creator,duythanhphan/qt-creator,omniacreator/qtcreator,hdweiss/qt-creator-visualizer,KDE/android-qt-creator,farseerri/git_code
51ddb1e236c2d403d940b98d099c20d1f9a2bd8a
graphics/size.h++
graphics/size.h++
/** * The MIT License (MIT) * * Copyright © 2017-2018 Ruben Van Boxem * * 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. **/ /* * Size * Width and height properties in one nice package. */ #ifndef SKUI_GRAPHICS_SIZE_H #define SKUI_GRAPHICS_SIZE_H #include "graphics/pixel.h++" #include "graphics/scalar.h++" #include <core/utility/bound.h++> #include <core/utility/norm.h++> #include <limits> #include <cmath> #include <iostream> namespace skui::graphics { template<typename ValueType> struct size2D { using value_type = ValueType; value_type width; value_type height; constexpr size2D& operator+=(const size2D& other); constexpr size2D& operator-=(const size2D& other); template<typename FactorType> constexpr size2D& operator*=(const FactorType& factor); template<typename FactorType> constexpr size2D& operator/=(const FactorType& factor); }; template<typename ValueType> constexpr bool operator==(const size2D<ValueType>& left, const size2D<ValueType>& right) { return left.width == right.width && left.height == right.height; } template<typename ValueType> constexpr bool operator!=(const size2D<ValueType>& left, const size2D<ValueType>& right) { return left.width != right.width || left.height != right.height; } template<typename ValueType> constexpr size2D<ValueType>& size2D<ValueType>::operator+=(const size2D<ValueType>& other) { width += other.width; height += other.height; return *this; } template<typename ValueType> constexpr size2D<ValueType>& size2D<ValueType>::operator-=(const size2D<ValueType>& other) { width -= other.width; height -= other.height; return *this; } template<typename ValueType> template<typename FactorType> constexpr size2D<ValueType>& size2D<ValueType>::operator*=(const FactorType& factor) { width *= factor; height *= factor; return *this; } template<typename ValueType> template<typename FactorType> constexpr size2D<ValueType>& size2D<ValueType>::operator/=(const FactorType& factor) { width /= factor; height /= factor; return *this; } template<typename ValueType> constexpr size2D<ValueType> operator+(const size2D<ValueType>& left, const size2D<ValueType>& right) { return {left.width + right.width, left.height + right.height}; } template<typename ValueType> constexpr size2D<ValueType> operator-(const size2D<ValueType>& left, const size2D<ValueType>& right) { return {left.width - right.width, left.height - right.height}; } template<typename ValueType, typename FactorType> constexpr size2D<ValueType> operator*(const size2D<ValueType>& size, FactorType factor) { return {size.width*static_cast<ValueType>(factor), size.height*static_cast<ValueType>(factor)}; } template<typename ValueType, typename FactorType> constexpr size2D<ValueType> operator*(FactorType factor, const size2D<ValueType>& size) { return size*factor; } template<typename ValueType, typename FactorType> constexpr size2D<ValueType> operator/(const size2D<ValueType>& size, FactorType factor) { return {size.width/static_cast<ValueType>(factor), size.height/static_cast<ValueType>(factor)}; } template<typename ValueType> std::ostream& operator<<(std::ostream& os, const size2D<ValueType>& size) { return os << '[' << size.width << ", " << size.height << ']'; } // pixel here means "device independent pixel" aka scaled from 72dpi using pixel_size = size2D<pixel>; using scalar_size = size2D<scalar>; } namespace core { template<typename ValueType> struct bound<graphics::size2D<ValueType>> { constexpr graphics::size2D<ValueType> operator()(const graphics::size2D<ValueType>& value, const graphics::size2D<ValueType>& lower_bound, const graphics::size2D<ValueType>& upper_bound) const { return {bound<ValueType>{}(value.width, lower_bound.width, upper_bound.width), bound<ValueType>{}(value.height, lower_bound.height, upper_bound.height)}; } }; template<typename ValueType> struct norm<graphics::size2D<ValueType>> { constexpr ValueType operator()(const graphics::size2D<ValueType>& value) const { return std::abs(value.width)+std::abs(value.height); } }; } namespace std { template<typename ValueType> class numeric_limits<skui::graphics::size2D<ValueType>> : public numeric_limits<ValueType> { private: using size = skui::graphics::size2D<ValueType>; using base = numeric_limits<ValueType>; public: static constexpr size min() { return { base::min(), base::min() }; } static constexpr size lowest() { return { base::lowest(), base::lowest() }; } static constexpr size max() { return { base::max(), base::max() }; } }; } #endif
/** * The MIT License (MIT) * * Copyright © 2017-2018 Ruben Van Boxem * * 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. **/ /* * Size * Width and height properties in one nice package. */ #ifndef SKUI_GRAPHICS_SIZE_H #define SKUI_GRAPHICS_SIZE_H #include "graphics/pixel.h++" #include "graphics/scalar.h++" #include <core/utility/bound.h++> #include <core/utility/norm.h++> #include <limits> #include <cmath> #include <iostream> namespace skui::graphics { template<typename ValueType> struct size2D { using value_type = ValueType; value_type width; value_type height; constexpr size2D& operator+=(const size2D& other); constexpr size2D& operator-=(const size2D& other); template<typename FactorType> constexpr size2D& operator*=(const FactorType& factor); template<typename FactorType> constexpr size2D& operator/=(const FactorType& factor); }; template<typename ValueType> constexpr bool operator==(const size2D<ValueType>& left, const size2D<ValueType>& right) { return left.width == right.width && left.height == right.height; } template<typename ValueType> constexpr bool operator!=(const size2D<ValueType>& left, const size2D<ValueType>& right) { return left.width != right.width || left.height != right.height; } template<typename ValueType> constexpr size2D<ValueType>& size2D<ValueType>::operator+=(const size2D<ValueType>& other) { width += other.width; height += other.height; return *this; } template<typename ValueType> constexpr size2D<ValueType>& size2D<ValueType>::operator-=(const size2D<ValueType>& other) { width -= other.width; height -= other.height; return *this; } template<typename ValueType> template<typename FactorType> constexpr size2D<ValueType>& size2D<ValueType>::operator*=(const FactorType& factor) { width *= factor; height *= factor; return *this; } template<typename ValueType> template<typename FactorType> constexpr size2D<ValueType>& size2D<ValueType>::operator/=(const FactorType& factor) { width /= factor; height /= factor; return *this; } template<typename ValueType> constexpr size2D<ValueType> operator+(const size2D<ValueType>& left, const size2D<ValueType>& right) { return {left.width + right.width, left.height + right.height}; } template<typename ValueType> constexpr size2D<ValueType> operator-(const size2D<ValueType>& left, const size2D<ValueType>& right) { return {left.width - right.width, left.height - right.height}; } template<typename ValueType, typename FactorType> constexpr size2D<ValueType> operator*(const size2D<ValueType>& size, FactorType factor) { return {size.width*static_cast<ValueType>(factor), size.height*static_cast<ValueType>(factor)}; } template<typename ValueType, typename FactorType> constexpr size2D<ValueType> operator*(FactorType factor, const size2D<ValueType>& size) { return size*factor; } template<typename ValueType, typename FactorType> constexpr size2D<ValueType> operator/(const size2D<ValueType>& size, FactorType factor) { return {size.width/static_cast<ValueType>(factor), size.height/static_cast<ValueType>(factor)}; } template<typename ValueType> std::ostream& operator<<(std::ostream& os, const size2D<ValueType>& size) { return os << '[' << size.width << ", " << size.height << ']'; } // pixel here means "device independent pixel" aka scaled from 72dpi using pixel_size = size2D<pixel>; using scalar_size = size2D<scalar>; } namespace skui::core { template<typename ValueType> struct bound<graphics::size2D<ValueType>> { constexpr graphics::size2D<ValueType> operator()(const graphics::size2D<ValueType>& value, const graphics::size2D<ValueType>& lower_bound, const graphics::size2D<ValueType>& upper_bound) const { return {bound<ValueType>{}(value.width, lower_bound.width, upper_bound.width), bound<ValueType>{}(value.height, lower_bound.height, upper_bound.height)}; } }; template<typename ValueType> struct norm<graphics::size2D<ValueType>> { constexpr ValueType operator()(const graphics::size2D<ValueType>& value) const { return std::abs(value.width)+std::abs(value.height); } }; } namespace std { template<typename ValueType> class numeric_limits<skui::graphics::size2D<ValueType>> : public numeric_limits<ValueType> { private: using size = skui::graphics::size2D<ValueType>; using base = numeric_limits<ValueType>; public: static constexpr size min() { return { base::min(), base::min() }; } static constexpr size lowest() { return { base::lowest(), base::lowest() }; } static constexpr size max() { return { base::max(), base::max() }; } }; } #endif
Fix broken namespace.
Fix broken namespace.
C++
mit
rubenvb/skui,rubenvb/skui,skui-org/skui,skui-org/skui
14d4415c03c0fa427e1fd98c6d8ee83725a5454e
src/Search/SdkModel/SearchRefreshService.cpp
src/Search/SdkModel/SearchRefreshService.cpp
// Copyright eeGeo Ltd (2012-2015), All Rights Reserved #include "SearchRefreshService.h" #include "ISearchService.h" #include "ISearchQueryPerformer.h" #include "LatLongAltitude.h" #include "ICameraTransitionController.h" #include <algorithm> namespace ExampleApp { namespace Search { namespace SdkModel { SearchRefreshService::SearchRefreshService(ISearchService& searchService, ISearchQueryPerformer& searchQueryPerformer, CameraTransitions::SdkModel::ICameraTransitionController& cameraTransitionsController, float minimumSecondsBetweenUpdates, float minimumInterestLateralDeltaAt1km, float maximumInterestLateralSpeedAt1km) : m_minimumSecondsBetweenUpdates(minimumSecondsBetweenUpdates) , m_minimumInterestLateralDeltaAt1km(minimumInterestLateralDeltaAt1km) , m_maximumInterestLateralSpeedAt1km(maximumInterestLateralSpeedAt1km) , m_searchService(searchService) , m_searchQueryPerformer(searchQueryPerformer) , m_cameraTransitionsController(cameraTransitionsController) , m_pSearchResultQueryIssuedCallback(Eegeo_NEW((Eegeo::Helpers::TCallback1<SearchRefreshService, const SearchQuery&>))(this, &SearchRefreshService::HandleSearchQueryIssued)) , m_pSearchResultResponseReceivedCallback(Eegeo_NEW((Eegeo::Helpers::TCallback2<SearchRefreshService, const SearchQuery&, const std::vector<SearchResultModel>& >))(this, &SearchRefreshService::HandleSearchResultsResponseReceived)) , m_pSearchQueryResultsClearedCallback(Eegeo_NEW(Eegeo::Helpers::TCallback0<SearchRefreshService>)(this, &SearchRefreshService::HandleSearchQueryResultsCleared)) , m_queriesPending(0) , m_searchResultsExist(false) , m_secondsSincePreviousRefresh(0.f) , m_enabled(true) , m_previousQueryLocationEcef(Eegeo::dv3::Zero()) , m_previousInterestEcefLocation(Eegeo::dv3::Zero()) , m_previousQueryInterestDistance(0.f) { m_searchService.InsertOnPerformedQueryCallback(*m_pSearchResultQueryIssuedCallback); m_searchService.InsertOnReceivedQueryResultsCallback(*m_pSearchResultResponseReceivedCallback); m_searchQueryPerformer.InsertOnSearchResultsClearedCallback(*m_pSearchQueryResultsClearedCallback); } SearchRefreshService::~SearchRefreshService() { m_searchQueryPerformer.RemoveOnSearchResultsClearedCallback(*m_pSearchQueryResultsClearedCallback); m_searchService.RemoveOnReceivedQueryResultsCallback(*m_pSearchResultResponseReceivedCallback); m_searchService.RemoveOnPerformedQueryCallback(*m_pSearchResultQueryIssuedCallback); Eegeo_DELETE m_pSearchResultResponseReceivedCallback; Eegeo_DELETE m_pSearchResultQueryIssuedCallback; Eegeo_DELETE m_pSearchQueryResultsClearedCallback; } void SearchRefreshService::SetEnabled(bool enabled) { m_enabled = enabled; } bool SearchRefreshService::ShouldRefreshSearch(float deltaSeconds, const Eegeo::dv3& interestPointEcef, const Eegeo::dv3& viewpointEcef) const { if (!m_enabled) { return false; } if (!m_searchResultsExist) { return false; } if (m_queriesPending != 0) { return false; } if (m_cameraTransitionsController.IsTransitioning()) { return false; } if (m_secondsSincePreviousRefresh < m_minimumSecondsBetweenUpdates) { return false; } const float viewpointDistance = (viewpointEcef - interestPointEcef).Length(); const float distanceRatio = std::min(viewpointDistance, m_previousQueryInterestDistance) / std::max(viewpointDistance, m_previousQueryInterestDistance); if (distanceRatio < 0.75) { return true; } const float angularInterestDeltaFromQuery = (interestPointEcef - m_previousQueryLocationEcef).Length() / viewpointDistance; const float minimumInterestLateralDeltaAngle = m_minimumInterestLateralDeltaAt1km * 0.001f; const bool belowLateralThreshold = (angularInterestDeltaFromQuery < minimumInterestLateralDeltaAngle); if (belowLateralThreshold) { return false; } const float angularInterestDelta = (interestPointEcef - m_previousInterestEcefLocation).Length() / viewpointDistance; const float maxInterestAngularSpeed = m_maximumInterestLateralSpeedAt1km * 0.001f; const bool aboveSpeedThreshold = angularInterestDelta > maxInterestAngularSpeed*deltaSeconds; if (aboveSpeedThreshold) { return false; } return true; } void SearchRefreshService::TryRefreshSearch(float deltaSeconds, const Eegeo::dv3& interestPointEcef, const Eegeo::dv3& viewpointEcef) { m_secondsSincePreviousRefresh += deltaSeconds; const bool shouldRefresh = ShouldRefreshSearch(deltaSeconds, interestPointEcef, viewpointEcef); if (shouldRefresh) { const Eegeo::Space::LatLongAltitude& currentLocation = Eegeo::Space::LatLongAltitude::FromECEF(interestPointEcef); const SearchQuery& previousQuery = m_searchQueryPerformer.GetPreviousSearchQuery(); m_searchQueryPerformer.PerformSearchQuery(previousQuery.Query(), previousQuery.IsCategory(), currentLocation); m_previousQueryLocationEcef = interestPointEcef; m_secondsSincePreviousRefresh = 0.f; m_previousQueryInterestDistance = (viewpointEcef - interestPointEcef).Length(); } m_previousInterestEcefLocation = interestPointEcef; } void SearchRefreshService::HandleSearchQueryIssued(const SearchQuery& query) { ++ m_queriesPending; } void SearchRefreshService::HandleSearchResultsResponseReceived(const SearchQuery& query, const std::vector<SearchResultModel>& results) { m_searchResultsExist = true; m_previousQueryLocationEcef = query.Location().ToECEF(); -- m_queriesPending; Eegeo_ASSERT(m_queriesPending >= 0); } void SearchRefreshService::HandleSearchQueryResultsCleared() { m_searchResultsExist = false; } } } }
// Copyright eeGeo Ltd (2012-2015), All Rights Reserved #include "SearchRefreshService.h" #include "ISearchService.h" #include "ISearchQueryPerformer.h" #include "LatLongAltitude.h" #include "ICameraTransitionController.h" #include <algorithm> namespace ExampleApp { namespace Search { namespace SdkModel { SearchRefreshService::SearchRefreshService(ISearchService& searchService, ISearchQueryPerformer& searchQueryPerformer, CameraTransitions::SdkModel::ICameraTransitionController& cameraTransitionsController, float minimumSecondsBetweenUpdates, float minimumInterestLateralDeltaAt1km, float maximumInterestLateralSpeedAt1km) : m_minimumSecondsBetweenUpdates(minimumSecondsBetweenUpdates) , m_minimumInterestLateralDeltaAt1km(minimumInterestLateralDeltaAt1km) , m_maximumInterestLateralSpeedAt1km(maximumInterestLateralSpeedAt1km) , m_searchService(searchService) , m_searchQueryPerformer(searchQueryPerformer) , m_cameraTransitionsController(cameraTransitionsController) , m_pSearchResultQueryIssuedCallback(Eegeo_NEW((Eegeo::Helpers::TCallback1<SearchRefreshService, const SearchQuery&>))(this, &SearchRefreshService::HandleSearchQueryIssued)) , m_pSearchResultResponseReceivedCallback(Eegeo_NEW((Eegeo::Helpers::TCallback2<SearchRefreshService, const SearchQuery&, const std::vector<SearchResultModel>& >))(this, &SearchRefreshService::HandleSearchResultsResponseReceived)) , m_pSearchQueryResultsClearedCallback(Eegeo_NEW(Eegeo::Helpers::TCallback0<SearchRefreshService>)(this, &SearchRefreshService::HandleSearchQueryResultsCleared)) , m_queriesPending(0) , m_searchResultsExist(false) , m_secondsSincePreviousRefresh(0.f) , m_enabled(true) , m_previousQueryLocationEcef(Eegeo::dv3::Zero()) , m_previousInterestEcefLocation(Eegeo::dv3::Zero()) , m_previousQueryInterestDistance(0.f) { m_searchService.InsertOnPerformedQueryCallback(*m_pSearchResultQueryIssuedCallback); m_searchService.InsertOnReceivedQueryResultsCallback(*m_pSearchResultResponseReceivedCallback); m_searchQueryPerformer.InsertOnSearchResultsClearedCallback(*m_pSearchQueryResultsClearedCallback); } SearchRefreshService::~SearchRefreshService() { m_searchQueryPerformer.RemoveOnSearchResultsClearedCallback(*m_pSearchQueryResultsClearedCallback); m_searchService.RemoveOnReceivedQueryResultsCallback(*m_pSearchResultResponseReceivedCallback); m_searchService.RemoveOnPerformedQueryCallback(*m_pSearchResultQueryIssuedCallback); Eegeo_DELETE m_pSearchResultResponseReceivedCallback; Eegeo_DELETE m_pSearchResultQueryIssuedCallback; Eegeo_DELETE m_pSearchQueryResultsClearedCallback; } void SearchRefreshService::SetEnabled(bool enabled) { m_enabled = enabled; } bool SearchRefreshService::ShouldRefreshSearch(float deltaSeconds, const Eegeo::dv3& interestPointEcef, const Eegeo::dv3& viewpointEcef) const { if (!m_enabled) { return false; } if (!m_searchResultsExist) { return false; } if (m_queriesPending != 0) { return false; } if (m_cameraTransitionsController.IsTransitioning()) { return false; } if (m_secondsSincePreviousRefresh < m_minimumSecondsBetweenUpdates) { return false; } const float viewpointDistance = (viewpointEcef - interestPointEcef).Length(); const float distanceRatio = std::min(viewpointDistance, m_previousQueryInterestDistance) / std::max(viewpointDistance, m_previousQueryInterestDistance); if (distanceRatio < 0.75) { return true; } const float angularInterestDeltaFromQuery = (interestPointEcef - m_previousQueryLocationEcef).Length() / viewpointDistance; const float minimumInterestLateralDeltaAngle = m_minimumInterestLateralDeltaAt1km * 0.001f; const bool belowLateralThreshold = (angularInterestDeltaFromQuery < minimumInterestLateralDeltaAngle); if (belowLateralThreshold) { return false; } const float angularInterestDelta = (interestPointEcef - m_previousInterestEcefLocation).Length() / viewpointDistance; const float maxInterestAngularSpeed = m_maximumInterestLateralSpeedAt1km * 0.001f; const bool aboveSpeedThreshold = angularInterestDelta > maxInterestAngularSpeed*deltaSeconds; if (aboveSpeedThreshold) { return false; } return true; } void SearchRefreshService::TryRefreshSearch(float deltaSeconds, const Eegeo::dv3& interestPointEcef, const Eegeo::dv3& viewpointEcef) { m_secondsSincePreviousRefresh += deltaSeconds; bool shouldRefresh = ShouldRefreshSearch(deltaSeconds, interestPointEcef, viewpointEcef); if(m_previousQueryInterestDistance == 0.0f) { shouldRefresh = false; } if (shouldRefresh) { const Eegeo::Space::LatLongAltitude& currentLocation = Eegeo::Space::LatLongAltitude::FromECEF(interestPointEcef); const SearchQuery& previousQuery = m_searchQueryPerformer.GetPreviousSearchQuery(); m_searchQueryPerformer.PerformSearchQuery(previousQuery.Query(), previousQuery.IsCategory(), currentLocation); m_previousQueryLocationEcef = interestPointEcef; m_secondsSincePreviousRefresh = 0.f; } m_previousQueryInterestDistance = (viewpointEcef - interestPointEcef).Length(); m_previousInterestEcefLocation = interestPointEcef; } void SearchRefreshService::HandleSearchQueryIssued(const SearchQuery& query) { ++ m_queriesPending; } void SearchRefreshService::HandleSearchResultsResponseReceived(const SearchQuery& query, const std::vector<SearchResultModel>& results) { m_searchResultsExist = true; m_previousQueryLocationEcef = query.Location().ToECEF(); -- m_queriesPending; Eegeo_ASSERT(m_queriesPending >= 0); } void SearchRefreshService::HandleSearchQueryResultsCleared() { m_searchResultsExist = false; } } } }
Fix for: MPLY-6870, interest point was not being set hence the difference between the view and interest point distance was not zero causing it to refresh first time around. Buddy: Scott
Fix for: MPLY-6870, interest point was not being set hence the difference between the view and interest point distance was not zero causing it to refresh first time around. Buddy: Scott
C++
bsd-2-clause
eegeo/eegeo-example-app,wrld3d/wrld-example-app,eegeo/eegeo-example-app,eegeo/eegeo-example-app,eegeo/eegeo-example-app,wrld3d/wrld-example-app,wrld3d/wrld-example-app,wrld3d/wrld-example-app,wrld3d/wrld-example-app,wrld3d/wrld-example-app,eegeo/eegeo-example-app,wrld3d/wrld-example-app,eegeo/eegeo-example-app,eegeo/eegeo-example-app,wrld3d/wrld-example-app
16412186e028811d0ec6cc3c40b98da3743ba1c8
Source/Urho3D/Resource/JSONFile.cpp
Source/Urho3D/Resource/JSONFile.cpp
// // Copyright (c) 2008-2017 the Urho3D project. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // #include "../Precompiled.h" #include "../Container/ArrayPtr.h" #include "../Core/Profiler.h" #include "../Core/Context.h" #include "../IO/Deserializer.h" #include "../IO/Log.h" #include "../IO/MemoryBuffer.h" #include "../Resource/JSONFile.h" #include "../Resource/ResourceCache.h" #include <rapidjson/document.h> #include <rapidjson/stringbuffer.h> #include <rapidjson/prettywriter.h> #include "../DebugNew.h" using namespace rapidjson; namespace Urho3D { JSONFile::JSONFile(Context* context) : Resource(context) { } JSONFile::~JSONFile() { } void JSONFile::RegisterObject(Context* context) { context->RegisterFactory<JSONFile>(); } // Convert rapidjson value to JSON value. static void ToJSONValue(JSONValue& jsonValue, const rapidjson::Value& rapidjsonValue) { switch (rapidjsonValue.GetType()) { case kNullType: // Reset to null type jsonValue.SetType(JSON_NULL); break; case kFalseType: jsonValue = false; break; case kTrueType: jsonValue = true; break; case kNumberType: if (rapidjsonValue.IsInt()) jsonValue = rapidjsonValue.GetInt(); else if (rapidjsonValue.IsUint()) jsonValue = rapidjsonValue.GetUint(); else jsonValue = rapidjsonValue.GetDouble(); break; case kStringType: jsonValue = rapidjsonValue.GetString(); break; case kArrayType: { jsonValue.Resize(rapidjsonValue.Size()); for (unsigned i = 0; i < rapidjsonValue.Size(); ++i) { ToJSONValue(jsonValue[i], rapidjsonValue[i]); } } break; case kObjectType: { jsonValue.SetType(JSON_OBJECT); for (rapidjson::Value::ConstMemberIterator i = rapidjsonValue.MemberBegin(); i != rapidjsonValue.MemberEnd(); ++i) { JSONValue& value = jsonValue[String(i->name.GetString())]; ToJSONValue(value, i->value); } } break; default: break; } } bool JSONFile::BeginLoad(Deserializer& source) { unsigned dataSize = source.GetSize(); if (!dataSize && !source.GetName().Empty()) { URHO3D_LOGERROR("Zero sized JSON data in " + source.GetName()); return false; } SharedArrayPtr<char> buffer(new char[dataSize + 1]); if (source.Read(buffer.Get(), dataSize) != dataSize) return false; buffer[dataSize] = '\0'; rapidjson::Document document; if (document.Parse<kParseCommentsFlag>(buffer).HasParseError()) { URHO3D_LOGERROR("Could not parse JSON data from " + source.GetName()); return false; } ToJSONValue(root_, document); SetMemoryUse(dataSize); return true; } static void ToRapidjsonValue(rapidjson::Value& rapidjsonValue, const JSONValue& jsonValue, rapidjson::MemoryPoolAllocator<>& allocator) { switch (jsonValue.GetValueType()) { case JSON_NULL: rapidjsonValue.SetNull(); break; case JSON_BOOL: rapidjsonValue.SetBool(jsonValue.GetBool()); break; case JSON_NUMBER: { switch (jsonValue.GetNumberType()) { case JSONNT_INT: rapidjsonValue.SetInt(jsonValue.GetInt()); break; case JSONNT_UINT: rapidjsonValue.SetUint(jsonValue.GetUInt()); break; default: rapidjsonValue.SetDouble(jsonValue.GetDouble()); break; } } break; case JSON_STRING: rapidjsonValue.SetString(jsonValue.GetCString(), allocator); break; case JSON_ARRAY: { const JSONArray& jsonArray = jsonValue.GetArray(); rapidjsonValue.SetArray(); rapidjsonValue.Reserve(jsonArray.Size(), allocator); for (unsigned i = 0; i < jsonArray.Size(); ++i) { rapidjson::Value value; ToRapidjsonValue(value, jsonArray[i], allocator); rapidjsonValue.PushBack(value, allocator); } } break; case JSON_OBJECT: { const JSONObject& jsonObject = jsonValue.GetObject(); rapidjsonValue.SetObject(); for (JSONObject::ConstIterator i = jsonObject.Begin(); i != jsonObject.End(); ++i) { const char* name = i->first_.CString(); rapidjson::Value value; ToRapidjsonValue(value, i->second_, allocator); rapidjsonValue.AddMember(StringRef(name), value, allocator); } } break; default: break; } } bool JSONFile::Save(Serializer& dest) const { return Save(dest, "\t"); } bool JSONFile::Save(Serializer& dest, const String& indendation) const { rapidjson::Document document; ToRapidjsonValue(document, root_, document.GetAllocator()); StringBuffer buffer; PrettyWriter<StringBuffer> writer(buffer); writer.SetIndent(!indendation.Empty() ? indendation.Front() : '\0', indendation.Length()); document.Accept(writer); unsigned size = (unsigned)buffer.GetSize(); return dest.Write(buffer.GetString(), size) == size; } bool JSONFile::FromString(const String & source) { if (source.Empty()) return false; MemoryBuffer buffer(source.CString(), source.Length()); return Load(buffer); } }
// // Copyright (c) 2008-2017 the Urho3D project. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // #include "../Precompiled.h" #include "../Container/ArrayPtr.h" #include "../Core/Profiler.h" #include "../Core/Context.h" #include "../IO/Deserializer.h" #include "../IO/Log.h" #include "../IO/MemoryBuffer.h" #include "../Resource/JSONFile.h" #include "../Resource/ResourceCache.h" #include <rapidjson/document.h> #include <rapidjson/stringbuffer.h> #include <rapidjson/prettywriter.h> #include "../DebugNew.h" using namespace rapidjson; namespace Urho3D { JSONFile::JSONFile(Context* context) : Resource(context) { } JSONFile::~JSONFile() { } void JSONFile::RegisterObject(Context* context) { context->RegisterFactory<JSONFile>(); } // Convert rapidjson value to JSON value. static void ToJSONValue(JSONValue& jsonValue, const rapidjson::Value& rapidjsonValue) { switch (rapidjsonValue.GetType()) { case kNullType: // Reset to null type jsonValue.SetType(JSON_NULL); break; case kFalseType: jsonValue = false; break; case kTrueType: jsonValue = true; break; case kNumberType: if (rapidjsonValue.IsInt()) jsonValue = rapidjsonValue.GetInt(); else if (rapidjsonValue.IsUint()) jsonValue = rapidjsonValue.GetUint(); else jsonValue = rapidjsonValue.GetDouble(); break; case kStringType: jsonValue = rapidjsonValue.GetString(); break; case kArrayType: { jsonValue.Resize(rapidjsonValue.Size()); for (unsigned i = 0; i < rapidjsonValue.Size(); ++i) { ToJSONValue(jsonValue[i], rapidjsonValue[i]); } } break; case kObjectType: { jsonValue.SetType(JSON_OBJECT); for (rapidjson::Value::ConstMemberIterator i = rapidjsonValue.MemberBegin(); i != rapidjsonValue.MemberEnd(); ++i) { JSONValue& value = jsonValue[String(i->name.GetString())]; ToJSONValue(value, i->value); } } break; default: break; } } bool JSONFile::BeginLoad(Deserializer& source) { unsigned dataSize = source.GetSize(); if (!dataSize && !source.GetName().Empty()) { URHO3D_LOGERROR("Zero sized JSON data in " + source.GetName()); return false; } SharedArrayPtr<char> buffer(new char[dataSize + 1]); if (source.Read(buffer.Get(), dataSize) != dataSize) return false; buffer[dataSize] = '\0'; rapidjson::Document document; if (document.Parse<kParseCommentsFlag | kParseTrailingCommasFlag>(buffer).HasParseError()) { URHO3D_LOGERROR("Could not parse JSON data from " + source.GetName()); return false; } ToJSONValue(root_, document); SetMemoryUse(dataSize); return true; } static void ToRapidjsonValue(rapidjson::Value& rapidjsonValue, const JSONValue& jsonValue, rapidjson::MemoryPoolAllocator<>& allocator) { switch (jsonValue.GetValueType()) { case JSON_NULL: rapidjsonValue.SetNull(); break; case JSON_BOOL: rapidjsonValue.SetBool(jsonValue.GetBool()); break; case JSON_NUMBER: { switch (jsonValue.GetNumberType()) { case JSONNT_INT: rapidjsonValue.SetInt(jsonValue.GetInt()); break; case JSONNT_UINT: rapidjsonValue.SetUint(jsonValue.GetUInt()); break; default: rapidjsonValue.SetDouble(jsonValue.GetDouble()); break; } } break; case JSON_STRING: rapidjsonValue.SetString(jsonValue.GetCString(), allocator); break; case JSON_ARRAY: { const JSONArray& jsonArray = jsonValue.GetArray(); rapidjsonValue.SetArray(); rapidjsonValue.Reserve(jsonArray.Size(), allocator); for (unsigned i = 0; i < jsonArray.Size(); ++i) { rapidjson::Value value; ToRapidjsonValue(value, jsonArray[i], allocator); rapidjsonValue.PushBack(value, allocator); } } break; case JSON_OBJECT: { const JSONObject& jsonObject = jsonValue.GetObject(); rapidjsonValue.SetObject(); for (JSONObject::ConstIterator i = jsonObject.Begin(); i != jsonObject.End(); ++i) { const char* name = i->first_.CString(); rapidjson::Value value; ToRapidjsonValue(value, i->second_, allocator); rapidjsonValue.AddMember(StringRef(name), value, allocator); } } break; default: break; } } bool JSONFile::Save(Serializer& dest) const { return Save(dest, "\t"); } bool JSONFile::Save(Serializer& dest, const String& indendation) const { rapidjson::Document document; ToRapidjsonValue(document, root_, document.GetAllocator()); StringBuffer buffer; PrettyWriter<StringBuffer> writer(buffer); writer.SetIndent(!indendation.Empty() ? indendation.Front() : '\0', indendation.Length()); document.Accept(writer); unsigned size = (unsigned)buffer.GetSize(); return dest.Write(buffer.GetString(), size) == size; } bool JSONFile::FromString(const String & source) { if (source.Empty()) return false; MemoryBuffer buffer(source.CString(), source.Length()); return Load(buffer); } }
Allow trailing commas in JSON
Allow trailing commas in JSON
C++
mit
rokups/Urho3D,299299/Urho3D,299299/Urho3D,urho3d/Urho3D,fire/Urho3D-1,SirNate0/Urho3D,rokups/Urho3D,MeshGeometry/Urho3D,MonkeyFirst/Urho3D,SirNate0/Urho3D,cosmy1/Urho3D,codemon66/Urho3D,codedash64/Urho3D,victorholt/Urho3D,codemon66/Urho3D,codedash64/Urho3D,kostik1337/Urho3D,cosmy1/Urho3D,299299/Urho3D,xiliu98/Urho3D,kostik1337/Urho3D,eugeneko/Urho3D,PredatorMF/Urho3D,SuperWangKai/Urho3D,SuperWangKai/Urho3D,SirNate0/Urho3D,victorholt/Urho3D,PredatorMF/Urho3D,henu/Urho3D,iainmerrick/Urho3D,weitjong/Urho3D,rokups/Urho3D,c4augustus/Urho3D,xiliu98/Urho3D,codedash64/Urho3D,MonkeyFirst/Urho3D,c4augustus/Urho3D,MeshGeometry/Urho3D,fire/Urho3D-1,orefkov/Urho3D,henu/Urho3D,rokups/Urho3D,c4augustus/Urho3D,weitjong/Urho3D,henu/Urho3D,299299/Urho3D,carnalis/Urho3D,fire/Urho3D-1,xiliu98/Urho3D,orefkov/Urho3D,SuperWangKai/Urho3D,iainmerrick/Urho3D,PredatorMF/Urho3D,weitjong/Urho3D,kostik1337/Urho3D,victorholt/Urho3D,eugeneko/Urho3D,carnalis/Urho3D,MeshGeometry/Urho3D,tommy3/Urho3D,tommy3/Urho3D,SuperWangKai/Urho3D,cosmy1/Urho3D,fire/Urho3D-1,tommy3/Urho3D,MeshGeometry/Urho3D,codemon66/Urho3D,orefkov/Urho3D,cosmy1/Urho3D,codedash64/Urho3D,kostik1337/Urho3D,urho3d/Urho3D,kostik1337/Urho3D,iainmerrick/Urho3D,tommy3/Urho3D,eugeneko/Urho3D,SirNate0/Urho3D,codedash64/Urho3D,iainmerrick/Urho3D,victorholt/Urho3D,tommy3/Urho3D,xiliu98/Urho3D,orefkov/Urho3D,rokups/Urho3D,weitjong/Urho3D,codemon66/Urho3D,henu/Urho3D,299299/Urho3D,victorholt/Urho3D,MonkeyFirst/Urho3D,PredatorMF/Urho3D,carnalis/Urho3D,MonkeyFirst/Urho3D,urho3d/Urho3D,SirNate0/Urho3D,carnalis/Urho3D,iainmerrick/Urho3D,MeshGeometry/Urho3D,bacsmar/Urho3D,bacsmar/Urho3D,weitjong/Urho3D,fire/Urho3D-1,bacsmar/Urho3D,299299/Urho3D,c4augustus/Urho3D,bacsmar/Urho3D,henu/Urho3D,SuperWangKai/Urho3D,xiliu98/Urho3D,MonkeyFirst/Urho3D,carnalis/Urho3D,urho3d/Urho3D,rokups/Urho3D,c4augustus/Urho3D,eugeneko/Urho3D,cosmy1/Urho3D,codemon66/Urho3D
332f1848240f2c557476b21e993d8b3910f32db5
base/hostinfo.cc
base/hostinfo.cc
/* * Copyright (c) 2003-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. */ #include <ctype.h> #include <errno.h> #include <math.h> #include <unistd.h> #include <cstdio> #include <cstdlib> #include <cstring> #include <string> #include "base/misc.hh" #include "sim/host.hh" using namespace std; string __get_hostname() { char host[256]; if (gethostname(host, sizeof host) == -1) warn("could not get host name!"); return host; } string & hostname() { static string hostname = __get_hostname(); return hostname; } uint64_t procInfo(char *filename, char *target) { int done = 0; char line[80]; char format[80]; long usage; FILE *fp = fopen(filename, "r"); while (fp && !feof(fp) && !done) { if (fgets(line, 80, fp)) { if (strncmp(line, target, strlen(target)) == 0) { snprintf(format, sizeof(format), "%s %%lld", target); sscanf(line, format, &usage); fclose(fp); return usage ; } } } if (fp) fclose(fp); return 0; }
/* * Copyright (c) 2003-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. */ #include <ctype.h> #include <errno.h> #include <math.h> #include <unistd.h> #include <cstdio> #include <cstdlib> #include <cstring> #include <string> #include "base/misc.hh" #include "sim/host.hh" using namespace std; string __get_hostname() { char host[256]; if (gethostname(host, sizeof host) == -1) warn("could not get host name!"); return host; } string & hostname() { static string hostname = __get_hostname(); return hostname; } uint64_t procInfo(char *filename, char *target) { int done = 0; char line[80]; char format[80]; long usage; FILE *fp = fopen(filename, "r"); while (fp && !feof(fp) && !done) { if (fgets(line, 80, fp)) { if (strncmp(line, target, strlen(target)) == 0) { snprintf(format, sizeof(format), "%s %%ld", target); sscanf(line, format, &usage); fclose(fp); return usage ; } } } if (fp) fclose(fp); return 0; }
format string did not match variable size -> stack corruption
format string did not match variable size -> stack corruption --HG-- extra : convert_revision : b7c5aaa9d1f1242cfe337d6555e476f622a2aa6d
C++
bsd-3-clause
samueldotj/TeeRISC-Simulator,aclifton/cpeg853-gem5,gem5/gem5,yb-kim/gemV,KuroeKurose/gem5,samueldotj/TeeRISC-Simulator,KuroeKurose/gem5,austinharris/gem5-riscv,joerocklin/gem5,powerjg/gem5-ci-test,markoshorro/gem5,austinharris/gem5-riscv,aclifton/cpeg853-gem5,yb-kim/gemV,joerocklin/gem5,samueldotj/TeeRISC-Simulator,rallylee/gem5,Weil0ng/gem5,rjschof/gem5,samueldotj/TeeRISC-Simulator,kaiyuanl/gem5,gedare/gem5,cancro7/gem5,rjschof/gem5,zlfben/gem5,markoshorro/gem5,kaiyuanl/gem5,rallylee/gem5,yb-kim/gemV,gedare/gem5,austinharris/gem5-riscv,qizenguf/MLC-STT,cancro7/gem5,zlfben/gem5,zlfben/gem5,powerjg/gem5-ci-test,KuroeKurose/gem5,cancro7/gem5,aclifton/cpeg853-gem5,KuroeKurose/gem5,briancoutinho0905/2dsampling,gedare/gem5,gedare/gem5,SanchayanMaity/gem5,aclifton/cpeg853-gem5,markoshorro/gem5,joerocklin/gem5,HwisooSo/gemV-update,sobercoder/gem5,SanchayanMaity/gem5,KuroeKurose/gem5,KuroeKurose/gem5,gedare/gem5,qizenguf/MLC-STT,briancoutinho0905/2dsampling,powerjg/gem5-ci-test,joerocklin/gem5,austinharris/gem5-riscv,aclifton/cpeg853-gem5,joerocklin/gem5,Weil0ng/gem5,TUD-OS/gem5-dtu,HwisooSo/gemV-update,kaiyuanl/gem5,gem5/gem5,SanchayanMaity/gem5,yb-kim/gemV,samueldotj/TeeRISC-Simulator,HwisooSo/gemV-update,gem5/gem5,sobercoder/gem5,HwisooSo/gemV-update,briancoutinho0905/2dsampling,gem5/gem5,aclifton/cpeg853-gem5,SanchayanMaity/gem5,joerocklin/gem5,Weil0ng/gem5,HwisooSo/gemV-update,sobercoder/gem5,Weil0ng/gem5,qizenguf/MLC-STT,kaiyuanl/gem5,samueldotj/TeeRISC-Simulator,gedare/gem5,powerjg/gem5-ci-test,HwisooSo/gemV-update,qizenguf/MLC-STT,rjschof/gem5,zlfben/gem5,TUD-OS/gem5-dtu,yb-kim/gemV,rallylee/gem5,sobercoder/gem5,TUD-OS/gem5-dtu,kaiyuanl/gem5,cancro7/gem5,qizenguf/MLC-STT,rallylee/gem5,yb-kim/gemV,SanchayanMaity/gem5,rjschof/gem5,powerjg/gem5-ci-test,austinharris/gem5-riscv,zlfben/gem5,markoshorro/gem5,Weil0ng/gem5,zlfben/gem5,powerjg/gem5-ci-test,qizenguf/MLC-STT,cancro7/gem5,kaiyuanl/gem5,cancro7/gem5,markoshorro/gem5,briancoutinho0905/2dsampling,rallylee/gem5,KuroeKurose/gem5,yb-kim/gemV,rallylee/gem5,briancoutinho0905/2dsampling,markoshorro/gem5,gem5/gem5,sobercoder/gem5,austinharris/gem5-riscv,kaiyuanl/gem5,joerocklin/gem5,powerjg/gem5-ci-test,SanchayanMaity/gem5,rjschof/gem5,TUD-OS/gem5-dtu,briancoutinho0905/2dsampling,Weil0ng/gem5,briancoutinho0905/2dsampling,zlfben/gem5,gem5/gem5,TUD-OS/gem5-dtu,Weil0ng/gem5,yb-kim/gemV,TUD-OS/gem5-dtu,rallylee/gem5,sobercoder/gem5,samueldotj/TeeRISC-Simulator,joerocklin/gem5,qizenguf/MLC-STT,markoshorro/gem5,SanchayanMaity/gem5,HwisooSo/gemV-update,sobercoder/gem5,cancro7/gem5,rjschof/gem5,TUD-OS/gem5-dtu,gedare/gem5,rjschof/gem5,aclifton/cpeg853-gem5,austinharris/gem5-riscv,gem5/gem5
b6eff47bac0a2745da6e3aa95ffa340eb71c7248
scene/3d/navigation_region_3d.cpp
scene/3d/navigation_region_3d.cpp
/*************************************************************************/ /* navigation_region_3d.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* 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 "navigation_region_3d.h" #include "mesh_instance_3d.h" #include "servers/navigation_server_3d.h" void NavigationRegion3D::set_enabled(bool p_enabled) { if (enabled == p_enabled) { return; } enabled = p_enabled; if (!is_inside_tree()) { return; } if (!enabled) { NavigationServer3D::get_singleton()->region_set_map(region, RID()); } else { NavigationServer3D::get_singleton()->region_set_map(region, get_world_3d()->get_navigation_map()); } if (debug_view) { MeshInstance3D *dm = Object::cast_to<MeshInstance3D>(debug_view); if (is_enabled()) { dm->set_material_override(get_tree()->get_debug_navigation_material()); } else { dm->set_material_override(get_tree()->get_debug_navigation_disabled_material()); } } update_gizmos(); } bool NavigationRegion3D::is_enabled() const { return enabled; } void NavigationRegion3D::set_layers(uint32_t p_layers) { NavigationServer3D::get_singleton()->region_set_layers(region, p_layers); } uint32_t NavigationRegion3D::get_layers() const { return NavigationServer3D::get_singleton()->region_get_layers(region); } RID NavigationRegion3D::get_region_rid() const { return region; } ///////////////////////////// void NavigationRegion3D::_notification(int p_what) { switch (p_what) { case NOTIFICATION_ENTER_TREE: { if (enabled) { NavigationServer3D::get_singleton()->region_set_map(region, get_world_3d()->get_navigation_map()); } if (navmesh.is_valid() && get_tree()->is_debugging_navigation_hint()) { MeshInstance3D *dm = memnew(MeshInstance3D); dm->set_mesh(navmesh->get_debug_mesh()); if (is_enabled()) { dm->set_material_override(get_tree()->get_debug_navigation_material()); } else { dm->set_material_override(get_tree()->get_debug_navigation_disabled_material()); } add_child(dm); debug_view = dm; } } break; case NOTIFICATION_TRANSFORM_CHANGED: { NavigationServer3D::get_singleton()->region_set_transform(region, get_global_transform()); } break; case NOTIFICATION_EXIT_TREE: { NavigationServer3D::get_singleton()->region_set_map(region, RID()); if (debug_view) { debug_view->queue_delete(); debug_view = nullptr; } } break; } } void NavigationRegion3D::set_navigation_mesh(const Ref<NavigationMesh> &p_navmesh) { if (p_navmesh == navmesh) { return; } if (navmesh.is_valid()) { navmesh->disconnect("changed", callable_mp(this, &NavigationRegion3D::_navigation_changed)); } navmesh = p_navmesh; if (navmesh.is_valid()) { navmesh->connect("changed", callable_mp(this, &NavigationRegion3D::_navigation_changed)); } NavigationServer3D::get_singleton()->region_set_navmesh(region, p_navmesh); if (debug_view && navmesh.is_valid()) { Object::cast_to<MeshInstance3D>(debug_view)->set_mesh(navmesh->get_debug_mesh()); } emit_signal(SNAME("navigation_mesh_changed")); update_gizmos(); update_configuration_warnings(); } Ref<NavigationMesh> NavigationRegion3D::get_navigation_mesh() const { return navmesh; } struct BakeThreadsArgs { NavigationRegion3D *nav_region = nullptr; }; void _bake_navigation_mesh(void *p_user_data) { BakeThreadsArgs *args = static_cast<BakeThreadsArgs *>(p_user_data); if (args->nav_region->get_navigation_mesh().is_valid()) { Ref<NavigationMesh> nav_mesh = args->nav_region->get_navigation_mesh()->duplicate(); NavigationServer3D::get_singleton()->region_bake_navmesh(nav_mesh, args->nav_region); args->nav_region->call_deferred(SNAME("_bake_finished"), nav_mesh); memdelete(args); } else { ERR_PRINT("Can't bake the navigation mesh if the `NavigationMesh` resource doesn't exist"); args->nav_region->call_deferred(SNAME("_bake_finished"), Ref<NavigationMesh>()); memdelete(args); } } void NavigationRegion3D::bake_navigation_mesh(bool p_on_thread) { ERR_FAIL_COND_MSG(bake_thread.is_started(), "Unable to start another bake request. The navigation mesh bake thread is already baking a navigation mesh."); BakeThreadsArgs *args = memnew(BakeThreadsArgs); args->nav_region = this; if (p_on_thread && !OS::get_singleton()->can_use_threads()) { WARN_PRINT("NavigationMesh bake 'on_thread' will be disabled as the current OS does not support multiple threads." "\nAs a fallback the navigation mesh will bake on the main thread which can cause framerate issues."); } if (p_on_thread && OS::get_singleton()->can_use_threads()) { bake_thread.start(_bake_navigation_mesh, args); } else { _bake_navigation_mesh(args); } } void NavigationRegion3D::_bake_finished(Ref<NavigationMesh> p_nav_mesh) { set_navigation_mesh(p_nav_mesh); bake_thread.wait_to_finish(); emit_signal(SNAME("bake_finished")); } TypedArray<String> NavigationRegion3D::get_configuration_warnings() const { TypedArray<String> warnings = Node::get_configuration_warnings(); if (is_visible_in_tree() && is_inside_tree()) { if (!navmesh.is_valid()) { warnings.push_back(RTR("A NavigationMesh resource must be set or created for this node to work.")); } } return warnings; } void NavigationRegion3D::_bind_methods() { ClassDB::bind_method(D_METHOD("set_navigation_mesh", "navmesh"), &NavigationRegion3D::set_navigation_mesh); ClassDB::bind_method(D_METHOD("get_navigation_mesh"), &NavigationRegion3D::get_navigation_mesh); ClassDB::bind_method(D_METHOD("set_enabled", "enabled"), &NavigationRegion3D::set_enabled); ClassDB::bind_method(D_METHOD("is_enabled"), &NavigationRegion3D::is_enabled); ClassDB::bind_method(D_METHOD("set_layers", "layers"), &NavigationRegion3D::set_layers); ClassDB::bind_method(D_METHOD("get_layers"), &NavigationRegion3D::get_layers); ClassDB::bind_method(D_METHOD("get_region_rid"), &NavigationRegion3D::get_region_rid); ClassDB::bind_method(D_METHOD("bake_navigation_mesh", "on_thread"), &NavigationRegion3D::bake_navigation_mesh, DEFVAL(true)); ClassDB::bind_method(D_METHOD("_bake_finished", "nav_mesh"), &NavigationRegion3D::_bake_finished); ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "navmesh", PROPERTY_HINT_RESOURCE_TYPE, "NavigationMesh"), "set_navigation_mesh", "get_navigation_mesh"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "enabled"), "set_enabled", "is_enabled"); ADD_PROPERTY(PropertyInfo(Variant::INT, "layers", PROPERTY_HINT_LAYERS_3D_NAVIGATION), "set_layers", "get_layers"); ADD_SIGNAL(MethodInfo("navigation_mesh_changed")); ADD_SIGNAL(MethodInfo("bake_finished")); } void NavigationRegion3D::_navigation_changed() { update_gizmos(); update_configuration_warnings(); } NavigationRegion3D::NavigationRegion3D() { set_notify_transform(true); region = NavigationServer3D::get_singleton()->region_create(); } NavigationRegion3D::~NavigationRegion3D() { if (navmesh.is_valid()) { navmesh->disconnect("changed", callable_mp(this, &NavigationRegion3D::_navigation_changed)); } NavigationServer3D::get_singleton()->free(region); }
/*************************************************************************/ /* navigation_region_3d.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* 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 "navigation_region_3d.h" #include "mesh_instance_3d.h" #include "servers/navigation_server_3d.h" void NavigationRegion3D::set_enabled(bool p_enabled) { if (enabled == p_enabled) { return; } enabled = p_enabled; if (!is_inside_tree()) { return; } if (!enabled) { NavigationServer3D::get_singleton()->region_set_map(region, RID()); } else { NavigationServer3D::get_singleton()->region_set_map(region, get_world_3d()->get_navigation_map()); } if (debug_view) { MeshInstance3D *dm = Object::cast_to<MeshInstance3D>(debug_view); if (is_enabled()) { dm->set_material_override(get_tree()->get_debug_navigation_material()); } else { dm->set_material_override(get_tree()->get_debug_navigation_disabled_material()); } } update_gizmos(); } bool NavigationRegion3D::is_enabled() const { return enabled; } void NavigationRegion3D::set_layers(uint32_t p_layers) { NavigationServer3D::get_singleton()->region_set_layers(region, p_layers); } uint32_t NavigationRegion3D::get_layers() const { return NavigationServer3D::get_singleton()->region_get_layers(region); } RID NavigationRegion3D::get_region_rid() const { return region; } ///////////////////////////// void NavigationRegion3D::_notification(int p_what) { switch (p_what) { case NOTIFICATION_ENTER_TREE: { if (enabled) { NavigationServer3D::get_singleton()->region_set_map(region, get_world_3d()->get_navigation_map()); } if (navmesh.is_valid() && get_tree()->is_debugging_navigation_hint()) { MeshInstance3D *dm = memnew(MeshInstance3D); dm->set_mesh(navmesh->get_debug_mesh()); if (is_enabled()) { dm->set_material_override(get_tree()->get_debug_navigation_material()); } else { dm->set_material_override(get_tree()->get_debug_navigation_disabled_material()); } add_child(dm); debug_view = dm; } } break; case NOTIFICATION_TRANSFORM_CHANGED: { NavigationServer3D::get_singleton()->region_set_transform(region, get_global_transform()); } break; case NOTIFICATION_EXIT_TREE: { NavigationServer3D::get_singleton()->region_set_map(region, RID()); if (debug_view) { debug_view->queue_delete(); debug_view = nullptr; } } break; } } void NavigationRegion3D::set_navigation_mesh(const Ref<NavigationMesh> &p_navmesh) { if (p_navmesh == navmesh) { return; } if (navmesh.is_valid()) { navmesh->disconnect("changed", callable_mp(this, &NavigationRegion3D::_navigation_changed)); } navmesh = p_navmesh; if (navmesh.is_valid()) { navmesh->connect("changed", callable_mp(this, &NavigationRegion3D::_navigation_changed)); } NavigationServer3D::get_singleton()->region_set_navmesh(region, p_navmesh); if (debug_view == nullptr && is_inside_tree() && navmesh.is_valid() && get_tree()->is_debugging_navigation_hint()) { MeshInstance3D *dm = memnew(MeshInstance3D); dm->set_mesh(navmesh->get_debug_mesh()); if (is_enabled()) { dm->set_material_override(get_tree()->get_debug_navigation_material()); } else { dm->set_material_override(get_tree()->get_debug_navigation_disabled_material()); } add_child(dm); debug_view = dm; } if (debug_view && navmesh.is_valid()) { Object::cast_to<MeshInstance3D>(debug_view)->set_mesh(navmesh->get_debug_mesh()); } emit_signal(SNAME("navigation_mesh_changed")); update_gizmos(); update_configuration_warnings(); } Ref<NavigationMesh> NavigationRegion3D::get_navigation_mesh() const { return navmesh; } struct BakeThreadsArgs { NavigationRegion3D *nav_region = nullptr; }; void _bake_navigation_mesh(void *p_user_data) { BakeThreadsArgs *args = static_cast<BakeThreadsArgs *>(p_user_data); if (args->nav_region->get_navigation_mesh().is_valid()) { Ref<NavigationMesh> nav_mesh = args->nav_region->get_navigation_mesh()->duplicate(); NavigationServer3D::get_singleton()->region_bake_navmesh(nav_mesh, args->nav_region); args->nav_region->call_deferred(SNAME("_bake_finished"), nav_mesh); memdelete(args); } else { ERR_PRINT("Can't bake the navigation mesh if the `NavigationMesh` resource doesn't exist"); args->nav_region->call_deferred(SNAME("_bake_finished"), Ref<NavigationMesh>()); memdelete(args); } } void NavigationRegion3D::bake_navigation_mesh(bool p_on_thread) { ERR_FAIL_COND_MSG(bake_thread.is_started(), "Unable to start another bake request. The navigation mesh bake thread is already baking a navigation mesh."); BakeThreadsArgs *args = memnew(BakeThreadsArgs); args->nav_region = this; if (p_on_thread && !OS::get_singleton()->can_use_threads()) { WARN_PRINT("NavigationMesh bake 'on_thread' will be disabled as the current OS does not support multiple threads." "\nAs a fallback the navigation mesh will bake on the main thread which can cause framerate issues."); } if (p_on_thread && OS::get_singleton()->can_use_threads()) { bake_thread.start(_bake_navigation_mesh, args); } else { _bake_navigation_mesh(args); } } void NavigationRegion3D::_bake_finished(Ref<NavigationMesh> p_nav_mesh) { set_navigation_mesh(p_nav_mesh); bake_thread.wait_to_finish(); emit_signal(SNAME("bake_finished")); } TypedArray<String> NavigationRegion3D::get_configuration_warnings() const { TypedArray<String> warnings = Node::get_configuration_warnings(); if (is_visible_in_tree() && is_inside_tree()) { if (!navmesh.is_valid()) { warnings.push_back(RTR("A NavigationMesh resource must be set or created for this node to work.")); } } return warnings; } void NavigationRegion3D::_bind_methods() { ClassDB::bind_method(D_METHOD("set_navigation_mesh", "navmesh"), &NavigationRegion3D::set_navigation_mesh); ClassDB::bind_method(D_METHOD("get_navigation_mesh"), &NavigationRegion3D::get_navigation_mesh); ClassDB::bind_method(D_METHOD("set_enabled", "enabled"), &NavigationRegion3D::set_enabled); ClassDB::bind_method(D_METHOD("is_enabled"), &NavigationRegion3D::is_enabled); ClassDB::bind_method(D_METHOD("set_layers", "layers"), &NavigationRegion3D::set_layers); ClassDB::bind_method(D_METHOD("get_layers"), &NavigationRegion3D::get_layers); ClassDB::bind_method(D_METHOD("get_region_rid"), &NavigationRegion3D::get_region_rid); ClassDB::bind_method(D_METHOD("bake_navigation_mesh", "on_thread"), &NavigationRegion3D::bake_navigation_mesh, DEFVAL(true)); ClassDB::bind_method(D_METHOD("_bake_finished", "nav_mesh"), &NavigationRegion3D::_bake_finished); ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "navmesh", PROPERTY_HINT_RESOURCE_TYPE, "NavigationMesh"), "set_navigation_mesh", "get_navigation_mesh"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "enabled"), "set_enabled", "is_enabled"); ADD_PROPERTY(PropertyInfo(Variant::INT, "layers", PROPERTY_HINT_LAYERS_3D_NAVIGATION), "set_layers", "get_layers"); ADD_SIGNAL(MethodInfo("navigation_mesh_changed")); ADD_SIGNAL(MethodInfo("bake_finished")); } void NavigationRegion3D::_navigation_changed() { update_gizmos(); update_configuration_warnings(); } NavigationRegion3D::NavigationRegion3D() { set_notify_transform(true); region = NavigationServer3D::get_singleton()->region_create(); } NavigationRegion3D::~NavigationRegion3D() { if (navmesh.is_valid()) { navmesh->disconnect("changed", callable_mp(this, &NavigationRegion3D::_navigation_changed)); } NavigationServer3D::get_singleton()->free(region); }
Add NavigationMesh debug when navmesh is added later through scripts
Add NavigationMesh debug when navmesh is added later through scripts Add NavigationMesh debug when navmesh is added later through scripts
C++
mit
Shockblast/godot,josempans/godot,guilhermefelipecgs/godot,vkbsb/godot,ZuBsPaCe/godot,vkbsb/godot,sanikoyes/godot,akien-mga/godot,guilhermefelipecgs/godot,guilhermefelipecgs/godot,guilhermefelipecgs/godot,Shockblast/godot,akien-mga/godot,pkowal1982/godot,pkowal1982/godot,firefly2442/godot,ZuBsPaCe/godot,Valentactive/godot,Zylann/godot,BastiaanOlij/godot,Shockblast/godot,BastiaanOlij/godot,josempans/godot,pkowal1982/godot,sanikoyes/godot,pkowal1982/godot,ZuBsPaCe/godot,pkowal1982/godot,josempans/godot,BastiaanOlij/godot,pkowal1982/godot,Zylann/godot,josempans/godot,Shockblast/godot,Valentactive/godot,sanikoyes/godot,josempans/godot,ZuBsPaCe/godot,firefly2442/godot,Zylann/godot,pkowal1982/godot,Valentactive/godot,akien-mga/godot,BastiaanOlij/godot,firefly2442/godot,sanikoyes/godot,Zylann/godot,godotengine/godot,godotengine/godot,vkbsb/godot,sanikoyes/godot,firefly2442/godot,godotengine/godot,vkbsb/godot,guilhermefelipecgs/godot,Valentactive/godot,Zylann/godot,vkbsb/godot,Valentactive/godot,guilhermefelipecgs/godot,ZuBsPaCe/godot,BastiaanOlij/godot,Zylann/godot,Valentactive/godot,josempans/godot,Shockblast/godot,sanikoyes/godot,firefly2442/godot,BastiaanOlij/godot,Shockblast/godot,pkowal1982/godot,sanikoyes/godot,Zylann/godot,vkbsb/godot,Shockblast/godot,firefly2442/godot,Valentactive/godot,godotengine/godot,BastiaanOlij/godot,BastiaanOlij/godot,godotengine/godot,guilhermefelipecgs/godot,ZuBsPaCe/godot,josempans/godot,ZuBsPaCe/godot,guilhermefelipecgs/godot,akien-mga/godot,Shockblast/godot,akien-mga/godot,sanikoyes/godot,akien-mga/godot,firefly2442/godot,Valentactive/godot,firefly2442/godot,Zylann/godot,akien-mga/godot,vkbsb/godot,josempans/godot,akien-mga/godot,godotengine/godot,ZuBsPaCe/godot,godotengine/godot,vkbsb/godot,godotengine/godot
9d46685b650afa537b0afa203dd4ad3e37be7585
webkit/glue/webfilesystem_impl.cc
webkit/glue/webfilesystem_impl.cc
// Copyright (c) 2010 The Chromium Authors. All rights reserved. Use of this // source code is governed by a BSD-style license that can be found in the // LICENSE file. #include "webkit/glue/webfilesystem_impl.h" #include "base/file_path.h" #include "base/file_util.h" #include "base/logging.h" #include "net/base/file_stream.h" #include "net/base/net_util.h" #include "third_party/WebKit/WebKit/chromium/public/WebString.h" #include "third_party/WebKit/WebKit/chromium/public/WebURL.h" #include "webkit/glue/webkit_glue.h" using WebKit::WebString; namespace webkit_glue { WebFileSystemImpl::WebFileSystemImpl() : sandbox_enabled_(true) { } bool WebFileSystemImpl::fileExists(const WebString& path) { FilePath::StringType file_path = WebStringToFilePathString(path); return file_util::PathExists(FilePath(file_path)); } bool WebFileSystemImpl::deleteFile(const WebString& path) { NOTREACHED(); return false; } bool WebFileSystemImpl::deleteEmptyDirectory(const WebString& path) { NOTREACHED(); return false; } bool WebFileSystemImpl::getFileSize(const WebString& path, long long& result) { if (sandbox_enabled_) { NOTREACHED(); return false; } return file_util::GetFileSize(WebStringToFilePath(path), reinterpret_cast<int64*>(&result)); } bool WebFileSystemImpl::getFileModificationTime(const WebString& path, double& result) { if (sandbox_enabled_) { NOTREACHED(); return false; } file_util::FileInfo info; if (!file_util::GetFileInfo(WebStringToFilePath(path), &info)) return false; result = info.last_modified.ToDoubleT(); return true; } WebString WebFileSystemImpl::directoryName(const WebString& path) { NOTREACHED(); return WebString(); } WebString WebFileSystemImpl::pathByAppendingComponent( const WebString& webkit_path, const WebString& webkit_component) { FilePath path(WebStringToFilePathString(webkit_path)); FilePath component(WebStringToFilePathString(webkit_component)); FilePath combined_path = path.Append(component); return FilePathStringToWebString(combined_path.value()); } bool WebFileSystemImpl::makeAllDirectories(const WebString& path) { DCHECK(!sandbox_enabled_); FilePath::StringType file_path = WebStringToFilePathString(path); return file_util::CreateDirectory(FilePath(file_path)); } WebString WebFileSystemImpl::getAbsolutePath(const WebString& path) { FilePath file_path(WebStringToFilePathString(path)); file_util::AbsolutePath(&file_path); return FilePathStringToWebString(file_path.value()); } bool WebFileSystemImpl::isDirectory(const WebString& path) { FilePath file_path(WebStringToFilePathString(path)); return file_util::DirectoryExists(file_path); } WebKit::WebURL WebFileSystemImpl::filePathToURL(const WebString& path) { return net::FilePathToFileURL(WebStringToFilePath(path)); } base::PlatformFile WebFileSystemImpl::openFile(const WebString& path, int mode) { if (sandbox_enabled_) { NOTREACHED(); return base::kInvalidPlatformFileValue; } return base::CreatePlatformFile( WebStringToFilePath(path), (mode == 0) ? (base::PLATFORM_FILE_OPEN | base::PLATFORM_FILE_READ) : (base::PLATFORM_FILE_CREATE_ALWAYS | base::PLATFORM_FILE_WRITE), NULL); } void WebFileSystemImpl::closeFile(base::PlatformFile& handle) { if (handle == base::kInvalidPlatformFileValue) return; if (base::ClosePlatformFile(handle)) handle = base::kInvalidPlatformFileValue; } long long WebFileSystemImpl::seekFile(base::PlatformFile handle, long long offset, int origin) { if (handle == base::kInvalidPlatformFileValue) return -1; net::FileStream file_stream(handle, 0); return file_stream.Seek(static_cast<net::Whence>(origin), offset); } bool WebFileSystemImpl::truncateFile(base::PlatformFile handle, long long offset) { if (handle == base::kInvalidPlatformFileValue || offset < 0) return false; net::FileStream file_stream(handle, base::PLATFORM_FILE_WRITE); return file_stream.Truncate(offset) >= 0; } int WebFileSystemImpl::readFromFile(base::PlatformFile handle, char* data, int length) { if (handle == base::kInvalidPlatformFileValue || !data || length <= 0) return -1; std::string buffer; buffer.resize(length); net::FileStream file_stream(handle, base::PLATFORM_FILE_READ); return file_stream.Read(data, length, NULL); } int WebFileSystemImpl::writeToFile(base::PlatformFile handle, const char* data, int length) { if (handle == base::kInvalidPlatformFileValue || !data || length <= 0) return -1; net::FileStream file_stream(handle, base::PLATFORM_FILE_WRITE); return file_stream.Write(data, length, NULL); } } // namespace webkit_glue
// 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 "webkit/glue/webfilesystem_impl.h" #include "base/file_path.h" #include "base/file_util.h" #include "base/logging.h" #include "net/base/file_stream.h" #include "net/base/net_util.h" #include "third_party/WebKit/WebKit/chromium/public/WebString.h" #include "third_party/WebKit/WebKit/chromium/public/WebURL.h" #include "webkit/glue/webkit_glue.h" using WebKit::WebString; namespace webkit_glue { WebFileSystemImpl::WebFileSystemImpl() : sandbox_enabled_(true) { } bool WebFileSystemImpl::fileExists(const WebString& path) { FilePath::StringType file_path = WebStringToFilePathString(path); return file_util::PathExists(FilePath(file_path)); } bool WebFileSystemImpl::deleteFile(const WebString& path) { NOTREACHED(); return false; } bool WebFileSystemImpl::deleteEmptyDirectory(const WebString& path) { NOTREACHED(); return false; } bool WebFileSystemImpl::getFileSize(const WebString& path, long long& result) { if (sandbox_enabled_) { NOTREACHED(); return false; } return file_util::GetFileSize(WebStringToFilePath(path), reinterpret_cast<int64*>(&result)); } bool WebFileSystemImpl::getFileModificationTime(const WebString& path, double& result) { if (sandbox_enabled_) { NOTREACHED(); return false; } file_util::FileInfo info; if (!file_util::GetFileInfo(WebStringToFilePath(path), &info)) return false; result = info.last_modified.ToDoubleT(); return true; } WebString WebFileSystemImpl::directoryName(const WebString& path) { FilePath file_path(WebStringToFilePathString(path)); return FilePathToWebString(file_path.DirName()); } WebString WebFileSystemImpl::pathByAppendingComponent( const WebString& webkit_path, const WebString& webkit_component) { FilePath path(WebStringToFilePathString(webkit_path)); FilePath component(WebStringToFilePathString(webkit_component)); FilePath combined_path = path.Append(component); return FilePathStringToWebString(combined_path.value()); } bool WebFileSystemImpl::makeAllDirectories(const WebString& path) { DCHECK(!sandbox_enabled_); FilePath::StringType file_path = WebStringToFilePathString(path); return file_util::CreateDirectory(FilePath(file_path)); } WebString WebFileSystemImpl::getAbsolutePath(const WebString& path) { FilePath file_path(WebStringToFilePathString(path)); file_util::AbsolutePath(&file_path); return FilePathStringToWebString(file_path.value()); } bool WebFileSystemImpl::isDirectory(const WebString& path) { FilePath file_path(WebStringToFilePathString(path)); return file_util::DirectoryExists(file_path); } WebKit::WebURL WebFileSystemImpl::filePathToURL(const WebString& path) { return net::FilePathToFileURL(WebStringToFilePath(path)); } base::PlatformFile WebFileSystemImpl::openFile(const WebString& path, int mode) { if (sandbox_enabled_) { NOTREACHED(); return base::kInvalidPlatformFileValue; } return base::CreatePlatformFile( WebStringToFilePath(path), (mode == 0) ? (base::PLATFORM_FILE_OPEN | base::PLATFORM_FILE_READ) : (base::PLATFORM_FILE_CREATE_ALWAYS | base::PLATFORM_FILE_WRITE), NULL); } void WebFileSystemImpl::closeFile(base::PlatformFile& handle) { if (handle == base::kInvalidPlatformFileValue) return; if (base::ClosePlatformFile(handle)) handle = base::kInvalidPlatformFileValue; } long long WebFileSystemImpl::seekFile(base::PlatformFile handle, long long offset, int origin) { if (handle == base::kInvalidPlatformFileValue) return -1; net::FileStream file_stream(handle, 0); return file_stream.Seek(static_cast<net::Whence>(origin), offset); } bool WebFileSystemImpl::truncateFile(base::PlatformFile handle, long long offset) { if (handle == base::kInvalidPlatformFileValue || offset < 0) return false; net::FileStream file_stream(handle, base::PLATFORM_FILE_WRITE); return file_stream.Truncate(offset) >= 0; } int WebFileSystemImpl::readFromFile(base::PlatformFile handle, char* data, int length) { if (handle == base::kInvalidPlatformFileValue || !data || length <= 0) return -1; std::string buffer; buffer.resize(length); net::FileStream file_stream(handle, base::PLATFORM_FILE_READ); return file_stream.Read(data, length, NULL); } int WebFileSystemImpl::writeToFile(base::PlatformFile handle, const char* data, int length) { if (handle == base::kInvalidPlatformFileValue || !data || length <= 0) return -1; net::FileStream file_stream(handle, base::PLATFORM_FILE_WRITE); return file_stream.Write(data, length, NULL); } } // namespace webkit_glue
Implement WebFileSystemImpl::directoryName. This is needed for directory upload (including webkit layout tests).
Implement WebFileSystemImpl::directoryName. This is needed for directory upload (including webkit layout tests). BUG=41762 TEST=webkit layout test fast/forms/input-file-directory-upload.html Review URL: http://codereview.chromium.org/2847056 git-svn-id: http://src.chromium.org/svn/trunk/src@52829 4ff67af0-8c30-449e-8e8b-ad334ec8d88c Former-commit-id: 34db75cdcdce7c303cfd5622770ba2b3bec4993f
C++
bsd-3-clause
meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser
716b6b2dc8bc1c497495c276fa3e73418a341e49
chrome/browser/sync/test/integration/performance/passwords_sync_perf_test.cc
chrome/browser/sync/test/integration/performance/passwords_sync_perf_test.cc
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/stringprintf.h" #include "base/utf_string_conversions.h" #include "chrome/browser/password_manager/password_store.h" #include "chrome/browser/sync/profile_sync_service_harness.h" #include "chrome/browser/sync/test/integration/passwords_helper.h" #include "chrome/browser/sync/test/integration/performance/sync_timing_helper.h" #include "chrome/browser/sync/test/integration/sync_test.h" using passwords_helper::AddLogin; using passwords_helper::CreateTestPasswordForm; using passwords_helper::GetLogins; using passwords_helper::GetPasswordCount; using passwords_helper::GetPasswordStore; using passwords_helper::UpdateLogin; static const int kNumPasswords = 150; class PasswordsSyncPerfTest : public SyncTest { public: PasswordsSyncPerfTest() : SyncTest(TWO_CLIENT), password_number_(0) {} // Adds |num_logins| new unique passwords to |profile|. void AddLogins(int profile, int num_logins); // Updates the password for all logins for |profile|. void UpdateLogins(int profile); // Removes all logins for |profile|. void RemoveLogins(int profile); private: // Returns a new unique login. webkit_glue::PasswordForm NextLogin(); // Returns a new unique password value. std::string NextPassword(); int password_number_; DISALLOW_COPY_AND_ASSIGN(PasswordsSyncPerfTest); }; void PasswordsSyncPerfTest::AddLogins(int profile, int num_logins) { for (int i = 0; i < num_logins; ++i) { AddLogin(GetPasswordStore(profile), NextLogin()); } } void PasswordsSyncPerfTest::UpdateLogins(int profile) { std::vector<webkit_glue::PasswordForm> logins; GetLogins(GetPasswordStore(profile), logins); for (std::vector<webkit_glue::PasswordForm>::iterator it = logins.begin(); it != logins.end(); ++it) { (*it).password_value = ASCIIToUTF16(NextPassword()); UpdateLogin(GetPasswordStore(profile), (*it)); } } void PasswordsSyncPerfTest::RemoveLogins(int profile) { passwords_helper::RemoveLogins(GetPasswordStore(profile)); } webkit_glue::PasswordForm PasswordsSyncPerfTest::NextLogin() { return CreateTestPasswordForm(password_number_++); } std::string PasswordsSyncPerfTest::NextPassword() { return base::StringPrintf("password%d", password_number_++); } // Flaky on Windows, see http://crbug.com/105787 #if defined(OS_WIN) #define MAYBE_P0 FLAKY_P0 #else #define MAYBE_P0 P0 #endif IN_PROC_BROWSER_TEST_F(PasswordsSyncPerfTest, MAYBE_P0) { ASSERT_TRUE(SetupSync()) << "SetupSync() failed."; // TCM ID - 7367749. AddLogins(0, kNumPasswords); base::TimeDelta dt = SyncTimingHelper::TimeMutualSyncCycle(GetClient(0), GetClient(1)); ASSERT_EQ(kNumPasswords, GetPasswordCount(1)); SyncTimingHelper::PrintResult("passwords", "add_passwords", dt); // TCM ID - 7365093. UpdateLogins(0); dt = SyncTimingHelper::TimeMutualSyncCycle(GetClient(0), GetClient(1)); ASSERT_EQ(kNumPasswords, GetPasswordCount(1)); SyncTimingHelper::PrintResult("passwords", "update_passwords", dt); // TCM ID - 7557852 RemoveLogins(0); dt = SyncTimingHelper::TimeMutualSyncCycle(GetClient(0), GetClient(1)); ASSERT_EQ(0, GetPasswordCount(1)); SyncTimingHelper::PrintResult("passwords", "delete_passwords", dt); }
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/stringprintf.h" #include "base/utf_string_conversions.h" #include "chrome/browser/password_manager/password_store.h" #include "chrome/browser/sync/profile_sync_service_harness.h" #include "chrome/browser/sync/test/integration/passwords_helper.h" #include "chrome/browser/sync/test/integration/performance/sync_timing_helper.h" #include "chrome/browser/sync/test/integration/sync_test.h" using passwords_helper::AddLogin; using passwords_helper::CreateTestPasswordForm; using passwords_helper::GetLogins; using passwords_helper::GetPasswordCount; using passwords_helper::GetPasswordStore; using passwords_helper::UpdateLogin; static const int kNumPasswords = 150; class PasswordsSyncPerfTest : public SyncTest { public: PasswordsSyncPerfTest() : SyncTest(TWO_CLIENT), password_number_(0) {} // Adds |num_logins| new unique passwords to |profile|. void AddLogins(int profile, int num_logins); // Updates the password for all logins for |profile|. void UpdateLogins(int profile); // Removes all logins for |profile|. void RemoveLogins(int profile); private: // Returns a new unique login. webkit_glue::PasswordForm NextLogin(); // Returns a new unique password value. std::string NextPassword(); int password_number_; DISALLOW_COPY_AND_ASSIGN(PasswordsSyncPerfTest); }; void PasswordsSyncPerfTest::AddLogins(int profile, int num_logins) { for (int i = 0; i < num_logins; ++i) { AddLogin(GetPasswordStore(profile), NextLogin()); } } void PasswordsSyncPerfTest::UpdateLogins(int profile) { std::vector<webkit_glue::PasswordForm> logins; GetLogins(GetPasswordStore(profile), logins); for (std::vector<webkit_glue::PasswordForm>::iterator it = logins.begin(); it != logins.end(); ++it) { (*it).password_value = ASCIIToUTF16(NextPassword()); UpdateLogin(GetPasswordStore(profile), (*it)); } } void PasswordsSyncPerfTest::RemoveLogins(int profile) { passwords_helper::RemoveLogins(GetPasswordStore(profile)); } webkit_glue::PasswordForm PasswordsSyncPerfTest::NextLogin() { return CreateTestPasswordForm(password_number_++); } std::string PasswordsSyncPerfTest::NextPassword() { return base::StringPrintf("password%d", password_number_++); } // Flaky on Windows, timing out on Mac, see http://crbug.com/105999 #if defined(OS_WIN) || defined(OS_MAC) #define MAYBE_P0 DISABLED_P0 #else #define MAYBE_P0 P0 #endif IN_PROC_BROWSER_TEST_F(PasswordsSyncPerfTest, MAYBE_P0) { ASSERT_TRUE(SetupSync()) << "SetupSync() failed."; // TCM ID - 7367749. AddLogins(0, kNumPasswords); base::TimeDelta dt = SyncTimingHelper::TimeMutualSyncCycle(GetClient(0), GetClient(1)); ASSERT_EQ(kNumPasswords, GetPasswordCount(1)); SyncTimingHelper::PrintResult("passwords", "add_passwords", dt); // TCM ID - 7365093. UpdateLogins(0); dt = SyncTimingHelper::TimeMutualSyncCycle(GetClient(0), GetClient(1)); ASSERT_EQ(kNumPasswords, GetPasswordCount(1)); SyncTimingHelper::PrintResult("passwords", "update_passwords", dt); // TCM ID - 7557852 RemoveLogins(0); dt = SyncTimingHelper::TimeMutualSyncCycle(GetClient(0), GetClient(1)); ASSERT_EQ(0, GetPasswordCount(1)); SyncTimingHelper::PrintResult("passwords", "delete_passwords", dt); }
Disable passwords perf test on Mac/Win
[Sync] Disable passwords perf test on Mac/Win BUG=105999 TEST= TBR=rsimha Review URL: http://codereview.chromium.org/8763015 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@112376 0039d316-1c4b-4281-b951-d872f2087c98
C++
bsd-3-clause
mogoweb/chromium-crosswalk,krieger-od/nwjs_chromium.src,timopulkkinen/BubbleFish,littlstar/chromium.src,nacl-webkit/chrome_deps,keishi/chromium,patrickm/chromium.src,dushu1203/chromium.src,hujiajie/pa-chromium,keishi/chromium,axinging/chromium-crosswalk,Just-D/chromium-1,hgl888/chromium-crosswalk-efl,ltilve/chromium,markYoungH/chromium.src,chuan9/chromium-crosswalk,fujunwei/chromium-crosswalk,littlstar/chromium.src,Just-D/chromium-1,hgl888/chromium-crosswalk-efl,dushu1203/chromium.src,mogoweb/chromium-crosswalk,Jonekee/chromium.src,crosswalk-project/chromium-crosswalk-efl,ChromiumWebApps/chromium,keishi/chromium,zcbenz/cefode-chromium,pozdnyakov/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,chuan9/chromium-crosswalk,Pluto-tv/chromium-crosswalk,keishi/chromium,zcbenz/cefode-chromium,Chilledheart/chromium,patrickm/chromium.src,mohamed--abdel-maksoud/chromium.src,Pluto-tv/chromium-crosswalk,zcbenz/cefode-chromium,robclark/chromium,chuan9/chromium-crosswalk,Jonekee/chromium.src,Jonekee/chromium.src,nacl-webkit/chrome_deps,hujiajie/pa-chromium,littlstar/chromium.src,mogoweb/chromium-crosswalk,junmin-zhu/chromium-rivertrail,anirudhSK/chromium,markYoungH/chromium.src,zcbenz/cefode-chromium,dednal/chromium.src,mogoweb/chromium-crosswalk,axinging/chromium-crosswalk,axinging/chromium-crosswalk,dushu1203/chromium.src,crosswalk-project/chromium-crosswalk-efl,Chilledheart/chromium,fujunwei/chromium-crosswalk,axinging/chromium-crosswalk,junmin-zhu/chromium-rivertrail,ChromiumWebApps/chromium,jaruba/chromium.src,anirudhSK/chromium,keishi/chromium,Just-D/chromium-1,mogoweb/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,ltilve/chromium,pozdnyakov/chromium-crosswalk,dednal/chromium.src,Pluto-tv/chromium-crosswalk,ChromiumWebApps/chromium,Fireblend/chromium-crosswalk,dushu1203/chromium.src,mogoweb/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,hgl888/chromium-crosswalk,patrickm/chromium.src,PeterWangIntel/chromium-crosswalk,Pluto-tv/chromium-crosswalk,M4sse/chromium.src,hgl888/chromium-crosswalk-efl,jaruba/chromium.src,axinging/chromium-crosswalk,markYoungH/chromium.src,dednal/chromium.src,anirudhSK/chromium,axinging/chromium-crosswalk,Just-D/chromium-1,pozdnyakov/chromium-crosswalk,littlstar/chromium.src,ChromiumWebApps/chromium,hgl888/chromium-crosswalk,anirudhSK/chromium,Fireblend/chromium-crosswalk,hujiajie/pa-chromium,Fireblend/chromium-crosswalk,bright-sparks/chromium-spacewalk,TheTypoMaster/chromium-crosswalk,fujunwei/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,anirudhSK/chromium,nacl-webkit/chrome_deps,jaruba/chromium.src,timopulkkinen/BubbleFish,krieger-od/nwjs_chromium.src,ltilve/chromium,dednal/chromium.src,rogerwang/chromium,markYoungH/chromium.src,ondra-novak/chromium.src,dednal/chromium.src,ondra-novak/chromium.src,M4sse/chromium.src,ondra-novak/chromium.src,TheTypoMaster/chromium-crosswalk,dednal/chromium.src,robclark/chromium,axinging/chromium-crosswalk,ondra-novak/chromium.src,bright-sparks/chromium-spacewalk,junmin-zhu/chromium-rivertrail,anirudhSK/chromium,anirudhSK/chromium,Chilledheart/chromium,rogerwang/chromium,nacl-webkit/chrome_deps,ChromiumWebApps/chromium,dednal/chromium.src,bright-sparks/chromium-spacewalk,Fireblend/chromium-crosswalk,Fireblend/chromium-crosswalk,junmin-zhu/chromium-rivertrail,dushu1203/chromium.src,hgl888/chromium-crosswalk,hujiajie/pa-chromium,jaruba/chromium.src,krieger-od/nwjs_chromium.src,M4sse/chromium.src,fujunwei/chromium-crosswalk,pozdnyakov/chromium-crosswalk,anirudhSK/chromium,ltilve/chromium,dushu1203/chromium.src,hujiajie/pa-chromium,hgl888/chromium-crosswalk-efl,zcbenz/cefode-chromium,rogerwang/chromium,M4sse/chromium.src,keishi/chromium,dednal/chromium.src,keishi/chromium,Just-D/chromium-1,M4sse/chromium.src,ChromiumWebApps/chromium,pozdnyakov/chromium-crosswalk,nacl-webkit/chrome_deps,ltilve/chromium,pozdnyakov/chromium-crosswalk,jaruba/chromium.src,robclark/chromium,krieger-od/nwjs_chromium.src,Jonekee/chromium.src,ltilve/chromium,timopulkkinen/BubbleFish,M4sse/chromium.src,pozdnyakov/chromium-crosswalk,jaruba/chromium.src,zcbenz/cefode-chromium,zcbenz/cefode-chromium,mohamed--abdel-maksoud/chromium.src,dushu1203/chromium.src,markYoungH/chromium.src,robclark/chromium,Pluto-tv/chromium-crosswalk,markYoungH/chromium.src,mohamed--abdel-maksoud/chromium.src,hgl888/chromium-crosswalk,chuan9/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,junmin-zhu/chromium-rivertrail,Fireblend/chromium-crosswalk,robclark/chromium,nacl-webkit/chrome_deps,dushu1203/chromium.src,littlstar/chromium.src,dushu1203/chromium.src,timopulkkinen/BubbleFish,robclark/chromium,Jonekee/chromium.src,nacl-webkit/chrome_deps,keishi/chromium,markYoungH/chromium.src,bright-sparks/chromium-spacewalk,bright-sparks/chromium-spacewalk,nacl-webkit/chrome_deps,mohamed--abdel-maksoud/chromium.src,mogoweb/chromium-crosswalk,Fireblend/chromium-crosswalk,keishi/chromium,Jonekee/chromium.src,M4sse/chromium.src,TheTypoMaster/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,M4sse/chromium.src,mohamed--abdel-maksoud/chromium.src,rogerwang/chromium,Just-D/chromium-1,patrickm/chromium.src,nacl-webkit/chrome_deps,pozdnyakov/chromium-crosswalk,littlstar/chromium.src,krieger-od/nwjs_chromium.src,bright-sparks/chromium-spacewalk,ChromiumWebApps/chromium,Pluto-tv/chromium-crosswalk,hujiajie/pa-chromium,robclark/chromium,hgl888/chromium-crosswalk,hujiajie/pa-chromium,robclark/chromium,timopulkkinen/BubbleFish,Chilledheart/chromium,fujunwei/chromium-crosswalk,anirudhSK/chromium,Just-D/chromium-1,hgl888/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,jaruba/chromium.src,PeterWangIntel/chromium-crosswalk,rogerwang/chromium,bright-sparks/chromium-spacewalk,TheTypoMaster/chromium-crosswalk,hujiajie/pa-chromium,keishi/chromium,ltilve/chromium,chuan9/chromium-crosswalk,dednal/chromium.src,ondra-novak/chromium.src,ondra-novak/chromium.src,patrickm/chromium.src,krieger-od/nwjs_chromium.src,Pluto-tv/chromium-crosswalk,dushu1203/chromium.src,zcbenz/cefode-chromium,fujunwei/chromium-crosswalk,littlstar/chromium.src,ChromiumWebApps/chromium,zcbenz/cefode-chromium,dushu1203/chromium.src,robclark/chromium,timopulkkinen/BubbleFish,dednal/chromium.src,Jonekee/chromium.src,ChromiumWebApps/chromium,crosswalk-project/chromium-crosswalk-efl,PeterWangIntel/chromium-crosswalk,hgl888/chromium-crosswalk-efl,krieger-od/nwjs_chromium.src,Fireblend/chromium-crosswalk,junmin-zhu/chromium-rivertrail,Chilledheart/chromium,PeterWangIntel/chromium-crosswalk,markYoungH/chromium.src,patrickm/chromium.src,crosswalk-project/chromium-crosswalk-efl,fujunwei/chromium-crosswalk,littlstar/chromium.src,mohamed--abdel-maksoud/chromium.src,markYoungH/chromium.src,patrickm/chromium.src,TheTypoMaster/chromium-crosswalk,Pluto-tv/chromium-crosswalk,pozdnyakov/chromium-crosswalk,ltilve/chromium,hgl888/chromium-crosswalk-efl,Chilledheart/chromium,ltilve/chromium,Jonekee/chromium.src,Fireblend/chromium-crosswalk,timopulkkinen/BubbleFish,chuan9/chromium-crosswalk,mogoweb/chromium-crosswalk,timopulkkinen/BubbleFish,rogerwang/chromium,krieger-od/nwjs_chromium.src,mogoweb/chromium-crosswalk,dednal/chromium.src,hujiajie/pa-chromium,PeterWangIntel/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,nacl-webkit/chrome_deps,ChromiumWebApps/chromium,hgl888/chromium-crosswalk,timopulkkinen/BubbleFish,PeterWangIntel/chromium-crosswalk,markYoungH/chromium.src,mohamed--abdel-maksoud/chromium.src,ChromiumWebApps/chromium,Just-D/chromium-1,hujiajie/pa-chromium,hgl888/chromium-crosswalk-efl,Jonekee/chromium.src,M4sse/chromium.src,TheTypoMaster/chromium-crosswalk,jaruba/chromium.src,pozdnyakov/chromium-crosswalk,Pluto-tv/chromium-crosswalk,anirudhSK/chromium,TheTypoMaster/chromium-crosswalk,chuan9/chromium-crosswalk,axinging/chromium-crosswalk,hgl888/chromium-crosswalk,Chilledheart/chromium,chuan9/chromium-crosswalk,anirudhSK/chromium,hgl888/chromium-crosswalk,timopulkkinen/BubbleFish,rogerwang/chromium,junmin-zhu/chromium-rivertrail,hgl888/chromium-crosswalk-efl,hgl888/chromium-crosswalk-efl,zcbenz/cefode-chromium,mogoweb/chromium-crosswalk,markYoungH/chromium.src,junmin-zhu/chromium-rivertrail,axinging/chromium-crosswalk,M4sse/chromium.src,Jonekee/chromium.src,Chilledheart/chromium,ChromiumWebApps/chromium,jaruba/chromium.src,bright-sparks/chromium-spacewalk,fujunwei/chromium-crosswalk,Just-D/chromium-1,Chilledheart/chromium,rogerwang/chromium,ondra-novak/chromium.src,patrickm/chromium.src,axinging/chromium-crosswalk,ondra-novak/chromium.src,krieger-od/nwjs_chromium.src,keishi/chromium,krieger-od/nwjs_chromium.src,jaruba/chromium.src,pozdnyakov/chromium-crosswalk,krieger-od/nwjs_chromium.src,zcbenz/cefode-chromium,patrickm/chromium.src,crosswalk-project/chromium-crosswalk-efl,anirudhSK/chromium,rogerwang/chromium,fujunwei/chromium-crosswalk,ondra-novak/chromium.src,junmin-zhu/chromium-rivertrail,PeterWangIntel/chromium-crosswalk,bright-sparks/chromium-spacewalk,nacl-webkit/chrome_deps,mohamed--abdel-maksoud/chromium.src,junmin-zhu/chromium-rivertrail,chuan9/chromium-crosswalk,junmin-zhu/chromium-rivertrail,hgl888/chromium-crosswalk-efl,axinging/chromium-crosswalk,jaruba/chromium.src,rogerwang/chromium,mohamed--abdel-maksoud/chromium.src,timopulkkinen/BubbleFish,hujiajie/pa-chromium,Jonekee/chromium.src,mohamed--abdel-maksoud/chromium.src,M4sse/chromium.src,robclark/chromium
7124c9b0875f8fa9ee8887050dc8508f2f0803a7
variants/units/zephyrus/unit_data.hpp
variants/units/zephyrus/unit_data.hpp
#ifndef UNIT_DATA_HPP_ #define UNIT_DATA_HPP_ #include "communication/communicator.hpp" #include "estimator/world_estimator.hpp" #include "estimator/atmospheric_location_estimator.hpp" #include "estimator/dcm_attitude_estimator.hpp" #include "filesystem/logger.hpp" #include "input/offboard_input_source.hpp" #include "motor/multirotor_tri_motor_mapper.hpp" #include "sensor/sensor_measurements.hpp" #include "system/multirotor_vehicle_system.hpp" #include "util/optional.hpp" #include "variant/platform.hpp" static const float MOTOR_PWM_MIN = 0.53f; static const float MOTOR_PWM_MAX = 0.93f; static const float MOTOR_PWM_SAFE = 0.30f; // TODO(yoos): Use actual values. static const float SERVO_PWM_MIN = 0.53f; static const float SERVO_PWM_MAX = 0.93f; static const float SERVO_PWM_SAFE = 0.30f; struct UnitData { PWMDeviceGroup<3> motors; PWMDeviceGroup<1> servos; MultirotorTriMotorMapper motorMapper; WorldEstimator world; AtmosphericLocationEstimator location; DCMAttitudeEstimator attitude; OffboardInputSource inputSource; MultirotorVehicleSystem system; UnitData(Platform& platform, Communicator& communicator, Logger& logger) : motors(platform.get<PWMPlatform>(), { 0, 1, 2 }, // channels { 0.0f, 0.0f, 0.0f }, // offsets 0.0f, 1.0f, // input range MOTOR_PWM_MIN, MOTOR_PWM_MAX, MOTOR_PWM_SAFE // output range ), servos(platform.get<PWMPlatform>(), { 4 }, // channels { 0.0f }, // offsets 0.0f, 1.0f, // input range SERVO_PWM_MIN, SERVO_PWM_MAX, SERVO_PWM_SAFE // output range ), motorMapper(motors, servos, communicator, logger), location(communicator, logger), attitude(communicator, logger), world(location, attitude, communicator, logger), inputSource(communicator), system(platform.get<Gyroscope>(), platform.get<Accelerometer>(), std::experimental::make_optional(&platform.get<Barometer>()), std::experimental::make_optional(&platform.get<GPS>()), std::experimental::nullopt, // No magnetometer world, inputSource, motorMapper, communicator, logger, platform) { } }; #endif
#ifndef UNIT_DATA_HPP_ #define UNIT_DATA_HPP_ #include "communication/communicator.hpp" #include "estimator/world_estimator.hpp" #include "estimator/atmospheric_location_estimator.hpp" #include "estimator/dcm_attitude_estimator.hpp" #include "filesystem/logger.hpp" #include "input/ppm_input_source.hpp" #include "motor/multirotor_tri_motor_mapper.hpp" #include "sensor/sensor_measurements.hpp" #include "system/multirotor_vehicle_system.hpp" #include "util/optional.hpp" #include "variant/platform.hpp" static const float MOTOR_PWM_MIN = 0.53f; static const float MOTOR_PWM_MAX = 0.93f; static const float MOTOR_PWM_SAFE = 0.30f; // TODO(yoos): Use actual values. static const float SERVO_PWM_MIN = 0.53f; static const float SERVO_PWM_MAX = 0.93f; static const float SERVO_PWM_SAFE = 0.30f; struct UnitData { PWMDeviceGroup<3> motors; PWMDeviceGroup<1> servos; MultirotorTriMotorMapper motorMapper; WorldEstimator world; AtmosphericLocationEstimator location; DCMAttitudeEstimator attitude; PPMInputSource inputSource; MultirotorVehicleSystem system; UnitData(Platform& platform, Communicator& communicator, Logger& logger) : motors(platform.get<PWMPlatform>(), { 0, 1, 2 }, // channels { 0.0f, 0.0f, 0.0f }, // offsets 0.0f, 1.0f, // input range MOTOR_PWM_MIN, MOTOR_PWM_MAX, MOTOR_PWM_SAFE // output range ), servos(platform.get<PWMPlatform>(), { 4 }, // channels { 0.0f }, // offsets 0.0f, 1.0f, // input range SERVO_PWM_MIN, SERVO_PWM_MAX, SERVO_PWM_SAFE // output range ), motorMapper(motors, servos, communicator, logger), location(communicator, logger), attitude(communicator, logger), world(location, attitude, communicator, logger), inputSource(), system(platform.get<Gyroscope>(), platform.get<Accelerometer>(), std::experimental::make_optional(&platform.get<Barometer>()), std::experimental::make_optional(&platform.get<GPS>()), std::experimental::nullopt, // No magnetometer world, inputSource, motorMapper, communicator, logger, platform) { } }; #endif
Use PPM input source.
Use PPM input source.
C++
mit
OSURoboticsClub/aerial_control,OSURoboticsClub/aerial_control,OSURoboticsClub/aerial_control
cf58f133d421befb8282fcd833402d21e1c5fdbf
vm/src/platform/ilib_os_interface.cpp
vm/src/platform/ilib_os_interface.cpp
/****************************************************************************** * Copyright (c) 2008 - 2010 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * David Ungar, IBM Research - Initial Implementation * Sam Adams, IBM Research - Initial Implementation * Stefan Marr, Vrije Universiteit Brussel - Port to x86 Multi-Core Systems ******************************************************************************/ # if On_Tilera #include "headers.h" static ILib_OS_Interface::OS_Heap us_heap; static bool created = false; void* ILib_OS_Interface::malloc_in_mem(int alignment, int size) { if (alignment == 0) alignment = ilib_mem_get_cacheline_size(); if (!created) { int err = ilib_mem_create_heap(ILIB_MEM_UNCACHEABLE | ILIB_MEM_SHARED, &us_heap); abort_if_error("malloc_in_mem", err); created = true; } void* r = ilib_mem_memalign_heap(us_heap, alignment, size); if (r == NULL) fatal("malloc_in_mem"); return r; } void ILib_OS_Interface::start_processes(void (*helper_core_main)(), char* argv[]) { // go parallel; one core returns; others run helper_core_main fn # warning STEFAN: refactor, add a setter method for initializing those values. Logical_Core::remaining = ilib_proc_remaining(); Logical_Core::group_size = ilib_group_size(ILIB_GROUP_SIBLINGS); Memory_Semantics::_my_rank = ilib_group_rank(ILIB_GROUP_SIBLINGS); Memory_Semantics::_my_rank_mask = 1LL << u_int64(Memory_Semantics::_my_rank); CPU_Coordinate::_my_x = udn_tile_coord_x(); CPU_Coordinate::_my_y = udn_tile_coord_y(); if (Logical_Core::group_size == 1 && Logical_Core::group_size < Logical_Core::num_cores) { ilibProcParam params; memset(&params, 0, sizeof(params)); params.num_procs = Logical_Core::num_cores; params.binary_name = NULL; params.argv = argv; params.tiles.x = params.tiles.y = 0; if (CPU_Coordinate::width * CPU_Coordinate::height == Logical_Core::num_cores) { params.tiles.width = CPU_Coordinate::width; params.tiles.height = CPU_Coordinate::height; } else { params.tiles.width = 0; params.tiles.height = 0; } // skip params.init_block/size lprintf("Will ask for num_proc: %d on w:%d;h:%d\n", params.num_procs, params.tiles.width, params.tiles.height); int err = ilib_proc_exec(1, &params); abort_if_error("exec", err); ilib_die("impossible"); } Logical_Core::initialize_all_cores(); Memory_Semantics::_my_core = &logical_cores[Memory_Semantics::_my_rank]; Memory_Semantics::initialize_interpreter(); Memory_Semantics::initialize_local_interpreter(); ILib_Message_Queue::setup_channels(); if (Measure_Communication) Logical_Core::my_core()->message_queue.measure_communication(); if (CPU_Coordinate::is_center() != (CPU_Coordinate::center_rank == Logical_Core::my_rank())) fatal("center_rank is wrong\n"); if (Logical_Core::running_on_main()) { fprintf(stdout, "spawned %d helpers\n", Logical_Core::group_size - 1); return; } else { (*helper_core_main)(); char buf[BUFSIZ]; Logical_Core::my_print_string(buf, sizeof(buf)); lprintf( "helper finsihed: %s\n", buf); rvm_exit(); } } int ILib_OS_Interface::abort_if_error(const char* msg, int err) { if (err >= 0) return err; lprintf( "%s failed: %s\n", msg, ilib_debug_strerror(err)); ilib_abort(); return 0; } # endif // On_Tilera
/****************************************************************************** * Copyright (c) 2008 - 2010 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * David Ungar, IBM Research - Initial Implementation * Sam Adams, IBM Research - Initial Implementation * Stefan Marr, Vrije Universiteit Brussel - Port to x86 Multi-Core Systems ******************************************************************************/ # if On_Tilera #include "headers.h" static ILib_OS_Interface::OS_Heap us_heap; static bool created = false; void* ILib_OS_Interface::malloc_in_mem(int alignment, int size) { if (alignment == 0) alignment = ilib_mem_get_cacheline_size(); if (!created) { int err = ilib_mem_create_heap(ILIB_MEM_UNCACHEABLE | ILIB_MEM_SHARED, &us_heap); abort_if_error("malloc_in_mem", err); created = true; } void* r = ilib_mem_memalign_heap(us_heap, alignment, size); if (r == NULL) fatal("malloc_in_mem"); return r; } void ILib_OS_Interface::start_processes(void (*helper_core_main)(), char* argv[]) { // go parallel; one core returns; others run helper_core_main fn # warning STEFAN: refactor, add a setter method for initializing those values. Logical_Core::remaining = ilib_proc_remaining(); Logical_Core::group_size = ilib_group_size(ILIB_GROUP_SIBLINGS); Memory_Semantics::_my_rank = ilib_group_rank(ILIB_GROUP_SIBLINGS); Memory_Semantics::_my_rank_mask = 1LL << u_int64(Memory_Semantics::_my_rank); CPU_Coordinate::_my_x = udn_tile_coord_x(); CPU_Coordinate::_my_y = udn_tile_coord_y(); if (Logical_Core::group_size == 1 && Logical_Core::group_size < Logical_Core::num_cores) { ilibProcParam params; memset(&params, 0, sizeof(params)); params.num_procs = Logical_Core::num_cores; params.binary_name = NULL; params.argv = argv; params.tiles.x = params.tiles.y = 0; params.tiles.width = CPU_Coordinate::width; params.tiles.height = CPU_Coordinate::height; // skip params.init_block/size lprintf("Will ask for num_proc: %d on w:%d;h:%d\n", params.num_procs, params.tiles.width, params.tiles.height); int err = ilib_proc_exec(1, &params); abort_if_error("exec", err); ilib_die("impossible"); } Logical_Core::initialize_all_cores(); Memory_Semantics::_my_core = &logical_cores[Memory_Semantics::_my_rank]; Memory_Semantics::initialize_interpreter(); Memory_Semantics::initialize_local_interpreter(); ILib_Message_Queue::setup_channels(); if (Measure_Communication) Logical_Core::my_core()->message_queue.measure_communication(); // lprintf("is_center: %s, center_rank: %d, main_rank: %d, my_rank: %d\n", // CPU_Coordinate::is_center() ? "true" : "false", // CPU_Coordinate::center_rank, // Logical_Core::main_rank, // Logical_Core::my_rank()); // // lprintf("center_x: %d, center_y: %d, my_x: %d, my_y: %d\n", // Tile_CPU_Coordinate::center_x, // Tile_CPU_Coordinate::center_y, // Tile_CPU_Coordinate::_my_x, // Tile_CPU_Coordinate::_my_y); if (CPU_Coordinate::is_center() != (CPU_Coordinate::center_rank == Logical_Core::my_rank())) fatal("center_rank is wrong\n"); if (Logical_Core::running_on_main()) { fprintf(stdout, "spawned %d helpers\n", Logical_Core::group_size - 1); return; } else { (*helper_core_main)(); char buf[BUFSIZ]; Logical_Core::my_print_string(buf, sizeof(buf)); lprintf( "helper finsihed: %s\n", buf); rvm_exit(); } } int ILib_OS_Interface::abort_if_error(const char* msg, int err) { if (err >= 0) return err; lprintf( "%s failed: %s\n", msg, ilib_debug_strerror(err)); ilib_abort(); return 0; } # endif // On_Tilera
Set bounding box for requested cores also if the box is bigger than number of requested cores.
Set bounding box for requested cores also if the box is bigger than number of requested cores. This fixes problems with allocating cores and knowing the central core id. The library does just the right thing by allocating the correct number of processes in the requested grid.
C++
epl-1.0
smarr/OmniVM,smarr/OmniVM,smarr/OmniVM,smarr/OmniVM,smarr/OmniVM,smarr/OmniVM,smarr/OmniVM,smarr/OmniVM
131e85e7fb1dfa7ff33761eb60440dbb84a72123
vtk/vtkXdmfRenderWindowInteractor.cxx
vtk/vtkXdmfRenderWindowInteractor.cxx
/*******************************************************************/ /* XDMF */ /* eXtensible Data Model and Format */ /* */ /* Id : Id */ /* Date : $Date$ */ /* Version : $Revision$ */ /* */ /* Author: */ /* Jerry A. Clarke */ /* [email protected] */ /* US Army Research Laboratory */ /* Aberdeen Proving Ground, MD */ /* */ /* Copyright @ 2002 US Army Research Laboratory */ /* All Rights Reserved */ /* See Copyright.txt or http://www.arl.hpc.mil/ice for details */ /* */ /* This software is distributed WITHOUT ANY WARRANTY; without */ /* even the implied warranty of MERCHANTABILITY or FITNESS */ /* FOR A PARTICULAR PURPOSE. See the above copyright notice */ /* for more information. */ /* */ /*******************************************************************/ #include <vtkXdmfRenderWindowInteractor.h> #include <vtkObjectFactory.h> #include <vtkCommand.h> //---------------------------------------------------------------------------- vtkXdmfRenderWindowInteractor* vtkXdmfRenderWindowInteractor::New() { // First try to create the object from the vtkObjectFactory vtkObject* ret = vtkObjectFactory::CreateInstance("vtkXdmfRenderWindowInteractor"); if(ret) { return (vtkXdmfRenderWindowInteractor*)ret; } // If the factory was unable to create the object, then create it here. return new vtkXdmfRenderWindowInteractor; } void vtkXdmfRenderWindowInteractor::Start( int Block ) { if ( Block ) { #if !defined(CYGWIN) vtkXRenderWindowInteractor::Start(); #else vtkWin32RenderWindowInteractor::Start(); #endif } else { this->LoopOnce(); } } void vtkXdmfRenderWindowInteractor::LoopOnce( ) { #if !defined(CYGWIN) XEvent event; if (!this->Initialized) { this->Initialize(); } if (! this->Initialized ) { return; } this->BreakLoopFlag = 0; while( XtAppPending( this->App )) { XtAppNextEvent(this->App, &event); XtDispatchEvent(&event); } #endif }
/*******************************************************************/ /* XDMF */ /* eXtensible Data Model and Format */ /* */ /* Id : Id */ /* Date : $Date$ */ /* Version : $Revision$ */ /* */ /* Author: */ /* Jerry A. Clarke */ /* [email protected] */ /* US Army Research Laboratory */ /* Aberdeen Proving Ground, MD */ /* */ /* Copyright @ 2002 US Army Research Laboratory */ /* All Rights Reserved */ /* See Copyright.txt or http://www.arl.hpc.mil/ice for details */ /* */ /* This software is distributed WITHOUT ANY WARRANTY; without */ /* even the implied warranty of MERCHANTABILITY or FITNESS */ /* FOR A PARTICULAR PURPOSE. See the above copyright notice */ /* for more information. */ /* */ /*******************************************************************/ #include <vtkXdmfRenderWindowInteractor.h> #include <vtkObjectFactory.h> #include <vtkCommand.h> //---------------------------------------------------------------------------- vtkXdmfRenderWindowInteractor* vtkXdmfRenderWindowInteractor::New() { // First try to create the object from the vtkObjectFactory vtkObject* ret = vtkObjectFactory::CreateInstance("vtkXdmfRenderWindowInteractor"); if(ret) { return (vtkXdmfRenderWindowInteractor*)ret; } // If the factory was unable to create the object, then create it here. return new vtkXdmfRenderWindowInteractor; } void vtkXdmfRenderWindowInteractor::Start( int Block ) { if ( Block ) { // Check for WIN32 but without Cygwin with X11 #if defined(_WIN32) && !defined(VTK_USE_OGLR) vtkWin32RenderWindowInteractor::Start(); #else vtkXRenderWindowInteractor::Start(); #endif } else { this->LoopOnce(); } } void vtkXdmfRenderWindowInteractor::LoopOnce( ) { // Check for WIN32 but without Cygwin with X11 #if defined(_WIN32) && !defined(VTK_USE_OGLR) #else XEvent event; if (!this->Initialized) { this->Initialize(); } if (! this->Initialized ) { return; } this->BreakLoopFlag = 0; while( XtAppPending( this->App )) { XtAppNextEvent(this->App, &event); XtDispatchEvent(&event); } #endif }
Improve checks for Win32
BUG: Improve checks for Win32
C++
bsd-3-clause
cjh1/Xdmf2,cjh1/Xdmf2,cjh1/Xdmf2
29e6a345e58aaab8f40b04d6850c930b4433e12a
src/app/clusters/bindings/BindingManager.cpp
src/app/clusters/bindings/BindingManager.cpp
/* * * Copyright (c) 2022 Project CHIP Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <app/clusters/bindings/BindingManager.h> #include <app/util/binding-table.h> #include <credentials/FabricTable.h> namespace { class BindingFabricTableDelegate : public chip::FabricTableDelegate { void OnFabricDeletedFromStorage(chip::CompressedFabricId compressedFabricId, chip::FabricIndex fabricIndex) { for (uint8_t i = 0; i < EMBER_BINDING_TABLE_SIZE; i++) { EmberBindingTableEntry entry; emberGetBinding(i, &entry); if (entry.fabricIndex == fabricIndex) { ChipLogProgress(Zcl, "Remove binding for fabric %d\n", entry.fabricIndex); entry.type = EMBER_UNUSED_BINDING; } } chip::BindingManager::GetInstance().FabricRemoved(compressedFabricId, fabricIndex); } // Intentionally left blank void OnFabricRetrievedFromStorage(chip::FabricInfo * fabricInfo) {} // Intentionally left blank void OnFabricPersistedToStorage(chip::FabricInfo * fabricInfo) {} }; BindingFabricTableDelegate gFabricTableDelegate; } // namespace namespace { chip::PeerId PeerIdForNode(chip::FabricTable & fabricTable, chip::FabricIndex fabric, chip::NodeId node) { chip::FabricInfo * fabricInfo = fabricTable.FindFabricWithIndex(fabric); if (fabricInfo == nullptr) { return chip::PeerId(); } return fabricInfo->GetPeerIdForNode(node); } } // namespace namespace chip { BindingManager BindingManager::sBindingManager; CHIP_ERROR BindingManager::UnicastBindingCreated(const EmberBindingTableEntry & bindingEntry) { return EstablishConnection(bindingEntry.fabricIndex, bindingEntry.nodeId); } CHIP_ERROR BindingManager::UnicastBindingRemoved(uint8_t bindingEntryId) { EmberBindingTableEntry entry{}; emberGetBinding(bindingEntryId, &entry); mPendingNotificationMap.RemoveEntry(bindingEntryId); return CHIP_NO_ERROR; } void BindingManager::SetAppServer(Server * appServer) { mAppServer = appServer; mAppServer->GetFabricTable().AddFabricDelegate(&gFabricTableDelegate); } CHIP_ERROR BindingManager::EstablishConnection(FabricIndex fabric, NodeId node) { VerifyOrReturnError(mAppServer != nullptr, CHIP_ERROR_INCORRECT_STATE); PeerId peer = PeerIdForNode(mAppServer->GetFabricTable(), fabric, node); VerifyOrReturnError(peer.GetNodeId() != kUndefinedNodeId, CHIP_ERROR_NOT_FOUND); CHIP_ERROR error = mAppServer->GetCASESessionManager()->FindOrEstablishSession(peer, &mOnConnectedCallback, &mOnConnectionFailureCallback); if (error == CHIP_ERROR_NO_MEMORY) { // Release the least recently used entry // TODO: Some reference counting mechanism shall be added the CASESessionManager // so that other session clients don't get accidentally closed. FabricIndex fabricToRemove; NodeId nodeToRemove; if (mPendingNotificationMap.FindLRUConnectPeer(&fabricToRemove, &nodeToRemove) == CHIP_NO_ERROR) { mPendingNotificationMap.RemoveAllEntriesForNode(fabricToRemove, nodeToRemove); PeerId lruPeer = PeerIdForNode(mAppServer->GetFabricTable(), fabricToRemove, nodeToRemove); mAppServer->GetCASESessionManager()->ReleaseSession(lruPeer); // Now retry error = mAppServer->GetCASESessionManager()->FindOrEstablishSession(peer, &mOnConnectedCallback, &mOnConnectionFailureCallback); } } return error; } void BindingManager::HandleDeviceConnected(void * context, OperationalDeviceProxy * device) { BindingManager * manager = static_cast<BindingManager *>(context); manager->HandleDeviceConnected(device); } void BindingManager::HandleDeviceConnected(OperationalDeviceProxy * device) { FabricIndex fabricToRemove = kUndefinedFabricIndex; NodeId nodeToRemove = kUndefinedNodeId; for (const PendingNotificationEntry & pendingNotification : mPendingNotificationMap) { EmberBindingTableEntry entry; emberGetBinding(pendingNotification.mBindingEntryId, &entry); PeerId peer = PeerIdForNode(mAppServer->GetFabricTable(), entry.fabricIndex, entry.nodeId); if (device->GetPeerId() == peer) { fabricToRemove = entry.fabricIndex; nodeToRemove = entry.nodeId; mBoundDeviceChangedHandler(&entry, device, pendingNotification.mContext); } } mPendingNotificationMap.RemoveAllEntriesForNode(fabricToRemove, nodeToRemove); } void BindingManager::HandleDeviceConnectionFailure(void * context, PeerId peerId, CHIP_ERROR error) { BindingManager * manager = static_cast<BindingManager *>(context); manager->HandleDeviceConnectionFailure(peerId, error); } void BindingManager::HandleDeviceConnectionFailure(PeerId peerId, CHIP_ERROR error) { // Simply release the entry, the connection will be re-established as needed. ChipLogError(AppServer, "Failed to establish connection to node 0x" ChipLogFormatX64, ChipLogValueX64(peerId.GetNodeId())); mAppServer->GetCASESessionManager()->ReleaseSession(peerId); } void BindingManager::FabricRemoved(CompressedFabricId compressedFabricId, FabricIndex fabricIndex) { mPendingNotificationMap.RemoveAllEntriesForFabric(fabricIndex); mAppServer->GetCASESessionManager()->ReleaseSessionForFabric(compressedFabricId); } CHIP_ERROR BindingManager::NotifyBoundClusterChanged(EndpointId endpoint, ClusterId cluster, void * context) { VerifyOrReturnError(mAppServer != nullptr, CHIP_ERROR_INCORRECT_STATE); for (uint8_t i = 0; i < EMBER_BINDING_TABLE_SIZE; i++) { EmberBindingTableEntry entry; if (emberGetBinding(i, &entry) == EMBER_SUCCESS && entry.type != EMBER_UNUSED_BINDING && entry.local == endpoint && entry.clusterId == cluster) { if (entry.type == EMBER_UNICAST_BINDING) { FabricInfo * fabricInfo = mAppServer->GetFabricTable().FindFabricWithIndex(entry.fabricIndex); VerifyOrReturnError(fabricInfo != nullptr, CHIP_ERROR_NOT_FOUND); PeerId peer = fabricInfo->GetPeerIdForNode(entry.nodeId); OperationalDeviceProxy * peerDevice = mAppServer->GetCASESessionManager()->FindExistingSession(peer); if (peerDevice != nullptr && mBoundDeviceChangedHandler) { // We already have an active connection mBoundDeviceChangedHandler(&entry, peerDevice, context); } else { mPendingNotificationMap.AddPendingNotification(i, context); ReturnErrorOnFailure(EstablishConnection(entry.fabricIndex, entry.nodeId)); } } else if (entry.type == EMBER_MULTICAST_BINDING) { mBoundDeviceChangedHandler(&entry, nullptr, context); } } } return CHIP_NO_ERROR; } } // namespace chip
/* * * Copyright (c) 2022 Project CHIP Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <app/clusters/bindings/BindingManager.h> #include <app/util/binding-table.h> #include <credentials/FabricTable.h> namespace { class BindingFabricTableDelegate : public chip::FabricTableDelegate { void OnFabricDeletedFromStorage(chip::CompressedFabricId compressedFabricId, chip::FabricIndex fabricIndex) { for (uint8_t i = 0; i < EMBER_BINDING_TABLE_SIZE; i++) { EmberBindingTableEntry entry; emberGetBinding(i, &entry); if (entry.fabricIndex == fabricIndex) { ChipLogProgress(Zcl, "Remove binding for fabric %d\n", entry.fabricIndex); entry.type = EMBER_UNUSED_BINDING; } } chip::BindingManager::GetInstance().FabricRemoved(compressedFabricId, fabricIndex); } // Intentionally left blank void OnFabricRetrievedFromStorage(chip::FabricInfo * fabricInfo) {} // Intentionally left blank void OnFabricPersistedToStorage(chip::FabricInfo * fabricInfo) {} }; BindingFabricTableDelegate gFabricTableDelegate; } // namespace namespace { chip::PeerId PeerIdForNode(chip::FabricTable & fabricTable, chip::FabricIndex fabric, chip::NodeId node) { chip::FabricInfo * fabricInfo = fabricTable.FindFabricWithIndex(fabric); if (fabricInfo == nullptr) { return chip::PeerId(); } return fabricInfo->GetPeerIdForNode(node); } } // namespace namespace chip { BindingManager BindingManager::sBindingManager; CHIP_ERROR BindingManager::UnicastBindingCreated(const EmberBindingTableEntry & bindingEntry) { return EstablishConnection(bindingEntry.fabricIndex, bindingEntry.nodeId); } CHIP_ERROR BindingManager::UnicastBindingRemoved(uint8_t bindingEntryId) { EmberBindingTableEntry entry{}; emberGetBinding(bindingEntryId, &entry); mPendingNotificationMap.RemoveEntry(bindingEntryId); return CHIP_NO_ERROR; } void BindingManager::SetAppServer(Server * appServer) { mAppServer = appServer; mAppServer->GetFabricTable().AddFabricDelegate(&gFabricTableDelegate); } CHIP_ERROR BindingManager::EstablishConnection(FabricIndex fabric, NodeId node) { VerifyOrReturnError(mAppServer != nullptr, CHIP_ERROR_INCORRECT_STATE); PeerId peer = PeerIdForNode(mAppServer->GetFabricTable(), fabric, node); VerifyOrReturnError(peer.GetNodeId() != kUndefinedNodeId, CHIP_ERROR_NOT_FOUND); CHIP_ERROR error = mAppServer->GetCASESessionManager()->FindOrEstablishSession(peer, &mOnConnectedCallback, &mOnConnectionFailureCallback); if (error == CHIP_ERROR_NO_MEMORY) { // Release the least recently used entry // TODO: Some reference counting mechanism shall be added the CASESessionManager // so that other session clients don't get accidentally closed. FabricIndex fabricToRemove; NodeId nodeToRemove; if (mPendingNotificationMap.FindLRUConnectPeer(&fabricToRemove, &nodeToRemove) == CHIP_NO_ERROR) { mPendingNotificationMap.RemoveAllEntriesForNode(fabricToRemove, nodeToRemove); PeerId lruPeer = PeerIdForNode(mAppServer->GetFabricTable(), fabricToRemove, nodeToRemove); mAppServer->GetCASESessionManager()->ReleaseSession(lruPeer); // Now retry error = mAppServer->GetCASESessionManager()->FindOrEstablishSession(peer, &mOnConnectedCallback, &mOnConnectionFailureCallback); } } return error; } void BindingManager::HandleDeviceConnected(void * context, OperationalDeviceProxy * device) { BindingManager * manager = static_cast<BindingManager *>(context); manager->HandleDeviceConnected(device); } void BindingManager::HandleDeviceConnected(OperationalDeviceProxy * device) { FabricIndex fabricToRemove = kUndefinedFabricIndex; NodeId nodeToRemove = kUndefinedNodeId; // Note: not using a const ref here, because the mPendingNotificationMap // iterator returns things by value anyway. for (PendingNotificationEntry pendingNotification : mPendingNotificationMap) { EmberBindingTableEntry entry; emberGetBinding(pendingNotification.mBindingEntryId, &entry); PeerId peer = PeerIdForNode(mAppServer->GetFabricTable(), entry.fabricIndex, entry.nodeId); if (device->GetPeerId() == peer) { fabricToRemove = entry.fabricIndex; nodeToRemove = entry.nodeId; mBoundDeviceChangedHandler(&entry, device, pendingNotification.mContext); } } mPendingNotificationMap.RemoveAllEntriesForNode(fabricToRemove, nodeToRemove); } void BindingManager::HandleDeviceConnectionFailure(void * context, PeerId peerId, CHIP_ERROR error) { BindingManager * manager = static_cast<BindingManager *>(context); manager->HandleDeviceConnectionFailure(peerId, error); } void BindingManager::HandleDeviceConnectionFailure(PeerId peerId, CHIP_ERROR error) { // Simply release the entry, the connection will be re-established as needed. ChipLogError(AppServer, "Failed to establish connection to node 0x" ChipLogFormatX64, ChipLogValueX64(peerId.GetNodeId())); mAppServer->GetCASESessionManager()->ReleaseSession(peerId); } void BindingManager::FabricRemoved(CompressedFabricId compressedFabricId, FabricIndex fabricIndex) { mPendingNotificationMap.RemoveAllEntriesForFabric(fabricIndex); mAppServer->GetCASESessionManager()->ReleaseSessionForFabric(compressedFabricId); } CHIP_ERROR BindingManager::NotifyBoundClusterChanged(EndpointId endpoint, ClusterId cluster, void * context) { VerifyOrReturnError(mAppServer != nullptr, CHIP_ERROR_INCORRECT_STATE); for (uint8_t i = 0; i < EMBER_BINDING_TABLE_SIZE; i++) { EmberBindingTableEntry entry; if (emberGetBinding(i, &entry) == EMBER_SUCCESS && entry.type != EMBER_UNUSED_BINDING && entry.local == endpoint && entry.clusterId == cluster) { if (entry.type == EMBER_UNICAST_BINDING) { FabricInfo * fabricInfo = mAppServer->GetFabricTable().FindFabricWithIndex(entry.fabricIndex); VerifyOrReturnError(fabricInfo != nullptr, CHIP_ERROR_NOT_FOUND); PeerId peer = fabricInfo->GetPeerIdForNode(entry.nodeId); OperationalDeviceProxy * peerDevice = mAppServer->GetCASESessionManager()->FindExistingSession(peer); if (peerDevice != nullptr && mBoundDeviceChangedHandler) { // We already have an active connection mBoundDeviceChangedHandler(&entry, peerDevice, context); } else { mPendingNotificationMap.AddPendingNotification(i, context); ReturnErrorOnFailure(EstablishConnection(entry.fabricIndex, entry.nodeId)); } } else if (entry.type == EMBER_MULTICAST_BINDING) { mBoundDeviceChangedHandler(&entry, nullptr, context); } } } return CHIP_NO_ERROR; } } // namespace chip
Fix compilation on newer clang. (#14868)
Fix compilation on newer clang. (#14868) There's a warning about thinking you are iterating without copying when you get copied anyway that this code was triggering.
C++
apache-2.0
nestlabs/connectedhomeip,nestlabs/connectedhomeip,project-chip/connectedhomeip,nestlabs/connectedhomeip,nestlabs/connectedhomeip,nestlabs/connectedhomeip,project-chip/connectedhomeip,project-chip/connectedhomeip,project-chip/connectedhomeip,nestlabs/connectedhomeip,project-chip/connectedhomeip,project-chip/connectedhomeip,nestlabs/connectedhomeip
4dbfca6923afc7738ac980dd95ebf279dea78128
src/api.cpp
src/api.cpp
/// /// @file api.cpp /// primecount's C++ API. /// /// Copyright (C) 2020 Kim Walisch, <[email protected]> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <primecount.hpp> #include <primecount-internal.hpp> #include <primesieve.hpp> #include <gourdon.hpp> #include <int128_t.hpp> #include <cmath> #include <limits> #include <string> #include <stdint.h> #ifdef _OPENMP #include <omp.h> #endif using namespace std; namespace { #ifdef _OPENMP int threads_ = 0; #endif } // namespace namespace primecount { int64_t pi(int64_t x) { return pi(x, get_num_threads()); } int64_t pi(int64_t x, int threads) { // For [0, 10^5] Legendre's algorithm runs fastest if (x <= (int64_t) 1e5) return pi_legendre(x, threads); // For ]10^5, 5*10^7] Meissel's algorithm runs fastest if (x <= (int64_t) 5e7) return pi_meissel(x, threads); // Above 10^7 Xavier Gourdon's algorithm runs fastest return pi_gourdon_64(x, threads); } #ifdef HAVE_INT128_T int128_t pi(int128_t x) { return pi(x, get_num_threads()); } int128_t pi(int128_t x, int threads) { // use 64-bit if possible if (x <= numeric_limits<int64_t>::max()) return pi((int64_t) x, threads); return pi_gourdon_128(x, threads); } #endif string pi(const string& x) { return pi(x, get_num_threads()); } string pi(const string& x, int threads) { maxint_t n = to_maxint(x); maxint_t res = pi(n, threads); return to_str(res); } int64_t pi_deleglise_rivat(int64_t x, int threads) { return pi_deleglise_rivat_64(x, threads); } int64_t pi_gourdon(int64_t x, int threads) { return pi_gourdon_64(x, threads); } #ifdef HAVE_INT128_T int128_t pi_deleglise_rivat(int128_t x, int threads) { // use 64-bit if possible if (x <= numeric_limits<int64_t>::max()) return pi_deleglise_rivat_64((int64_t) x, threads); else return pi_deleglise_rivat_128(x, threads); } int128_t pi_gourdon(int128_t x, int threads) { // use 64-bit if possible if (x <= numeric_limits<int64_t>::max()) return pi_gourdon_64((int64_t) x, threads); else return pi_gourdon_128(x, threads); } #endif int64_t nth_prime(int64_t n) { return nth_prime(n, get_num_threads()); } int64_t phi(int64_t x, int64_t a) { return phi(x, a, get_num_threads()); } string primecount_version() { return PRIMECOUNT_VERSION; } /// Returns the largest x supported by pi(x). /// The S2_hard, P2, B and D functions are limited by: /// x / y <= 2^62, with y = x^(1/3) * alpha_y /// Hence x^(2/3) / alpha_y <= 2^62 /// x <= (2^62 * alpha_y)^(3/2) /// maxint_t get_max_x(double alpha_y) { #ifdef HAVE_INT128_T double max_x = pow((1ull << 62) * alpha_y, 3.0 / 2.0); return (int128_t) max_x; #else unused_param(alpha_y); return numeric_limits<int64_t>::max(); #endif } std::string get_max_x() { #ifdef HAVE_INT128_T // 10^31 return "10000000000000000000000000000000"; #else // 2^63-1 return "9223372036854775807"; #endif } int get_num_threads() { #ifdef _OPENMP if (threads_) return threads_; else return max(1, omp_get_max_threads()); #else return 1; #endif } void set_num_threads(int threads) { #ifdef _OPENMP threads_ = in_between(1, threads, omp_get_max_threads()); #endif primesieve::set_num_threads(threads); } } // namespace
/// /// @file api.cpp /// primecount's C++ API. /// /// Copyright (C) 2020 Kim Walisch, <[email protected]> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <primecount.hpp> #include <primecount-internal.hpp> #include <primesieve.hpp> #include <gourdon.hpp> #include <int128_t.hpp> #include <cmath> #include <limits> #include <string> #include <stdint.h> #ifdef _OPENMP #include <omp.h> #endif using namespace std; namespace { #ifdef _OPENMP int threads_ = 0; #endif } // namespace namespace primecount { int64_t pi(int64_t x) { return pi(x, get_num_threads()); } int64_t pi(int64_t x, int threads) { // For [0, 10^5] Legendre's algorithm runs fastest if (x <= (int64_t) 1e5) return pi_legendre(x, threads); // For ]10^5, 5*10^7] Meissel's algorithm runs fastest if (x <= (int64_t) 5e7) return pi_meissel(x, threads); // For large x Gourdon's algorithm runs fastest return pi_gourdon_64(x, threads); } #ifdef HAVE_INT128_T int128_t pi(int128_t x) { return pi(x, get_num_threads()); } int128_t pi(int128_t x, int threads) { // use 64-bit if possible if (x <= numeric_limits<int64_t>::max()) return pi((int64_t) x, threads); return pi_gourdon_128(x, threads); } #endif string pi(const string& x) { return pi(x, get_num_threads()); } string pi(const string& x, int threads) { maxint_t n = to_maxint(x); maxint_t res = pi(n, threads); return to_str(res); } int64_t pi_deleglise_rivat(int64_t x, int threads) { return pi_deleglise_rivat_64(x, threads); } int64_t pi_gourdon(int64_t x, int threads) { return pi_gourdon_64(x, threads); } #ifdef HAVE_INT128_T int128_t pi_deleglise_rivat(int128_t x, int threads) { // use 64-bit if possible if (x <= numeric_limits<int64_t>::max()) return pi_deleglise_rivat_64((int64_t) x, threads); else return pi_deleglise_rivat_128(x, threads); } int128_t pi_gourdon(int128_t x, int threads) { // use 64-bit if possible if (x <= numeric_limits<int64_t>::max()) return pi_gourdon_64((int64_t) x, threads); else return pi_gourdon_128(x, threads); } #endif int64_t nth_prime(int64_t n) { return nth_prime(n, get_num_threads()); } int64_t phi(int64_t x, int64_t a) { return phi(x, a, get_num_threads()); } string primecount_version() { return PRIMECOUNT_VERSION; } /// Returns the largest x supported by pi(x). /// The S2_hard, P2, B and D functions are limited by: /// x / y <= 2^62, with y = x^(1/3) * alpha_y /// Hence x^(2/3) / alpha_y <= 2^62 /// x <= (2^62 * alpha_y)^(3/2) /// maxint_t get_max_x(double alpha_y) { #ifdef HAVE_INT128_T double max_x = pow((1ull << 62) * alpha_y, 3.0 / 2.0); return (int128_t) max_x; #else unused_param(alpha_y); return numeric_limits<int64_t>::max(); #endif } std::string get_max_x() { #ifdef HAVE_INT128_T // 10^31 return "10000000000000000000000000000000"; #else // 2^63-1 return "9223372036854775807"; #endif } int get_num_threads() { #ifdef _OPENMP if (threads_) return threads_; else return max(1, omp_get_max_threads()); #else return 1; #endif } void set_num_threads(int threads) { #ifdef _OPENMP threads_ = in_between(1, threads, omp_get_max_threads()); #endif primesieve::set_num_threads(threads); } } // namespace
Update comment
Update comment
C++
bsd-2-clause
kimwalisch/primecount,kimwalisch/primecount,kimwalisch/primecount
9f7a7a5e3afba6cec1d11ed8a7ee848c76140e06
You-DataStore-Tests/internal/internal_datastore_test.cpp
You-DataStore-Tests/internal/internal_datastore_test.cpp
#include "stdafx.h" #include "CppUnitTest.h" #include "../dummy_values.h" #include "internal/operations/erase_operation.h" #include "internal/operations/post_operation.h" #include "internal/operations/put_operation.h" #include "internal/internal_datastore.h" using Assert = Microsoft::VisualStudio::CppUnitTestFramework::Assert; namespace You { namespace DataStore { namespace UnitTests { using DataStore = You::DataStore::Internal::DataStore; /// Unit Test Class for DataStore class TEST_CLASS(DataStoreTest) { public: TEST_METHOD(beginTransactionAddToTransactionStack) { DataStore& sut = DataStore::get(); Assert::IsTrue(sut.transactionStack.empty()); Transaction t(sut.begin()); Assert::AreEqual(1U, sut.transactionStack.size()); } TEST_METHOD(pushedOperationsAddedToTransactionOperationsQueue) { DataStore& sut = DataStore::get(); Transaction t(sut.begin()); sut.post(10, task1); Assert::AreEqual(1U, t->operationsQueue.size()); sut.put(10, task2); Assert::AreEqual(2U, t->operationsQueue.size()); sut.erase(10); Assert::AreEqual(3U, t->operationsQueue.size()); } TEST_METHOD(commitChangesDocumentTree) { DataStore& sut = DataStore::get(); sut.document.reset(); sut.saveData(); assert(sut.document.first_child.empty()); Transaction t(sut.begin()); sut.post(10, task1); // document must not change without commit Assert::IsTrue(sut.document.first_child().empty()); t.commit(); // document changes after commit Assert::IsFalse(sut.document.first_child().empty()); Transaction t2(sut.begin()); sut.erase(10); // document must not change without commit Assert::IsFalse(sut.document.first_child().empty()); t2.commit(); // document changes after commit Assert::IsTrue(sut.document.first_child().empty()); } TEST_METHOD(rollbackCleanUpTransactionStack) { DataStore& sut = DataStore::get(); Transaction t(sut.begin()); Assert::AreEqual(1U, sut.transactionStack.size()); t.rollback(); Assert::AreEqual(0U, sut.transactionStack.size()); } TEST_METHOD(getAllTasksFromTreeCorrectly) { DataStore& sut = DataStore::get(); sut.document.append_child(L"task"). append_child(pugi::xml_node_type::node_pcdata).set_value(L"what"); std::vector<SerializedTask> result = sut.getAllTask(); Assert::AreEqual(1U, result.size()); // Clean up sut.document.reset(); sut.saveData(); } TEST_METHOD(getAllTaskFromFile) { DataStore& sut = DataStore::get(); sut.document.reset(); // create mock sut.document.append_child(L"task"). append_child(pugi::xml_node_type::node_pcdata).set_value(L"what"); std::vector<SerializedTask> result = sut.getAllTask(); Assert::AreEqual(1U, result.size()); // Clean up sut.document.reset(); sut.saveData(); } TEST_METHOD(saveThenLoad) { DataStore& sut = DataStore::get(); sut.document.append_child(L"task"). append_child(pugi::xml_node_type::node_pcdata).set_value(L"what"); bool result = sut.saveData(); Assert::IsTrue(result); sut.loadData(); std::wstring value = sut.document.child(L"task").child_value(); Assert::AreEqual(std::wstring(L"what"), value); sut.document.reset(); sut.saveData(); } TEST_METHOD(pushOperationToTransactionWithoutDataStore) { Internal::Transaction sut; std::unique_ptr<Internal::IOperation> post = std::make_unique<Internal::PostOperation>(0, task1); sut.push(std::move(post)); Assert::AreEqual(1U, sut.operationsQueue.size()); std::unique_ptr<Internal::IOperation> put = std::make_unique<Internal::PutOperation>(0, task1); sut.push(std::move(put)); Assert::AreEqual(2U, sut.operationsQueue.size()); std::unique_ptr<Internal::IOperation> erase = std::make_unique<Internal::EraseOperation>(0); sut.push(std::move(erase)); Assert::AreEqual(3U, sut.operationsQueue.size()); sut.operationsQueue.clear(); } TEST_METHOD(mergeOperationsQueueIsAppend) { boost::ptr_deque<Internal::IOperation> q1; boost::ptr_deque<Internal::IOperation> q2; std::unique_ptr<Internal::IOperation> post = std::make_unique<Internal::PostOperation>(0, task1); std::unique_ptr<Internal::IOperation> erase = std::make_unique<Internal::EraseOperation>(0); q1.push_back(post.get()); q2.push_back(erase.get()); Internal::Transaction sut; sut.mergeOperationsQueue(q1); Assert::AreEqual(1U, sut.mergedOperationsQueue.size()); sut.mergeOperationsQueue(q2); Assert::AreEqual(2U, sut.mergedOperationsQueue.size()); // TODO(digawp): Check if the order is correct } }; } // namespace UnitTests } // namespace DataStore } // namespace You
#include "stdafx.h" #include "CppUnitTest.h" #include "../dummy_values.h" #include "internal/operations/erase_operation.h" #include "internal/operations/post_operation.h" #include "internal/operations/put_operation.h" #include "internal/internal_datastore.h" using Assert = Microsoft::VisualStudio::CppUnitTestFramework::Assert; namespace You { namespace DataStore { namespace UnitTests { using DataStore = You::DataStore::Internal::DataStore; /// Unit Test Class for DataStore class TEST_CLASS(DataStoreTest) { public: TEST_METHOD(beginTransactionAddToTransactionStack) { DataStore& sut = DataStore::get(); Assert::IsTrue(sut.transactionStack.empty()); Transaction t(sut.begin()); Assert::AreEqual(1U, sut.transactionStack.size()); } TEST_METHOD(pushedOperationsAddedToTransactionOperationsQueue) { DataStore& sut = DataStore::get(); Transaction t(sut.begin()); sut.post(10, task1); Assert::AreEqual(1U, t->operationsQueue.size()); sut.put(10, task2); Assert::AreEqual(2U, t->operationsQueue.size()); sut.erase(10); Assert::AreEqual(3U, t->operationsQueue.size()); } TEST_METHOD(commitChangesDocumentTree) { DataStore& sut = DataStore::get(); sut.document.reset(); sut.saveData(); assert(sut.document.first_child.empty()); Transaction t(sut.begin()); sut.post(10, task1); // document must not change without commit Assert::IsTrue(sut.document.first_child().empty()); t.commit(); // document changes after commit Assert::IsFalse(sut.document.first_child().empty()); Transaction t2(sut.begin()); sut.erase(10); // document must not change without commit Assert::IsFalse(sut.document.first_child().empty()); t2.commit(); // document changes after commit Assert::IsTrue(sut.document.first_child().empty()); } TEST_METHOD(rollbackCleanUpTransactionStack) { DataStore& sut = DataStore::get(); Transaction t(sut.begin()); Assert::AreEqual(1U, sut.transactionStack.size()); t.rollback(); Assert::AreEqual(0U, sut.transactionStack.size()); } TEST_METHOD(getAllTasksFromTreeCorrectly) { DataStore& sut = DataStore::get(); sut.document.append_child(L"task"). append_child(pugi::xml_node_type::node_pcdata).set_value(L"what"); std::vector<SerializedTask> result = sut.getAllTask(); Assert::AreEqual(1U, result.size()); // Clean up sut.document.reset(); sut.saveData(); } TEST_METHOD(getAllTaskFromFile) { DataStore& sut = DataStore::get(); sut.document.reset(); // create mock sut.document.append_child(L"task"). append_child(pugi::xml_node_type::node_pcdata).set_value(L"what"); std::vector<SerializedTask> result = sut.getAllTask(); Assert::AreEqual(1U, result.size()); // Clean up sut.document.reset(); sut.saveData(); } TEST_METHOD(saveThenLoad) { DataStore& sut = DataStore::get(); sut.document.append_child(L"task"). append_child(pugi::xml_node_type::node_pcdata).set_value(L"what"); bool result = sut.saveData(); Assert::IsTrue(result); sut.loadData(); std::wstring value = sut.document.child(L"task").child_value(); Assert::AreEqual(std::wstring(L"what"), value); sut.document.reset(); sut.saveData(); } TEST_METHOD(pushOperationToTransactionWithoutDataStore) { Internal::Transaction sut; std::unique_ptr<Internal::IOperation> post = std::make_unique<Internal::PostOperation>(0, task1); sut.push(std::move(post)); Assert::AreEqual(1U, sut.operationsQueue.size()); std::unique_ptr<Internal::IOperation> put = std::make_unique<Internal::PutOperation>(0, task1); sut.push(std::move(put)); Assert::AreEqual(2U, sut.operationsQueue.size()); std::unique_ptr<Internal::IOperation> erase = std::make_unique<Internal::EraseOperation>(0); sut.push(std::move(erase)); Assert::AreEqual(3U, sut.operationsQueue.size()); sut.operationsQueue.clear(); } /* TEST_METHOD(mergeOperationsQueueIsAppend) { boost::ptr_deque<Internal::IOperation> q1; boost::ptr_deque<Internal::IOperation> q2; std::unique_ptr<Internal::IOperation> post = std::make_unique<Internal::PostOperation>(0, task1); std::unique_ptr<Internal::IOperation> erase = std::make_unique<Internal::EraseOperation>(0); q1.push_back(post.get()); q2.push_back(erase.get()); Internal::Transaction sut; sut.mergeOperationsQueue(q1); Assert::AreEqual(1U, sut.mergedOperationsQueue.size()); sut.mergeOperationsQueue(q2); Assert::AreEqual(2U, sut.mergedOperationsQueue.size()); // TODO(digawp): Check if the order is correct }*/ }; } // namespace UnitTests } // namespace DataStore } // namespace You
Remove test that causes appveyor to crash
Remove test that causes appveyor to crash
C++
mit
cs2103aug2014-w10-1c/main,cs2103aug2014-w10-1c/main
5a9b43d48378fb0592811e9b340aabd3d8041ca6
win32gdk/src/TGWin32ProxyBase.cxx
win32gdk/src/TGWin32ProxyBase.cxx
// @(#)root/win32gdk:$Name: $:$Id: TGWin32ProxyBase.cxx,v 1.14 2004/05/10 15:06:35 brun Exp $ // Author: Valeriy Onuchin 08/08/2003 /************************************************************************* * Copyright (C) 1995-2001, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // Proxy classes provide thread-safe interface to global objects. // // For example: TGWin32VirtualXProxy (to gVirtualX), // TGWin32InterpreterProxy (to gInterpreter). // // Proxy object creates callback object and posts a windows message to // "processing thread". When windows message is received callback // ("real method") is executed. // // For example: // gVirtualX->ClearWindow() // // - callback object created containing pointer to function // corresponding TGWin32::ClearWindow() method // - message to "processing thread" (main thread) is posted // - TGWin32::ClearWindow() method is executed inside main thread // - thread containing gVirtualX proxy object waits for reply // from main thread that TGWin32::ClearWindow() is completed. // // Howto create proxy class: // // 1. Naming. // name of proxy = TGWin32 + the name of "virtual base class" + Proxy // // e.g. TGWin32VirtualXProxy = TGWin32 + VirtualX + Proxy // // 2. Definition of global object // As example check definition and implementation of // gVirtualX, gInterpreter global objects // // 3. Class definition. // proxy class must be inherited from "virtual base class" and // TGWin32ProxyBase class. For example: // // class TGWin32VirtualX : public TVirtualX , public TGWin32ProxyBase // // 4. Constructors, destructor, extra methods. // - constructors and destructor of proxy class do nothing // - proxy class must contain two extra static methods // RealObject(), ProxyObject(). Each of them return pointer to object // of virtual base class. // // For example: // static TInterpreter *RealObject(); // static TInterpreter *ProxyObject(); // // 5. Implementation // TGWin32ProxyDefs.h file contains a set of macros which very // simplify implementation. // - RETURN_PROXY_OBJECT macro implements ProxyObject() method, e.g. // RETURN_PROXY_OBJECT(Interpreter) // - the names of other macros say about itself. // // For example: // VOID_METHOD_ARG0(Interpreter,ClearFileBusy,1) // void TGWin32InterpreterProxy::ClearFileBusy() // // RETURN_METHOD_ARG0_CONST(VirtualX,Visual_t,GetVisual) // Visual_t TGWin32VirtualXProxy::GetVisual() const // // RETURN_METHOD_ARG2(VirtualX,Int_t,OpenPixmap,UInt_t,w,UInt_t,h) // Int_t TGWin32VirtualXProxy::OpenPixmap,UInt_t w,UInt_t h) // // - few methods has _LOCK part in the name // VOID_METHOD_ARG1_LOCK(Interpreter,CreateListOfMethods,TClass*,cl) // // /////////////////////////////////////////////////////////////////////////////// #include "Windows4Root.h" #include <windows.h> #include "TGWin32ProxyBase.h" #include "TRefCnt.h" #include "TList.h" #include "TGWin32.h" //////////////////////////////////////////////////////////////////////////////// class TGWin32CallBackObject : public TObject { public: TGWin32CallBack fCallBack; // callback function (called by GUI thread) void *fParam; // arguments passed to/from callback function TGWin32CallBackObject(TGWin32CallBack cb,void *p):fCallBack(cb),fParam(p) {} ~TGWin32CallBackObject() { if (fParam) delete fParam; } }; //////////////////////////////////////////////////////////////////////////////// class TGWin32ProxyBasePrivate { public: HANDLE fEvent; // event used for syncronization TGWin32ProxyBasePrivate(); ~TGWin32ProxyBasePrivate(); }; //______________________________________________________________________________ TGWin32ProxyBasePrivate::TGWin32ProxyBasePrivate() { // ctor fEvent = ::CreateEvent(NULL, TRUE, FALSE, NULL); } //______________________________________________________________________________ TGWin32ProxyBasePrivate::~TGWin32ProxyBasePrivate() { // dtor if (fEvent) ::CloseHandle(fEvent); fEvent = 0; } ULong_t TGWin32ProxyBase::fgPostMessageId = 0; ULong_t TGWin32ProxyBase::fgPingMessageId = 0; ULong_t TGWin32ProxyBase::fgMainThreadId = 0; Long_t TGWin32ProxyBase::fgLock = 0; UInt_t TGWin32ProxyBase::fMaxResponseTime = 0; //////////////////////////////////////////////////////////////////////////////// //______________________________________________________________________________ TGWin32ProxyBase::TGWin32ProxyBase() { // ctor fCallBack = 0; fParam = 0; fListOfCallBacks = new TList(); fBatchLimit = 100; fId = ::GetCurrentThreadId(); fPimpl = new TGWin32ProxyBasePrivate(); if (!fgPostMessageId) fgPostMessageId = ::RegisterWindowMessage("TGWin32ProxyBase::Post"); if (!fgPingMessageId) fgPingMessageId = ::RegisterWindowMessage("TGWin32ProxyBase::Ping"); } //______________________________________________________________________________ TGWin32ProxyBase::~TGWin32ProxyBase() { // dtor fListOfCallBacks->Delete(); delete fListOfCallBacks; fListOfCallBacks = 0; delete fPimpl; } //______________________________________________________________________________ void TGWin32ProxyBase::Lock() { // enter critical section TGWin32::Lock(); } //______________________________________________________________________________ void TGWin32ProxyBase::Unlock() { // leave critical section TGWin32::Unlock(); } //______________________________________________________________________________ void TGWin32ProxyBase::GlobalLock() { // lock any proxy (client thread) if (IsGloballyLocked()) return; ::InterlockedIncrement(&fgLock); } //______________________________________________________________________________ void TGWin32ProxyBase::GlobalUnlock() { // unlock any proxy (client thread) if (!IsGloballyLocked()) return; ::InterlockedDecrement(&fgLock); } //______________________________________________________________________________ Bool_t TGWin32ProxyBase::Ping() { // send ping messsage to server thread return ::PostThreadMessage(fgMainThreadId, fgPingMessageId, (WPARAM)0, 0L); } //______________________________________________________________________________ Double_t TGWin32ProxyBase::GetMilliSeconds() { // returns elapsed time in milliseconds with microseconds precision static LARGE_INTEGER freq; static Bool_t first = kTRUE; LARGE_INTEGER count; static Double_t overhead = 0; if (first) { LARGE_INTEGER count0; ::QueryPerformanceFrequency(&freq); ::QueryPerformanceCounter(&count0); if (1) { Double_t dummy; dummy = ((Double_t)count0.QuadPart - overhead)*1000./((Double_t)freq.QuadPart); } ::QueryPerformanceCounter(&count); overhead = (Double_t)count.QuadPart - (Double_t)count0.QuadPart; first = kFALSE; } ::QueryPerformanceCounter(&count); return ((Double_t)count.QuadPart - overhead)*1000./((Double_t)freq.QuadPart); } //______________________________________________________________________________ void TGWin32ProxyBase::ExecuteCallBack(Bool_t sync) { // Executes all batched callbacks and the latest callback // This method is executed by server thread // process batched callbacks if (fListOfCallBacks && fListOfCallBacks->GetSize()) { TIter next(fListOfCallBacks); TGWin32CallBackObject *obj; while ((obj = (TGWin32CallBackObject*)next())) { obj->fCallBack(obj->fParam); // execute callback } } if (sync) { if (fCallBack) fCallBack(fParam); ::SetEvent(fPimpl->fEvent); } } //______________________________________________________________________________ Bool_t TGWin32ProxyBase::ForwardCallBack(Bool_t sync) { // if sync is kTRUE: // - post message to main thread. // - execute callbacks from fListOfCallBacks // - wait for response // else // - add callback to fListOfCallBacks // // returns kTRUE if callback execution is delayed (batched) Int_t wait = 0; if (!fgMainThreadId) return kFALSE; while (IsGloballyLocked()) { Ping(); ::SleepEx(10, 1); // take a rest if (!fgMainThreadId) return kFALSE; // server thread terminated } Bool_t batch = !sync && (fListOfCallBacks->GetSize()<fBatchLimit); if (batch) { fListOfCallBacks->Add(new TGWin32CallBackObject(fCallBack, fParam)); return kTRUE; } while (!::PostThreadMessage(fgMainThreadId, fgPostMessageId, (WPARAM)this, 0L)) { // wait because there is a chance that message queue does not exist yet ::SleepEx(50, 1); if (wait++ > 5) return kFALSE; // failed to post } // limiting wait time DWORD res = ::WaitForSingleObject(fPimpl->fEvent, fMaxResponseTime); ::ResetEvent(fPimpl->fEvent); if (res == WAIT_TIMEOUT) { // server thread is blocked GlobalLock(); return kTRUE; } fListOfCallBacks->Delete(); return kFALSE; } //______________________________________________________________________________ void TGWin32ProxyBase::SendExitMessage() { // send exit message to server thread ::PostThreadMessage(fgMainThreadId, WM_QUIT, 0, 0L); }
// @(#)root/win32gdk:$Name: $:$Id: TGWin32ProxyBase.cxx,v 1.15 2005/04/21 18:46:25 brun Exp $ // Author: Valeriy Onuchin 08/08/2003 /************************************************************************* * Copyright (C) 1995-2001, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // Proxy classes provide thread-safe interface to global objects. // // For example: TGWin32VirtualXProxy (to gVirtualX), // TGWin32InterpreterProxy (to gInterpreter). // // Proxy object creates callback object and posts a windows message to // "processing thread". When windows message is received callback // ("real method") is executed. // // For example: // gVirtualX->ClearWindow() // // - callback object created containing pointer to function // corresponding TGWin32::ClearWindow() method // - message to "processing thread" (main thread) is posted // - TGWin32::ClearWindow() method is executed inside main thread // - thread containing gVirtualX proxy object waits for reply // from main thread that TGWin32::ClearWindow() is completed. // // Howto create proxy class: // // 1. Naming. // name of proxy = TGWin32 + the name of "virtual base class" + Proxy // // e.g. TGWin32VirtualXProxy = TGWin32 + VirtualX + Proxy // // 2. Definition of global object // As example check definition and implementation of // gVirtualX, gInterpreter global objects // // 3. Class definition. // proxy class must be inherited from "virtual base class" and // TGWin32ProxyBase class. For example: // // class TGWin32VirtualX : public TVirtualX , public TGWin32ProxyBase // // 4. Constructors, destructor, extra methods. // - constructors and destructor of proxy class do nothing // - proxy class must contain two extra static methods // RealObject(), ProxyObject(). Each of them return pointer to object // of virtual base class. // // For example: // static TInterpreter *RealObject(); // static TInterpreter *ProxyObject(); // // 5. Implementation // TGWin32ProxyDefs.h file contains a set of macros which very // simplify implementation. // - RETURN_PROXY_OBJECT macro implements ProxyObject() method, e.g. // RETURN_PROXY_OBJECT(Interpreter) // - the names of other macros say about itself. // // For example: // VOID_METHOD_ARG0(Interpreter,ClearFileBusy,1) // void TGWin32InterpreterProxy::ClearFileBusy() // // RETURN_METHOD_ARG0_CONST(VirtualX,Visual_t,GetVisual) // Visual_t TGWin32VirtualXProxy::GetVisual() const // // RETURN_METHOD_ARG2(VirtualX,Int_t,OpenPixmap,UInt_t,w,UInt_t,h) // Int_t TGWin32VirtualXProxy::OpenPixmap,UInt_t w,UInt_t h) // // - few methods has _LOCK part in the name // VOID_METHOD_ARG1_LOCK(Interpreter,CreateListOfMethods,TClass*,cl) // // /////////////////////////////////////////////////////////////////////////////// #include "Windows4Root.h" #include <windows.h> #include "TGWin32ProxyBase.h" #include "TRefCnt.h" #include "TList.h" #include "TGWin32.h" //////////////////////////////////////////////////////////////////////////////// class TGWin32CallBackObject : public TObject { public: TGWin32CallBack fCallBack; // callback function (called by GUI thread) void *fParam; // arguments passed to/from callback function TGWin32CallBackObject(TGWin32CallBack cb,void *p):fCallBack(cb),fParam(p) {} ~TGWin32CallBackObject() { if (fParam) delete fParam; } }; //////////////////////////////////////////////////////////////////////////////// class TGWin32ProxyBasePrivate { public: HANDLE fEvent; // event used for syncronization TGWin32ProxyBasePrivate(); ~TGWin32ProxyBasePrivate(); }; //______________________________________________________________________________ TGWin32ProxyBasePrivate::TGWin32ProxyBasePrivate() { // ctor fEvent = ::CreateEvent(NULL, TRUE, FALSE, NULL); } //______________________________________________________________________________ TGWin32ProxyBasePrivate::~TGWin32ProxyBasePrivate() { // dtor if (fEvent) ::CloseHandle(fEvent); fEvent = 0; } ULong_t TGWin32ProxyBase::fgPostMessageId = 0; ULong_t TGWin32ProxyBase::fgPingMessageId = 0; ULong_t TGWin32ProxyBase::fgMainThreadId = 0; Long_t TGWin32ProxyBase::fgLock = 0; UInt_t TGWin32ProxyBase::fMaxResponseTime = 0; //////////////////////////////////////////////////////////////////////////////// //______________________________________________________________________________ TGWin32ProxyBase::TGWin32ProxyBase() { // ctor fCallBack = 0; fParam = 0; fListOfCallBacks = new TList(); fBatchLimit = 100; fId = ::GetCurrentThreadId(); fPimpl = new TGWin32ProxyBasePrivate(); if (!fgPostMessageId) fgPostMessageId = ::RegisterWindowMessage("TGWin32ProxyBase::Post"); if (!fgPingMessageId) fgPingMessageId = ::RegisterWindowMessage("TGWin32ProxyBase::Ping"); } //______________________________________________________________________________ TGWin32ProxyBase::~TGWin32ProxyBase() { // dtor fListOfCallBacks->Delete(); delete fListOfCallBacks; fListOfCallBacks = 0; delete fPimpl; } //______________________________________________________________________________ void TGWin32ProxyBase::Lock() { // enter critical section TGWin32::Lock(); } //______________________________________________________________________________ void TGWin32ProxyBase::Unlock() { // leave critical section TGWin32::Unlock(); } //______________________________________________________________________________ void TGWin32ProxyBase::GlobalLock() { // lock any proxy (client thread) if (IsGloballyLocked()) return; ::InterlockedIncrement(&fgLock); } //______________________________________________________________________________ void TGWin32ProxyBase::GlobalUnlock() { // unlock any proxy (client thread) if (!IsGloballyLocked()) return; ::InterlockedDecrement(&fgLock); } //______________________________________________________________________________ Bool_t TGWin32ProxyBase::Ping() { // send ping messsage to server thread return ::PostThreadMessage(fgMainThreadId, fgPingMessageId, (WPARAM)0, 0L); } //______________________________________________________________________________ Double_t TGWin32ProxyBase::GetMilliSeconds() { // returns elapsed time in milliseconds with microseconds precision static LARGE_INTEGER freq; static Bool_t first = kTRUE; LARGE_INTEGER count; static Double_t overhead = 0; if (first) { LARGE_INTEGER count0; ::QueryPerformanceFrequency(&freq); ::QueryPerformanceCounter(&count0); if (1) { Double_t dummy; dummy = ((Double_t)count0.QuadPart - overhead)*1000./((Double_t)freq.QuadPart); } ::QueryPerformanceCounter(&count); overhead = (Double_t)count.QuadPart - (Double_t)count0.QuadPart; first = kFALSE; } ::QueryPerformanceCounter(&count); return ((Double_t)count.QuadPart - overhead)*1000./((Double_t)freq.QuadPart); } //______________________________________________________________________________ void TGWin32ProxyBase::ExecuteCallBack(Bool_t sync) { // Executes all batched callbacks and the latest callback // This method is executed by server thread // process batched callbacks if (fListOfCallBacks && fListOfCallBacks->GetSize()) { TIter next(fListOfCallBacks); TGWin32CallBackObject *obj; while ((obj = (TGWin32CallBackObject*)next())) { obj->fCallBack(obj->fParam); // execute callback } } if (sync) { if (fCallBack) fCallBack(fParam); ::SetEvent(fPimpl->fEvent); } } //______________________________________________________________________________ Bool_t TGWin32ProxyBase::ForwardCallBack(Bool_t sync) { // if sync is kTRUE: // - post message to main thread. // - execute callbacks from fListOfCallBacks // - wait for response // else // - add callback to fListOfCallBacks // // returns kTRUE if callback execution is delayed (batched) Int_t wait = 0; if (!fgMainThreadId) return kFALSE; while (IsGloballyLocked()) { Ping(); ::SleepEx(10, 1); // take a rest if (!fgMainThreadId) return kFALSE; // server thread terminated } Bool_t batch = !sync && (fListOfCallBacks->GetSize()<fBatchLimit); if (batch) { fListOfCallBacks->Add(new TGWin32CallBackObject(fCallBack, fParam)); return kTRUE; } while (!::PostThreadMessage(fgMainThreadId, fgPostMessageId, (WPARAM)this, 0L)) { // wait because there is a chance that message queue does not exist yet ::SleepEx(50, 1); if (wait++ > 5) return kFALSE; // failed to post } // limiting wait time DWORD res = ::WaitForSingleObject(fPimpl->fEvent, INFINITE); //fMaxResponseTime); ::ResetEvent(fPimpl->fEvent); if (res == WAIT_TIMEOUT) { // server thread is blocked GlobalLock(); return kTRUE; } fListOfCallBacks->Delete(); return kFALSE; } //______________________________________________________________________________ void TGWin32ProxyBase::SendExitMessage() { // send exit message to server thread ::PostThreadMessage(fgMainThreadId, WM_QUIT, 0, 0L); }
Fix proposed by Bertrand that seems to fix several type of crashes under Windows when using the GL viewer.
Fix proposed by Bertrand that seems to fix several type of crashes under Windows when using the GL viewer. git-svn-id: ecbadac9c76e8cf640a0bca86f6bd796c98521e3@12163 27541ba8-7e3a-0410-8455-c3a389f83636
C++
lgpl-2.1
dawehner/root,dawehner/root,bbannier/ROOT,dawehner/root,bbannier/ROOT,dawehner/root,dawehner/root,dawehner/root,dawehner/root,bbannier/ROOT,bbannier/ROOT,bbannier/ROOT,bbannier/ROOT,dawehner/root,bbannier/ROOT
fba9b4a9110862ae8d88f74259cd15c52bc03f4c
4/main.cpp
4/main.cpp
#include<mutex> #include<thread> #include<vector> #include<functional> #include<iostream> #include<atomic> //#include"GYAtomicInt.h" using std::thread; using std::cout; int g_i = 0; std::timed_mutex g_i_mutex = {}; std::unique_lock<std::timed_mutex> g_i_mutex_lock = { g_i_mutex, std::defer_lock }; //sai = simple atomic int std::atomic_int g_sai(0); //whether incremented within `thProcTimedMutex` bool g_isMutexInc = false; //------------------------------------------------------------- //Slow solution to the issue: void thProcTimedMutex() { if (g_i_mutex_lock.try_lock_for(std::chrono::milliseconds(18))) { g_isMutexInc = true; //std::timed_mutex has non-recursive ownership semantics: //ONLY ONE lock can be acquired within the same thread //(that's why the lock is not inside the `for` { loop }) for (int k = 0; k < 10; ++k) ++g_i; g_i_mutex_lock.unlock(); }//try lock //OK, but REM: if (g_i_mutex_lock.owns_lock()) g_i_mutex_lock.unlock(); } //Primary (fastest) solution to the issue: void thProcAtomic() { //shake things up, with style, via zzzleep and run: std::this_thread::sleep_for(std::chrono::milliseconds(18)); for (int k = 0; k < 10; ++k) ++g_sai; } //ISSUE : incremented value of `g_i` is unknow void thProc() { //shake things up, with style, via zzzleep and run: std::this_thread::sleep_for(std::chrono::milliseconds(18)); for (int k = 0; k < 10; ++k) ++g_i; } void doShakeThingzUp(std::function<void ()> inThreadProc) { std::vector<std::thread> vTh; //TO_DO *1* : why sleep inside `thProcTimedMutex` causes crash? //shake things up via zzzleep and run: std::this_thread::sleep_for(std::chrono::milliseconds(180)); for (int i = 0; i < 18; ++i) vTh.emplace_back(inThreadProc); for (auto& th : vTh) th.join(); //ONE main thread rules here: cout << (g_i > 0 ? (g_isMutexInc ? "Mutex" : "Unsafe") : "Atomic") << " increment : "; cout << (g_i > 0 ? g_i : g_sai) << "\n"; g_i = 0; g_sai = 0; g_isMutexInc = false; } //============================================ int main() { doShakeThingzUp(thProc); doShakeThingzUp(thProc); doShakeThingzUp(thProc); doShakeThingzUp(thProc); cout << "--------------------------\n"; doShakeThingzUp(thProcAtomic); doShakeThingzUp(thProcAtomic); doShakeThingzUp(thProcAtomic); doShakeThingzUp(thProcAtomic); cout << "\nHit Enter...\n"; getchar(); return 0; }
#include<mutex> #include<thread> #include<vector> #include<functional> #include<iostream> #include<atomic> //#include"GYAtomicInt.h" using std::thread; using std::cout; int g_i = 0; std::timed_mutex g_i_mutex = {}; std::unique_lock<std::timed_mutex> g_i_mutex_lock = { g_i_mutex, std::defer_lock }; //sai = simple atomic int std::atomic_int g_sai(0); //whether incremented within `thProcTimedMutex` bool g_isMutexInc = false; //------------------------------------------------------------- //Slow solution to the issue: void thProcTimedMutex() { if (g_i_mutex_lock.try_lock_for(std::chrono::milliseconds(18))) { g_isMutexInc = true; //std::timed_mutex has non-recursive ownership semantics: //ONLY ONE lock can be acquired within the same thread //(that's why the lock is not inside the `for` { loop }) for (int k = 0; k < 10; ++k) ++g_i; g_i_mutex_lock.unlock(); }//try lock //OK, but REM: if (g_i_mutex_lock.owns_lock()) g_i_mutex_lock.unlock(); } //Primary (fastest) solution to the issue: void thProcAtomic() { //shake things up, with style, via zzzleep and run: std::this_thread::sleep_for(std::chrono::milliseconds(18)); for (int k = 0; k < 10; ++k) ++g_sai; } //ISSUE : incremented value of `g_i` is unknow void thProc() { //shake things up, with style, via zzzleep and run: std::this_thread::sleep_for(std::chrono::milliseconds(18)); for (int k = 0; k < 10; ++k) ++g_i; } void doShakeThingzUp(std::function<void ()> inThreadProc) { std::vector<thread> vTh; //TO_DO *1* : why sleep inside `thProcTimedMutex` causes crash? //shake things up via zzzleep and run: std::this_thread::sleep_for(std::chrono::milliseconds(180)); for (int i = 0; i < 18; ++i) vTh.emplace_back(inThreadProc); for (auto& th : vTh) th.join(); //ONE main thread rules here: cout << (g_i > 0 ? (g_isMutexInc ? "Mutex" : "Unsafe") : "Atomic") << " increment : "; cout << (g_i > 0 ? g_i : g_sai) << "\n"; g_i = 0; g_sai = 0; g_isMutexInc = false; } //============================================ int main() { doShakeThingzUp(thProc); doShakeThingzUp(thProc); doShakeThingzUp(thProc); doShakeThingzUp(thProc); cout << "--------------------------\n"; doShakeThingzUp(thProcAtomic); doShakeThingzUp(thProcAtomic); doShakeThingzUp(thProcAtomic); doShakeThingzUp(thProcAtomic); cout << "\nHit Enter...\n"; getchar(); return 0; }
Update main.cpp
Update main.cpp
C++
mit
grandyossi/quiz-meytal,grandyossi/quiz-meytal
fdd66cd5344bdc4c3b7a8d3cd3ad875c35857408
src/MathEval/GaussFermi.cc
src/MathEval/GaussFermi.cc
/*** DEVSIM Copyright 2021 Devsim LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ***/ #include "GaussFermi.hh" #include "BoostConstants.hh" #include "MiscMathFunc.hh" #ifdef DEVSIM_EXTENDED_PRECISION #include "Float128.hh" #endif #include <cmath> using std::abs; #ifdef DEVSIM_UNIT_TEST #include <iostream> #include <iomanip> #endif template <typename T> T gfi(T zeta, T s) { const T S = s * s; // S is static const T sqrt2 = boost::math::constants::root_two<T>(); static const T sqrt2_pi = sqrt2 * boost::math::constants::one_div_root_pi<T>(); T H = sqrt2 / s * erfc_inv(exp(-0.5 * S)); T value; if (zeta < -S) { const T K = 2 * (1. - H / s * sqrt2_pi * exp(0.5 * S * (1. - H * H))); value = exp(0.5 * S + zeta) / (exp(K*(zeta+S)) + 1); } else { value = 0.5 * erfc(-zeta / (s*sqrt2) * H); } return value; } template <typename T> T dgfidx(T zeta, T s) { const T S = s * s; // S is static const T sqrt2 = boost::math::constants::root_two<T>(); static const T sqrt2_pi = sqrt2 * boost::math::constants::one_div_root_pi<T>(); T H = sqrt2 / s * erfc_inv(exp(-0.5 * S)); T dvalue; if (zeta < -S) { const T K = 2 * (1. - H / s * sqrt2_pi * exp(0.5 * S * (1. - H * H))); const T den_inv = 1. / (exp(K * (S + zeta)) + 1.); dvalue = exp(0.5 * S + zeta) * den_inv * (1. - K*exp(K * (S+zeta)) * den_inv); } else { static const T one_div_root_two_pi = boost::math::constants::one_div_root_two_pi<T>(); dvalue = one_div_root_two_pi * H / s * exp(-0.5 * pow(H*zeta,2)/S); } return dvalue; } //### inverse function for Gaussian Fermi Integral namespace { template <typename T> T good_relerror() { } template <> double good_relerror() { return 1e-12; } #ifdef DEVSIM_EXTENDED_PRECISION template <> float128 good_relerror() { return 1e-31; } #endif } template <typename T> T igfi(T g, T s) { // using the Newton method // The initial guess // perhaps the degenerate approximation // or provided from the last call // improves speed static const T sqrt2 = boost::math::constants::root_two<T>(); T x = 0.0; // This is a good initial guess, but can blow up // x = s * sqrt2 * erf_inv(g*2-1); T rerr = 0.0; size_t i = 0; T f; T fp; T upd; //printf("%d %1.15e %1.15e\n", -1, x, rerr); #ifdef DEVSIM_UNIT_TEST std::cout << std::setprecision(std::numeric_limits<T>::max_digits10); #endif do { f = gfi(x, s) - g; fp = dgfidx(x, s); upd = -f / fp; x += upd; rerr = abs(upd)/(abs(x) + good_relerror<T>()); #ifdef DEVSIM_UNIT_TEST std::cout << i << " " << x << " " << rerr << "\n"; #endif ++i; } while ((rerr > good_relerror<T>()) && (i < 200)); return x; } template <typename T> T digfidx(T g, T s) { return 1.0 / dgfidx(igfi(g,s), s); } template double gfi<double>(double, double); template double dgfidx<double>(double, double); template double igfi<double>(double, double); template double digfidx<double>(double, double); #ifdef DEVSIM_EXTENDED_PRECISION template float128 gfi<float128>(float128, float128); template float128 dgfidx<float128>(float128, float128); template float128 igfi<float128>(float128, float128); template float128 digfidx<float128>(float128, float128); #endif #ifdef DEVSIM_UNIT_TEST template <typename DoubleType> void unit() { DoubleType k_B = 1.380649e-23; DoubleType e = 1.602176634e-19; DoubleType T = 300; DoubleType sigma = 0.10; DoubleType s = (sigma*e)/(k_B*T); DoubleType S = s*s; DoubleType V_0 = 0; DoubleType V_f = V_0-S*k_B*T/e;// # (-0.65372119-1.2) ; DoubleType zeta = (V_f*e-V_0*e)/(k_B*T); // zeta =-0.5 DoubleType zeta_1 = (V_f*e-V_0*e-pow(sigma*e, 2)/k_B*T)/(k_B*T); DoubleType g= gfi(zeta,s); DoubleType dg= dgfidx(zeta,s); DoubleType ginv= igfi(g,s); DoubleType dginv= digfidx(g,s); // print(g,dg,ginv) std::cout << std::setprecision(std::numeric_limits<DoubleType>::max_digits10); std::cout << " zeta\t" << zeta << "\n" << " gfi\t" << g << "\n" << " dgfidx\t" << dg << "\n" << " igfi\t" << ginv << "\n" << " digfidx\t" << dginv << " " << 1.0/dginv << "\n"; } int main() { unit<double>(); #ifdef DEVSIM_EXTENDED_PRECISION unit<float128>(); #endif } #endif
/*** DEVSIM Copyright 2021 Devsim LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ***/ #include "GaussFermi.hh" #include "BoostConstants.hh" #include "MiscMathFunc.hh" #ifdef DEVSIM_EXTENDED_PRECISION #include "Float128.hh" #endif #include <cmath> using std::abs; #ifdef DEVSIM_UNIT_TEST #include <iostream> #include <iomanip> #endif /* Implementation of: https://doi.org/10.1063/1.3374475 @article{doi:10.1063/1.3374475, author = {Paasch,Gernot and Scheinert,Susanne }, title = {Charge carrier density of organics with Gaussian density of states: Analytical approximation for the Gauss–Fermi integral}, journal = {Journal of Applied Physics}, volume = {107}, number = {10}, pages = {104501}, year = {2010}, doi = {10.1063/1.3374475}, URL = { https://doi.org/10.1063/1.3374475 }, eprint = { https://doi.org/10.1063/1.3374475 } } */ namespace { template <typename T> struct MC { static constexpr T sqrt2 = boost::math::constants::root_two<T>(); static constexpr T sqrt2_pi = boost::math::constants::root_two<T>() * boost::math::constants::one_div_root_pi<T>(); static constexpr T one_div_root_two_pi = boost::math::constants::one_div_root_two_pi<T>(); }; template <typename T> inline T calcH(const T &s, const T &S) { const T &sqrt2 = MC<T>::sqrt2; T H = sqrt2 / s * erfc_inv(exp(-0.5 * S)); return H; } template <typename T> inline T calcK(const T &s, const T &S, const T &H) { const T &sqrt2_pi = MC<T>::sqrt2_pi; T K = 2 * (1. - H / s * sqrt2_pi * exp(0.5 * S * (1. - H * H))); return K; } } template <typename T> T gfi(T zeta, T s) { const T &sqrt2 = MC<T>::sqrt2; const T S = s * s; T H = calcH(s, S); T value; if (zeta < -S) { const T K = calcK(s, S, H); value = exp(0.5 * S + zeta) / (exp(K*(zeta+S)) + 1); } else { value = 0.5 * erfc(-zeta / (s*sqrt2) * H); } return value; } template <typename T> T dgfidx(T zeta, T s) { const T &sqrt2 = MC<T>::sqrt2; const T &sqrt2_pi = MC<T>::sqrt2_pi; const T S = s * s; T H = calcH(s, S); T dvalue; if (zeta < -S) { const T K = calcK(s, S, H); const T den_inv = 1. / (exp(K * (S + zeta)) + 1.); dvalue = exp(0.5 * S + zeta) * den_inv * (1. - K*exp(K * (S+zeta)) * den_inv); } else { const T &one_div_root_two_pi = MC<T>::one_div_root_two_pi; dvalue = one_div_root_two_pi * H / s * exp(-0.5 * pow(H*zeta,2)/S); } return dvalue; } //### inverse function for Gaussian Fermi Integral namespace { template <typename T> T good_relerror(); template <> double good_relerror() { return 1e-12; } #ifdef DEVSIM_EXTENDED_PRECISION template <> float128 good_relerror() { return 1e-31; } #endif } template <typename T> T igfi(T g, T s) { // using the Newton method // The initial guess // perhaps the degenerate approximation // or provided from the last call // improves speed T x = 0.0; T rerr = 0.0; size_t i = 0; T f; T fp; T upd; //printf("%d %1.15e %1.15e\n", -1, x, rerr); #ifdef DEVSIM_UNIT_TEST std::cout << std::setprecision(std::numeric_limits<T>::max_digits10); #endif T arg = 1. - 2. * g; static constexpr T bound = 1.0 - std::numeric_limits<T>::epsilon(); // prevent infinite results if (arg <= -1.0) { arg = -bound; } else if (arg >= 1.0) { arg = bound; } const T &sqrt2 = MC<T>::sqrt2; // using the degenerate approximation const T H = calcH(s, s*s); x = -s * sqrt2 * erf_inv(arg) / H; do { f = gfi(x, s) - g; fp = dgfidx(x, s); upd = -f / fp; x += upd; rerr = abs(upd)/(abs(x) + good_relerror<T>()); #ifdef DEVSIM_UNIT_TEST std::cout << i << " " << x << " " << rerr << "\n"; #endif ++i; } while ((rerr > good_relerror<T>()) && (i < 200)); return x; } template <typename T> T digfidx(T g, T s) { return 1.0 / dgfidx(igfi(g,s), s); } template double gfi<double>(double, double); template double dgfidx<double>(double, double); template double igfi<double>(double, double); template double digfidx<double>(double, double); #ifdef DEVSIM_EXTENDED_PRECISION template float128 gfi<float128>(float128, float128); template float128 dgfidx<float128>(float128, float128); template float128 igfi<float128>(float128, float128); template float128 digfidx<float128>(float128, float128); #endif #ifdef DEVSIM_UNIT_TEST template <typename DoubleType> void unit() { DoubleType k_B = 1.380649e-23; DoubleType e = 1.602176634e-19; DoubleType T = 300; DoubleType sigma = 0.10; DoubleType s = (sigma*e)/(k_B*T); DoubleType S = s*s; DoubleType V_0 = 0; DoubleType V_f = V_0-S*k_B*T/e;// # (-0.65372119-1.2) ; DoubleType zeta = (V_f*e-V_0*e)/(k_B*T); // zeta =-0.5 DoubleType zeta_1 = (V_f*e-V_0*e-pow(sigma*e, 2)/k_B*T)/(k_B*T); DoubleType g= gfi(zeta,s); DoubleType dg= dgfidx(zeta,s); DoubleType ginv= igfi(g,s); DoubleType dginv= digfidx(g,s); // print(g,dg,ginv) std::cout << std::setprecision(std::numeric_limits<DoubleType>::max_digits10); std::cout << " zeta\t" << zeta << "\n" << " gfi\t" << g << "\n" << " dgfidx\t" << dg << "\n" << " igfi\t" << ginv << "\n" << " digfidx\t" << dginv << " " << 1.0/dginv << "\n"; } int main() { unit<double>(); #ifdef DEVSIM_EXTENDED_PRECISION unit<float128>(); #endif } #endif
improve initial guess, add journal reference
improve initial guess, add journal reference
C++
apache-2.0
devsim/devsim,devsim/devsim,devsim/devsim
d9c5d25e68cd77696ce986e7a1cd955d24fa4472
src/coco.cc
src/coco.cc
#include "coco.hh" #include <algorithm> #include <fstream> #include <functional> #include <iostream> #include <numeric> #include <regex> #include <stdexcept> #include <string> #include <vector> #include <tuple> #include <nanojson.hpp> #include <cmdline.h> #include "filter.hh" #include "ncurses.hh" #include "utf8.hh" using curses::Window; using curses::Event; using curses::Key; enum class Coco::Status { Selected, Escaped, Continue, }; std::ostream& operator<<(std::ostream& os, FilterMode mode) { switch (mode) { case FilterMode::CaseSensitive: return os << "CaseSensitive"; case FilterMode::SmartCase: return os << "SmartCase"; case FilterMode::Regex: return os << "Regex"; default: throw std::logic_error(std::string(__FUNCTION__) + ": bad enum"); } } constexpr size_t y_offset = 1; void Config::read_from(int argc, char const** argv) { cmdline::parser parser; parser.set_program_name("coco"); parser.add<std::string>("query", 0, "initial value for query", false, ""); parser.add<std::string>("prompt", 0, "specify the prompt string", false, "QUERY> "); parser.add<std::size_t>("max-buffer", 'b', "maximum length of lines", false, 4096); parser.add<double>("score-min", 's', "threshold of score", false, 0.01); parser.add<std::string>("filter", 'f', "type of filter", false, "smart-case", cmdline::oneof<std::string>("case-sensitive", "smart-case", "regex")); parser.footer("filename..."); parser.parse_check(argc, argv); query = parser.get<std::string>("query"); prompt = parser.get<std::string>("prompt"); score_min = parser.get<double>("score-min"); max_buffer = parser.get<std::size_t>("max-buffer"); filter = parser.get<std::string>("filter"); lines.resize(0); lines.reserve(max_buffer); if (parser.rest().size() > 0) { for (auto&& path : parser.rest()) { std::ifstream ifs{path}; read_lines(ifs, max_buffer); } } else { read_lines(std::cin, max_buffer); } } void Config::read_lines(std::istream& is, std::size_t max_len) { static std::regex ansi(R"(\x1B\[([0-9]{1,2}(;[0-9]{1,2})?)?[m|K])"); for (std::string line; std::getline(is, line);) { if (lines.size() == max_len) return; lines.push_back(std::regex_replace(line, ansi, "")); } } Coco::Coco(Config const& config) : config(config) { query = config.query; if (config.filter == "case-sensitive") { filter_mode = FilterMode::CaseSensitive; } else if (config.filter == "smart-case") { filter_mode = FilterMode::SmartCase; } else if (config.filter == "regex") { filter_mode = FilterMode::Regex; } else { throw std::logic_error(std::string(__FUNCTION__) + ": bad option"); } choices.resize(config.lines.size()); std::generate(choices.begin(), choices.end(), [n = 0]() mutable { return Choice(n++); }); update_filter_list(); } std::vector<std::string> Coco::select_line() { // initialize ncurses screen. Window term; render_screen(term); while (true) { auto result = handle_key_event(term); if (result == Status::Selected) { std::vector<std::string> lines; for (std::size_t i = 0; i < filtered_len; ++i) { if (choices[i].selected) lines.push_back(config.lines[choices[i].index]); } if (lines.empty()) { return {config.lines[cursor + offset]}; } else { return lines; } } else if (result == Status::Escaped) { break; } render_screen(term); } return {}; } void Coco::render_screen(Window& term) { term.erase(); int width, height; std::tie(width, height) = term.get_size(); for (size_t y = 0; y < std::min<size_t>(filtered_len - offset, height - 1); ++y) { if (choices[y + offset].selected) { term.add_str(0, y + y_offset, ">"); } term.add_str(2, y + 1, config.lines[choices[y + offset].index]); if (y == cursor) { term.change_attr(0, y + 1, -1, 0); } } std::string query_str = config.prompt + query; std::stringstream ss; ss << filter_mode << " [" << cursor + offset << "/" << filtered_len << "]"; std::string mode_str = ss.str(); term.add_str(width - 1 - mode_str.length(), 0, mode_str); term.add_str(0, 0, query_str); term.refresh(); } auto Coco::handle_key_event(Window& term) -> Status { auto ev = term.poll_event(); if (ev == Key::Enter) { return Status::Selected; } else if (ev == Key::Esc) { return Status::Escaped; } else if (ev == Key::Up) { if (cursor == 0) { offset = std::max(0, (int)offset - 1); } else { cursor--; } return Status::Continue; } else if (ev == Key::Down) { int height; std::tie(std::ignore, height) = term.get_size(); if (cursor == static_cast<size_t>(height - 1 - y_offset)) { offset = std::min<size_t>(offset + 1, std::max<int>(0, filtered_len - height + y_offset)); } else { cursor = std::min<size_t>(cursor + 1, std::min<size_t>(filtered_len - offset, height - y_offset) - 1); } return Status::Continue; } else if (ev == Key::Tab) { choices[cursor + offset].selected ^= true; return Status::Continue; } else if (ev == Key::Backspace) { if (!query.empty()) { pop_back_utf8(query); update_filter_list(); } return Status::Continue; } else if (ev == Key::Ctrl) { if (ev.get_mod() == 'r') { filter_mode = static_cast<FilterMode>((static_cast<int>(filter_mode) + 1) % 3); update_filter_list(); } return Status::Continue; } else if (ev == Key::Char) { query += ev.as_chars(); update_filter_list(); return Status::Continue; } else { return Status::Continue; } } void Coco::update_filter_list() { try { auto scorer = score_by(filter_mode, query); scorer->scoring(choices, config.lines); filtered_len = std::find_if(choices.begin(), choices.end(), [this](auto& choice) { return choice.score <= config.score_min; }) - choices.begin(); } catch (std::regex_error&) { } cursor = 0; offset = 0; }
#include "coco.hh" #include <algorithm> #include <fstream> #include <functional> #include <iostream> #include <numeric> #include <regex> #include <stdexcept> #include <string> #include <vector> #include <tuple> #include <nanojson.hpp> #include <cmdline.h> #include "filter.hh" #include "ncurses.hh" #include "utf8.hh" using curses::Window; using curses::Event; using curses::Key; enum class Coco::Status { Selected, Escaped, Continue, }; std::ostream& operator<<(std::ostream& os, FilterMode mode) { switch (mode) { case FilterMode::CaseSensitive: return os << "CaseSensitive"; case FilterMode::SmartCase: return os << "SmartCase"; case FilterMode::Regex: return os << "Regex"; default: throw std::logic_error(std::string(__FUNCTION__) + ": bad enum"); } } constexpr size_t y_offset = 1; void Config::read_from(int argc, char const** argv) { cmdline::parser parser; parser.set_program_name("coco"); parser.add<std::string>("query", 0, "initial value for query", false, ""); parser.add<std::string>("prompt", 0, "specify the prompt string", false, "QUERY> "); parser.add<std::size_t>("max-buffer", 'b', "maximum length of lines", false, 4096); parser.add<double>("score-min", 's', "threshold of score", false, 0.01); parser.add<std::string>("filter", 'f', "type of filter", false, "smart-case", cmdline::oneof<std::string>("case-sensitive", "smart-case", "regex")); parser.footer("filename..."); parser.parse_check(argc, argv); query = parser.get<std::string>("query"); prompt = parser.get<std::string>("prompt"); score_min = parser.get<double>("score-min"); max_buffer = parser.get<std::size_t>("max-buffer"); filter = parser.get<std::string>("filter"); lines.resize(0); lines.reserve(max_buffer); if (parser.rest().size() > 0) { for (auto&& path : parser.rest()) { std::ifstream ifs{path}; read_lines(ifs, max_buffer); } } else { read_lines(std::cin, max_buffer); } } void Config::read_lines(std::istream& is, std::size_t max_len) { static std::regex ansi(R"(\x1B\[([0-9]{1,2}(;[0-9]{1,2})?)?[m|K])"); for (std::string line; std::getline(is, line);) { if (lines.size() == max_len) return; lines.push_back(std::regex_replace(line, ansi, "")); } } Coco::Coco(Config const& config) : config(config) { query = config.query; if (config.filter == "case-sensitive") { filter_mode = FilterMode::CaseSensitive; } else if (config.filter == "smart-case") { filter_mode = FilterMode::SmartCase; } else if (config.filter == "regex") { filter_mode = FilterMode::Regex; } else { throw std::logic_error(std::string(__FUNCTION__) + ": bad option"); } choices.resize(config.lines.size()); std::generate(choices.begin(), choices.end(), [n = 0]() mutable { return Choice(n++); }); update_filter_list(); } std::vector<std::string> Coco::select_line() { // initialize ncurses screen. Window term; render_screen(term); while (true) { auto result = handle_key_event(term); if (result == Status::Selected) { std::vector<std::string> lines; for (std::size_t i = 0; i < filtered_len; ++i) { if (choices[i].selected) lines.push_back(config.lines[choices[i].index]); } if (lines.empty()) { return {config.lines[cursor + offset]}; } else { return lines; } } else if (result == Status::Escaped) { break; } render_screen(term); } return {}; } void Coco::render_screen(Window& term) { term.erase(); int width, height; std::tie(width, height) = term.get_size(); for (size_t y = 0; y < std::min<size_t>(filtered_len - offset, height - 1); ++y) { if (choices[y + offset].selected) { term.add_str(0, y + y_offset, ">"); } term.add_str(2, y + 1, config.lines[choices[y + offset].index]); if (y == cursor) { term.change_attr(0, y + 1, -1, 0); } } std::string query_str = config.prompt + query; std::stringstream ss; ss << filter_mode << " [" << cursor + offset << "/" << filtered_len << "]"; std::string mode_str = ss.str(); term.add_str(width - 1 - mode_str.length(), 0, mode_str); term.add_str(0, 0, query_str); term.refresh(); } auto Coco::handle_key_event(Window& term) -> Status { auto ev = term.poll_event(); if (ev == Key::Enter) { return Status::Selected; } else if (ev == Key::Esc) { return Status::Escaped; } else if (ev == Key::Up) { if (cursor == 0) { offset = std::max(0, (int)offset - 1); } else { cursor--; } return Status::Continue; } else if (ev == Key::Down) { int height; std::tie(std::ignore, height) = term.get_size(); if (cursor == static_cast<size_t>(height - 1 - y_offset)) { offset = std::min<size_t>(offset + 1, std::max<int>(0, filtered_len - height + y_offset)); } else { cursor = std::min<size_t>(cursor + 1, std::min<size_t>(filtered_len - offset, height - y_offset) - 1); } return Status::Continue; } else if (ev == Key::Tab) { choices[cursor + offset].selected ^= true; return Status::Continue; } else if (ev == Key::Backspace) { if (!query.empty()) { pop_back_utf8(query); update_filter_list(); } return Status::Continue; } else if (ev == Key::Ctrl) { if (ev.get_mod() == 'r') { filter_mode = static_cast<FilterMode>((static_cast<int>(filter_mode) + 1) % 3); update_filter_list(); } return Status::Continue; } else if (ev == Key::Char) { query += ev.as_chars(); update_filter_list(); return Status::Continue; } else { return Status::Continue; } } void Coco::update_filter_list() { try { auto scorer = score_by(filter_mode, query); scorer->scoring(choices, config.lines); filtered_len = std::find_if(choices.begin(), choices.end(), [this](auto& choice) { return choice.score <= config.score_min; }) - choices.begin(); } catch (std::regex_error&) { } // mark hidden choices unselected. for (size_t i = filtered_len; i < choices.size(); ++i) { choices[i].selected = false; } // reset cursor cursor = 0; offset = 0; }
mark invisible choices as unselected
mark invisible choices as unselected
C++
mit
ys-nuem/coco,ys-nuem/coco
d298b34c19d8e91bf790eb391db729676dc1205d
glm/gtx/range.hpp
glm/gtx/range.hpp
/////////////////////////////////////////////////////////////////////////////////// /// OpenGL Mathematics (glm.g-truc.net) /// /// Copyright (c) 2005 - 2014 G-Truc Creation (www.g-truc.net) /// Permission is hereby granted, free of charge, to any person obtaining a copy /// of this software and associated documentation files (the "Software"), to deal /// in the Software without restriction, including without limitation the rights /// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell /// copies of the Software, and to permit persons to whom the Software is /// furnished to do so, subject to the following conditions: /// /// The above copyright notice and this permission notice shall be included in /// all copies or substantial portions of the Software. /// /// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR /// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, /// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE /// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER /// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, /// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN /// THE SOFTWARE. /// /// @ref gtx_range /// @file glm/gtx/range.hpp /// @date 2014-09-19 / 2014-09-19 /// @author Joshua Moerman /// /// @brief Defines begin and end for vectors and matrices. Useful for range-based for loop. /// The range is defined over the elements, not over columns or rows (e.g. mat4 has 16 elements). /// /////////////////////////////////////////////////////////////////////////////////// #pragma once #include "../detail/setup.hpp" #if !GLM_HAS_RANGE_FOR # error "GLM_GTX_range requires C++11 suppport or 'range for'" #endif #include "../gtc/type_ptr.hpp" namespace glm { /* The glm types provide a .length() member, but for matrices this only defines the number of columns, so we need to work around this */ template <typename T, precision P> detail::component_count_t number_of_elements_(tvec2<T, P> const & v){ return detail::component_count(v); } template <typename T, precision P> detail::component_count_t number_of_elements_(tvec3<T, P> const & v){ return detail::component_count(v); } template <typename T, precision P> detail::component_count_t number_of_elements_(tvec4<T, P> const & v){ return detail::component_count(v); } template <typename genType> detail::component_count_t number_of_elements_(genType const & m){ return detail::component_count(m) * detail::component_count(m[0]); } template <typename genType> const typename genType::value_type * begin(genType const & v){ return value_ptr(v); } template <typename genType> const typename genType::value_type * end(genType const & v){ return begin(v) + number_of_elements_(v); } template <typename genType> typename genType::value_type * begin(genType& v){ return value_ptr(v); } template <typename genType> typename genType::value_type * end(genType& v){ return begin(v) + number_of_elements_(v); } }//namespace glm
/////////////////////////////////////////////////////////////////////////////////// /// OpenGL Mathematics (glm.g-truc.net) /// /// Copyright (c) 2005 - 2014 G-Truc Creation (www.g-truc.net) /// Permission is hereby granted, free of charge, to any person obtaining a copy /// of this software and associated documentation files (the "Software"), to deal /// in the Software without restriction, including without limitation the rights /// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell /// copies of the Software, and to permit persons to whom the Software is /// furnished to do so, subject to the following conditions: /// /// The above copyright notice and this permission notice shall be included in /// all copies or substantial portions of the Software. /// /// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR /// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, /// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE /// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER /// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, /// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN /// THE SOFTWARE. /// /// @ref gtx_range /// @file glm/gtx/range.hpp /// @date 2014-09-19 / 2014-09-19 /// @author Joshua Moerman /// /// @brief Defines begin and end for vectors and matrices. Useful for range-based for loop. /// The range is defined over the elements, not over columns or rows (e.g. mat4 has 16 elements). /// /////////////////////////////////////////////////////////////////////////////////// #pragma once #include "../detail/setup.hpp" #if !GLM_HAS_RANGE_FOR # error "GLM_GTX_range requires C++11 suppport or 'range for'" #endif #include "../gtc/type_ptr.hpp" namespace glm{ namespace detail { /* The glm types provide a .length() member, but for matrices this only defines the number of columns, so we need to work around this */ template <typename T, precision P> detail::component_count_t number_of_elements_(tvec2<T, P> const & v){ return detail::component_count(v); } template <typename T, precision P> detail::component_count_t number_of_elements_(tvec3<T, P> const & v){ return detail::component_count(v); } template <typename T, precision P> detail::component_count_t number_of_elements_(tvec4<T, P> const & v){ return detail::component_count(v); } template <typename genType> detail::component_count_t number_of_elements_(genType const & m){ return detail::component_count(m) * detail::component_count(m[0]); } }//namespace template <typename genType> const typename genType::value_type * begin(genType const & v){ return value_ptr(v); } template <typename genType> const typename genType::value_type * end(genType const & v){ return begin(v) + detail::number_of_elements_(v); } template <typename genType> typename genType::value_type * begin(genType& v){ return value_ptr(v); } template <typename genType> typename genType::value_type * end(genType& v){ return begin(v) + detail::number_of_elements_(v); } }//namespace glm
Add detail namespace for number_of_elements
Add detail namespace for number_of_elements
C++
mit
hrehfeld/glm,hrehfeld/glm
28fde280db96df57d1b98e6928f061fcf474f4d0
dreal/api/test/api_test.cc
dreal/api/test/api_test.cc
#include "dreal/api/api.h" #include <cmath> #include <gtest/gtest.h> #include "dreal/solver/formula_evaluator.h" namespace dreal { namespace { class ApiTest : public ::testing::Test { protected: const Variable x_{"x", Variable::Type::CONTINUOUS}; const Variable y_{"y", Variable::Type::CONTINUOUS}; const Variable z_{"z", Variable::Type::CONTINUOUS}; const Variable binary1_{"binary1", Variable::Type::BINARY}; const Variable binary2_{"binary2", Variable::Type::BINARY}; const Variable b1_{"b1", Variable::Type::BOOLEAN}; const Variable b2_{"b2", Variable::Type::BOOLEAN}; }; ::testing::AssertionResult CheckSolution(const Formula& f, const Box& solution) { FormulaEvaluator formula_evaluator{make_relational_formula_evaluator(f)}; const FormulaEvaluationResult formula_evaluation_result{ formula_evaluator(solution)}; if (formula_evaluation_result.type() == FormulaEvaluationResult::Type::UNSAT) { return ::testing::AssertionFailure() << "UNSAT detected!"; } if (!formula_evaluation_result.evaluation().contains(0.0)) { return ::testing::AssertionFailure() << "The interval evaluation indicates " "that the solution does not " "satisfy the constraint."; } return ::testing::AssertionSuccess(); } // Tests CheckSatisfiability (δ-SAT case). TEST_F(ApiTest, CheckSatisfiabilityMixedBooleanAndContinuous) { const auto result = CheckSatisfiability( !b1_ && b2_ && (sin(x_) == 1) && x_ > 0 && x_ < 2 * 3.141592, 0.001); ASSERT_TRUE(result); EXPECT_EQ((*result)[b1_], 0.0); EXPECT_EQ((*result)[b2_], 1.0); EXPECT_NEAR(std::sin((*result)[x_].mid()), 1.0, 0.001); } TEST_F(ApiTest, CheckSatisfiabilityBinaryVariables1) { const Formula f{2 * binary1_ + 4 * binary2_ == 0}; const auto result = CheckSatisfiability(f, 0.001); ASSERT_TRUE(result); const Box& solution{*result}; EXPECT_EQ(solution[binary1_].mid(), 0.0); EXPECT_EQ(solution[binary2_].mid(), 0.0); EXPECT_EQ(solution[binary1_].diam(), 0.0); EXPECT_EQ(solution[binary2_].diam(), 0.0); } TEST_F(ApiTest, CheckSatisfiabilityBinaryVariables2) { const Formula f{binary1_ + binary2_ > 3}; const auto result = CheckSatisfiability(f, 0.001); EXPECT_FALSE(result); } // Tests CheckSatisfiability (δ-SAT case). TEST_F(ApiTest, CheckSatisfiabilityDeltaSat) { // 0 ≤ x ≤ 5 // 0 ≤ y ≤ 5 // 0 ≤ z ≤ 5 // 2x + y = z const Formula f1{0 <= x_ && x_ <= 5}; const Formula f2{0 <= y_ && y_ <= 5}; const Formula f3{0 <= z_ && z_ <= 5}; const Formula f4{2 * x_ + y_ == z_}; // Checks the API returning an optional. { auto result = CheckSatisfiability(f1 && f2 && f3 && f4, 0.001); ASSERT_TRUE(result); EXPECT_TRUE(CheckSolution(f4, *result)); } // Checks the API returning a bool. { Box b; const bool result{CheckSatisfiability(f1 && f2 && f3 && f4, 0.001, &b)}; ASSERT_TRUE(result); EXPECT_TRUE(CheckSolution(f4, b)); } } // Tests CheckSatisfiability (UNSAT case). TEST_F(ApiTest, CheckSatisfiabilityUnsat) { // 2x² + 6x + 5 < 0 // -10 ≤ x ≤ 10 const Formula f1{2 * x_ * x_ + 6 * x_ + 5 < 0}; const Formula f2{-10 <= x_ && x_ <= 10}; // Checks the API returning an optional. { auto result = CheckSatisfiability(f1 && f2, 0.001); EXPECT_FALSE(result); } // Checks the API returning a bool. { Box b; const bool result{CheckSatisfiability(f1 && f2, 0.001, &b)}; EXPECT_FALSE(result); } } TEST_F(ApiTest, Minimize1) { // minimize 2x² + 6x + 5 s.t. -4 ≤ x ≤ 0 const Expression objective{2 * x_ * x_ + 6 * x_ + 5}; const Formula constraint{-10 <= x_ && x_ <= 10}; const double delta{0.01}; const double known_minimum = 0.5; // Checks the API returning an optional. { const auto result = Minimize(objective, constraint, delta); ASSERT_TRUE(result); const double x = (*result)[x_].mid(); EXPECT_TRUE(-10 <= x && x <= 10); EXPECT_LT(2 * x * x + 6 * x + 5, known_minimum + delta); } // Checks the API returning a bool. { Box b; const bool result = Minimize(objective, constraint, delta, &b); ASSERT_TRUE(result); const double x = b[x_].mid(); EXPECT_TRUE(-10 <= x && x <= 10); EXPECT_LT(2 * x * x + 6 * x + 5, known_minimum + delta); } } TEST_F(ApiTest, Minimize2) { // minimize sin(3x) - 2cos(x) s.t. -3 ≤ x ≤ 3 const Expression objective{sin(3 * x_) - 2 * cos(x_)}; const Formula constraint{-3 <= x_ && x_ <= 3}; const double delta{0.001}; const double known_minimum = -2.77877; // Checks the API returning an optional. { const auto result = Minimize(objective, constraint, delta); ASSERT_TRUE(result); const double x = (*result)[x_].mid(); EXPECT_TRUE(-3 <= x && x <= 3); EXPECT_LT(sin(3 * x) - 2 * cos(x), known_minimum + delta); } // Checks the API returning a bool. { Box b; const bool result = Minimize(objective, constraint, delta, &b); ASSERT_TRUE(result); const double x = b[x_].mid(); EXPECT_TRUE(-3 <= x && x <= 3); EXPECT_LT(sin(3 * x) - 2 * cos(x), known_minimum + delta); } } TEST_F(ApiTest, CheckSatisfiabilityDisjunction) { const double delta{0.001}; const Variable b1{"b1", Variable::Type::BOOLEAN}; const Variable b2{"b2", Variable::Type::BOOLEAN}; const Variable b3{"b3", Variable::Type::BOOLEAN}; const auto result = CheckSatisfiability(b1 || !b2 || b3, delta); const Box& solution{*result}; EXPECT_EQ(solution[b1].diam(), 0); EXPECT_EQ(solution[b2].diam(), 0); EXPECT_EQ(solution[b3].diam(), 0); const double v1{solution[b1].mid()}; const double v2{solution[b2].mid()}; const double v3{solution[b3].mid()}; EXPECT_TRUE(v1 == 1.0 || v1 == 0.0); EXPECT_TRUE(v2 == 1.0 || v2 == 0.0); EXPECT_TRUE(v3 == 1.0 || v3 == 0.0); EXPECT_TRUE(v1 || !v2 || v3); } } // namespace } // namespace dreal
#include "dreal/api/api.h" #include <cmath> #include <gtest/gtest.h> #include "dreal/solver/formula_evaluator.h" namespace dreal { namespace { class ApiTest : public ::testing::Test { protected: const Variable x_{"x", Variable::Type::CONTINUOUS}; const Variable y_{"y", Variable::Type::CONTINUOUS}; const Variable z_{"z", Variable::Type::CONTINUOUS}; const Variable binary1_{"binary1", Variable::Type::BINARY}; const Variable binary2_{"binary2", Variable::Type::BINARY}; const Variable b1_{"b1", Variable::Type::BOOLEAN}; const Variable b2_{"b2", Variable::Type::BOOLEAN}; }; ::testing::AssertionResult CheckSolution(const Formula& f, const Box& solution) { FormulaEvaluator formula_evaluator{make_relational_formula_evaluator(f)}; const FormulaEvaluationResult formula_evaluation_result{ formula_evaluator(solution)}; if (formula_evaluation_result.type() == FormulaEvaluationResult::Type::UNSAT) { return ::testing::AssertionFailure() << "UNSAT detected!"; } if (!formula_evaluation_result.evaluation().contains(0.0)) { return ::testing::AssertionFailure() << "The interval evaluation indicates " "that the solution does not " "satisfy the constraint."; } return ::testing::AssertionSuccess(); } // Tests CheckSatisfiability (δ-SAT case). TEST_F(ApiTest, CheckSatisfiabilityMixedBooleanAndContinuous) { const auto result = CheckSatisfiability( !b1_ && b2_ && (sin(x_) == 1) && x_ > 0 && x_ < 2 * 3.141592, 0.001); ASSERT_TRUE(result); EXPECT_EQ((*result)[b1_], 0.0); EXPECT_EQ((*result)[b2_], 1.0); EXPECT_NEAR(std::sin((*result)[x_].mid()), 1.0, 0.001); } TEST_F(ApiTest, CheckSatisfiabilityBinaryVariables1) { const Formula f{2 * binary1_ + 4 * binary2_ == 0}; const auto result = CheckSatisfiability(f, 0.001); ASSERT_TRUE(result); const Box& solution{*result}; EXPECT_EQ(solution[binary1_].mid(), 0.0); EXPECT_EQ(solution[binary2_].mid(), 0.0); EXPECT_EQ(solution[binary1_].diam(), 0.0); EXPECT_EQ(solution[binary2_].diam(), 0.0); } TEST_F(ApiTest, CheckSatisfiabilityBinaryVariables2) { const Formula f{binary1_ + binary2_ > 3}; const auto result = CheckSatisfiability(f, 0.001); EXPECT_FALSE(result); } // Tests CheckSatisfiability (δ-SAT case). TEST_F(ApiTest, CheckSatisfiabilityDeltaSat) { // 0 ≤ x ≤ 5 // 0 ≤ y ≤ 5 // 0 ≤ z ≤ 5 // 2x + y = z const Formula f1{0 <= x_ && x_ <= 5}; const Formula f2{0 <= y_ && y_ <= 5}; const Formula f3{0 <= z_ && z_ <= 5}; const Formula f4{2 * x_ + y_ == z_}; // Checks the API returning an optional. { auto result = CheckSatisfiability(f1 && f2 && f3 && f4, 0.001); ASSERT_TRUE(result); EXPECT_TRUE(CheckSolution(f4, *result)); } // Checks the API returning a bool. { Box b; const bool result{CheckSatisfiability(f1 && f2 && f3 && f4, 0.001, &b)}; ASSERT_TRUE(result); EXPECT_TRUE(CheckSolution(f4, b)); } } // Tests CheckSatisfiability (UNSAT case). TEST_F(ApiTest, CheckSatisfiabilityUnsat) { // 2x² + 6x + 5 < 0 // -10 ≤ x ≤ 10 const Formula f1{2 * x_ * x_ + 6 * x_ + 5 < 0}; const Formula f2{-10 <= x_ && x_ <= 10}; // Checks the API returning an optional. { auto result = CheckSatisfiability(f1 && f2, 0.001); EXPECT_FALSE(result); } // Checks the API returning a bool. { Box b; const bool result{CheckSatisfiability(f1 && f2, 0.001, &b)}; EXPECT_FALSE(result); } } TEST_F(ApiTest, Minimize1) { // minimize 2x² + 6x + 5 s.t. -4 ≤ x ≤ 0 const Expression objective{2 * x_ * x_ + 6 * x_ + 5}; const Formula constraint{-10 <= x_ && x_ <= 10}; const double delta{0.01}; const double known_minimum = 0.5; // Checks the API returning an optional. { const auto result = Minimize(objective, constraint, delta); ASSERT_TRUE(result); const double x = (*result)[x_].mid(); EXPECT_TRUE(-10 <= x && x <= 10); EXPECT_LT(2 * x * x + 6 * x + 5, known_minimum + delta); } // Checks the API returning a bool. { Box b; const bool result = Minimize(objective, constraint, delta, &b); ASSERT_TRUE(result); const double x = b[x_].mid(); EXPECT_TRUE(-10 <= x && x <= 10); EXPECT_LT(2 * x * x + 6 * x + 5, known_minimum + delta); } } TEST_F(ApiTest, Minimize2) { // minimize sin(3x) - 2cos(x) s.t. -3 ≤ x ≤ 3 const Expression objective{sin(3 * x_) - 2 * cos(x_)}; const Formula constraint{-3 <= x_ && x_ <= 3}; const double delta{0.001}; const double known_minimum = -2.77877; // Checks the API returning an optional. { const auto result = Minimize(objective, constraint, delta); ASSERT_TRUE(result); const double x = (*result)[x_].mid(); EXPECT_TRUE(-3 <= x && x <= 3); EXPECT_LT(sin(3 * x) - 2 * cos(x), known_minimum + delta); } // Checks the API returning a bool. { Box b; const bool result = Minimize(objective, constraint, delta, &b); ASSERT_TRUE(result); const double x = b[x_].mid(); EXPECT_TRUE(-3 <= x && x <= 3); EXPECT_LT(sin(3 * x) - 2 * cos(x), known_minimum + delta); } } TEST_F(ApiTest, CheckSatisfiabilityDisjunction) { const double delta{0.001}; const Variable b1{"b1", Variable::Type::BOOLEAN}; const Variable b2{"b2", Variable::Type::BOOLEAN}; const Variable b3{"b3", Variable::Type::BOOLEAN}; const auto result = CheckSatisfiability(b1 || !b2 || b3, delta); const Box& solution{*result}; EXPECT_EQ(solution[b1].diam(), 0); EXPECT_EQ(solution[b2].diam(), 0); EXPECT_EQ(solution[b3].diam(), 0); const double v1{solution[b1].mid()}; const double v2{solution[b2].mid()}; const double v3{solution[b3].mid()}; EXPECT_TRUE(v1 == 1.0 || v1 == 0.0); EXPECT_TRUE(v2 == 1.0 || v2 == 0.0); EXPECT_TRUE(v3 == 1.0 || v3 == 0.0); EXPECT_TRUE(v1 || !v2 || v3); } TEST_F(ApiTest, CheckSatisfiabilityIfThenElse1) { const double delta{0.001}; const Formula f1{if_then_else(x_ > y_, x_, y_) == z_}; const Formula f2{x_ == 100}; const Formula f3{y_ == 50}; const auto result = CheckSatisfiability(f1 && f2 && f3, delta); ASSERT_TRUE(result); const Box& solution{*result}; EXPECT_EQ(solution[z_].mid(), 100); } TEST_F(ApiTest, CheckSatisfiabilityIfThenElse2) { const double delta{0.001}; const Formula f1{if_then_else(x_ > y_, x_, y_) == z_}; const Formula f2{x_ == 50}; const Formula f3{y_ == 100}; const auto result = CheckSatisfiability(f1 && f2 && f3, delta); ASSERT_TRUE(result); const Box& solution{*result}; EXPECT_EQ(solution[z_].mid(), 100); } } // namespace } // namespace dreal
Add IfThenElse tests
test(api): Add IfThenElse tests
C++
apache-2.0
dreal/dreal4,dreal/dreal4,dreal/dreal4,soonho-tri/dreal4,soonho-tri/dreal4,soonho-tri/dreal4,dreal/dreal4,soonho-tri/dreal4
db833d36e9e318252e01f9a7d4608702634e673c
xplat/Flipper/FlipperConnectionManagerImpl.cpp
xplat/Flipper/FlipperConnectionManagerImpl.cpp
/* * Copyright (c) 2018-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the LICENSE * file in the root directory of this source tree. * */ #include "FlipperConnectionManagerImpl.h" #include "FlipperStep.h" #include "ConnectionContextStore.h" #include "Log.h" #include <folly/String.h> #include <folly/futures/Future.h> #include <folly/io/async/SSLContext.h> #include <folly/json.h> #include <rsocket/Payload.h> #include <rsocket/RSocket.h> #include <rsocket/transports/tcp/TcpConnectionFactory.h> #include <thread> #include <folly/io/async/AsyncSocketException.h> #include <stdexcept> #define WRONG_THREAD_EXIT_MSG \ "ERROR: Aborting flipper initialization because it's not running in the flipper thread." static constexpr int reconnectIntervalSeconds = 2; static constexpr int connectionKeepaliveSeconds = 10; static constexpr int securePort = 8088; static constexpr int insecurePort = 8089; namespace facebook { namespace flipper { class ConnectionEvents : public rsocket::RSocketConnectionEvents { private: FlipperConnectionManagerImpl* websocket_; public: ConnectionEvents(FlipperConnectionManagerImpl* websocket) : websocket_(websocket) {} void onConnected() { websocket_->isOpen_ = true; if (websocket_->connectionIsTrusted_) { websocket_->callbacks_->onConnected(); } } void onDisconnected(const folly::exception_wrapper&) { if (!websocket_->isOpen_) return; websocket_->isOpen_ = false; if (websocket_->connectionIsTrusted_) { websocket_->connectionIsTrusted_ = false; websocket_->callbacks_->onDisconnected(); } websocket_->reconnect(); } void onClosed(const folly::exception_wrapper& e) { onDisconnected(e); } }; class Responder : public rsocket::RSocketResponder { private: FlipperConnectionManagerImpl* websocket_; public: Responder(FlipperConnectionManagerImpl* websocket) : websocket_(websocket) {} void handleFireAndForget( rsocket::Payload request, rsocket::StreamId streamId) { const auto payload = request.moveDataToString(); websocket_->callbacks_->onMessageReceived(folly::parseJson(payload)); } }; FlipperConnectionManagerImpl::FlipperConnectionManagerImpl(FlipperInitConfig config, std::shared_ptr<FlipperState> state, std::shared_ptr<ConnectionContextStore> contextStore) : deviceData_(config.deviceData), flipperState_(state), flipperEventBase_(config.callbackWorker), connectionEventBase_(config.connectionWorker), contextStore_(contextStore) { CHECK_THROW(config.callbackWorker, std::invalid_argument); CHECK_THROW(config.connectionWorker, std::invalid_argument); } FlipperConnectionManagerImpl::~FlipperConnectionManagerImpl() { stop(); } void FlipperConnectionManagerImpl::start() { auto step = flipperState_->start("Start connection thread"); folly::makeFuture() .via(flipperEventBase_->getEventBase()) .delayed(std::chrono::milliseconds(0)) .thenValue([this, step](auto&&){ step->complete(); startSync();}); } void FlipperConnectionManagerImpl::startSync() { if (!isRunningInOwnThread()) { log(WRONG_THREAD_EXIT_MSG); return; } if (isOpen()) { log("Already connected"); return; } auto connect = flipperState_->start("Connect to desktop"); try { if (isCertificateExchangeNeeded()) { doCertificateExchange(); return; } connectSecurely(); connect->complete(); } catch (const folly::AsyncSocketException& e) { if (e.getType() == folly::AsyncSocketException::NOT_OPEN) { // The expected code path when flipper desktop is not running. // Don't count as a failed attempt. connect->fail("Port not open"); } else { log(e.what()); failedConnectionAttempts_++; connect->fail(e.what()); } reconnect(); } catch (const std::exception& e) { log(e.what()); connect->fail(e.what()); failedConnectionAttempts_++; reconnect(); } } void FlipperConnectionManagerImpl::doCertificateExchange() { rsocket::SetupParameters parameters; folly::SocketAddress address; parameters.payload = rsocket::Payload( folly::toJson(folly::dynamic::object("os", deviceData_.os)( "device", deviceData_.device)("app", deviceData_.app))); address.setFromHostPort(deviceData_.host, insecurePort); auto connectingInsecurely = flipperState_->start("Connect insecurely"); connectionIsTrusted_ = false; client_ = rsocket::RSocket::createConnectedClient( std::make_unique<rsocket::TcpConnectionFactory>( *connectionEventBase_->getEventBase(), std::move(address)), std::move(parameters), nullptr, std::chrono::seconds(connectionKeepaliveSeconds), // keepaliveInterval nullptr, // stats std::make_shared<ConnectionEvents>(this)) .get(); connectingInsecurely->complete(); requestSignedCertFromFlipper(); } void FlipperConnectionManagerImpl::connectSecurely() { rsocket::SetupParameters parameters; folly::SocketAddress address; auto loadingDeviceId = flipperState_->start("Load Device Id"); auto deviceId = contextStore_->getDeviceId(); if (deviceId.compare("unknown")) { loadingDeviceId->complete(); } parameters.payload = rsocket::Payload(folly::toJson(folly::dynamic::object( "os", deviceData_.os)("device", deviceData_.device)( "device_id", deviceId)("app", deviceData_.app))); address.setFromHostPort(deviceData_.host, securePort); std::shared_ptr<folly::SSLContext> sslContext = contextStore_->getSSLContext(); auto connectingSecurely = flipperState_->start("Connect securely"); connectionIsTrusted_ = true; client_ = rsocket::RSocket::createConnectedClient( std::make_unique<rsocket::TcpConnectionFactory>( *connectionEventBase_->getEventBase(), std::move(address), std::move(sslContext)), std::move(parameters), std::make_shared<Responder>(this), std::chrono::seconds(connectionKeepaliveSeconds), // keepaliveInterval nullptr, // stats std::make_shared<ConnectionEvents>(this)) .get(); connectingSecurely->complete(); failedConnectionAttempts_ = 0; } void FlipperConnectionManagerImpl::reconnect() { folly::makeFuture() .via(flipperEventBase_->getEventBase()) .delayed(std::chrono::seconds(reconnectIntervalSeconds)) .thenValue([this](auto&&){ startSync(); }); } void FlipperConnectionManagerImpl::stop() { if (client_) { client_->disconnect(); } client_ = nullptr; } bool FlipperConnectionManagerImpl::isOpen() const { return isOpen_ && connectionIsTrusted_; } void FlipperConnectionManagerImpl::setCallbacks(Callbacks* callbacks) { callbacks_ = callbacks; } void FlipperConnectionManagerImpl::sendMessage(const folly::dynamic& message) { flipperEventBase_->add([this, message]() { if (client_) { client_->getRequester() ->fireAndForget(rsocket::Payload(folly::toJson(message))) ->subscribe([]() {}); } }); } bool FlipperConnectionManagerImpl::isCertificateExchangeNeeded() { if (failedConnectionAttempts_ >= 2) { return true; } auto step = flipperState_->start("Check required certificates are present"); bool hasRequiredFiles = contextStore_->hasRequiredFiles(); if (hasRequiredFiles) { step->complete(); } return !hasRequiredFiles; } void FlipperConnectionManagerImpl::requestSignedCertFromFlipper() { auto generatingCSR = flipperState_->start("Generate CSR"); std::string csr = contextStore_->createCertificateSigningRequest(); generatingCSR->complete(); folly::dynamic message = folly::dynamic::object("method", "signCertificate")( "csr", csr.c_str())("destination", contextStore_->getCertificateDirectoryPath().c_str()); auto gettingCert = flipperState_->start("Getting cert from desktop"); flipperEventBase_->add([this, message, gettingCert]() { client_->getRequester() ->requestResponse(rsocket::Payload(folly::toJson(message))) ->subscribe([this, gettingCert](rsocket::Payload p) { auto response = p.moveDataToString(); if (!response.empty()) { folly::dynamic config = folly::parseJson(response); contextStore_->storeConnectionConfig(config); } gettingCert->complete(); log("Certificate exchange complete."); // Disconnect after message sending is complete. // This will trigger a reconnect which should use the secure channel. // TODO: Connect immediately, without waiting for reconnect client_ = nullptr; }, [this, message](folly::exception_wrapper e) { e.handle( [&](rsocket::ErrorWithPayload& errorWithPayload) { std::string errorMessage = errorWithPayload.payload.moveDataToString(); if (errorMessage.compare("not implemented")) { log("Desktop failed to provide certificates. Error from flipper desktop:\n" + errorMessage); client_ = nullptr; } else { sendLegacyCertificateRequest(message); } }, [e](...) { log(("Error during certificate exchange:" + e.what()).c_str()); } ); }); }); failedConnectionAttempts_ = 0; } void FlipperConnectionManagerImpl::sendLegacyCertificateRequest(folly::dynamic message) { // Desktop is using an old version of Flipper. // Fall back to fireAndForget, instead of requestResponse. auto sendingRequest = flipperState_->start("Sending fallback certificate request"); client_->getRequester() ->fireAndForget(rsocket::Payload(folly::toJson(message))) ->subscribe([this, sendingRequest]() { sendingRequest->complete(); folly::dynamic config = folly::dynamic::object(); contextStore_->storeConnectionConfig(config); client_ = nullptr; }); } bool FlipperConnectionManagerImpl::isRunningInOwnThread() { return flipperEventBase_->isInEventBaseThread(); } } // namespace flipper } // namespace facebook
/* * Copyright (c) 2018-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the LICENSE * file in the root directory of this source tree. * */ #include "FlipperConnectionManagerImpl.h" #include "FlipperStep.h" #include "ConnectionContextStore.h" #include "Log.h" #include <folly/String.h> #include <folly/futures/Future.h> #include <folly/io/async/SSLContext.h> #include <folly/json.h> #include <rsocket/Payload.h> #include <rsocket/RSocket.h> #include <rsocket/transports/tcp/TcpConnectionFactory.h> #include <thread> #include <folly/io/async/AsyncSocketException.h> #include <stdexcept> #define WRONG_THREAD_EXIT_MSG \ "ERROR: Aborting flipper initialization because it's not running in the flipper thread." static constexpr int reconnectIntervalSeconds = 2; static constexpr int connectionKeepaliveSeconds = 10; static constexpr int securePort = 8088; static constexpr int insecurePort = 8089; static constexpr int maxPayloadSize = 0xFFFFFF; namespace facebook { namespace flipper { class ConnectionEvents : public rsocket::RSocketConnectionEvents { private: FlipperConnectionManagerImpl* websocket_; public: ConnectionEvents(FlipperConnectionManagerImpl* websocket) : websocket_(websocket) {} void onConnected() { websocket_->isOpen_ = true; if (websocket_->connectionIsTrusted_) { websocket_->callbacks_->onConnected(); } } void onDisconnected(const folly::exception_wrapper&) { if (!websocket_->isOpen_) return; websocket_->isOpen_ = false; if (websocket_->connectionIsTrusted_) { websocket_->connectionIsTrusted_ = false; websocket_->callbacks_->onDisconnected(); } websocket_->reconnect(); } void onClosed(const folly::exception_wrapper& e) { onDisconnected(e); } }; class Responder : public rsocket::RSocketResponder { private: FlipperConnectionManagerImpl* websocket_; public: Responder(FlipperConnectionManagerImpl* websocket) : websocket_(websocket) {} void handleFireAndForget( rsocket::Payload request, rsocket::StreamId streamId) { const auto payload = request.moveDataToString(); websocket_->callbacks_->onMessageReceived(folly::parseJson(payload)); } }; FlipperConnectionManagerImpl::FlipperConnectionManagerImpl(FlipperInitConfig config, std::shared_ptr<FlipperState> state, std::shared_ptr<ConnectionContextStore> contextStore) : deviceData_(config.deviceData), flipperState_(state), flipperEventBase_(config.callbackWorker), connectionEventBase_(config.connectionWorker), contextStore_(contextStore) { CHECK_THROW(config.callbackWorker, std::invalid_argument); CHECK_THROW(config.connectionWorker, std::invalid_argument); } FlipperConnectionManagerImpl::~FlipperConnectionManagerImpl() { stop(); } void FlipperConnectionManagerImpl::start() { auto step = flipperState_->start("Start connection thread"); folly::makeFuture() .via(flipperEventBase_->getEventBase()) .delayed(std::chrono::milliseconds(0)) .thenValue([this, step](auto&&){ step->complete(); startSync();}); } void FlipperConnectionManagerImpl::startSync() { if (!isRunningInOwnThread()) { log(WRONG_THREAD_EXIT_MSG); return; } if (isOpen()) { log("Already connected"); return; } auto connect = flipperState_->start("Connect to desktop"); try { if (isCertificateExchangeNeeded()) { doCertificateExchange(); return; } connectSecurely(); connect->complete(); } catch (const folly::AsyncSocketException& e) { if (e.getType() == folly::AsyncSocketException::NOT_OPEN) { // The expected code path when flipper desktop is not running. // Don't count as a failed attempt. connect->fail("Port not open"); } else { log(e.what()); failedConnectionAttempts_++; connect->fail(e.what()); } reconnect(); } catch (const std::exception& e) { log(e.what()); connect->fail(e.what()); failedConnectionAttempts_++; reconnect(); } } void FlipperConnectionManagerImpl::doCertificateExchange() { rsocket::SetupParameters parameters; folly::SocketAddress address; parameters.payload = rsocket::Payload( folly::toJson(folly::dynamic::object("os", deviceData_.os)( "device", deviceData_.device)("app", deviceData_.app))); address.setFromHostPort(deviceData_.host, insecurePort); auto connectingInsecurely = flipperState_->start("Connect insecurely"); connectionIsTrusted_ = false; client_ = rsocket::RSocket::createConnectedClient( std::make_unique<rsocket::TcpConnectionFactory>( *connectionEventBase_->getEventBase(), std::move(address)), std::move(parameters), nullptr, std::chrono::seconds(connectionKeepaliveSeconds), // keepaliveInterval nullptr, // stats std::make_shared<ConnectionEvents>(this)) .get(); connectingInsecurely->complete(); requestSignedCertFromFlipper(); } void FlipperConnectionManagerImpl::connectSecurely() { rsocket::SetupParameters parameters; folly::SocketAddress address; auto loadingDeviceId = flipperState_->start("Load Device Id"); auto deviceId = contextStore_->getDeviceId(); if (deviceId.compare("unknown")) { loadingDeviceId->complete(); } parameters.payload = rsocket::Payload(folly::toJson(folly::dynamic::object( "os", deviceData_.os)("device", deviceData_.device)( "device_id", deviceId)("app", deviceData_.app))); address.setFromHostPort(deviceData_.host, securePort); std::shared_ptr<folly::SSLContext> sslContext = contextStore_->getSSLContext(); auto connectingSecurely = flipperState_->start("Connect securely"); connectionIsTrusted_ = true; client_ = rsocket::RSocket::createConnectedClient( std::make_unique<rsocket::TcpConnectionFactory>( *connectionEventBase_->getEventBase(), std::move(address), std::move(sslContext)), std::move(parameters), std::make_shared<Responder>(this), std::chrono::seconds(connectionKeepaliveSeconds), // keepaliveInterval nullptr, // stats std::make_shared<ConnectionEvents>(this)) .get(); connectingSecurely->complete(); failedConnectionAttempts_ = 0; } void FlipperConnectionManagerImpl::reconnect() { folly::makeFuture() .via(flipperEventBase_->getEventBase()) .delayed(std::chrono::seconds(reconnectIntervalSeconds)) .thenValue([this](auto&&){ startSync(); }); } void FlipperConnectionManagerImpl::stop() { if (client_) { client_->disconnect(); } client_ = nullptr; } bool FlipperConnectionManagerImpl::isOpen() const { return isOpen_ && connectionIsTrusted_; } void FlipperConnectionManagerImpl::setCallbacks(Callbacks* callbacks) { callbacks_ = callbacks; } void FlipperConnectionManagerImpl::sendMessage(const folly::dynamic& message) { flipperEventBase_->add([this, message]() { std::string json = folly::toJson(message); rsocket::Payload payload = rsocket::Payload(json); auto payloadLength = payload.data->computeChainDataLength(); DCHECK_LE(payloadLength, maxPayloadSize); if (payloadLength > maxPayloadSize) { auto logMessage = std::string( "Error: Skipping sending message larger than max rsocket payload: ") + json; log(logMessage); return; } if (client_) { client_->getRequester() ->fireAndForget(std::move(payload)) ->subscribe([]() {}); } }); } bool FlipperConnectionManagerImpl::isCertificateExchangeNeeded() { if (failedConnectionAttempts_ >= 2) { return true; } auto step = flipperState_->start("Check required certificates are present"); bool hasRequiredFiles = contextStore_->hasRequiredFiles(); if (hasRequiredFiles) { step->complete(); } return !hasRequiredFiles; } void FlipperConnectionManagerImpl::requestSignedCertFromFlipper() { auto generatingCSR = flipperState_->start("Generate CSR"); std::string csr = contextStore_->createCertificateSigningRequest(); generatingCSR->complete(); folly::dynamic message = folly::dynamic::object("method", "signCertificate")( "csr", csr.c_str())("destination", contextStore_->getCertificateDirectoryPath().c_str()); auto gettingCert = flipperState_->start("Getting cert from desktop"); flipperEventBase_->add([this, message, gettingCert]() { client_->getRequester() ->requestResponse(rsocket::Payload(folly::toJson(message))) ->subscribe([this, gettingCert](rsocket::Payload p) { auto response = p.moveDataToString(); if (!response.empty()) { folly::dynamic config = folly::parseJson(response); contextStore_->storeConnectionConfig(config); } gettingCert->complete(); log("Certificate exchange complete."); // Disconnect after message sending is complete. // This will trigger a reconnect which should use the secure channel. // TODO: Connect immediately, without waiting for reconnect client_ = nullptr; }, [this, message](folly::exception_wrapper e) { e.handle( [&](rsocket::ErrorWithPayload& errorWithPayload) { std::string errorMessage = errorWithPayload.payload.moveDataToString(); if (errorMessage.compare("not implemented")) { log("Desktop failed to provide certificates. Error from flipper desktop:\n" + errorMessage); client_ = nullptr; } else { sendLegacyCertificateRequest(message); } }, [e](...) { log(("Error during certificate exchange:" + e.what()).c_str()); } ); }); }); failedConnectionAttempts_ = 0; } void FlipperConnectionManagerImpl::sendLegacyCertificateRequest(folly::dynamic message) { // Desktop is using an old version of Flipper. // Fall back to fireAndForget, instead of requestResponse. auto sendingRequest = flipperState_->start("Sending fallback certificate request"); client_->getRequester() ->fireAndForget(rsocket::Payload(folly::toJson(message))) ->subscribe([this, sendingRequest]() { sendingRequest->complete(); folly::dynamic config = folly::dynamic::object(); contextStore_->storeConnectionConfig(config); client_ = nullptr; }); } bool FlipperConnectionManagerImpl::isRunningInOwnThread() { return flipperEventBase_->isInEventBaseThread(); } } // namespace flipper } // namespace facebook
Add max rsocket payload size
Add max rsocket payload size Summary: We're seeing some crashes when attempting to send payloads larger than are supported by rsocket. Instead of crashing, skip the message, but log it so we can see what it's containing. This is where the failure occurs: https://github.com/rsocket/rsocket-cpp/blob/master/rsocket/framing/FramedDuplexConnection.cpp#L64 Reviewed By: passy Differential Revision: D12857616 fbshipit-source-id: 2b02d7f5dd6499ba81783d3f8aefcbb64d9d408a
C++
mit
facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper
e6e225e081ca1b2584d8b8ba4b795771aa7f3741
Engine/source/core/stringTable.cpp
Engine/source/core/stringTable.cpp
//----------------------------------------------------------------------------- // Copyright (c) 2012 GarageGames, LLC // // 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 "core/strings/stringFunctions.h" #include "core/stringTable.h" _StringTable *_gStringTable = NULL; const U32 _StringTable::csm_stInitSize = 29; //--------------------------------------------------------------- // // StringTable functions // //--------------------------------------------------------------- namespace { bool sgInitTable = true; U8 sgHashTable[256]; void initTolowerTable() { for (U32 i = 0; i < 256; i++) { U8 c = dTolower(i); sgHashTable[i] = c * c; } sgInitTable = false; } } // namespace {} U32 _StringTable::hashString(const char* str) { if (sgInitTable) initTolowerTable(); if(!str) return -1; U32 ret = 0; char c; while((c = *str++) != 0) { ret <<= 1; ret ^= sgHashTable[static_cast<U32>(c)]; } return ret; } U32 _StringTable::hashStringn(const char* str, S32 len) { if (sgInitTable) initTolowerTable(); U32 ret = 0; char c; while((c = *str++) != 0 && len--) { ret <<= 1; ret ^= sgHashTable[static_cast<U32>(c)]; } return ret; } //-------------------------------------- _StringTable::_StringTable() { buckets = (Node **) dMalloc(csm_stInitSize * sizeof(Node *)); for(U32 i = 0; i < csm_stInitSize; i++) { buckets[i] = 0; } numBuckets = csm_stInitSize; itemCount = 0; } //-------------------------------------- _StringTable::~_StringTable() { dFree(buckets); } //-------------------------------------- void _StringTable::create() { //AssertFatal(_gStringTable == NULL, "StringTable::create: StringTable already exists."); if(!_gStringTable) { _gStringTable = new _StringTable; _gStringTable->_EmptyString = _gStringTable->insert(""); } } //-------------------------------------- void _StringTable::destroy() { AssertFatal(StringTable != NULL, "StringTable::destroy: StringTable does not exist."); delete _gStringTable; _gStringTable = NULL; } //-------------------------------------- StringTableEntry _StringTable::insert(const char* _val, const bool caseSens) { // Added 3/29/2007 -- If this is undesirable behavior, let me know -patw const char *val = _val; if( val == NULL ) val = ""; //- Node **walk, *temp; U32 key = hashString(val); walk = &buckets[key % numBuckets]; while((temp = *walk) != NULL) { if(caseSens && !dStrcmp(temp->val, val)) return temp->val; else if(!caseSens && !dStricmp(temp->val, val)) return temp->val; walk = &(temp->next); } char *ret = 0; if(!*walk) { *walk = (Node *) mempool.alloc(sizeof(Node)); (*walk)->next = 0; (*walk)->val = (char *) mempool.alloc(dStrlen(val) + 1); dStrcpy((*walk)->val, val); ret = (*walk)->val; itemCount ++; } if(itemCount > 2 * numBuckets) { resize(4 * numBuckets - 1); } return ret; } //-------------------------------------- StringTableEntry _StringTable::insertn(const char* src, S32 len, const bool caseSens) { char val[256]; AssertFatal(len < 255, "Invalid string to insertn"); dStrncpy(val, src, len); val[len] = 0; return insert(val, caseSens); } //-------------------------------------- StringTableEntry _StringTable::lookup(const char* val, const bool caseSens) { Node **walk, *temp; U32 key = hashString(val); walk = &buckets[key % numBuckets]; while((temp = *walk) != NULL) { if(caseSens && !dStrcmp(temp->val, val)) return temp->val; else if(!caseSens && !dStricmp(temp->val, val)) return temp->val; walk = &(temp->next); } return NULL; } //-------------------------------------- StringTableEntry _StringTable::lookupn(const char* val, S32 len, const bool caseSens) { Node **walk, *temp; U32 key = hashStringn(val, len); walk = &buckets[key % numBuckets]; while((temp = *walk) != NULL) { if(caseSens && !dStrncmp(temp->val, val, len) && temp->val[len] == 0) return temp->val; else if(!caseSens && !dStrnicmp(temp->val, val, len) && temp->val[len] == 0) return temp->val; walk = &(temp->next); } return NULL; } //-------------------------------------- void _StringTable::resize(const U32 newSize) { Node *head = NULL, *walk, *temp; U32 i; // reverse individual bucket lists // we do this because new strings are added at the end of bucket // lists so that case sens strings are always after their // corresponding case insens strings for(i = 0; i < numBuckets; i++) { walk = buckets[i]; while(walk) { temp = walk->next; walk->next = head; head = walk; walk = temp; } } buckets = (Node **) dRealloc(buckets, newSize * sizeof(Node)); for(i = 0; i < newSize; i++) { buckets[i] = 0; } numBuckets = newSize; walk = head; while(walk) { U32 key; Node *temp = walk; walk = walk->next; key = hashString(temp->val); temp->next = buckets[key % newSize]; buckets[key % newSize] = temp; } }
//----------------------------------------------------------------------------- // Copyright (c) 2012 GarageGames, LLC // // 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 "core/strings/stringFunctions.h" #include "core/stringTable.h" _StringTable *_gStringTable = NULL; const U32 _StringTable::csm_stInitSize = 29; //--------------------------------------------------------------- // // StringTable functions // //--------------------------------------------------------------- namespace { bool sgInitTable = true; U8 sgHashTable[256]; void initTolowerTable() { for (U32 i = 0; i < 256; i++) { U8 c = dTolower(i); sgHashTable[i] = c * c; } sgInitTable = false; } } // namespace {} U32 _StringTable::hashString(const char* str) { if (sgInitTable) initTolowerTable(); if(!str) return -1; U32 ret = 0; char c; while((c = *str++) != 0) { ret <<= 1; ret ^= sgHashTable[static_cast<U32>(c)]; } return ret; } U32 _StringTable::hashStringn(const char* str, S32 len) { if (sgInitTable) initTolowerTable(); U32 ret = 0; char c; while((c = *str++) != 0 && len--) { ret <<= 1; ret ^= sgHashTable[static_cast<U32>(c)]; } return ret; } //-------------------------------------- _StringTable::_StringTable() { buckets = (Node **) dMalloc(csm_stInitSize * sizeof(Node *)); for(U32 i = 0; i < csm_stInitSize; i++) { buckets[i] = 0; } numBuckets = csm_stInitSize; itemCount = 0; } //-------------------------------------- _StringTable::~_StringTable() { dFree(buckets); } //-------------------------------------- void _StringTable::create() { //AssertFatal(_gStringTable == NULL, "StringTable::create: StringTable already exists."); if(!_gStringTable) { _gStringTable = new _StringTable; _gStringTable->_EmptyString = _gStringTable->insert(""); } } //-------------------------------------- void _StringTable::destroy() { AssertFatal(StringTable != NULL, "StringTable::destroy: StringTable does not exist."); delete _gStringTable; _gStringTable = NULL; } //-------------------------------------- StringTableEntry _StringTable::insert(const char* _val, const bool caseSens) { // Added 3/29/2007 -- If this is undesirable behavior, let me know -patw const char *val = _val; if( val == NULL ) val = ""; //- Node **walk, *temp; U32 key = hashString(val); walk = &buckets[key % numBuckets]; while((temp = *walk) != NULL) { if(caseSens && !dStrcmp(temp->val, val)) return temp->val; else if(!caseSens && !dStricmp(temp->val, val)) return temp->val; walk = &(temp->next); } char *ret = 0; if(!*walk) { *walk = (Node *) mempool.alloc(sizeof(Node)); (*walk)->next = 0; (*walk)->val = (char *) mempool.alloc(dStrlen(val) + 1); dStrcpy((*walk)->val, val); ret = (*walk)->val; itemCount ++; } if(itemCount > 2 * numBuckets) { resize(4 * numBuckets - 1); } return ret; } //-------------------------------------- StringTableEntry _StringTable::insertn(const char* src, S32 len, const bool caseSens) { char val[256]; AssertFatal(len < 255, "Invalid string to insertn"); dStrncpy(val, src, len); val[len] = 0; return insert(val, caseSens); } //-------------------------------------- StringTableEntry _StringTable::lookup(const char* val, const bool caseSens) { Node **walk, *temp; U32 key = hashString(val); walk = &buckets[key % numBuckets]; while((temp = *walk) != NULL) { if(caseSens && !dStrcmp(temp->val, val)) return temp->val; else if(!caseSens && !dStricmp(temp->val, val)) return temp->val; walk = &(temp->next); } return NULL; } //-------------------------------------- StringTableEntry _StringTable::lookupn(const char* val, S32 len, const bool caseSens) { Node **walk, *temp; U32 key = hashStringn(val, len); walk = &buckets[key % numBuckets]; while((temp = *walk) != NULL) { if(caseSens && !dStrncmp(temp->val, val, len) && temp->val[len] == 0) return temp->val; else if(!caseSens && !dStrnicmp(temp->val, val, len) && temp->val[len] == 0) return temp->val; walk = &(temp->next); } return NULL; } //-------------------------------------- void _StringTable::resize(const U32 _newSize) { /// avoid a possible 0 division const U32 newSize = _newSize ? _newSize : 1; Node *head = NULL, *walk, *temp; U32 i; // reverse individual bucket lists // we do this because new strings are added at the end of bucket // lists so that case sens strings are always after their // corresponding case insens strings for(i = 0; i < numBuckets; i++) { walk = buckets[i]; while(walk) { temp = walk->next; walk->next = head; head = walk; walk = temp; } } buckets = (Node **) dRealloc(buckets, newSize * sizeof(Node)); for(i = 0; i < newSize; i++) { buckets[i] = 0; } numBuckets = newSize; walk = head; while(walk) { U32 key; Node *temp = walk; walk = walk->next; key = hashString(temp->val); temp->next = buckets[key % newSize]; buckets[key % newSize] = temp; } }
Fix for avoid a zero division on _StringTable::resize.
Fix for avoid a zero division on _StringTable::resize.
C++
mit
lukaspj/Speciality,Bloodknight/Torque3D,rextimmy/Torque3D,Azaezel/Torque3D,rextimmy/Torque3D,John3/Torque3D,Will-of-the-Wisp/Torque3D,Phantom139/Torque3D,ValtoGameEngines/Torque3D,JeffProgrammer/Torque3D,Duion/Torque3D,FITTeamIndecisive/Torque3D,aaravamudan2014/Torque3D,chaigler/Torque3D,FITTeamIndecisive/Torque3D,lukaspj/Speciality,aaravamudan2014/Torque3D,Phantom139/Torque3D,rextimmy/Torque3D,JeffProgrammer/Torque3D,Torque3D-GameEngine/Torque3D,aaravamudan2014/Torque3D,Torque3D-GameEngine/Torque3D,Phantom139/Torque3D,Azaezel/Torque3D,John3/Torque3D,lukaspj/Speciality,ValtoGameEngines/Torque3D,Torque3D-GameEngine/Torque3D,rextimmy/Torque3D,chaigler/Torque3D,ValtoGameEngines/Torque3D,GarageGames/Torque3D,Duion/Torque3D,FITTeamIndecisive/Torque3D,aaravamudan2014/Torque3D,John3/Torque3D,Bloodknight/Torque3D,Azaezel/Torque3D,ValtoGameEngines/Torque3D,GarageGames/Torque3D,ValtoGameEngines/Torque3D,Phantom139/Torque3D,FITTeamIndecisive/Torque3D,ValtoGameEngines/Torque3D,John3/Torque3D,rextimmy/Torque3D,Torque3D-GameEngine/Torque3D,elfprince13/Torque3D,FITTeamIndecisive/Torque3D,GarageGames/Torque3D,Azaezel/Torque3D,GarageGames/Torque3D,chaigler/Torque3D,lukaspj/Speciality,elfprince13/Torque3D,rextimmy/Torque3D,Azaezel/Torque3D,GarageGames/Torque3D,JeffProgrammer/Torque3D,Will-of-the-Wisp/Torque3D,FITTeamIndecisive/Torque3D,Duion/Torque3D,Will-of-the-Wisp/Torque3D,elfprince13/Torque3D,Will-of-the-Wisp/Torque3D,John3/Torque3D,ValtoGameEngines/Torque3D,GarageGames/Torque3D,elfprince13/Torque3D,elfprince13/Torque3D,FITTeamIndecisive/Torque3D,Torque3D-GameEngine/Torque3D,Torque3D-GameEngine/Torque3D,Duion/Torque3D,John3/Torque3D,Bloodknight/Torque3D,chaigler/Torque3D,aaravamudan2014/Torque3D,Bloodknight/Torque3D,Duion/Torque3D,lukaspj/Speciality,chaigler/Torque3D,elfprince13/Torque3D,aaravamudan2014/Torque3D,aaravamudan2014/Torque3D,Phantom139/Torque3D,rextimmy/Torque3D,John3/Torque3D,Torque3D-GameEngine/Torque3D,elfprince13/Torque3D,Duion/Torque3D,Will-of-the-Wisp/Torque3D,Duion/Torque3D,chaigler/Torque3D,elfprince13/Torque3D,lukaspj/Speciality,FITTeamIndecisive/Torque3D,Phantom139/Torque3D,rextimmy/Torque3D,aaravamudan2014/Torque3D,Phantom139/Torque3D,Bloodknight/Torque3D,lukaspj/Speciality,lukaspj/Speciality,ValtoGameEngines/Torque3D,Duion/Torque3D,Torque3D-GameEngine/Torque3D,Will-of-the-Wisp/Torque3D,JeffProgrammer/Torque3D,Azaezel/Torque3D,chaigler/Torque3D,FITTeamIndecisive/Torque3D,JeffProgrammer/Torque3D,Bloodknight/Torque3D,Duion/Torque3D,GarageGames/Torque3D,Will-of-the-Wisp/Torque3D,John3/Torque3D,Phantom139/Torque3D,rextimmy/Torque3D,FITTeamIndecisive/Torque3D,lukaspj/Speciality,Will-of-the-Wisp/Torque3D,elfprince13/Torque3D,JeffProgrammer/Torque3D,Azaezel/Torque3D,ValtoGameEngines/Torque3D,elfprince13/Torque3D,Torque3D-GameEngine/Torque3D,John3/Torque3D,Azaezel/Torque3D,aaravamudan2014/Torque3D,Bloodknight/Torque3D,Torque3D-GameEngine/Torque3D,Azaezel/Torque3D,JeffProgrammer/Torque3D,Duion/Torque3D,ValtoGameEngines/Torque3D,Bloodknight/Torque3D,chaigler/Torque3D,Will-of-the-Wisp/Torque3D,lukaspj/Speciality,Will-of-the-Wisp/Torque3D,JeffProgrammer/Torque3D,Will-of-the-Wisp/Torque3D,John3/Torque3D,chaigler/Torque3D,GarageGames/Torque3D,aaravamudan2014/Torque3D,Phantom139/Torque3D,Azaezel/Torque3D,GarageGames/Torque3D,Bloodknight/Torque3D,rextimmy/Torque3D,Phantom139/Torque3D
de06e3042dc0fdb836df963ae8387eca95f2d131
src/core/hooks.cc
src/core/hooks.cc
#include <string> #include <ccspec/core/hooks.h> #include <ccspec/core/example_group.h> namespace ccspec { namespace core { void before(std::string scope, Hook hook) { ExampleGroup* parent_group = groups_being_defined.top(); if (scope == "each" || scope == "example") parent_group->addBeforeEachHook(hook); else if (scope == "all" || scope == "context") parent_group->addBeforeAllHook(hook); else throw "no such before hook type"; } void after(std::string scope, Hook hook) { ExampleGroup* parent_group = groups_being_defined.top(); if (scope == "each" || scope == "example") parent_group->addAfterEachHook(hook); else if (scope == "all" || scope == "context") parent_group->addAfterAllHook(hook); else throw "no such before hook type"; } } // namespace core } // namespace ccspec
#include <string> #include <ccspec/core/hooks.h> #include <ccspec/core/example_group.h> namespace ccspec { namespace core { void before(std::string scope, Hook hook) { ExampleGroup* parent_group = groups_being_defined.top(); if (scope == "each" || scope == "example") parent_group->addBeforeEachHook(hook); else if (scope == "all" || scope == "context") parent_group->addBeforeAllHook(hook); else throw "no such before hook type"; } void after(std::string scope, Hook hook) { ExampleGroup* parent_group = groups_being_defined.top(); if (scope == "each" || scope == "example") parent_group->addAfterEachHook(hook); else if (scope == "all" || scope == "context") parent_group->addAfterAllHook(hook); else throw "no such after hook type"; } } // namespace core } // namespace ccspec
Correct after hook exception message
Correct after hook exception message
C++
mit
zhangsu/ccspec,tempbottle/ccspec,tempbottle/ccspec,michaelachrisco/ccspec,tempbottle/ccspec,zhangsu/ccspec,michaelachrisco/ccspec,michaelachrisco/ccspec,zhangsu/ccspec
b432d6600652b235053177270f86a3b4329caa43
src/OpenGL/HUDRenderer.cpp
src/OpenGL/HUDRenderer.cpp
// // WulfGame/OpenGL/HUDRenderer.cpp // Copyright (C) 2012 Lexi Robinson // This code is freely available under the MIT licence. // #include "OpenGL/HUDRenderer.h" using namespace Wulf::OpenGL; HUDRenderer::HUDRenderer() { // . . . } HUDRenderer::~HUDRenderer() { // . . . } void HUDRenderer::Setup(Wulf::OpenGL::ResourceManager& mgr, GLsizei textxureoffset) { VAO = mgr.CreateVAO(); shader = mgr.LoadShaders("HUD", "HUD", "HUD"); glUseProgram(shader); GLsizei bgtex = textxureoffset; // other texes are + etc glActiveTexture(GL_TEXTURE0 + bgtex); glBindTexture(GL_TEXTURE, mgr.LoadSingleTexture("pics/STATUSBARPIC.tga")); // BG Texture unit glUniform1i(glGetUniformLocation(shader, "bgsampler"), bgtex); // All done glUseProgram(0); } void HUDRenderer::Draw() { glUseProgram(shader); glBindVertexArray(VAO); glDrawArrays(GL_POINTS, 0, 1); glBindVertexArray(0); glUseProgram(0); } void HUDRenderer::UpdatePlayerInfo(const Wulf::Player& ply) { // . . . }
// // WulfGame/OpenGL/HUDRenderer.cpp // Copyright (C) 2012 Lexi Robinson // This code is freely available under the MIT licence. // #include "OpenGL/HUDRenderer.h" using namespace Wulf::OpenGL; HUDRenderer::HUDRenderer() { // . . . } HUDRenderer::~HUDRenderer() { // . . . } void HUDRenderer::Setup(Wulf::OpenGL::ResourceManager& mgr, GLsizei textxureoffset) { VAO = mgr.CreateVAO(); shader = mgr.LoadShaders("HUD", "HUD", "HUD"); glUseProgram(shader); GLsizei bgtex = textxureoffset; // other texes are + etc glActiveTexture(GL_TEXTURE0 + bgtex); glBindTexture(GL_TEXTURE_2D, mgr.LoadSingleTexture("pics/STATUSBARPIC.tga")); // BG Texture unit glUniform1i(glGetUniformLocation(shader, "bgsampler"), bgtex); // All done glUseProgram(0); } void HUDRenderer::Draw() { glUseProgram(shader); glBindVertexArray(VAO); glDrawArrays(GL_POINTS, 0, 1); glBindVertexArray(0); glUseProgram(0); } void HUDRenderer::UpdatePlayerInfo(const Wulf::Player& ply) { // . . . }
Fix invalid texture usage
Fix invalid texture usage
C++
mit
Lexicality/Wulf2012,Lexicality/Wulf2012
8ba05fa1286816e4a1f7ca4317e6ad1e260de4a8
SSPSolution/AIDLL/AIHandler.cpp
SSPSolution/AIDLL/AIHandler.cpp
#include "AIHandler.h" #define SUCCESS 1 #define FAIL 0 AIHandler::AIHandler(){} AIHandler::~AIHandler(){} int AIHandler::Shutdown() { for (int i = 0; i < this->m_maxOfAIComponents; i++) { delete this->m_AIComponents.at(i); } return SUCCESS; } int AIHandler::Initialize(int max) { this->WaypointUpdated = false; this->m_nrOfAIComponents = 0; if (max <= 0) { // Don't allow negative or zero initiated components max = 2; } this->m_maxOfAIComponents = max; for (int i = 0; i < this->m_maxOfAIComponents; i++) { this->m_AIComponents.push_back(CreateAIComponent(-1)); } return SUCCESS; } int AIHandler::Update(float deltaTime) { for (int i = 0; i < this->m_nrOfAIComponents; i++) { if (this->m_AIComponents.at(i)->AP_active && this->m_AIComponents.at(i)->AP_triggered) { // AIComponent logic/behavior, movement of e.g. platforms DirectX::XMVECTOR pos = this->m_AIComponents.at(i)->AP_position; int currentWaypoint = this->m_AIComponents.at(i)->AP_latestWaypointID; int nrOfWaypoint = this->m_AIComponents.at(i)->AP_nrOfWaypoint; int pattern = this->m_AIComponents.at(i)->AP_pattern; int time = this->m_AIComponents.at(i)->AP_time; int direction = this->m_AIComponents.at(i)->AP_direction; if (pattern == 1) { if (currentWaypoint == 0 || currentWaypoint == nrOfWaypoint) { if (direction == 0) this->m_AIComponents.at(i)->AP_direction = 1; else this->m_AIComponents.at(i)->AP_direction = 0; } } else if (pattern == 3) { //TODO Round-trip pattern } else { //Identical to pattern 2 (Circular) if (direction == 0) { if (WaypointApprox(i)) { currentWaypoint = this->m_AIComponents.at(i)->AP_nextWaypointID; this->m_AIComponents.at(i)->AP_nextWaypointID++; if (this->m_AIComponents.at(i)->AP_nextWaypointID >= this->m_AIComponents.at(i)->AP_nrOfWaypoint) this->m_AIComponents.at(i)->AP_nextWaypointID = 0; } } else { if (WaypointApprox(i)) { currentWaypoint = this->m_AIComponents.at(i)->AP_nextWaypointID; this->m_AIComponents.at(i)->AP_nextWaypointID--; if (this->m_AIComponents.at(i)->AP_nextWaypointID <= this->m_AIComponents.at(i)->AP_nrOfWaypoint) this->m_AIComponents.at(i)->AP_nextWaypointID = nrOfWaypoint; } } } //Update position if (this->WaypointUpdated == false) { this->m_AIComponents.at(i)->AP_dir = DirectX::XMVectorSubtract( this->m_AIComponents.at(i)->AP_waypoints[this->m_AIComponents.at(i)->AP_nextWaypointID], pos); this->WaypointUpdated = true; } DirectX::XMVECTOR v; v = DirectX::XMVectorScale(DirectX::XMVector3Normalize(v), this->m_AIComponents.at(i)->AP_speed); v = DirectX::XMVectorScale(v, deltaTime); this->m_AIComponents.at(i)->AP_position = DirectX::XMVectorMultiply(v, this->m_AIComponents.at(i)->AP_position); } } return SUCCESS; } void AIHandler::SetComponentActive(int compID) { this->m_AIComponents.at(compID)->AP_active = true; } void AIHandler::SetComponentFalse(int compID) { this->m_AIComponents.at(compID)->AP_active = false; } void AIHandler::SetEntityID(int compID, int entityID) { this->m_AIComponents.at(compID)->AP_entityID = entityID; } void AIHandler::SetTriggered(int compID, bool triggered) { this->m_AIComponents.at(compID)->AP_triggered = triggered; } void AIHandler::SetTime(int compID, int time) { this->m_AIComponents.at(compID)->AP_time = time; } void AIHandler::SetSpeed(int compID, float speed) { this->m_AIComponents.at(compID)->AP_speed = speed; } void AIHandler::SetDirection(int compID, int direction) { this->m_AIComponents.at(compID)->AP_direction = direction; } void AIHandler::SetCurrentWaypoint(int compID, int latestWaypoint) { this->m_AIComponents.at(compID)->AP_latestWaypointID = latestWaypoint; } void AIHandler::SetPattern(int compID, int pattern) { this->m_AIComponents.at(compID)->AP_pattern = pattern; } void AIHandler::SetWaypoints(int compID, DirectX::XMVECTOR waypoints[]) { for (int i = 0; i < 8; i++) { this->m_AIComponents.at(compID)->AP_waypoints[i] = waypoints[i]; this->m_AIComponents.at(compID)->AP_nrOfWaypoint++; } } int AIHandler::GetNrOfAIComponents() const { return this->m_nrOfAIComponents; } DirectX::XMVECTOR AIHandler::GetPosition(int compID) const { return this->m_AIComponents.at(compID)->AP_position; } AIComponent * AIHandler::GetNextAvailableComponents() { // Increase vector by initiating new AIComponents if (this->m_nrOfAIComponents == this->m_maxOfAIComponents) { int oldMax = this->m_maxOfAIComponents; this->m_maxOfAIComponents += this->m_maxOfAIComponents; for (int i = oldMax; i < this->m_maxOfAIComponents; i++) { this->m_AIComponents.push_back(CreateAIComponent(i)); } } this->m_nrOfAIComponents++; return this->m_AIComponents[this->m_nrOfAIComponents - 1]; } AIComponent* AIHandler::CreateAIComponent(int entityID) { AIComponent* newComponent = nullptr; newComponent = new AIComponent; newComponent->AP_active = 0; newComponent->AP_entityID = entityID; newComponent->AP_position = DirectX::XMVECTOR(); newComponent->AP_triggered = false; newComponent->AP_pattern = 0; newComponent->AP_time = 0; newComponent->AP_speed = 0; newComponent->AP_direction = 0; newComponent->AP_nextWaypointID = 0; newComponent->AP_latestWaypointID = 0; newComponent->AP_nrOfWaypoint = 0; for (int i = 0; i < 8; i++) { newComponent->AP_waypoints[i] = DirectX::XMVECTOR(); } return newComponent; } bool AIHandler::WaypointApprox(int compID) { using namespace DirectX; int next = this->m_AIComponents.at(compID)->AP_latestWaypointID; int current = this->m_AIComponents.at(compID)->AP_nextWaypointID; DirectX::XMVECTOR v = DirectX::XMVectorSubtract(this->m_AIComponents.at(compID)->AP_waypoints[next] ,this->m_AIComponents.at(compID)->AP_waypoints[current]); float length = VectorLength(v); if (length > 0.01) { this->WaypointUpdated = false; return true; } return false; } int AIHandler::GetNextWaypoint(int compID, int pattern) { int next = this->m_AIComponents.at(compID)->AP_latestWaypointID; int current = this->m_AIComponents.at(compID)->AP_nextWaypointID; if (pattern == 1) { //TODO Linear pattern next waypoint logic } else { } if (next == current) { } this->m_AIComponents.at(compID)->AP_latestWaypointID; this->m_AIComponents.at(compID)->AP_direction; return 0; } float AIHandler::VectorLength(DirectX::XMVECTOR v) { float length = DirectX::XMVectorGetX(DirectX::XMVector3Length(v)); return length; }
#include "AIHandler.h" #define SUCCESS 1 #define FAIL 0 AIHandler::AIHandler(){} AIHandler::~AIHandler(){} int AIHandler::Shutdown() { for (int i = 0; i < this->m_maxOfAIComponents; i++) { delete this->m_AIComponents.at(i); } return SUCCESS; } int AIHandler::Initialize(int max) { this->WaypointUpdated = false; this->m_nrOfAIComponents = 0; if (max <= 0) { // Don't allow negative or zero initiated components max = 2; } this->m_maxOfAIComponents = max; for (int i = 0; i < this->m_maxOfAIComponents; i++) { this->m_AIComponents.push_back(CreateAIComponent(-1)); } return SUCCESS; } int AIHandler::Update(float deltaTime) { for (int i = 0; i < this->m_nrOfAIComponents; i++) { if (this->m_AIComponents.at(i)->AP_active && this->m_AIComponents.at(i)->AP_triggered) { // AIComponent logic/behavior, movement of e.g. platforms DirectX::XMVECTOR pos = this->m_AIComponents.at(i)->AP_position; int currentWaypoint = this->m_AIComponents.at(i)->AP_latestWaypointID; int nrOfWaypoint = this->m_AIComponents.at(i)->AP_nrOfWaypoint; int pattern = this->m_AIComponents.at(i)->AP_pattern; int time = this->m_AIComponents.at(i)->AP_time; int direction = this->m_AIComponents.at(i)->AP_direction; if (pattern == 1) { if (currentWaypoint == 0 || currentWaypoint == nrOfWaypoint) { if (direction == 0) this->m_AIComponents.at(i)->AP_direction = 1; else this->m_AIComponents.at(i)->AP_direction = 0; } } else if (pattern == 3) { //TODO Round-trip pattern } else { //Identical to pattern 2 (Circular) if (direction == 0) { if (WaypointApprox(i)) { currentWaypoint = this->m_AIComponents.at(i)->AP_nextWaypointID; this->m_AIComponents.at(i)->AP_nextWaypointID++; if (this->m_AIComponents.at(i)->AP_nextWaypointID >= this->m_AIComponents.at(i)->AP_nrOfWaypoint) this->m_AIComponents.at(i)->AP_nextWaypointID = 0; } } else { if (WaypointApprox(i)) { currentWaypoint = this->m_AIComponents.at(i)->AP_nextWaypointID; this->m_AIComponents.at(i)->AP_nextWaypointID--; if (this->m_AIComponents.at(i)->AP_nextWaypointID <= this->m_AIComponents.at(i)->AP_nrOfWaypoint) this->m_AIComponents.at(i)->AP_nextWaypointID = nrOfWaypoint; } } } //Update position if (this->WaypointUpdated == false) { this->m_AIComponents.at(i)->AP_dir = DirectX::XMVectorSubtract( this->m_AIComponents.at(i)->AP_waypoints[this->m_AIComponents.at(i)->AP_nextWaypointID], pos); this->WaypointUpdated = true; } DirectX::XMVECTOR v = DirectX::XMVECTOR(); v = DirectX::XMVectorScale(DirectX::XMVector3Normalize(v), this->m_AIComponents.at(i)->AP_speed); v = DirectX::XMVectorScale(v, deltaTime); this->m_AIComponents.at(i)->AP_position = DirectX::XMVectorMultiply(v, this->m_AIComponents.at(i)->AP_position); } } return SUCCESS; } void AIHandler::SetComponentActive(int compID) { this->m_AIComponents.at(compID)->AP_active = true; } void AIHandler::SetComponentFalse(int compID) { this->m_AIComponents.at(compID)->AP_active = false; } void AIHandler::SetEntityID(int compID, int entityID) { this->m_AIComponents.at(compID)->AP_entityID = entityID; } void AIHandler::SetTriggered(int compID, bool triggered) { this->m_AIComponents.at(compID)->AP_triggered = triggered; } void AIHandler::SetTime(int compID, int time) { this->m_AIComponents.at(compID)->AP_time = time; } void AIHandler::SetSpeed(int compID, float speed) { this->m_AIComponents.at(compID)->AP_speed = speed; } void AIHandler::SetDirection(int compID, int direction) { this->m_AIComponents.at(compID)->AP_direction = direction; } void AIHandler::SetCurrentWaypoint(int compID, int latestWaypoint) { this->m_AIComponents.at(compID)->AP_latestWaypointID = latestWaypoint; } void AIHandler::SetPattern(int compID, int pattern) { this->m_AIComponents.at(compID)->AP_pattern = pattern; } void AIHandler::SetWaypoints(int compID, DirectX::XMVECTOR waypoints[]) { for (int i = 0; i < 8; i++) { this->m_AIComponents.at(compID)->AP_waypoints[i] = waypoints[i]; this->m_AIComponents.at(compID)->AP_nrOfWaypoint++; } } int AIHandler::GetNrOfAIComponents() const { return this->m_nrOfAIComponents; } DirectX::XMVECTOR AIHandler::GetPosition(int compID) const { return this->m_AIComponents.at(compID)->AP_position; } AIComponent * AIHandler::GetNextAvailableComponents() { // Increase vector by initiating new AIComponents if (this->m_nrOfAIComponents == this->m_maxOfAIComponents) { int oldMax = this->m_maxOfAIComponents; this->m_maxOfAIComponents += this->m_maxOfAIComponents; for (int i = oldMax; i < this->m_maxOfAIComponents; i++) { this->m_AIComponents.push_back(CreateAIComponent(i)); } } this->m_nrOfAIComponents++; return this->m_AIComponents[this->m_nrOfAIComponents - 1]; } AIComponent* AIHandler::CreateAIComponent(int entityID) { AIComponent* newComponent = nullptr; newComponent = new AIComponent; newComponent->AP_active = 0; newComponent->AP_entityID = entityID; newComponent->AP_position = DirectX::XMVECTOR(); newComponent->AP_triggered = false; newComponent->AP_pattern = 0; newComponent->AP_time = 0; newComponent->AP_speed = 0; newComponent->AP_direction = 0; newComponent->AP_nextWaypointID = 0; newComponent->AP_latestWaypointID = 0; newComponent->AP_nrOfWaypoint = 0; for (int i = 0; i < 8; i++) { newComponent->AP_waypoints[i] = DirectX::XMVECTOR(); } return newComponent; } bool AIHandler::WaypointApprox(int compID) { using namespace DirectX; int next = this->m_AIComponents.at(compID)->AP_latestWaypointID; int current = this->m_AIComponents.at(compID)->AP_nextWaypointID; DirectX::XMVECTOR v = DirectX::XMVectorSubtract(this->m_AIComponents.at(compID)->AP_waypoints[next] ,this->m_AIComponents.at(compID)->AP_waypoints[current]); float length = VectorLength(v); if (length > 0.01) { this->WaypointUpdated = false; return true; } return false; } int AIHandler::GetNextWaypoint(int compID, int pattern) { int next = this->m_AIComponents.at(compID)->AP_latestWaypointID; int current = this->m_AIComponents.at(compID)->AP_nextWaypointID; if (pattern == 1) { //TODO Linear pattern next waypoint logic } else { } if (next == current) { } this->m_AIComponents.at(compID)->AP_latestWaypointID; this->m_AIComponents.at(compID)->AP_direction; return 0; } float AIHandler::VectorLength(DirectX::XMVECTOR v) { float length = DirectX::XMVectorGetX(DirectX::XMVector3Length(v)); return length; }
UPDATE Warning handled by initializing XMVECTOR
UPDATE Warning handled by initializing XMVECTOR
C++
apache-2.0
Chringo/SSP,Chringo/SSP
f777ecc332095def132138ed20afbf86f98ec5dc
SSPSolution/AIDLL/AIHandler.cpp
SSPSolution/AIDLL/AIHandler.cpp
#include "AIHandler.h" #define SUCCESS 1 #define FAIL 0 AIHandler::AIHandler(){} AIHandler::~AIHandler(){} int AIHandler::Shutdown() { for (int i = 0; i < this->m_maxOfAIComponents; i++) { delete this->m_AIComponents.at(i); } return SUCCESS; } int AIHandler::Initialize(int max) { this->WaypointUpdated = false; this->m_nrOfAIComponents = 0; if (max <= 0) { // Don't allow negative or zero initiated components max = 2; } this->m_maxOfAIComponents = max; for (int i = 0; i < this->m_maxOfAIComponents; i++) { this->m_AIComponents.push_back(CreateAIComponent(-1)); } return SUCCESS; } int AIHandler::Update(float deltaTime) { for (int i = 0; i < this->m_nrOfAIComponents; i++) { if (this->m_AIComponents.at(i)->AP_active && this->m_AIComponents.at(i)->AP_triggered) { // AIComponent logic/behavior, movement of e.g. platforms DirectX::XMVECTOR pos = this->m_AIComponents.at(i)->AP_position; int currentWaypoint = this->m_AIComponents.at(i)->AP_latestWaypointID; int nrOfWaypoint = this->m_AIComponents.at(i)->AP_nrOfWaypoint; int pattern = this->m_AIComponents.at(i)->AP_pattern; int time = this->m_AIComponents.at(i)->AP_time; int direction = this->m_AIComponents.at(i)->AP_direction; if (pattern == 1) { if (currentWaypoint == 0 || currentWaypoint == nrOfWaypoint) { if (direction == 0) this->m_AIComponents.at(i)->AP_direction = 1; else this->m_AIComponents.at(i)->AP_direction = 0; } } else if (pattern == 3) { //TODO Round-trip pattern } else { //Identical to pattern 2 (Circular) if (direction == 0) { if (WaypointApprox(i)) { currentWaypoint = this->m_AIComponents.at(i)->AP_nextWaypointID; this->m_AIComponents.at(i)->AP_nextWaypointID++; if (this->m_AIComponents.at(i)->AP_nextWaypointID >= this->m_AIComponents.at(i)->AP_nrOfWaypoint) this->m_AIComponents.at(i)->AP_nextWaypointID = 0; } } else { if (WaypointApprox(i)) { currentWaypoint = this->m_AIComponents.at(i)->AP_nextWaypointID; this->m_AIComponents.at(i)->AP_nextWaypointID--; if (this->m_AIComponents.at(i)->AP_nextWaypointID <= this->m_AIComponents.at(i)->AP_nrOfWaypoint) this->m_AIComponents.at(i)->AP_nextWaypointID = nrOfWaypoint; } } } //Update position if (this->WaypointUpdated == false) { this->m_AIComponents.at(i)->AP_dir = DirectX::XMVectorSubtract( this->m_AIComponents.at(i)->AP_waypoints[this->m_AIComponents.at(i)->AP_nextWaypointID], pos); this->WaypointUpdated = true; } DirectX::XMVECTOR v = DirectX::XMVECTOR(); v = DirectX::XMVectorScale(DirectX::XMVector3Normalize(v), this->m_AIComponents.at(i)->AP_speed); v = DirectX::XMVectorScale(v, deltaTime); this->m_AIComponents.at(i)->AP_position = DirectX::XMVectorMultiply(v, this->m_AIComponents.at(i)->AP_position); } } return SUCCESS; } void AIHandler::SetComponentActive(int compID) { this->m_AIComponents.at(compID)->AP_active = true; } void AIHandler::SetComponentFalse(int compID) { this->m_AIComponents.at(compID)->AP_active = false; } void AIHandler::SetEntityID(int compID, int entityID) { this->m_AIComponents.at(compID)->AP_entityID = entityID; } void AIHandler::SetTriggered(int compID, bool triggered) { this->m_AIComponents.at(compID)->AP_triggered = triggered; } void AIHandler::SetTime(int compID, int time) { this->m_AIComponents.at(compID)->AP_time = time; } void AIHandler::SetSpeed(int compID, float speed) { this->m_AIComponents.at(compID)->AP_speed = speed; } void AIHandler::SetDirection(int compID, int direction) { this->m_AIComponents.at(compID)->AP_direction = direction; } void AIHandler::SetCurrentWaypoint(int compID, int latestWaypoint) { this->m_AIComponents.at(compID)->AP_latestWaypointID = latestWaypoint; } void AIHandler::SetPattern(int compID, int pattern) { this->m_AIComponents.at(compID)->AP_pattern = pattern; } void AIHandler::SetWaypoints(int compID, DirectX::XMVECTOR waypoints[]) { for (int i = 0; i < 8; i++) { this->m_AIComponents.at(compID)->AP_waypoints[i] = waypoints[i]; this->m_AIComponents.at(compID)->AP_nrOfWaypoint++; } } int AIHandler::GetNrOfAIComponents() const { return this->m_nrOfAIComponents; } DirectX::XMVECTOR AIHandler::GetPosition(int compID) const { return this->m_AIComponents.at(compID)->AP_position; } AIComponent * AIHandler::GetNextAvailableComponents() { // Increase vector by initiating new AIComponents if (this->m_nrOfAIComponents == this->m_maxOfAIComponents) { int oldMax = this->m_maxOfAIComponents; this->m_maxOfAIComponents += this->m_maxOfAIComponents; for (int i = oldMax; i < this->m_maxOfAIComponents; i++) { this->m_AIComponents.push_back(CreateAIComponent(i)); } } this->m_nrOfAIComponents++; return this->m_AIComponents[this->m_nrOfAIComponents - 1]; } AIComponent* AIHandler::CreateAIComponent(int entityID) { AIComponent* newComponent = nullptr; newComponent = new AIComponent; newComponent->AP_active = 0; newComponent->AP_entityID = entityID; newComponent->AP_position = DirectX::XMVECTOR(); newComponent->AP_triggered = false; newComponent->AP_pattern = 0; newComponent->AP_time = 0; newComponent->AP_speed = 0; newComponent->AP_direction = 0; newComponent->AP_nextWaypointID = 0; newComponent->AP_latestWaypointID = 0; newComponent->AP_nrOfWaypoint = 0; for (int i = 0; i < 8; i++) { newComponent->AP_waypoints[i] = DirectX::XMVECTOR(); } return newComponent; } bool AIHandler::WaypointApprox(int compID) { using namespace DirectX; int next = this->m_AIComponents.at(compID)->AP_latestWaypointID; int current = this->m_AIComponents.at(compID)->AP_nextWaypointID; DirectX::XMVECTOR v = DirectX::XMVectorSubtract(this->m_AIComponents.at(compID)->AP_waypoints[next] ,this->m_AIComponents.at(compID)->AP_waypoints[current]); float length = VectorLength(v); if (length > 0.01) { this->WaypointUpdated = false; return true; } return false; } int AIHandler::GetNextWaypoint(int compID, int pattern) { int next = this->m_AIComponents.at(compID)->AP_latestWaypointID; int current = this->m_AIComponents.at(compID)->AP_nextWaypointID; if (pattern == 1) { //TODO Linear pattern next waypoint logic } else { } if (next == current) { } this->m_AIComponents.at(compID)->AP_latestWaypointID; this->m_AIComponents.at(compID)->AP_direction; return 0; } float AIHandler::VectorLength(DirectX::XMVECTOR v) { float length = DirectX::XMVectorGetX(DirectX::XMVector3Length(v)); return length; }
#include "AIHandler.h" #define SUCCESS 1 #define FAIL 0 AIHandler::AIHandler(){} AIHandler::~AIHandler(){} int AIHandler::Shutdown() { for (int i = 0; i < this->m_maxOfAIComponents; i++) { delete this->m_AIComponents.at(i); } return SUCCESS; } int AIHandler::Initialize(int max) { this->WaypointUpdated = false; this->m_nrOfAIComponents = 0; if (max <= 0) { // Don't allow negative or zero initiated components max = 2; } this->m_maxOfAIComponents = max; for (int i = 0; i < this->m_maxOfAIComponents; i++) { this->m_AIComponents.push_back(CreateAIComponent(-1)); } return SUCCESS; } int AIHandler::Update(float deltaTime) { for (int i = 0; i < this->m_nrOfAIComponents; i++) { if (this->m_AIComponents.at(i)->AP_active && this->m_AIComponents.at(i)->AP_triggered) { // AIComponent logic/behavior, movement of e.g. platforms DirectX::XMVECTOR pos = this->m_AIComponents.at(i)->AP_position; int currentWaypoint = this->m_AIComponents.at(i)->AP_latestWaypointID; int nrOfWaypoint = this->m_AIComponents.at(i)->AP_nrOfWaypoint; int pattern = this->m_AIComponents.at(i)->AP_pattern; int time = this->m_AIComponents.at(i)->AP_time; int direction = this->m_AIComponents.at(i)->AP_direction; if (pattern == 1) { if (currentWaypoint == 0 || currentWaypoint == nrOfWaypoint) { if (direction == 0) this->m_AIComponents.at(i)->AP_direction = 1; else this->m_AIComponents.at(i)->AP_direction = 0; } } else if (pattern == 3) { //TODO Round-trip pattern } else { //Identical to pattern 2 (Circular) if (direction == 0) { if (WaypointApprox(i)) { currentWaypoint = this->m_AIComponents.at(i)->AP_nextWaypointID; this->m_AIComponents.at(i)->AP_nextWaypointID++; if (this->m_AIComponents.at(i)->AP_nextWaypointID >= this->m_AIComponents.at(i)->AP_nrOfWaypoint) this->m_AIComponents.at(i)->AP_nextWaypointID = 0; } } else { if (WaypointApprox(i)) { currentWaypoint = this->m_AIComponents.at(i)->AP_nextWaypointID; this->m_AIComponents.at(i)->AP_nextWaypointID--; if (this->m_AIComponents.at(i)->AP_nextWaypointID <= this->m_AIComponents.at(i)->AP_nrOfWaypoint) this->m_AIComponents.at(i)->AP_nextWaypointID = nrOfWaypoint; } } } //Update position if (this->WaypointUpdated == false) { this->m_AIComponents.at(i)->AP_dir = DirectX::XMVector4Normalize(DirectX::XMVectorSubtract( this->m_AIComponents.at(i)->AP_waypoints[this->m_AIComponents.at(i)->AP_nextWaypointID], pos)); this->WaypointUpdated = true; } DirectX::XMVECTOR v = DirectX::XMVECTOR(); v = DirectX::XMVectorScale(DirectX::XMVector3Normalize(this->m_AIComponents.at(i)->AP_dir), this->m_AIComponents.at(i)->AP_speed); v = DirectX::XMVectorScale(v, deltaTime); this->m_AIComponents.at(i)->AP_position = DirectX::XMVectorMultiply(v, this->m_AIComponents.at(i)->AP_position); } } return SUCCESS; } void AIHandler::SetComponentActive(int compID) { this->m_AIComponents.at(compID)->AP_active = true; } void AIHandler::SetComponentFalse(int compID) { this->m_AIComponents.at(compID)->AP_active = false; } void AIHandler::SetEntityID(int compID, int entityID) { this->m_AIComponents.at(compID)->AP_entityID = entityID; } void AIHandler::SetTriggered(int compID, bool triggered) { this->m_AIComponents.at(compID)->AP_triggered = triggered; } void AIHandler::SetTime(int compID, int time) { this->m_AIComponents.at(compID)->AP_time = time; } void AIHandler::SetSpeed(int compID, float speed) { this->m_AIComponents.at(compID)->AP_speed = speed; } void AIHandler::SetDirection(int compID, int direction) { this->m_AIComponents.at(compID)->AP_direction = direction; } void AIHandler::SetCurrentWaypoint(int compID, int latestWaypoint) { this->m_AIComponents.at(compID)->AP_latestWaypointID = latestWaypoint; } void AIHandler::SetPattern(int compID, int pattern) { this->m_AIComponents.at(compID)->AP_pattern = pattern; } void AIHandler::SetWaypoints(int compID, DirectX::XMVECTOR waypoints[]) { for (int i = 0; i < 8; i++) { this->m_AIComponents.at(compID)->AP_waypoints[i] = waypoints[i]; this->m_AIComponents.at(compID)->AP_nrOfWaypoint++; } } int AIHandler::GetNrOfAIComponents() const { return this->m_nrOfAIComponents; } DirectX::XMVECTOR AIHandler::GetPosition(int compID) const { return this->m_AIComponents.at(compID)->AP_position; } AIComponent * AIHandler::GetNextAvailableComponents() { // Increase vector by initiating new AIComponents if (this->m_nrOfAIComponents == this->m_maxOfAIComponents) { int oldMax = this->m_maxOfAIComponents; this->m_maxOfAIComponents += this->m_maxOfAIComponents; for (int i = oldMax; i < this->m_maxOfAIComponents; i++) { this->m_AIComponents.push_back(CreateAIComponent(i)); } } this->m_nrOfAIComponents++; return this->m_AIComponents[this->m_nrOfAIComponents - 1]; } AIComponent* AIHandler::CreateAIComponent(int entityID) { AIComponent* newComponent = nullptr; newComponent = new AIComponent; newComponent->AP_active = 0; newComponent->AP_entityID = entityID; newComponent->AP_position = DirectX::XMVECTOR(); newComponent->AP_triggered = false; newComponent->AP_pattern = 0; newComponent->AP_time = 0; newComponent->AP_speed = 0; newComponent->AP_direction = 0; newComponent->AP_nextWaypointID = 0; newComponent->AP_latestWaypointID = 0; newComponent->AP_nrOfWaypoint = 0; for (int i = 0; i < 8; i++) { newComponent->AP_waypoints[i] = DirectX::XMVECTOR(); } return newComponent; } bool AIHandler::WaypointApprox(int compID) { int current = this->m_AIComponents.at(compID)->AP_latestWaypointID; int next = this->m_AIComponents.at(compID)->AP_nextWaypointID; DirectX::XMVECTOR v = DirectX::XMVectorSubtract(this->m_AIComponents.at(compID)->AP_waypoints[next] ,this->m_AIComponents.at(compID)->AP_waypoints[current]); float length = VectorLength(v); if (length < 0.01) { this->WaypointUpdated = false; return true; } return false; } int AIHandler::GetNextWaypoint(int compID, int pattern) { int next = this->m_AIComponents.at(compID)->AP_latestWaypointID; int current = this->m_AIComponents.at(compID)->AP_nextWaypointID; if (pattern == 1) { //TODO Linear pattern next waypoint logic } else { } if (next == current) { } this->m_AIComponents.at(compID)->AP_latestWaypointID; this->m_AIComponents.at(compID)->AP_direction; return 0; } float AIHandler::VectorLength(DirectX::XMVECTOR v) { float length = DirectX::XMVectorGetX(DirectX::XMVector3Length(v)); return length; }
UPDATE position calculations
UPDATE position calculations
C++
apache-2.0
Chringo/SSP,Chringo/SSP
a5e37addc8a4dbab343f1ee27b2d74ef62a6db54
id.cpp
id.cpp
#include "id.hpp" ID::ID() { init(Department(), 0, ""); } ID::ID(const ID& c) { copy(c); } ID& ID::operator= (const ID &c) { if (this == &c) return *this; copy(c); return *this; } ID::ID(string str) { string d, d1, d2, n, s; int num; long firstSpace, firstDigit, lastDigit, lastChar; // cout << "Parsed '" << str << "' to get '"; // cout << "Called ID::ID() with string '" << str << "'" << endl; // Make sure everything is uppercase std::transform(str.begin(), str.end(), str.begin(), ::toupper); // Remove extraneous spaces if (str.at(0) == ' ') str.erase(0, 1); if (str.at(str.length()-1) == ' ') str = str.substr(0, str.length()-1); firstSpace = str.find_first_of(" "); firstDigit = str.find_first_of("0123456789"); lastDigit = str.find_last_of("0123456789"); lastChar = str.find_last_of("ABCDEFGHIJKLMNOPQRSTUVWXYZ"); // Split into Department, Number, and Section // pull out the department string if (firstSpace == string::npos) // if there is no space d = str.substr(0, firstDigit); else d = str.substr(0, firstSpace); // there is a space // check for one of those dastardly split departments if (d.find('/') != string::npos) { d1 = d.substr(0,2); d2 = d.substr(3,2); } n = str.substr(firstDigit, str.length()); if (!isdigit(n[n.length()-1])) n = str.substr(firstDigit, n.length()-1); num = stringToInt(n); if (lastChar > lastDigit) // there is a section s = str[lastChar]; // cout << "Parsed '" << str << "' to get '"; // cout << d << " "; // if (!d1.empty() && !d2.empty()) // cout << "(" << d1 << " " << d2 << ") "; // cout << n << s << "'." << endl; init(Department(d), num, s); if (!d1.empty() && !d2.empty()) { departments.clear(); departments.push_back(Department(d1)); departments.push_back(Department(d2)); } // cout << *this << endl; } ID::ID(string dn, string s) { ID(dn+s); } ID::ID(string d, string n, string s) { ID(d + n + s); } ID::ID(Department d, int n, string s) { init(d, n, s); } void ID::init(Department d, int n, string s) { departments.push_back(d); number = n; section = s; } void ID::copy(const ID& c) { departments = c.departments; number = c.number; section = c.section; } Department ID::getDepartment(int i = 0) { return departments.at(i); } const Department ID::getDepartment_const(int i = 0) { return departments.at(i); } int ID::getNumber() { return number; } string ID::getSection() { return section; } bool operator== (const ID &i1, const ID &i2) { bool dept = (i1.departments.at(0) < i2.departments.at(0)); bool num = (i1.number < i2.number); bool sec = (i1.section < i2.section); return (dept && num && sec); } bool operator!= (ID &i1, ID &i2) { return !(i1 == i2); } bool operator< (const ID &i1, const ID &i2) { bool dept = (i1.departments.at(0) < i2.departments.at(0)); bool num = (i1.number < i2.number); bool sec = (i1.section < i2.section); return (dept && num && sec); } ostream& ID::getData(ostream& os) { for (vector<Department>::iterator i = departments.begin(); i != departments.end(); ++i) { if (departments.size() == 1) os << i->getName(); else { os << i->getName(); if (i != departments.end()-1) os << "/"; } } os << " "; os << number; if (!section.empty()) os << "[" << section << "]"; return os; } ostream& operator<<(ostream& os, ID& item) { return item.getData(os); } void ID::display() { cout << *this << endl; }
#include "id.hpp" ID::ID() { init(Department(), 0, ""); } ID::ID(const ID& c) { copy(c); } ID& ID::operator= (const ID &c) { if (this == &c) return *this; copy(c); return *this; } ID::ID(string str) { string d, d1, d2, n, s; int num; long firstSpace, firstDigit, lastDigit, lastChar; // cout << "Parsed '" << str << "' to get '"; // cout << "Called ID::ID() with string '" << str << "'" << endl; // Make sure everything is uppercase std::transform(str.begin(), str.end(), str.begin(), ::toupper); // Remove extraneous spaces if (str.at(0) == ' ') str.erase(0, 1); if (str.at(str.length()-1) == ' ') str = str.substr(0, str.length()-1); firstSpace = str.find_first_of(" "); firstDigit = str.find_first_of("0123456789"); lastDigit = str.find_last_of("0123456789"); lastChar = str.find_last_of("ABCDEFGHIJKLMNOPQRSTUVWXYZ"); // Split into Department, Number, and Section // pull out the department string if (firstSpace == string::npos) // if there is no space d = str.substr(0, firstDigit); else d = str.substr(0, firstSpace); // there is a space // check for one of those dastardly split departments if (d.find('/') != string::npos) { d1 = d.substr(0,2); d2 = d.substr(3,2); } n = str.substr(firstDigit, str.length()); if (!isdigit(n[n.length()-1])) n = str.substr(firstDigit, n.length()-1); num = stringToInt(n); if (lastChar > lastDigit) // there is a section s = str[lastChar]; // cout << "Parsed '" << str << "' to get '"; // cout << d << " "; // if (!d1.empty() && !d2.empty()) // cout << "(" << d1 << " " << d2 << ") "; // cout << n << s << "'." << endl; init(Department(d), num, s); if (!d1.empty() && !d2.empty()) { departments.clear(); departments.push_back(Department(d1)); departments.push_back(Department(d2)); } // cout << *this << endl; } ID::ID(string dn, string s) { ID(dn+s); } ID::ID(string d, string n, string s) { ID(d + n + s); } ID::ID(Department d, int n, string s) { init(d, n, s); } void ID::init(Department d, int n, string s) { departments.push_back(d); number = n; section = s; } void ID::copy(const ID& c) { departments = c.departments; number = c.number; section = c.section; } Department ID::getDepartment(int i = 0) { return departments.at(i); } const Department ID::getDepartment_const(int i = 0) { return departments.at(i); } int ID::getNumber() { return number; } string ID::getSection() { return section; } bool operator== (const ID &i1, const ID &i2) { bool dept = (i1.departments.at(0) == i2.departments.at(0)); bool num = (i1.number == i2.number); bool sec = (i1.section == i2.section); return (dept && num && sec); } bool operator!= (ID &i1, ID &i2) { return !(i1 == i2); } bool operator< (const ID &i1, const ID &i2) { bool dept = (i1.departments.at(0) < i2.departments.at(0)); bool num = (i1.number < i2.number); bool sec = (i1.section < i2.section); return (dept && num && sec); } ostream& ID::getData(ostream& os) { for (vector<Department>::iterator i = departments.begin(); i != departments.end(); ++i) { if (departments.size() == 1) os << i->getName(); else { os << i->getName(); if (i != departments.end()-1) os << "/"; } } os << " "; os << number; if (!section.empty()) os << "[" << section << "]"; return os; } ostream& operator<<(ostream& os, ID& item) { return item.getData(os); } void ID::display() { cout << *this << endl; }
Fix ID's comparison function
Fix ID's comparison function it doesn't matter if something is *less than* something else, as long as they are *equal*.
C++
agpl-3.0
hawkrives/gobbldygook,hawkrives/gobbldygook,hawkrives/gobbldygook
451dc7b46780bb80e388e9d219957ad9a698684e
Source/Graphics/Framebuffer.cpp
Source/Graphics/Framebuffer.cpp
#include "Shiny/ShinyAssert.h" #include "Shiny/Graphics/Context.h" #include "Shiny/Graphics/Framebuffer.h" #include "Shiny/Graphics/Texture.h" namespace Shiny { Framebuffer::Framebuffer(GLsizei attachmentWidth, GLsizei attachmentHeight, bool withDepthStencil, const std::vector<Tex::InternalFormat>& attachmentFormats) : fbo(0), width(0), height(0) { glGenFramebuffers(1, &fbo); reset(attachmentWidth, attachmentHeight, withDepthStencil, attachmentFormats); } void Framebuffer::release() { if (fbo) { Context::current()->onFramebufferDeleted(fbo); glDeleteFramebuffers(1, &fbo); fbo = 0; } } void Framebuffer::move(Framebuffer&& other) { fbo = other.fbo; depthStencilAttachment = std::move(other.depthStencilAttachment); colorAttachments = std::move(other.colorAttachments); width = other.width; height = other.height; other.fbo = 0; other.width = 0; other.height = 0; } void Framebuffer::reset(GLsizei attachmentWidth, GLsizei attachmentHeight, bool withDepthStencil, const std::vector<Tex::InternalFormat>& attachmentFormats) { // Determine the texture size from the viewport GLint viewport[4]; glGetIntegerv(GL_VIEWPORT, viewport); width = attachmentWidth <= 0 ? viewport[2] : attachmentWidth; height = attachmentHeight <= 0 ? viewport[3] : attachmentHeight; Context::current()->bindFramebuffer(fbo); depthStencilAttachment = nullptr; if (withDepthStencil) { Tex::Specification depthStencilSpecification = Tex::Specification::create2d(); depthStencilSpecification.internalFormat = Tex::InternalFormat::kDepth24Stencil8; depthStencilSpecification.width = width; depthStencilSpecification.height = height; depthStencilSpecification.providedDataFormat = Tex::ProvidedDataFormat::kDepthStencil; depthStencilSpecification.providedDataType = Tex::ProvidedDataType::kUnsignedInt248; depthStencilAttachment = std::make_shared<Texture>(depthStencilSpecification); depthStencilAttachment->setParam(Tex::IntParam::kMinFilter, GL_NEAREST); depthStencilAttachment->setParam(Tex::IntParam::kMagFilter, GL_NEAREST); depthStencilAttachment->setParam(Tex::IntParam::kWrapS, GL_CLAMP_TO_EDGE); depthStencilAttachment->setParam(Tex::IntParam::kWrapT, GL_CLAMP_TO_EDGE); depthStencilAttachment->unbind(); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_TEXTURE_2D, depthStencilAttachment->getId(), 0); } Tex::Specification colorSpecification = Tex::Specification::create2d(); colorSpecification.width = width; colorSpecification.height = height; colorAttachments.clear(); colorAttachments.reserve(attachmentFormats.size()); for (GLsizei i = 0; i < attachmentFormats.size(); ++i) { colorSpecification.internalFormat = attachmentFormats[i]; colorAttachments.push_back(std::make_shared<Texture>(colorSpecification)); colorAttachments[i]->setParam(Tex::IntParam::kMinFilter, GL_LINEAR); colorAttachments[i]->setParam(Tex::IntParam::kMagFilter, GL_LINEAR); colorAttachments[i]->setParam(Tex::IntParam::kWrapS, GL_CLAMP_TO_BORDER); colorAttachments[i]->setParam(Tex::IntParam::kWrapT, GL_CLAMP_TO_BORDER); colorAttachments[i]->unbind(); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + i, GL_TEXTURE_2D, colorAttachments[i]->getId(), 0); } ASSERT(glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE); bindDefaultFramebuffer(); } void Framebuffer::setResolution(GLsizei attachmentWidth, GLsizei attachmentHeight) { std::vector<Tex::InternalFormat> internalFormats(colorAttachments.size()); for (std::size_t i = 0; i < internalFormats.size(); ++i) { internalFormats[i] = colorAttachments[i]->getSpecification().internalFormat; } reset(attachmentWidth, attachmentHeight, depthStencilAttachment != nullptr, internalFormats); } void Framebuffer::bind() { Context::current()->bindFramebuffer(fbo); glViewport(0, 0, width, height); ASSERT(glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE); } } // namespace Shiny
#include "Shiny/ShinyAssert.h" #include "Shiny/Graphics/Context.h" #include "Shiny/Graphics/Framebuffer.h" #include "Shiny/Graphics/Texture.h" namespace Shiny { Framebuffer::Framebuffer(GLsizei attachmentWidth, GLsizei attachmentHeight, bool withDepthStencil, const std::vector<Tex::InternalFormat>& attachmentFormats) : fbo(0), width(0), height(0) { glGenFramebuffers(1, &fbo); reset(attachmentWidth, attachmentHeight, withDepthStencil, attachmentFormats); } void Framebuffer::release() { if (fbo) { Context::current()->onFramebufferDeleted(fbo); glDeleteFramebuffers(1, &fbo); fbo = 0; } } void Framebuffer::move(Framebuffer&& other) { fbo = other.fbo; depthStencilAttachment = std::move(other.depthStencilAttachment); colorAttachments = std::move(other.colorAttachments); width = other.width; height = other.height; other.fbo = 0; other.width = 0; other.height = 0; } void Framebuffer::reset(GLsizei attachmentWidth, GLsizei attachmentHeight, bool withDepthStencil, const std::vector<Tex::InternalFormat>& attachmentFormats) { // Determine the texture size from the viewport GLint viewport[4]; glGetIntegerv(GL_VIEWPORT, viewport); width = attachmentWidth <= 0 ? viewport[2] : attachmentWidth; height = attachmentHeight <= 0 ? viewport[3] : attachmentHeight; Context::current()->bindFramebuffer(fbo); depthStencilAttachment = nullptr; if (withDepthStencil) { Tex::Specification depthStencilSpecification = Tex::Specification::create2d(); depthStencilSpecification.internalFormat = Tex::InternalFormat::kDepth24Stencil8; depthStencilSpecification.width = width; depthStencilSpecification.height = height; depthStencilSpecification.providedDataFormat = Tex::ProvidedDataFormat::kDepthStencil; depthStencilSpecification.providedDataType = Tex::ProvidedDataType::kUnsignedInt248; depthStencilAttachment = std::make_shared<Texture>(depthStencilSpecification); depthStencilAttachment->setParam(Tex::IntParam::kMinFilter, GL_NEAREST); depthStencilAttachment->setParam(Tex::IntParam::kMagFilter, GL_NEAREST); depthStencilAttachment->setParam(Tex::IntParam::kWrapS, GL_CLAMP_TO_EDGE); depthStencilAttachment->setParam(Tex::IntParam::kWrapT, GL_CLAMP_TO_EDGE); depthStencilAttachment->unbind(); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_TEXTURE_2D, depthStencilAttachment->getId(), 0); } Tex::Specification colorSpecification = Tex::Specification::create2d(); colorSpecification.width = width; colorSpecification.height = height; colorAttachments.resize(attachmentFormats.size()); std::vector<GLenum> drawBuffers(attachmentFormats.size()); for (GLsizei i = 0; i < attachmentFormats.size(); ++i) { colorSpecification.internalFormat = attachmentFormats[i]; colorAttachments[i] = std::make_shared<Texture>(colorSpecification); drawBuffers[i] = GL_COLOR_ATTACHMENT0 + i; colorAttachments[i]->setParam(Tex::IntParam::kMinFilter, GL_LINEAR); colorAttachments[i]->setParam(Tex::IntParam::kMagFilter, GL_LINEAR); colorAttachments[i]->setParam(Tex::IntParam::kWrapS, GL_CLAMP_TO_BORDER); colorAttachments[i]->setParam(Tex::IntParam::kWrapT, GL_CLAMP_TO_BORDER); colorAttachments[i]->unbind(); glFramebufferTexture2D(GL_FRAMEBUFFER, drawBuffers[i], GL_TEXTURE_2D, colorAttachments[i]->getId(), 0); } glDrawBuffers(drawBuffers.size(), drawBuffers.data()); ASSERT(glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE); bindDefaultFramebuffer(); } void Framebuffer::setResolution(GLsizei attachmentWidth, GLsizei attachmentHeight) { std::vector<Tex::InternalFormat> internalFormats(colorAttachments.size()); for (std::size_t i = 0; i < internalFormats.size(); ++i) { internalFormats[i] = colorAttachments[i]->getSpecification().internalFormat; } reset(attachmentWidth, attachmentHeight, depthStencilAttachment != nullptr, internalFormats); } void Framebuffer::bind() { Context::current()->bindFramebuffer(fbo); glViewport(0, 0, width, height); ASSERT(glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE); } } // namespace Shiny
Call glDrawBuffers() in framebuffer setup
Call glDrawBuffers() in framebuffer setup
C++
mit
aaronmjacobs/Shiny,aaronmjacobs/Shiny
7d64a2a4056704328211b6590888063700c29e6a
sdk-remote/src/liburbi/uclient.cc
sdk-remote/src/liburbi/uclient.cc
/*! \file uclient.cc **************************************************************************** * * Implementation of the URBI interface class * * Copyright (C) 2004-2009 Gostai S.A.S. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. **********************************************************************/ #include <cstdlib> #include <cerrno> #include <locale.h> #include <libport/windows.hh> #include <libport/unistd.h> #include <libport/sys/time.h> #if !defined WIN32 # include <time.h> # include <signal.h> #endif #include <libport/cstdio> #include <libport/sys/select.h> #include <libport/arpa/inet.h> #include <libport/netdb.h> #include <libport/errors.hh> #include <libport/lockable.hh> #include <libport/thread.hh> #include <libport/utime.hh> #include <urbi/uclient.hh> #include <urbi/utag.hh> namespace urbi { /*! Establish the connection with the server. Spawn a new thread that will listen to the socket, parse the incoming URBI messages, and notify the appropriate callbacks. */ UClient::UClient(const std::string& host, unsigned port, size_t buflen, bool server, unsigned semListenInc) : UAbstractClient(host, port, buflen, server) , thread(0) , pingInterval(0) , semListenInc_(semListenInc) { sd = -1; int pos = 0; setlocale(LC_NUMERIC, "C"); control_fd[0] = control_fd[1] = -1; #ifndef WIN32 if (::pipe(control_fd) == -1) { rc = -1; libport::perror("UClient::UClient failed to create pipe"); return; } //block sigpipe signal(SIGPIPE, SIG_IGN); #endif // Address resolution stage. struct sockaddr_in sa; // Internet address struct memset(&sa, 0, sizeof sa); #ifdef WIN32 WSADATA wsaData; WORD wVersionRequested; wVersionRequested = MAKEWORD(1, 1); WSAStartup(wVersionRequested, &wsaData); #endif sa.sin_family = AF_INET; sa.sin_port = htons(port); // host-to-IP translation struct hostent* hen = gethostbyname(host_.c_str()); if (!hen) { // maybe it is an IP address sa.sin_addr.s_addr = inet_addr(host_.c_str()); if (sa.sin_addr.s_addr == INADDR_NONE) { std::cerr << "UClient::UClient cannot resolve host name." << std::endl; rc = -1; return; } } else memcpy(&sa.sin_addr.s_addr, hen->h_addr_list[0], hen->h_length); sd = socket(AF_INET, SOCK_STREAM, 0); if (sd < 0) { rc = -1; libport::perror("UClient::UClient socket"); return; } if (!server_) { // Connect on given host and port rc = connect(sd, (struct sockaddr *) &sa, sizeof sa); // If we attempt to connect too fast to aperios ipstack it will fail. if (rc) { usleep(20000); rc = connect(sd, (struct sockaddr *) &sa, sizeof sa); } // Check there was no error. if (rc) { rc = -1; libport::perror("UClient::UClient connect"); return; } // Check that it really worked. while (!pos) pos = ::recv(sd, recvBuffer, buflen, 0); if (pos < 0) { rc = -1; libport::perror("UClient::UClient recv"); return; } } else { // Allow to rebind on the same port shortly after having used it. { int one = 1; rc = libport::setsockopt(sd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof one); if (rc) { rc = -1; libport::perror("UClient::UClient cannot use setsockopt"); return; } } // Bind socket rc = bind (sd, (struct sockaddr *) &sa, sizeof sa); if (rc) { rc = -1; libport::perror("UClient::UClient cannot bind"); return; } // Activate listen/passive mode, do not allow queued connections rc = listen (sd, 0); if (rc) { rc = -1; libport::perror("UClient::UClient cannot listen"); return; } // Create a thread waiting for incoming connection. // This must not be blocking in case of a remote server. // FIXME: block if normal remote ? init_ = false; thread = libport::startThread(this, &UClient::acceptThread); } recvBufferPosition = pos; recvBuffer[recvBufferPosition] = 0; // Do not create thread if one is already waiting for incoming connection if (!thread) { thread = libport::startThread(this, &UClient::listenThread); // Notify the base class that connection is established. onConnection(); } if (!defaultClient) defaultClient = this; listenSem_++; acceptSem_++; } UClient::~UClient() { if (sd >= 0) closeUClient (); } int UClient::closeUClient () { if (sd >= 0 && libport::closeSocket(sd) == -1) libport::perror ("cannot close sd"); sd = -1; if (control_fd[1] != -1 && ::write(control_fd[1], "a", 1) == -1) libport::perror ("cannot write to control_fd[1]"); // If the connection has failed while building the client, the // thread is not created. if (thread) // Must wait for listen thread to terminate. libport::joinThread(thread); if (control_fd[1] != -1 && close(control_fd[1]) == -1) libport::perror ("cannot close controlfd[1]"); if (control_fd[0] != -1 && close(control_fd[0]) == -1) libport::perror ("cannot close controlfd[0]"); return 0; } int UClient::effectiveSend(const void* buffer, size_t size) { #if DEBUG char output[size+1]; memcpy (static_cast<void*> (output), buffer, size); output[size]=0; std::cerr << ">>>> SENT : [" << output << "]" << std::endl; #endif if (rc) return -1; size_t pos = 0; while (pos != size) { int retval = ::send(sd, (char *) buffer + pos, size-pos, 0); if (retval< 0) { rc = retval; clientError("send error", rc); return rc; } pos += retval; } return 0; } void UClient::acceptThread() { // Wait for it... acceptSem_--; // Accept one connection struct sockaddr_in saClient; socklen_t addrlenClient; int acceptFD = 0; acceptFD = accept (sd, (struct sockaddr *) &saClient, &addrlenClient); if (acceptFD < 0) { libport::perror("UClient::UClient cannot accept"); rc = -1; return; } // Store client connection info host_ = inet_ntoa(saClient.sin_addr); port_ = saClient.sin_port; // Do not listen anymore. close(sd); // Redirect send/receive on accepted connection. sd = acceptFD; // FIXME: leaking ? thread = libport::startThread(this, &UClient::listenThread); init_ = true; onConnection(); // Stop this thread, the listen one is the real thing. return; } void UClient::listenThread() { // Wait for it... listenSem_ -= semListenInc_; int maxfd = 1 + std::max(sd, control_fd[0]); waitingPong = false; // Declare ping channel for kernel that requires it. if (2 <= kernelMajor()) send("if (isdef(Channel)) var lobby.%s = Channel.new(\"%s\") | {};", internalPongTag, internalPongTag); while (true) { if (sd == -1) return; fd_set rfds; FD_ZERO(&rfds); LIBPORT_FD_SET(sd, &rfds); fd_set efds; FD_ZERO(&efds); LIBPORT_FD_SET(sd, &efds); #ifndef WIN32 LIBPORT_FD_SET(control_fd[0], &rfds); #endif int selectReturn; if (pingInterval) { const unsigned delay = waitingPong ? pongTimeout : pingInterval; struct timeval timeout = { delay / 1000, (delay % 1000) * 1000}; selectReturn = ::select(maxfd + 1, &rfds, NULL, &efds, &timeout); } else { selectReturn = ::select(maxfd + 1, &rfds, NULL, &efds, NULL); } if (sd < 0) return; // Treat error if (selectReturn < 0 && errno != EINTR) { rc = -1; clientError("Connection error : ", errno); notifyCallbacks(UMessage(*this, 0, connectionTimeoutTag, "!!! Connection error", std::list<BinaryData>() )); return; } if (selectReturn < 0) // ::select catch a signal (errno == EINTR) continue; // timeout else if (selectReturn == 0) { if (waitingPong) // Timeout while waiting PONG { rc = -1; // FIXME: Choose between two differents way to alert user program clientError("Lost connection with server"); notifyCallbacks(UMessage(*this, 0, connectionTimeoutTag, "!!! Lost connection with server", std::list<BinaryData>())); return; } else // Timeout : Ping_interval { send("%s << 1,", internalPongTag); waitingPong = true; } } else { // We receive data, at least the "1" value sent through the pong tag // channel so we are no longer waiting for a pong. waitingPong = false; int count = ::recv(sd, &recvBuffer[recvBufferPosition], buflen - recvBufferPosition - 1, 0); if (count <= 0) { std::string errorMsg; int errorCode = 0; if (count < 0) { #ifdef WIN32 errorCode = WSAGetLastError(); #else errorCode = errno; #endif errorMsg = "!!! Connection error"; } else // count == 0 => Connection close { errorMsg = "!!! Connection closed"; } rc = -1; clientError(errorMsg.c_str(), errorCode); notifyCallbacks(UMessage(*this, 0, connectionTimeoutTag, errorMsg.c_str(), std::list<BinaryData>() )); return; } recvBufferPosition += count; recvBuffer[recvBufferPosition] = 0; processRecvBuffer(); } } } void UClient::printf(const char * format, ...) { va_list arg; va_start(arg, format); vfprintf(stderr, format, arg); va_end(arg); } unsigned int UClient::getCurrentTime() const { // FIXME: Put this into libport. #ifdef WIN32 return GetTickCount(); #else struct timeval tv; gettimeofday(&tv, NULL); return tv.tv_sec*1000+tv.tv_usec/1000; #endif } void execute() { while (true) sleep(100); } void exit(int code) { ::exit(code); } UClient& connect(const std::string& host) { return *new UClient(host); } void disconnect(UClient &client) { delete &client; } void UClient::setKeepAliveCheck(const unsigned pingInterval, const unsigned pongTimeout) { this->pingInterval = pingInterval; this->pongTimeout = pongTimeout; } } // namespace urbi
/*! \file uclient.cc **************************************************************************** * * Implementation of the URBI interface class * * Copyright (C) 2004-2009 Gostai S.A.S. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. **********************************************************************/ #include <cstdlib> #include <cerrno> #include <locale.h> #include <libport/windows.hh> #include <libport/unistd.h> #include <libport/sys/time.h> #if !defined WIN32 # include <time.h> # include <signal.h> #endif #include <libport/cstdio> #include <libport/sys/select.h> #include <libport/arpa/inet.h> #include <libport/netdb.h> #include <libport/errors.hh> #include <libport/lockable.hh> #include <libport/thread.hh> #include <libport/utime.hh> #include <urbi/uclient.hh> #include <urbi/utag.hh> namespace urbi { /*! Establish the connection with the server. Spawn a new thread that will listen to the socket, parse the incoming URBI messages, and notify the appropriate callbacks. */ UClient::UClient(const std::string& host, unsigned port, size_t buflen, bool server, unsigned semListenInc) : UAbstractClient(host, port, buflen, server) , thread(0) , pingInterval(0) , semListenInc_(semListenInc) { sd = -1; int pos = 0; setlocale(LC_NUMERIC, "C"); control_fd[0] = control_fd[1] = -1; #ifndef WIN32 if (::pipe(control_fd) == -1) { rc = -1; libport::perror("UClient::UClient failed to create pipe"); return; } //block sigpipe signal(SIGPIPE, SIG_IGN); #endif // Address resolution stage. struct sockaddr_in sa; // Internet address struct memset(&sa, 0, sizeof sa); #ifdef WIN32 WSADATA wsaData; WORD wVersionRequested; wVersionRequested = MAKEWORD(1, 1); WSAStartup(wVersionRequested, &wsaData); #endif sa.sin_family = AF_INET; sa.sin_port = htons(port); // host-to-IP translation struct hostent* hen = gethostbyname(host_.c_str()); if (!hen) { // maybe it is an IP address sa.sin_addr.s_addr = inet_addr(host_.c_str()); if (sa.sin_addr.s_addr == INADDR_NONE) { std::cerr << "UClient::UClient cannot resolve host name." << std::endl; rc = -1; return; } } else memcpy(&sa.sin_addr.s_addr, hen->h_addr_list[0], hen->h_length); sd = socket(AF_INET, SOCK_STREAM, 0); if (sd < 0) { rc = -1; libport::perror("UClient::UClient socket"); return; } if (!server_) { // Connect on given host and port rc = connect(sd, (struct sockaddr *) &sa, sizeof sa); // If we attempt to connect too fast to aperios ipstack it will fail. if (rc) { usleep(20000); rc = connect(sd, (struct sockaddr *) &sa, sizeof sa); } // Check there was no error. if (rc) { rc = -1; libport::perror("UClient::UClient connect"); return; } // Check that it really worked. while (!pos) pos = ::recv(sd, recvBuffer, buflen, 0); if (pos < 0) { rc = -1; libport::perror("UClient::UClient recv"); return; } } else { // Allow to rebind on the same port shortly after having used it. { int one = 1; rc = libport::setsockopt(sd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof one); if (rc) { rc = -1; libport::perror("UClient::UClient cannot use setsockopt"); return; } } // Bind socket rc = bind (sd, (struct sockaddr *) &sa, sizeof sa); if (rc) { rc = -1; libport::perror("UClient::UClient cannot bind"); return; } // Activate listen/passive mode, do not allow queued connections rc = listen (sd, 0); if (rc) { rc = -1; libport::perror("UClient::UClient cannot listen"); return; } // Create a thread waiting for incoming connection. // This must not be blocking in case of a remote server. // FIXME: block if normal remote ? init_ = false; thread = libport::startThread(this, &UClient::acceptThread); } recvBufferPosition = pos; recvBuffer[recvBufferPosition] = 0; // Do not create thread if one is already waiting for incoming connection if (!thread) { thread = libport::startThread(this, &UClient::listenThread); // Notify the base class that connection is established. onConnection(); } if (!defaultClient) defaultClient = this; listenSem_++; acceptSem_++; } UClient::~UClient() { if (sd >= 0) closeUClient (); } int UClient::closeUClient () { if (sd >= 0 && libport::closeSocket(sd) == -1) libport::perror ("cannot close sd"); sd = -1; if (control_fd[1] != -1 && ::write(control_fd[1], "a", 1) == -1) libport::perror ("cannot write to control_fd[1]"); // If the connection has failed while building the client, the // thread is not created. if (thread) // Must wait for listen thread to terminate. libport::joinThread(thread); if (control_fd[1] != -1 && close(control_fd[1]) == -1) libport::perror ("cannot close controlfd[1]"); if (control_fd[0] != -1 && close(control_fd[0]) == -1) libport::perror ("cannot close controlfd[0]"); return 0; } int UClient::effectiveSend(const void* buffer, size_t size) { #if DEBUG char output[size+1]; memcpy (static_cast<void*> (output), buffer, size); output[size]=0; std::cerr << ">>>> SENT : [" << output << "]" << std::endl; #endif if (rc) return -1; size_t pos = 0; while (pos != size) { int retval = ::send(sd, (char *) buffer + pos, size-pos, 0); if (retval< 0) { rc = retval; clientError("send error", rc); return rc; } pos += retval; } return 0; } void UClient::acceptThread() { // Wait for it... acceptSem_--; // Accept one connection struct sockaddr_in saClient; socklen_t addrlenClient; int acceptFD = 0; acceptFD = accept (sd, (struct sockaddr *) &saClient, &addrlenClient); if (acceptFD < 0) { libport::perror("UClient::UClient cannot accept"); rc = -1; return; } // Store client connection info host_ = inet_ntoa(saClient.sin_addr); port_ = saClient.sin_port; // Do not listen anymore. close(sd); // Redirect send/receive on accepted connection. sd = acceptFD; // FIXME: leaking ? thread = libport::startThread(this, &UClient::listenThread); init_ = true; onConnection(); // Stop this thread, the listen one is the real thing. return; } void UClient::listenThread() { // Wait for it... listenSem_ -= semListenInc_; int maxfd = 1 + std::max(sd, control_fd[0]); waitingPong = false; // Declare ping channel for kernel that requires it. Do not try // to depend on kernelMajor, because it has not been computed yet. // And computing kernelMajor requires this code to be run. So we // need to write something that both k1 and k2 will like. send("if (isdef(Channel)) var lobby.%s = Channel.new(\"%s\") | {};", internalPongTag, internalPongTag); while (true) { if (sd == -1) return; fd_set rfds; FD_ZERO(&rfds); LIBPORT_FD_SET(sd, &rfds); fd_set efds; FD_ZERO(&efds); LIBPORT_FD_SET(sd, &efds); #ifndef WIN32 LIBPORT_FD_SET(control_fd[0], &rfds); #endif int selectReturn; if (pingInterval) { const unsigned delay = waitingPong ? pongTimeout : pingInterval; struct timeval timeout = { delay / 1000, (delay % 1000) * 1000}; selectReturn = ::select(maxfd + 1, &rfds, NULL, &efds, &timeout); } else { selectReturn = ::select(maxfd + 1, &rfds, NULL, &efds, NULL); } if (sd < 0) return; // Treat error if (selectReturn < 0 && errno != EINTR) { rc = -1; clientError("Connection error : ", errno); notifyCallbacks(UMessage(*this, 0, connectionTimeoutTag, "!!! Connection error", std::list<BinaryData>())); return; } if (selectReturn < 0) // ::select catch a signal (errno == EINTR) continue; // timeout else if (selectReturn == 0) { if (waitingPong) // Timeout while waiting PONG { rc = -1; // FIXME: Choose between two differents way to alert user program clientError("Lost connection with server"); notifyCallbacks(UMessage(*this, 0, connectionTimeoutTag, "!!! Lost connection with server", std::list<BinaryData>())); return; } else // Timeout : Ping_interval { send("%s << 1,", internalPongTag); waitingPong = true; } } else { // We receive data, at least the "1" value sent through the pong tag // channel so we are no longer waiting for a pong. waitingPong = false; int count = ::recv(sd, &recvBuffer[recvBufferPosition], buflen - recvBufferPosition - 1, 0); if (count <= 0) { std::string errorMsg; int errorCode = 0; if (count < 0) { #ifdef WIN32 errorCode = WSAGetLastError(); #else errorCode = errno; #endif errorMsg = "!!! Connection error"; } else // count == 0 => Connection close { errorMsg = "!!! Connection closed"; } rc = -1; clientError(errorMsg.c_str(), errorCode); notifyCallbacks(UMessage(*this, 0, connectionTimeoutTag, errorMsg.c_str(), std::list<BinaryData>())); return; } recvBufferPosition += count; recvBuffer[recvBufferPosition] = 0; processRecvBuffer(); } } } void UClient::printf(const char * format, ...) { va_list arg; va_start(arg, format); vfprintf(stderr, format, arg); va_end(arg); } unsigned int UClient::getCurrentTime() const { // FIXME: Put this into libport. #ifdef WIN32 return GetTickCount(); #else struct timeval tv; gettimeofday(&tv, NULL); return tv.tv_sec*1000+tv.tv_usec/1000; #endif } void execute() { while (true) sleep(100); } void exit(int code) { ::exit(code); } UClient& connect(const std::string& host) { return *new UClient(host); } void disconnect(UClient &client) { delete &client; } void UClient::setKeepAliveCheck(const unsigned pingInterval, const unsigned pongTimeout) { this->pingInterval = pingInterval; this->pongTimeout = pongTimeout; } } // namespace urbi
Revert "liburbi: don't send k2 commands to k1 server."
Revert "liburbi: don't send k2 commands to k1 server." This reverts commit d556fc579694b29784aa60556a518fabcea7da29.
C++
bsd-3-clause
urbiforge/urbi,urbiforge/urbi,aldebaran/urbi,aldebaran/urbi,urbiforge/urbi,urbiforge/urbi,aldebaran/urbi,urbiforge/urbi,urbiforge/urbi,urbiforge/urbi,aldebaran/urbi,aldebaran/urbi,urbiforge/urbi,urbiforge/urbi,aldebaran/urbi,aldebaran/urbi,aldebaran/urbi
b8547c3b7e0ecdab566dd1c941ae7a5e67066acd
xchainer/array_body_leak_detection.cc
xchainer/array_body_leak_detection.cc
#include "xchainer/array_body_leak_detection.h" #include <memory> #include <sstream> #include <vector> #include "xchainer/array.h" #include "xchainer/array_body.h" #include "xchainer/array_node.h" #include "xchainer/graph.h" namespace xchainer { namespace internal { ArrayBodyLeakTracker* ArrayBodyLeakDetectionScope::array_body_leak_tracker_ = nullptr; void ArrayBodyLeakTracker::operator()(const std::shared_ptr<internal::ArrayBody>& array_body) { // Keep weak pointer weak_ptrs_.emplace_back(array_body); } std::vector<std::shared_ptr<ArrayBody>> ArrayBodyLeakTracker::GetAliveArrayBodies() const { std::vector<std::shared_ptr<ArrayBody>> alive_ptrs; for (const std::weak_ptr<ArrayBody> weak_ptr : weak_ptrs_) { std::shared_ptr<ArrayBody> ptr = weak_ptr.lock(); if (ptr != nullptr) { alive_ptrs.emplace_back(ptr); } } return alive_ptrs; } ArrayBodyLeakDetectionScope ::ArrayBodyLeakDetectionScope(ArrayBodyLeakTracker& tracker) { assert(array_body_leak_tracker_ == nullptr); // nested use is not supported array_body_leak_tracker_ = &tracker; } ArrayBodyLeakDetectionScope ::~ArrayBodyLeakDetectionScope() { if (!exited_) { array_body_leak_tracker_ = nullptr; exited_ = true; } } } // namespace internal } // namespace xchainer
#include "xchainer/array_body_leak_detection.h" #include <memory> #include <sstream> #include <vector> #include "xchainer/array.h" #include "xchainer/array_body.h" #include "xchainer/array_node.h" #include "xchainer/graph.h" namespace xchainer { namespace internal { ArrayBodyLeakTracker* ArrayBodyLeakDetectionScope::array_body_leak_tracker_ = nullptr; void ArrayBodyLeakTracker::operator()(const std::shared_ptr<internal::ArrayBody>& array_body) { // Keep weak pointer weak_ptrs_.emplace_back(array_body); } std::vector<std::shared_ptr<ArrayBody>> ArrayBodyLeakTracker::GetAliveArrayBodies() const { std::vector<std::shared_ptr<ArrayBody>> alive_ptrs; for (const std::weak_ptr<ArrayBody> weak_ptr : weak_ptrs_) { if (std::shared_ptr<ArrayBody> ptr = weak_ptr.lock()) { alive_ptrs.emplace_back(ptr); } } return alive_ptrs; } ArrayBodyLeakDetectionScope ::ArrayBodyLeakDetectionScope(ArrayBodyLeakTracker& tracker) { assert(array_body_leak_tracker_ == nullptr); // nested use is not supported array_body_leak_tracker_ = &tracker; } ArrayBodyLeakDetectionScope ::~ArrayBodyLeakDetectionScope() { if (!exited_) { array_body_leak_tracker_ = nullptr; exited_ = true; } } } // namespace internal } // namespace xchainer
Simplify the code
Simplify the code
C++
mit
tkerola/chainer,wkentaro/chainer,ktnyt/chainer,niboshi/chainer,okuta/chainer,chainer/chainer,jnishi/chainer,pfnet/chainer,okuta/chainer,chainer/chainer,niboshi/chainer,chainer/chainer,niboshi/chainer,keisuke-umezawa/chainer,ktnyt/chainer,okuta/chainer,hvy/chainer,jnishi/chainer,hvy/chainer,keisuke-umezawa/chainer,jnishi/chainer,ktnyt/chainer,wkentaro/chainer,jnishi/chainer,chainer/chainer,wkentaro/chainer,hvy/chainer,ktnyt/chainer,niboshi/chainer,keisuke-umezawa/chainer,keisuke-umezawa/chainer,okuta/chainer,hvy/chainer,wkentaro/chainer
75f9c64fd4290cbd0e35342df2043c7aab0305c6
src/main.cc
src/main.cc
// Copyright(c) 2016 - 2017 Federico Bolelli, Costantino Grana, Michele Cancilla, Lorenzo Baraldi and Roberto Vezzani // 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 YACCLAB 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 <cstdint> #include <fstream> #include <functional> #include <iomanip> #include <iostream> #include <map> #include <string> #include <vector> #include <opencv2/imgproc.hpp> #include "config_data.h" #include "file_manager.h" #include "labeling_algorithms.h" #include "latex_generator.h" #include "memory_tester.h" #include "performance_evaluator.h" #include "progress_bar.h" #include "stream_demultiplexer.h" #include "system_info.h" #include "utilities.h" #include "yacclab_tests.h" using namespace std; using namespace cv; int main() { // Redirect cv exceptions cvRedirectError(RedirectCvError); // Hide cursor from console HideConsoleCursor(); // To handle filesystem errors error_code ec; // Create StreamDemultiplexer object in order // to print output on both stdout and log file string logfile = "log.txt"; ofstream os(logfile); if (os.is_open()) { dmux::cout.AddStream(os); } OutputBox ob_setconf("Setting Configuration Parameters"); // Read yaml configuration file const string config_file = "config.yaml"; FileStorage fs; try { fs.open(config_file, FileStorage::READ); } catch (const cv::Exception&) { exit(EXIT_FAILURE); // Error redirected, // OpenCV redirected function will // print the error on stdout } if (!fs.isOpened()) { ob_setconf.Cerror("Failed to open '" + config_file + "'"); // EXIT_FAILURE } // Load configuration data from yaml ConfigData cfg(fs); // Release FileStorage fs.release(); /*************************************************************************/ /* Configuration parameters check */ /*************************************************************************/ // Check if all the specified algorithms exist for (auto& algo_name : cfg.ccl_algorithms) { if (!LabelingMapSingleton::Exists(algo_name)) { ob_setconf.Cwarning("Unable to find the algorithm '" + algo_name + "'"); } else { cfg.ccl_existing_algorithms.push_back(algo_name); } } if (cfg.ccl_existing_algorithms.size() == 0) { ob_setconf.Cerror("There are no valid values in the 'algorithms' list"); } // Check if labeling methods of the specified algorithms exist Labeling::img_ = Mat1b(1, 1, static_cast<uchar>(0)); for (const auto& algo_name : cfg.ccl_existing_algorithms) { const auto& algorithm = LabelingMapSingleton::GetLabeling(algo_name); if (cfg.perform_average || cfg.perform_density || cfg.perform_granularity || (cfg.perform_correctness && cfg.perform_check_8connectivity_std)) { try { algorithm->PerformLabeling(); cfg.ccl_average_algorithms.push_back(algo_name); } catch (const runtime_error& e) { ob_setconf.Cwarning(algo_name + ": " + e.what()); } } if (cfg.perform_average_ws || (cfg.perform_correctness && cfg.perform_check_8connectivity_ws)) { try { algorithm->PerformLabelingWithSteps(); cfg.ccl_average_ws_algorithms.push_back(algo_name); } catch (const runtime_error& e) { ob_setconf.Cwarning(algo_name + ": " + e.what()); } } if (cfg.perform_memory || (cfg.perform_correctness && cfg.perform_check_8connectivity_mem)) { try { vector<unsigned long int> temp; algorithm->PerformLabelingMem(temp); cfg.ccl_mem_algorithms.push_back(algo_name); } catch (const runtime_error& e) { ob_setconf.Cwarning(algo_name + ": " + e.what()); } } } if ((cfg.perform_average || (cfg.perform_correctness && cfg.perform_check_8connectivity_std)) && cfg.ccl_average_algorithms.size() == 0) { ob_setconf.Cwarning("There are no 'algorithms' with valid 'PerformLabeling()' method, related tests will be skipped"); cfg.perform_average = false; cfg.perform_check_8connectivity_std = false; } if ((cfg.perform_average_ws || (cfg.perform_correctness && cfg.perform_check_8connectivity_ws)) && cfg.ccl_average_ws_algorithms.size() == 0) { ob_setconf.Cwarning("There are no 'algorithms' with valid 'PerformLabelingWithSteps()' method, related tests will be skipped"); cfg.perform_average_ws = false; cfg.perform_check_8connectivity_ws = false; } if ((cfg.perform_memory || (cfg.perform_correctness && cfg.perform_check_8connectivity_mem)) && cfg.ccl_mem_algorithms.size() == 0) { ob_setconf.Cwarning("There are no 'algorithms' with valid 'PerformLabelingMem()' method, related tests will be skipped"); cfg.perform_memory = false; cfg.perform_check_8connectivity_mem = false; } if (cfg.perform_average && (cfg.average_tests_number < 1 || cfg.average_tests_number > 999)) { ob_setconf.Cwarning("'Average tests' repetitions cannot be less than 1 or more than 999, skipped"); cfg.perform_average = false; } if (cfg.perform_density && (cfg.density_tests_number < 1 || cfg.density_tests_number > 999)) { ob_setconf.Cwarning("'Density tests' repetitions cannot be less than 1 or more than 999, skipped"); cfg.perform_density = false; } if (cfg.perform_average_ws && (cfg.average_ws_tests_number < 1 || cfg.average_ws_tests_number > 999)) { ob_setconf.Cwarning("'Average tests with steps' repetitions cannot be less than 1 or more than 999, skipped"); cfg.perform_average_ws = false; } if ((cfg.perform_correctness) && cfg.check_datasets.size() == 0) { ob_setconf.Cwarning("There are no datasets specified for 'correctness tests', skipped"); cfg.perform_correctness = false; } if ((cfg.perform_average) && cfg.average_datasets.size() == 0) { ob_setconf.Cwarning("There are no datasets specified for 'average tests', skipped"); cfg.perform_average = false; } if ((cfg.perform_memory) && cfg.memory_datasets.size() == 0) { ob_setconf.Cwarning("There are no datasets specified for 'memory tests', skipped"); cfg.perform_memory = false; } if (!cfg.perform_average && !cfg.perform_correctness && !cfg.perform_density && !cfg.perform_memory && !cfg.perform_average_ws && !cfg.perform_granularity) { ob_setconf.Cerror("There are no tests to perform"); } // Check if datasets exist vector<String> ds; if (cfg.perform_correctness) { ds.insert(ds.end(), cfg.check_datasets.begin(), cfg.check_datasets.end()); } if (cfg.perform_memory) { ds.insert(ds.end(), cfg.memory_datasets.begin(), cfg.memory_datasets.end()); } if (cfg.perform_granularity) { ds.insert(ds.end(), cfg.granularity_datasets.begin(), cfg.granularity_datasets.end()); } std::sort(ds.begin(), ds.end()); ds.erase(unique(ds.begin(), ds.end()), ds.end()); // Check if inverted dataset exists in the wrong list for (auto& x : ds) { String dataset = x; if (dataset.find("_inverted") != string::npos) { ob_setconf.Cwarning("Inverted datasets are allowed only in 'average' and 'average with steps' tests, skipped"); } } if (cfg.perform_average) { // Name of the dataset and true if it is an "inverted" dataset for (size_t d = 0; d < cfg.average_datasets.size(); ++d) { string dataset = cfg.average_datasets[d]; bool inverted = false; size_t found = dataset.find("_inverted"); if (found != string::npos) { // found an inverted dataset dataset = dataset.substr(0, found); inverted = true; cfg.average_datasets[d] = dataset; } cfg.real_average_datasets.push_back(make_pair(dataset, inverted)); } ds.insert(ds.end(), cfg.average_datasets.begin(), cfg.average_datasets.end()); } if (cfg.perform_average_ws) { // Name of the dataset and true if it is an "inverted" dataset for (size_t d = 0; d < cfg.average_ws_datasets.size(); ++d) { string dataset = cfg.average_ws_datasets[d]; bool inverted = false; size_t found = dataset.find("_inverted"); if (found != string::npos) { // found an inverted dataset dataset = dataset.substr(0, found); inverted = true; cfg.average_ws_datasets[d] = dataset; } cfg.real_average_ws_datasets.push_back(make_pair(dataset, inverted)); } ds.insert(ds.end(), cfg.average_ws_datasets.begin(), cfg.average_ws_datasets.end()); } std::sort(ds.begin(), ds.end()); ds.erase(unique(ds.begin(), ds.end()), ds.end()); // Check if all the datasets files.txt exist for (auto& x : ds) { String dataset = x; if (dataset.find("_inverted") != string::npos) { dataset = dataset.substr(0, dataset.find("_inverted")); } path p = cfg.input_path / path(dataset) / path(cfg.input_txt); if (!exists(p, ec)) { ob_setconf.Cwarning("There is no dataset (no files.txt available) " + x + ", skipped"); } } if (cfg.perform_average || cfg.perform_average_ws || cfg.perform_density || cfg.perform_memory || cfg.perform_granularity) { // Set and create current output directory if (!create_directories(cfg.output_path, ec)) { ob_setconf.Cerror("Unable to create output directory '" + cfg.output_path.string() + "' - " + ec.message()); } // Create the directory for latex reports if (!create_directories(cfg.latex_path, ec)) { ob_setconf.Cerror("Unable to create output directory '" + cfg.latex_path.string() + "' - " + ec.message()); } } ob_setconf.Cmessage("Setting Configuration Parameters DONE"); ob_setconf.CloseBox(); YacclabTests yt(cfg); // Correctness test if (cfg.perform_correctness) { if (cfg.perform_check_8connectivity_std) { yt.CheckPerformLabeling(); } if (cfg.perform_check_8connectivity_ws) { yt.CheckPerformLabelingWithSteps(); } if (cfg.perform_check_8connectivity_mem) { yt.CheckPerformLabelingMem(); } } // Average tests if (cfg.perform_average) { yt.AverageTest(); } // Average with steps tests if (cfg.perform_average_ws) { yt.AverageTestWithSteps(); } // Density tests if (cfg.perform_density) { yt.DensityTest(); } // Granularity tests if (cfg.perform_granularity) { yt.GranularityTest(); } // Memory tests if (cfg.perform_memory) { yt.MemoryTest(); } // Latex Generator if (cfg.perform_average || cfg.perform_average_ws || cfg.perform_density || cfg.perform_memory || cfg.perform_granularity) { yt.LatexGenerator(); } // Copy log file into output folder dmux::cout.flush(); filesystem::copy(path(logfile), cfg.output_path / path(logfile), ec); return EXIT_SUCCESS; }
// Copyright(c) 2016 - 2017 Federico Bolelli, Costantino Grana, Michele Cancilla, Lorenzo Baraldi and Roberto Vezzani // 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 YACCLAB 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 <cstdint> #include <fstream> #include <functional> #include <iomanip> #include <iostream> #include <map> #include <string> #include <vector> #include <opencv2/imgproc.hpp> #include "config_data.h" #include "file_manager.h" #include "labeling_algorithms.h" #include "latex_generator.h" #include "memory_tester.h" #include "performance_evaluator.h" #include "progress_bar.h" #include "stream_demultiplexer.h" #include "system_info.h" #include "utilities.h" #include "yacclab_tests.h" using namespace std; using namespace cv; int main() { // Redirect cv exceptions cvRedirectError(RedirectCvError); // Hide cursor from console HideConsoleCursor(); // To handle filesystem errors error_code ec; // Create StreamDemultiplexer object in order // to print output on both stdout and log file string logfile = "log.txt"; ofstream os(logfile); if (os.is_open()) { dmux::cout.AddStream(os); } OutputBox ob_setconf("Setting Configuration Parameters"); // Read yaml configuration file const string config_file = "config.yaml"; FileStorage fs; try { fs.open(config_file, FileStorage::READ); } catch (const cv::Exception&) { exit(EXIT_FAILURE); // Error redirected, // OpenCV redirected function will // print the error on stdout } if (!fs.isOpened()) { ob_setconf.Cerror("Failed to open '" + config_file + "'"); // EXIT_FAILURE } // Load configuration data from yaml ConfigData cfg(fs); // Release FileStorage fs.release(); /*************************************************************************/ /* Configuration parameters check */ /*************************************************************************/ // Check if all the specified algorithms exist for (auto& algo_name : cfg.ccl_algorithms) { if (!LabelingMapSingleton::Exists(algo_name)) { ob_setconf.Cwarning("Unable to find the algorithm '" + algo_name + "'"); } else { cfg.ccl_existing_algorithms.push_back(algo_name); } } if (cfg.ccl_existing_algorithms.size() == 0) { ob_setconf.Cerror("There are no valid values in the 'algorithms' list"); } // Check if labeling methods of the specified algorithms exist Labeling::img_ = Mat1b(1, 1, static_cast<uchar>(0)); for (const auto& algo_name : cfg.ccl_existing_algorithms) { const auto& algorithm = LabelingMapSingleton::GetLabeling(algo_name); if (cfg.perform_average || cfg.perform_density || cfg.perform_granularity || (cfg.perform_correctness && cfg.perform_check_8connectivity_std)) { try { algorithm->PerformLabeling(); cfg.ccl_average_algorithms.push_back(algo_name); } catch (const runtime_error& e) { ob_setconf.Cwarning(algo_name + ": " + e.what()); } } if (cfg.perform_average_ws || (cfg.perform_correctness && cfg.perform_check_8connectivity_ws)) { try { algorithm->PerformLabelingWithSteps(); cfg.ccl_average_ws_algorithms.push_back(algo_name); } catch (const runtime_error& e) { ob_setconf.Cwarning(algo_name + ": " + e.what()); } } if (cfg.perform_memory || (cfg.perform_correctness && cfg.perform_check_8connectivity_mem)) { try { vector<unsigned long int> temp; algorithm->PerformLabelingMem(temp); cfg.ccl_mem_algorithms.push_back(algo_name); } catch (const runtime_error& e) { ob_setconf.Cwarning(algo_name + ": " + e.what()); } } } if ((cfg.perform_average || (cfg.perform_correctness && cfg.perform_check_8connectivity_std)) && cfg.ccl_average_algorithms.size() == 0) { ob_setconf.Cwarning("There are no 'algorithms' with valid 'PerformLabeling()' method, related tests will be skipped"); cfg.perform_average = false; cfg.perform_check_8connectivity_std = false; } if ((cfg.perform_average_ws || (cfg.perform_correctness && cfg.perform_check_8connectivity_ws)) && cfg.ccl_average_ws_algorithms.size() == 0) { ob_setconf.Cwarning("There are no 'algorithms' with valid 'PerformLabelingWithSteps()' method, related tests will be skipped"); cfg.perform_average_ws = false; cfg.perform_check_8connectivity_ws = false; } if ((cfg.perform_memory || (cfg.perform_correctness && cfg.perform_check_8connectivity_mem)) && cfg.ccl_mem_algorithms.size() == 0) { ob_setconf.Cwarning("There are no 'algorithms' with valid 'PerformLabelingMem()' method, related tests will be skipped"); cfg.perform_memory = false; cfg.perform_check_8connectivity_mem = false; } if (cfg.perform_average && (cfg.average_tests_number < 1 || cfg.average_tests_number > 999)) { ob_setconf.Cwarning("'Average tests' repetitions cannot be less than 1 or more than 999, skipped"); cfg.perform_average = false; } if (cfg.perform_density && (cfg.density_tests_number < 1 || cfg.density_tests_number > 999)) { ob_setconf.Cwarning("'Density tests' repetitions cannot be less than 1 or more than 999, skipped"); cfg.perform_density = false; } if (cfg.perform_average_ws && (cfg.average_ws_tests_number < 1 || cfg.average_ws_tests_number > 999)) { ob_setconf.Cwarning("'Average tests with steps' repetitions cannot be less than 1 or more than 999, skipped"); cfg.perform_average_ws = false; } if ((cfg.perform_correctness) && cfg.check_datasets.size() == 0) { ob_setconf.Cwarning("There are no datasets specified for 'correctness tests', skipped"); cfg.perform_correctness = false; } if ((cfg.perform_average) && cfg.average_datasets.size() == 0) { ob_setconf.Cwarning("There are no datasets specified for 'average tests', skipped"); cfg.perform_average = false; } if ((cfg.perform_memory) && cfg.memory_datasets.size() == 0) { ob_setconf.Cwarning("There are no datasets specified for 'memory tests', skipped"); cfg.perform_memory = false; } if (!cfg.perform_average && !cfg.perform_correctness && !cfg.perform_density && !cfg.perform_memory && !cfg.perform_average_ws && !cfg.perform_granularity) { ob_setconf.Cerror("There are no tests to perform"); } // Check if datasets exist vector<String> ds; if (cfg.perform_correctness) { ds.insert(ds.end(), cfg.check_datasets.begin(), cfg.check_datasets.end()); } if (cfg.perform_memory) { ds.insert(ds.end(), cfg.memory_datasets.begin(), cfg.memory_datasets.end()); } if (cfg.perform_granularity) { for (auto& d : cfg.granularity_datasets) { ds.push_back((path("granularity") / path(d)).string()); } } std::sort(ds.begin(), ds.end()); ds.erase(unique(ds.begin(), ds.end()), ds.end()); // Check if inverted dataset exists in the wrong list for (auto& x : ds) { String dataset = x; if (dataset.find("_inverted") != string::npos) { ob_setconf.Cwarning("Inverted datasets are allowed only in 'average' and 'average with steps' tests, skipped"); } } { auto find_inverted_dataset = [](vector<String>& datasets, vector<pair<String, bool>>& real_d) { for (size_t d = 0; d < datasets.size(); ++d) { string dataset_temp = datasets[d]; bool inverted = false; size_t found = dataset_temp.find("_inverted"); if (found != string::npos) { // found an inverted dataset dataset_temp = dataset_temp.substr(0, found); inverted = true; datasets[d] = dataset_temp; } real_d.push_back(make_pair(dataset_temp, inverted)); } }; if (cfg.perform_average) { // Name of the dataset and true if it is an "inverted" dataset find_inverted_dataset(cfg.average_datasets, cfg.real_average_datasets); ds.insert(ds.end(), cfg.average_datasets.begin(), cfg.average_datasets.end()); } if (cfg.perform_average_ws) { // Name of the dataset and true if it is an "inverted" dataset find_inverted_dataset(cfg.average_ws_datasets, cfg.real_average_ws_datasets); ds.insert(ds.end(), cfg.average_ws_datasets.begin(), cfg.average_ws_datasets.end()); } } std::sort(ds.begin(), ds.end()); ds.erase(unique(ds.begin(), ds.end()), ds.end()); // Check if all the datasets files.txt exist for (auto& x : ds) { path p = cfg.input_path / path(x) / path(cfg.input_txt); if (!exists(p, ec)) { ob_setconf.Cwarning("There is no dataset (no files.txt available) " + x + ", skipped"); } } if (cfg.perform_average || cfg.perform_average_ws || cfg.perform_density || cfg.perform_memory || cfg.perform_granularity) { // Set and create current output directory if (!create_directories(cfg.output_path, ec)) { ob_setconf.Cerror("Unable to create output directory '" + cfg.output_path.string() + "' - " + ec.message()); } // Create the directory for latex reports if (!create_directories(cfg.latex_path, ec)) { ob_setconf.Cerror("Unable to create output directory '" + cfg.latex_path.string() + "' - " + ec.message()); } } ob_setconf.Cmessage("Setting Configuration Parameters DONE"); ob_setconf.CloseBox(); YacclabTests yt(cfg); // Correctness test if (cfg.perform_correctness) { if (cfg.perform_check_8connectivity_std) { yt.CheckPerformLabeling(); } if (cfg.perform_check_8connectivity_ws) { yt.CheckPerformLabelingWithSteps(); } if (cfg.perform_check_8connectivity_mem) { yt.CheckPerformLabelingMem(); } } // Average tests if (cfg.perform_average) { yt.AverageTest(); } // Average with steps tests if (cfg.perform_average_ws) { yt.AverageTestWithSteps(); } // Density tests if (cfg.perform_density) { yt.DensityTest(); } // Granularity tests if (cfg.perform_granularity) { yt.GranularityTest(); } // Memory tests if (cfg.perform_memory) { yt.MemoryTest(); } // Latex Generator if (cfg.perform_average || cfg.perform_average_ws || cfg.perform_density || cfg.perform_memory || cfg.perform_granularity) { yt.LatexGenerator(); } // Copy log file into output folder dmux::cout.flush(); filesystem::copy(path(logfile), cfg.output_path / path(logfile), ec); return EXIT_SUCCESS; }
Add checks in order to use inverted datasets
Add checks in order to use inverted datasets
C++
bsd-3-clause
prittt/YACCLAB,prittt/YACCLAB,prittt/YACCLAB,prittt/YACCLAB
6128464bc9621ba657892fd0a90bce92220db0c5
src/main.cc
src/main.cc
/*===================================================================== QGroundControl Open Source Ground Control Station (c) 2009 - 2011 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org> This file is part of the QGROUNDCONTROL project QGROUNDCONTROL 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. QGROUNDCONTROL 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 QGROUNDCONTROL. If not, see <http://www.gnu.org/licenses/>. ======================================================================*/ /** * @file * @brief Main executable * @author Lorenz Meier <[email protected]> * */ #include <QtGui/QApplication> #include "QGCCore.h" #include "MainWindow.h" #include "configuration.h" #include "SerialLink.h" #include "TCPLink.h" #ifdef QT_DEBUG #include "AutoTest.h" #include "CmdLineOptParser.h" #ifdef Q_OS_WIN #include <crtdbg.h> #endif #endif /* SDL does ugly things to main() */ #ifdef main #undef main #endif #ifdef Q_OS_WIN /// @brief Message handler which is installed using qInstallMsgHandler so you do not need /// the MSFT debug tools installed to see qDebug(), qWarning(), qCritical and qAbort void msgHandler( QtMsgType type, const char* msg ) { const char symbols[] = { 'I', 'E', '!', 'X' }; QString output = QString("[%1] %2").arg( symbols[type] ).arg( msg ); std::cerr << output.toStdString() << std::endl; if( type == QtFatalMsg ) abort(); } /// @brief CRT Report Hook installed using _CrtSetReportHook. We install this hook when /// we don't want asserts to pop a dialog on windows. int WindowsCrtReportHook(int reportType, char* message, int* returnValue) { Q_UNUSED(reportType); std::cerr << message << std::endl; // Output message to stderr *returnValue = 0; // Don't break into debugger return true; // We handled this fully ourselves } #endif /** * @brief Starts the application * * @param argc Number of commandline arguments * @param argv Commandline arguments * @return exit code, 0 for normal exit and !=0 for error cases */ int main(int argc, char *argv[]) { // Prevent Apple's app nap from screwing us over // tip: the domain can be cross-checked on the command line with <defaults domains> QProcess::execute("defaults write org.qgroundcontrol.qgroundcontrol NSAppSleepDisabled -bool YES"); // install the message handler #ifdef Q_OS_WIN qInstallMsgHandler( msgHandler ); #endif // The following calls to qRegisterMetaType are done to silence debug output which warns // that we use these types in signals, and without calling qRegisterMetaType we can't queue // these signals. In general we don't queue these signals, but we do what the warning says // anyway to silence the debug output. qRegisterMetaType<QSerialPort::SerialPortError>(); qRegisterMetaType<QAbstractSocket::SocketError>(); #ifdef QT_DEBUG // We parse a small set of command line options here prior to QGCCore in order to handle the ones // which need to be handled before a QApplication object is started. bool runUnitTests = false; // Run unit test bool quietWindowsAsserts = false; // Don't let asserts pop dialog boxes CmdLineOpt_t rgCmdLineOptions[] = { { "--unittest", &runUnitTests }, { "--no-windows-assert-ui", &quietWindowsAsserts }, // Add additional command line option flags here }; ParseCmdLineOptions(argc, argv, rgCmdLineOptions, sizeof(rgCmdLineOptions)/sizeof(rgCmdLineOptions[0]), true); if (quietWindowsAsserts) { #ifdef Q_OS_WIN _CrtSetReportHook(WindowsCrtReportHook); #endif } if (runUnitTests) { // Run the test int failures = AutoTest::run(argc-1, argv); if (failures == 0) { qDebug() << "ALL TESTS PASSED"; } else { qDebug() << failures << " TESTS FAILED!"; } return failures; } #endif QGCCore* core = NULL; int val; bool firstStart = true; do { if (core) { delete core; firstStart = false; } core = new QGCCore(firstStart, argc, argv); val = core->exec(); } while (core->getRestartRequested()); return val; }
/*===================================================================== QGroundControl Open Source Ground Control Station (c) 2009 - 2011 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org> This file is part of the QGROUNDCONTROL project QGROUNDCONTROL 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. QGROUNDCONTROL 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 QGROUNDCONTROL. If not, see <http://www.gnu.org/licenses/>. ======================================================================*/ /** * @file * @brief Main executable * @author Lorenz Meier <[email protected]> * */ #include <QtGui/QApplication> #include "QGCCore.h" #include "MainWindow.h" #include "configuration.h" #include "SerialLink.h" #include "TCPLink.h" #ifdef QT_DEBUG #include "AutoTest.h" #include "CmdLineOptParser.h" #ifdef Q_OS_WIN #include <crtdbg.h> #endif #endif /* SDL does ugly things to main() */ #ifdef main #undef main #endif #ifdef Q_OS_WIN /// @brief Message handler which is installed using qInstallMsgHandler so you do not need /// the MSFT debug tools installed to see qDebug(), qWarning(), qCritical and qAbort void msgHandler( QtMsgType type, const char* msg ) { const char symbols[] = { 'I', 'E', '!', 'X' }; QString output = QString("[%1] %2").arg( symbols[type] ).arg( msg ); std::cerr << output.toStdString() << std::endl; if( type == QtFatalMsg ) abort(); } /// @brief CRT Report Hook installed using _CrtSetReportHook. We install this hook when /// we don't want asserts to pop a dialog on windows. int WindowsCrtReportHook(int reportType, char* message, int* returnValue) { Q_UNUSED(reportType); std::cerr << message << std::endl; // Output message to stderr *returnValue = 0; // Don't break into debugger return true; // We handled this fully ourselves } #endif /** * @brief Starts the application * * @param argc Number of commandline arguments * @param argv Commandline arguments * @return exit code, 0 for normal exit and !=0 for error cases */ int main(int argc, char *argv[]) { #ifdef Q_OS_MAC // Prevent Apple's app nap from screwing us over // tip: the domain can be cross-checked on the command line with <defaults domains> QProcess::execute("defaults write org.qgroundcontrol.qgroundcontrol NSAppSleepDisabled -bool YES"); #endif // install the message handler #ifdef Q_OS_WIN qInstallMsgHandler( msgHandler ); #endif // The following calls to qRegisterMetaType are done to silence debug output which warns // that we use these types in signals, and without calling qRegisterMetaType we can't queue // these signals. In general we don't queue these signals, but we do what the warning says // anyway to silence the debug output. qRegisterMetaType<QSerialPort::SerialPortError>(); qRegisterMetaType<QAbstractSocket::SocketError>(); #ifdef QT_DEBUG // We parse a small set of command line options here prior to QGCCore in order to handle the ones // which need to be handled before a QApplication object is started. bool runUnitTests = false; // Run unit test bool quietWindowsAsserts = false; // Don't let asserts pop dialog boxes CmdLineOpt_t rgCmdLineOptions[] = { { "--unittest", &runUnitTests }, { "--no-windows-assert-ui", &quietWindowsAsserts }, // Add additional command line option flags here }; ParseCmdLineOptions(argc, argv, rgCmdLineOptions, sizeof(rgCmdLineOptions)/sizeof(rgCmdLineOptions[0]), true); if (quietWindowsAsserts) { #ifdef Q_OS_WIN _CrtSetReportHook(WindowsCrtReportHook); #endif } if (runUnitTests) { // Run the test int failures = AutoTest::run(argc-1, argv); if (failures == 0) { qDebug() << "ALL TESTS PASSED"; } else { qDebug() << failures << " TESTS FAILED!"; } return failures; } #endif QGCCore* core = NULL; int val; bool firstStart = true; do { if (core) { delete core; firstStart = false; } core = new QGCCore(firstStart, argc, argv); val = core->exec(); } while (core->getRestartRequested()); return val; }
Add missing OS-guard
Add missing OS-guard
C++
agpl-3.0
mihadyuk/qgroundcontrol,catch-twenty-two/qgroundcontrol,dagoodma/qgroundcontrol,fizzaly/qgroundcontrol,mihadyuk/qgroundcontrol,dagoodma/qgroundcontrol,scott-eddy/qgroundcontrol,lis-epfl/qgroundcontrol,iidioter/qgroundcontrol,catch-twenty-two/qgroundcontrol,cfelipesouza/qgroundcontrol,iidioter/qgroundcontrol,TheIronBorn/qgroundcontrol,Hunter522/qgroundcontrol,RedoXyde/PX4_qGCS,Hunter522/qgroundcontrol,greenoaktree/qgroundcontrol,nado1688/qgroundcontrol,caoxiongkun/qgroundcontrol,CornerOfSkyline/qgroundcontrol,Hunter522/qgroundcontrol,RedoXyde/PX4_qGCS,UAVenture/qgroundcontrol,BMP-TECH/qgroundcontrol,lis-epfl/qgroundcontrol,caoxiongkun/qgroundcontrol,hejunbok/qgroundcontrol,scott-eddy/qgroundcontrol,greenoaktree/qgroundcontrol,nado1688/qgroundcontrol,mihadyuk/qgroundcontrol,dagoodma/qgroundcontrol,cfelipesouza/qgroundcontrol,greenoaktree/qgroundcontrol,dagoodma/qgroundcontrol,UAVenture/qgroundcontrol,jy723/qgroundcontrol,devbharat/qgroundcontrol,fizzaly/qgroundcontrol,nado1688/qgroundcontrol,nado1688/qgroundcontrol,ethz-asl/qgc_asl,hejunbok/qgroundcontrol,kd0aij/qgroundcontrol,devbharat/qgroundcontrol,jy723/qgroundcontrol,kd0aij/qgroundcontrol,fizzaly/qgroundcontrol,CornerOfSkyline/qgroundcontrol,CornerOfSkyline/qgroundcontrol,cfelipesouza/qgroundcontrol,RedoXyde/PX4_qGCS,scott-eddy/qgroundcontrol,fizzaly/qgroundcontrol,LIKAIMO/qgroundcontrol,LIKAIMO/qgroundcontrol,devbharat/qgroundcontrol,jy723/qgroundcontrol,BMP-TECH/qgroundcontrol,cfelipesouza/qgroundcontrol,caoxiongkun/qgroundcontrol,devbharat/qgroundcontrol,catch-twenty-two/qgroundcontrol,mihadyuk/qgroundcontrol,mihadyuk/qgroundcontrol,UAVenture/qgroundcontrol,jy723/qgroundcontrol,fizzaly/qgroundcontrol,catch-twenty-two/qgroundcontrol,hejunbok/qgroundcontrol,jy723/qgroundcontrol,scott-eddy/qgroundcontrol,BMP-TECH/qgroundcontrol,UAVenture/qgroundcontrol,TheIronBorn/qgroundcontrol,lis-epfl/qgroundcontrol,remspoor/qgroundcontrol,josephlewis42/UDenverQGC2,cfelipesouza/qgroundcontrol,lis-epfl/qgroundcontrol,hejunbok/qgroundcontrol,remspoor/qgroundcontrol,greenoaktree/qgroundcontrol,UAVenture/qgroundcontrol,remspoor/qgroundcontrol,ethz-asl/qgc_asl,scott-eddy/qgroundcontrol,josephlewis42/UDenverQGC2,hejunbok/qgroundcontrol,nado1688/qgroundcontrol,Hunter522/qgroundcontrol,Hunter522/qgroundcontrol,caoxiongkun/qgroundcontrol,josephlewis42/UDenverQGC2,ethz-asl/qgc_asl,kd0aij/qgroundcontrol,scott-eddy/qgroundcontrol,remspoor/qgroundcontrol,nado1688/qgroundcontrol,jy723/qgroundcontrol,fizzaly/qgroundcontrol,TheIronBorn/qgroundcontrol,BMP-TECH/qgroundcontrol,catch-twenty-two/qgroundcontrol,TheIronBorn/qgroundcontrol,devbharat/qgroundcontrol,kd0aij/qgroundcontrol,kd0aij/qgroundcontrol,LIKAIMO/qgroundcontrol,iidioter/qgroundcontrol,RedoXyde/PX4_qGCS,RedoXyde/PX4_qGCS,remspoor/qgroundcontrol,remspoor/qgroundcontrol,dagoodma/qgroundcontrol,devbharat/qgroundcontrol,TheIronBorn/qgroundcontrol,CornerOfSkyline/qgroundcontrol,LIKAIMO/qgroundcontrol,mihadyuk/qgroundcontrol,greenoaktree/qgroundcontrol,dagoodma/qgroundcontrol,LIKAIMO/qgroundcontrol,RedoXyde/PX4_qGCS,UAVenture/qgroundcontrol,catch-twenty-two/qgroundcontrol,cfelipesouza/qgroundcontrol,TheIronBorn/qgroundcontrol,iidioter/qgroundcontrol,kd0aij/qgroundcontrol,caoxiongkun/qgroundcontrol,LIKAIMO/qgroundcontrol,ethz-asl/qgc_asl,hejunbok/qgroundcontrol,lis-epfl/qgroundcontrol,caoxiongkun/qgroundcontrol,josephlewis42/UDenverQGC2,iidioter/qgroundcontrol,ethz-asl/qgc_asl,CornerOfSkyline/qgroundcontrol,BMP-TECH/qgroundcontrol,Hunter522/qgroundcontrol,BMP-TECH/qgroundcontrol,CornerOfSkyline/qgroundcontrol,iidioter/qgroundcontrol,greenoaktree/qgroundcontrol
8f3868f1e2b1f4f2e9b22c876cae774d81425136
src/main.cc
src/main.cc
#include <stdlib.h> #include <time.h> #include <cassert> #include <functional> #include <iostream> #include <string> #include <variant> #include <vector> #include <mpd/connection.h> #include "args.h" #include "ashuffle.h" #include "getpass.h" #include "load.h" #include "mpd_client.h" #include "shuffle.h" using namespace ashuffle; namespace { // The size of the rolling shuffle window. const int kWindowSize = 7; std::unique_ptr<Loader> BuildLoader(mpd::MPD* mpd, const Options& opts) { if (opts.file_in != nullptr && opts.check_uris) { return std::make_unique<FileMPDLoader>(mpd, opts.ruleset, opts.group_by, opts.file_in); } else if (opts.file_in != nullptr) { return std::make_unique<FileLoader>(opts.file_in); } return std::make_unique<MPDLoader>(mpd, opts.ruleset, opts.group_by); } } // namespace int main(int argc, const char* argv[]) { std::variant<Options, ParseError> parse = Options::ParseFromC(*mpd::client::Parser(), argv, argc); if (ParseError* err = std::get_if<ParseError>(&parse); err != nullptr) { switch (err->type) { case ParseError::Type::kUnknown: std::cerr << "unknown option parsing error. Please file a bug " << "at https://github.com/joshkunz/ashuffle" << std::endl; break; case ParseError::Type::kHelp: // We always print the help, so just break here. break; case ParseError::Type::kGeneric: std::cerr << "error: " << err->msg << std::endl; break; default: assert(false && "unreachable"); } std::cerr << DisplayHelp; exit(EXIT_FAILURE); } Options options = std::move(std::get<Options>(parse)); if (!options.check_uris && !options.group_by.empty()) { std::cerr << "-g/--group-by not supported with no-check" << std::endl; exit(EXIT_FAILURE); } std::function<std::string()> pass_f = [] { return GetPass(stdin, stdout, "mpd password: "); }; /* attempt to connect to MPD */ std::unique_ptr<mpd::MPD> mpd = Connect(*mpd::client::Dialer(), options, pass_f); ShuffleChain songs(kWindowSize); { // We construct the loader in a new scope, since loaders can // consume a lot of memory. std::unique_ptr<Loader> loader = BuildLoader(mpd.get(), options); loader->Load(&songs); } // For integration testing, we sometimes just want to have ashuffle // dump the list of songs in its shuffle chain. if (options.test.print_all_songs_and_exit) { bool first = true; for (auto&& group : songs.Items()) { if (!first) { std::cout << "---" << std::endl; } first = false; for (auto&& song : group) { std::cout << song << std::endl; } } exit(EXIT_SUCCESS); } if (songs.Len() == 0) { std::cerr << "Song pool is empty." << std::endl; exit(EXIT_FAILURE); } if (!options.group_by.empty()) { std::cout << absl::StrFormat("Picking from %u groups (%u songs).", songs.Len(), songs.LenURIs()) << std::endl; } else { std::cout << "Picking random songs out of a pool of " << songs.Len() << "." << std::endl; } /* do the main action */ if (options.queue_only) { for (unsigned i = 0; i < options.queue_only; i++) { mpd->Add(songs.Pick()); } std::cout << "Added " << options.queue_only << " songs." << std::endl; } else { Loop(mpd.get(), &songs, options); } return 0; }
#include <stdlib.h> #include <time.h> #include <cassert> #include <functional> #include <iostream> #include <string> #include <variant> #include <vector> #include <mpd/connection.h> #include "args.h" #include "ashuffle.h" #include "getpass.h" #include "load.h" #include "mpd_client.h" #include "shuffle.h" using namespace ashuffle; namespace { std::unique_ptr<Loader> BuildLoader(mpd::MPD* mpd, const Options& opts) { if (opts.file_in != nullptr && opts.check_uris) { return std::make_unique<FileMPDLoader>(mpd, opts.ruleset, opts.group_by, opts.file_in); } else if (opts.file_in != nullptr) { return std::make_unique<FileLoader>(opts.file_in); } return std::make_unique<MPDLoader>(mpd, opts.ruleset, opts.group_by); } } // namespace int main(int argc, const char* argv[]) { std::variant<Options, ParseError> parse = Options::ParseFromC(*mpd::client::Parser(), argv, argc); if (ParseError* err = std::get_if<ParseError>(&parse); err != nullptr) { switch (err->type) { case ParseError::Type::kUnknown: std::cerr << "unknown option parsing error. Please file a bug " << "at https://github.com/joshkunz/ashuffle" << std::endl; break; case ParseError::Type::kHelp: // We always print the help, so just break here. break; case ParseError::Type::kGeneric: std::cerr << "error: " << err->msg << std::endl; break; default: assert(false && "unreachable"); } std::cerr << DisplayHelp; exit(EXIT_FAILURE); } Options options = std::move(std::get<Options>(parse)); if (!options.check_uris && !options.group_by.empty()) { std::cerr << "-g/--group-by not supported with no-check" << std::endl; exit(EXIT_FAILURE); } std::function<std::string()> pass_f = [] { return GetPass(stdin, stdout, "mpd password: "); }; /* attempt to connect to MPD */ std::unique_ptr<mpd::MPD> mpd = Connect(*mpd::client::Dialer(), options, pass_f); ShuffleChain songs((size_t)options.tweak.window_size); { // We construct the loader in a new scope, since loaders can // consume a lot of memory. std::unique_ptr<Loader> loader = BuildLoader(mpd.get(), options); loader->Load(&songs); } // For integration testing, we sometimes just want to have ashuffle // dump the list of songs in its shuffle chain. if (options.test.print_all_songs_and_exit) { bool first = true; for (auto&& group : songs.Items()) { if (!first) { std::cout << "---" << std::endl; } first = false; for (auto&& song : group) { std::cout << song << std::endl; } } exit(EXIT_SUCCESS); } if (songs.Len() == 0) { std::cerr << "Song pool is empty." << std::endl; exit(EXIT_FAILURE); } if (!options.group_by.empty()) { std::cout << absl::StrFormat("Picking from %u groups (%u songs).", songs.Len(), songs.LenURIs()) << std::endl; } else { std::cout << "Picking random songs out of a pool of " << songs.Len() << "." << std::endl; } /* do the main action */ if (options.queue_only) { for (unsigned i = 0; i < options.queue_only; i++) { mpd->Add(songs.Pick()); } std::cout << "Added " << options.queue_only << " songs." << std::endl; } else { Loop(mpd.get(), &songs, options); } return 0; }
Use `window-size` tweak for shuffle chain window.
Use `window-size` tweak for shuffle chain window. Fixes #67.
C++
mit
Joshkunz/ashuffle
d7e78010bcc8b49c14eb4bc00524801d03c8d0a1
src/main.cc
src/main.cc
/** * @file main.cc * @brief gcsa_locate main program. * * Uses GCSA2 index to locate k-mers in the underlying graph. * * @author Ali Ghaffaari (\@cartoonist), <[email protected]> * * @internal * Created: Thu Aug 03, 2017 04:37 * Organization: Max-Planck-Institut fuer Informatik * Copyright: Copyright (c) 2017, Ali Ghaffaari * * This source code is released under the terms of the MIT License. * See LICENSE file for more information. */ #include <cstdlib> #include <csignal> #include <iostream> #include <fstream> #include <vector> #include <string> #include <seqan/arg_parse.h> #include <gcsa/gcsa.h> #include <config.h> #include "seed.h" #include "timer.h" #include "options.h" #include "release.h" seqan::ArgumentParser::ParseResult parse_args( Options& options, int argc, char* argv[] ); void setup_argparser( seqan::ArgumentParser& parser ); inline void get_option_values( Options& options, seqan::ArgumentParser& parser ); void locate_seeds( std::string& seq_name, std::string& gcsa_name, unsigned int seed_len, unsigned int distance, std::string& output_name ); void signal_handler( int signal ); std::size_t done_idx = 0; std::size_t total_no = 0; int main( int argc, char* argv[] ) { // Parse the command line. Options options; auto res = parse_args( options, argc, argv ); // If parsing was not successful then exit with code 1 if there were errors. // Otherwise, exit with code 0 (e.g. help was printed). if (res != seqan::ArgumentParser::PARSE_OK) return res == seqan::ArgumentParser::PARSE_ERROR; /* Install signal handler */ std::signal( SIGUSR1, signal_handler ); locate_seeds( options.seq_filename, options.gcsa_filename, options.seed_len, options.distance, options.output_filename ); return EXIT_SUCCESS; } void signal_handler( int ) { std::cout << "Located " << ::done_idx << " out of " << ::total_no << " in " << Timer<>::get_lap_str( "locate" ) << ": " << ::done_idx * 100 / total_no << "% done." << std::endl; } void locate_seeds( std::string& seq_name, std::string& gcsa_name, unsigned int seed_len, unsigned int distance, std::string& output_name ) { std::ifstream seq_file( seq_name, std::ifstream::in | std::ifstream::binary ); if ( !seq_file ) { throw std::runtime_error("could not open file '" + seq_name + "'" ); } std::ifstream gcsa_file( gcsa_name, std::ifstream::in | std::ifstream::binary ); if ( !gcsa_file ) { throw std::runtime_error("could not open file '" + gcsa_name + "'" ); } gcsa::GCSA index; std::vector< std::string > sequences; std::vector< std::string > patterns; std::vector< gcsa::node_type > results; std::cout << "Loading GCSA index..." << std::endl; index.load( gcsa_file ); std::cout << "Loading sequences..." << std::endl; { auto timer = Timer<>( "sequences" ); std::string line; while ( std::getline( seq_file, line ) ) { sequences.push_back( line ); } } std::cout << "Loaded " << sequences.size() << " sequences in " << Timer<>::get_duration_str( "sequences" ) << "." << std::endl; std::cout << "Generating patterns..." << std::endl; { auto timer = Timer<>( "patterns" ); seeding( patterns, sequences, seed_len, distance ); } ::total_no = patterns.size(); std::cout << "Generated " << patterns.size() << " patterns in " << Timer<>::get_duration_str( "patterns" ) << "." << std::endl; std::cout << "Locating patterns..." << std::endl; std::vector< gcsa::range_type > ranges; gcsa::size_type total = 0; { auto timer = Timer<>( "find" ); for ( const auto& p : patterns ) { gcsa::range_type range = index.find( p ); if( !gcsa::Range::empty( range ) ) { ranges.push_back( range ); total += index.count( range ); } } } std::cout << "Found " << ranges.size() << " patterns matching " << total << " paths in " << Timer<>::get_duration_str( "find" ) << "." << std::endl; total = 0; { auto timer = Timer<>( "locate" ); for ( const auto& range : ranges ) { index.locate( range, results, true ); ::done_idx++; } } std::cout << "Located " << results.size() << " occurrences in " << Timer<>::get_duration_str( "locate" ) << "." << std::endl; std::cout << "Writing occurrences into file..." << std::endl; std::ofstream output_file( output_name, std::ofstream::out ); for ( auto && r : results ) { output_file << gcsa::Node::id( r ) << "\t" << gcsa::Node::offset( r ) << std::endl; } } inline seqan::ArgumentParser::ParseResult parse_args( Options& options, int argc, char* argv[] ) { // setup ArgumentParser. seqan::ArgumentParser parser( release::name ); setup_argparser( parser ); // Embedding program's meta data and build information. setShortDescription( parser, release::short_desc ); setVersion( parser, release::version ); setDate( parser, LAST_MOD_DATE ); addDescription( parser, release::desc ); // parse command line. auto res = seqan::parse( parser, argc, argv ); // only extract options if the program will continue after parse_args() if ( res != seqan::ArgumentParser::PARSE_OK ) { return res; } get_option_values( options, parser ); return seqan::ArgumentParser::PARSE_OK; } inline void setup_argparser( seqan::ArgumentParser& parser ) { // positional arguments. std::string POSARG1 = "SEQ_FILE"; // add usage line. addUsageLine(parser, "[\\fIOPTIONS\\fP] \"\\fI" + POSARG1 + "\\fP\""); // sequence file -- positional argument. seqan::ArgParseArgument seq_arg( seqan::ArgParseArgument::INPUT_FILE, POSARG1 ); addArgument( parser, seq_arg ); // GCSA2 index file -- **required** option. seqan::ArgParseOption gcsa_arg( "g", "gcsa", "GCSA2 index file.", seqan::ArgParseArgument::INPUT_FILE, "GCSA2_FILE" ); setValidValues( gcsa_arg, gcsa::GCSA::EXTENSION ); addOption( parser, gcsa_arg ); setRequired( parser, "g" ); // Seed length. addOption( parser, seqan::ArgParseOption( "l", "seed-len", "Seed length.", seqan::ArgParseArgument::INTEGER, "INT" ) ); setRequired( parser, "l" ); // Overlapping seeds? addOption( parser, seqan::ArgParseOption( "d", "distance", "Distance between seeds [default: seed length given by \\fB-l\\fP]", seqan::ArgParseArgument::INTEGER, "INT" ) ); setDefaultValue( parser, "d", 0 ); /* Default value is seed length. */ // Output file. seqan::ArgParseOption output_arg( "o", "output", "Write positions where sequences are matched.", seqan::ArgParseArgument::OUTPUT_FILE, "OUTPUT" ); addOption( parser, output_arg ); setRequired( parser, "o" ); } inline void get_option_values( Options& options, seqan::ArgumentParser& parser ) { getArgumentValue( options.seq_filename, parser, 0 ); getOptionValue( options.gcsa_filename, parser, "gcsa" ); getOptionValue( options.output_filename, parser, "output" ); getOptionValue( options.seed_len, parser, "seed-len" ); getOptionValue( options.distance, parser, "distance" ); if ( options.distance == 0 ) options.distance = options.seed_len; }
/** * @file main.cc * @brief gcsa_locate main program. * * Uses GCSA2 index to locate k-mers in the underlying graph. * * @author Ali Ghaffaari (\@cartoonist), <[email protected]> * * @internal * Created: Thu Aug 03, 2017 04:37 * Organization: Max-Planck-Institut fuer Informatik * Copyright: Copyright (c) 2017, Ali Ghaffaari * * This source code is released under the terms of the MIT License. * See LICENSE file for more information. */ #include <cstdlib> #include <csignal> #include <iostream> #include <fstream> #include <vector> #include <string> #include <seqan/arg_parse.h> #include <gcsa/gcsa.h> #include <config.h> #include "seed.h" #include "timer.h" #include "options.h" #include "release.h" seqan::ArgumentParser::ParseResult parse_args( Options& options, int argc, char* argv[] ); void setup_argparser( seqan::ArgumentParser& parser ); inline void get_option_values( Options& options, seqan::ArgumentParser& parser ); void locate_seeds( std::string& seq_name, std::string& gcsa_name, unsigned int seed_len, unsigned int distance, std::string& output_name ); void signal_handler( int signal ); std::size_t done_idx = 0; std::size_t total_no = 0; std::size_t total_occs = 0; int main( int argc, char* argv[] ) { // Parse the command line. Options options; auto res = parse_args( options, argc, argv ); // If parsing was not successful then exit with code 1 if there were errors. // Otherwise, exit with code 0 (e.g. help was printed). if (res != seqan::ArgumentParser::PARSE_OK) return res == seqan::ArgumentParser::PARSE_ERROR; /* Install signal handler */ std::signal( SIGUSR1, signal_handler ); locate_seeds( options.seq_filename, options.gcsa_filename, options.seed_len, options.distance, options.output_filename ); return EXIT_SUCCESS; } void signal_handler( int ) { std::cout << "Located " << ::done_idx << " out of " << ::total_no << " with " << ::total_occs << " occurrences in " << Timer<>::get_lap_str( "locate" ) << ": " << ::done_idx * 100 / total_no << "% done." << std::endl; } void locate_seeds( std::string& seq_name, std::string& gcsa_name, unsigned int seed_len, unsigned int distance, std::string& output_name ) { std::ifstream seq_file( seq_name, std::ifstream::in | std::ifstream::binary ); if ( !seq_file ) { throw std::runtime_error("could not open file '" + seq_name + "'" ); } std::ifstream gcsa_file( gcsa_name, std::ifstream::in | std::ifstream::binary ); if ( !gcsa_file ) { throw std::runtime_error("could not open file '" + gcsa_name + "'" ); } gcsa::GCSA index; std::vector< std::string > sequences; std::vector< std::string > patterns; std::vector< gcsa::node_type > results; std::cout << "Loading GCSA index..." << std::endl; index.load( gcsa_file ); std::cout << "Loading sequences..." << std::endl; { auto timer = Timer<>( "sequences" ); std::string line; while ( std::getline( seq_file, line ) ) { sequences.push_back( line ); } } std::cout << "Loaded " << sequences.size() << " sequences in " << Timer<>::get_duration_str( "sequences" ) << "." << std::endl; std::cout << "Generating patterns..." << std::endl; { auto timer = Timer<>( "patterns" ); seeding( patterns, sequences, seed_len, distance ); } ::total_no = patterns.size(); std::cout << "Generated " << patterns.size() << " patterns in " << Timer<>::get_duration_str( "patterns" ) << "." << std::endl; std::cout << "Locating patterns..." << std::endl; std::vector< gcsa::range_type > ranges; gcsa::size_type total = 0; { auto timer = Timer<>( "find" ); for ( const auto& p : patterns ) { gcsa::range_type range = index.find( p ); if( !gcsa::Range::empty( range ) ) { ranges.push_back( range ); total += index.count( range ); } } } std::cout << "Found " << ranges.size() << " patterns matching " << total << " paths in " << Timer<>::get_duration_str( "find" ) << "." << std::endl; total = 0; { auto timer = Timer<>( "locate" ); for ( const auto& range : ranges ) { index.locate( range, results, true ); ::total_occs = results.size(); ::done_idx++; } } std::cout << "Located " << results.size() << " occurrences in " << Timer<>::get_duration_str( "locate" ) << "." << std::endl; std::cout << "Writing occurrences into file..." << std::endl; std::ofstream output_file( output_name, std::ofstream::out ); for ( auto && r : results ) { output_file << gcsa::Node::id( r ) << "\t" << gcsa::Node::offset( r ) << std::endl; } } inline seqan::ArgumentParser::ParseResult parse_args( Options& options, int argc, char* argv[] ) { // setup ArgumentParser. seqan::ArgumentParser parser( release::name ); setup_argparser( parser ); // Embedding program's meta data and build information. setShortDescription( parser, release::short_desc ); setVersion( parser, release::version ); setDate( parser, LAST_MOD_DATE ); addDescription( parser, release::desc ); // parse command line. auto res = seqan::parse( parser, argc, argv ); // only extract options if the program will continue after parse_args() if ( res != seqan::ArgumentParser::PARSE_OK ) { return res; } get_option_values( options, parser ); return seqan::ArgumentParser::PARSE_OK; } inline void setup_argparser( seqan::ArgumentParser& parser ) { // positional arguments. std::string POSARG1 = "SEQ_FILE"; // add usage line. addUsageLine(parser, "[\\fIOPTIONS\\fP] \"\\fI" + POSARG1 + "\\fP\""); // sequence file -- positional argument. seqan::ArgParseArgument seq_arg( seqan::ArgParseArgument::INPUT_FILE, POSARG1 ); addArgument( parser, seq_arg ); // GCSA2 index file -- **required** option. seqan::ArgParseOption gcsa_arg( "g", "gcsa", "GCSA2 index file.", seqan::ArgParseArgument::INPUT_FILE, "GCSA2_FILE" ); setValidValues( gcsa_arg, gcsa::GCSA::EXTENSION ); addOption( parser, gcsa_arg ); setRequired( parser, "g" ); // Seed length. addOption( parser, seqan::ArgParseOption( "l", "seed-len", "Seed length.", seqan::ArgParseArgument::INTEGER, "INT" ) ); setRequired( parser, "l" ); // Overlapping seeds? addOption( parser, seqan::ArgParseOption( "d", "distance", "Distance between seeds [default: seed length given by \\fB-l\\fP]", seqan::ArgParseArgument::INTEGER, "INT" ) ); setDefaultValue( parser, "d", 0 ); /* Default value is seed length. */ // Output file. seqan::ArgParseOption output_arg( "o", "output", "Write positions where sequences are matched.", seqan::ArgParseArgument::OUTPUT_FILE, "OUTPUT" ); addOption( parser, output_arg ); setRequired( parser, "o" ); } inline void get_option_values( Options& options, seqan::ArgumentParser& parser ) { getArgumentValue( options.seq_filename, parser, 0 ); getOptionValue( options.gcsa_filename, parser, "gcsa" ); getOptionValue( options.output_filename, parser, "output" ); getOptionValue( options.seed_len, parser, "seed-len" ); getOptionValue( options.distance, parser, "distance" ); if ( options.distance == 0 ) options.distance = options.seed_len; }
Include number of occurrences in USR1 signal report
Include number of occurrences in USR1 signal report
C++
mit
cartoonist/gcsa-locate,cartoonist/gcsa-locate
76f9feeb3f0bff9fa8cdb625ecd16a9e33f8ce67
FeatureComputation/opencv_hdf5.cpp
FeatureComputation/opencv_hdf5.cpp
#include <opencv/cv.h> #include <H5Cpp.h> #include <assert.h> using namespace cv; using namespace H5; using namespace std; static Size imsize; H5File create_feature_file(char *filename, const Mat &base_image) { imsize = base_image.size(); return H5File(filename, H5F_ACC_TRUNC); } H5File open_feature_file(char *filename) { return H5File(filename, H5F_ACC_RDONLY); } static DataSet create_dataset(H5File h5f, const char *name) { DSetCreatPropList cparms; hsize_t chunk_dims[2] = {256, 256}; hsize_t dims[2]; cparms.setChunk(2, chunk_dims); cparms.setShuffle(); cparms.setDeflate(5); dims[0] = imsize.height; dims[1] = imsize.width; return h5f.createDataSet(name, PredType::NATIVE_FLOAT, DataSpace(2, dims, dims), cparms); } void write_feature(H5File h5f, const Mat &image_in, const char *name) { // make sure the sizes match assert (imsize == image_in.size()); // make sure the image is in native float Mat image; if (image_in.type() != CV_32F) image_in.convertTo(image, CV_32F); else image = image_in; DataSet dataset = create_dataset(h5f, name); DataSpace imspace; float *imdata; if (image.isContinuous()) { imspace = dataset.getSpace(); // same size as imspace.selectAll(); imdata = image.ptr<float>(); } else { // we are working with an ROI assert (image.isSubmatrix()); Size parent_size; Point parent_ofs; image.locateROI(parent_size, parent_ofs); hsize_t parent_count[2]; parent_count[0] = parent_size.height; parent_count[1] = parent_size.width; imspace.setExtentSimple(2, parent_count); hsize_t im_offset[2], im_size[2]; im_offset[0] = parent_ofs.y; im_offset[1] = parent_ofs.x; im_size[0] = image.size().height; im_size[1] = image.size().width; imspace.selectHyperslab(H5S_SELECT_SET, im_size, im_offset); imdata = image.ptr<float>() - parent_ofs.x - parent_ofs.y * parent_size.width; } dataset.write(imdata, PredType::NATIVE_FLOAT, imspace); } void read_feature(H5File h5f, Mat &image_out, const char *name, const Rect &roi=Rect(0,0,0,0)) { DataSet dataset = h5f.openDataSet(name); DataSpace dspace = dataset.getSpace(); assert (dspace.getSimpleExtentNdims() == 2); hsize_t dims[2]; dspace.getSimpleExtentDims(dims); if ((roi.width == 0) && (roi.height == 0)) { image_out.create(dims[0], dims[1], CV_32F); dspace.selectAll(); } else { image_out.create(roi.height, roi.width, CV_32F); hsize_t _offset[2], _size[2]; _offset[0] = roi.y; _offset[1] = roi.x; _size[0] = roi.height; _size[1] = roi.width; dspace.selectHyperslab(H5S_SELECT_SET, _size, _offset); } DataSpace imspace; float *imdata; if (image_out.isContinuous()) { imspace = dataset.getSpace(); // same size as imspace.selectAll(); imdata = image_out.ptr<float>(); } else { // we are working with an ROI assert (image_out.isSubmatrix()); Size parent_size; Point parent_ofs; image_out.locateROI(parent_size, parent_ofs); hsize_t parent_count[2]; parent_count[0] = parent_size.height; parent_count[1] = parent_size.width; imspace.setExtentSimple(2, parent_count); hsize_t im_offset[2], im_size[2]; im_offset[0] = parent_ofs.y; im_offset[1] = parent_ofs.x; im_size[0] = image_out.size().height; im_size[1] = image_out.size().width; imspace.selectHyperslab(H5S_SELECT_SET, im_size, im_offset); imdata = image_out.ptr<float>() - parent_ofs.x - parent_ofs.y * parent_size.width; } dataset.read(imdata, PredType::NATIVE_FLOAT, imspace, dspace); } void read_feature_size(H5File h5f, Size &size_out, const char *name) { DataSet dataset = h5f.openDataSet(name); DataSpace dspace = dataset.getSpace(); assert (dspace.getSimpleExtentNdims() == 2); hsize_t dims[2]; dspace.getSimpleExtentDims(dims); size_out.height = dims[0]; size_out.width = dims[1]; } vector<string> get_feature_names(H5File h5f) { vector<string> out; int num_features; for (int i = 0; i < h5f.getNumObjs(); i++) out.push_back(h5f.getObjnameByIdx(i)); return out; }
#include <opencv/cv.h> #include <H5Cpp.h> #include <assert.h> using namespace cv; using namespace H5; using namespace std; static Size imsize; H5File create_feature_file(char *filename, const Mat &base_image) { imsize = base_image.size(); return H5File(filename, H5F_ACC_TRUNC); } H5File open_feature_file(char *filename) { return H5File(filename, H5F_ACC_RDONLY); } static DataSet create_dataset(H5File h5f, const char *name) { DSetCreatPropList cparms; hsize_t chunk_dims[2] = {256, 256}; hsize_t dims[2]; cparms.setChunk(2, chunk_dims); cparms.setShuffle(); cparms.setDeflate(5); dims[0] = imsize.height; dims[1] = imsize.width; return h5f.createDataSet(name, PredType::NATIVE_FLOAT, DataSpace(2, dims, dims), cparms); } void write_feature(H5File h5f, const Mat &image_in, const char *name) { // make sure the sizes match assert (imsize == image_in.size()); // make sure the image is in native float Mat image; if (image_in.type() != CV_32F) image_in.convertTo(image, CV_32F); else image = image_in; DataSet dataset = create_dataset(h5f, name); DataSpace imspace; float *imdata; if (image.isContinuous()) { imspace = dataset.getSpace(); // same size as imspace.selectAll(); imdata = image.ptr<float>(); } else { // we are working with an ROI assert (image.isSubmatrix()); Size parent_size; Point parent_ofs; image.locateROI(parent_size, parent_ofs); hsize_t parent_count[2]; parent_count[0] = parent_size.height; parent_count[1] = parent_size.width; imspace.setExtentSimple(2, parent_count); hsize_t im_offset[2], im_size[2]; im_offset[0] = parent_ofs.y; im_offset[1] = parent_ofs.x; im_size[0] = image.size().height; im_size[1] = image.size().width; imspace.selectHyperslab(H5S_SELECT_SET, im_size, im_offset); imdata = image.ptr<float>() - parent_ofs.x - parent_ofs.y * parent_size.width; } dataset.write(imdata, PredType::NATIVE_FLOAT, imspace); } void read_feature(H5File h5f, Mat &image_out, const char *name, const Rect &roi=Rect(0,0,0,0)) { DataSet dataset = h5f.openDataSet(name); DataSpace dspace = dataset.getSpace(); assert (dspace.getSimpleExtentNdims() == 2); hsize_t dims[2]; dspace.getSimpleExtentDims(dims); if ((roi.width == 0) && (roi.height == 0)) { image_out.create(dims[0], dims[1], CV_32F); dspace.selectAll(); } else { image_out.create(roi.height, roi.width, CV_32F); hsize_t _offset[2], _size[2]; _offset[0] = roi.y; _offset[1] = roi.x; _size[0] = roi.height; _size[1] = roi.width; dspace.selectHyperslab(H5S_SELECT_SET, _size, _offset); } DataSpace imspace; float *imdata; if (image_out.isContinuous()) { dims[0] = image_out.size().height; dims[1] = image_out.size().width; imspace = DataSpace(2, dims); imspace.selectAll(); imdata = image_out.ptr<float>(); } else { // we are working with an ROI assert (image_out.isSubmatrix()); Size parent_size; Point parent_ofs; image_out.locateROI(parent_size, parent_ofs); hsize_t parent_count[2]; parent_count[0] = parent_size.height; parent_count[1] = parent_size.width; imspace.setExtentSimple(2, parent_count); hsize_t im_offset[2], im_size[2]; im_offset[0] = parent_ofs.y; im_offset[1] = parent_ofs.x; im_size[0] = image_out.size().height; im_size[1] = image_out.size().width; imspace.selectHyperslab(H5S_SELECT_SET, im_size, im_offset); imdata = image_out.ptr<float>() - parent_ofs.x - parent_ofs.y * parent_size.width; } dataset.read(imdata, PredType::NATIVE_FLOAT, imspace, dspace); } void read_feature_size(H5File h5f, Size &size_out, const char *name) { DataSet dataset = h5f.openDataSet(name); DataSpace dspace = dataset.getSpace(); assert (dspace.getSimpleExtentNdims() == 2); hsize_t dims[2]; dspace.getSimpleExtentDims(dims); size_out.height = dims[0]; size_out.width = dims[1]; } vector<string> get_feature_names(H5File h5f) { vector<string> out; int num_features; for (int i = 0; i < h5f.getNumObjs(); i++) out.push_back(h5f.getObjnameByIdx(i)); return out; }
handle reading ROIs correctly
handle reading ROIs correctly
C++
mit
Rhoana/rhoana,Rhoana/rhoana,Rhoana/rhoana,Rhoana/rhoana,Rhoana/rhoana,Rhoana/rhoana
c08cbfe532d3123cfcbbab865ff5048968f80e4b
net.hh
net.hh
#ifndef NETSOCK_HH #define NETSOCK_HH #include "descriptors.hh" #include "task.hh" namespace ten { int netconnect(int fd, const address &addr, unsigned ms); int netdial(int fd, const char *addr, uint16_t port); int netaccept(int fd, address &addr, int flags, unsigned ms); ssize_t netrecv(int fd, void *buf, size_t len, int flags, unsigned ms); ssize_t netsend(int fd, const void *buf, size_t len, int flags, unsigned ms); class sockbase : boost::noncopyable { public: socket_fd s; sockbase(int fd=-1) throw (errno_error) : s(fd) {} sockbase(int domain, int type, int protocol=0) throw (errno_error) : s(domain, type | SOCK_NONBLOCK, protocol) {} virtual ~sockbase() {} void bind(address &addr) throw (errno_error) { s.bind(addr); } void listen(int backlog=128) throw (errno_error) { s.listen(backlog); } bool getpeername(address &addr) throw (errno_error) __attribute__((warn_unused_result)) { return s.getpeername(addr); } void getsockname(address &addr) throw (errno_error) { return s.getsockname(addr); } template <typename T> void getsockopt(int level, int optname, T &optval, socklen_t &optlen) throw (errno_error) { return s.getsockopt(level, optname, optval, optlen); } template <typename T> void setsockopt(int level, int optname, const T &optval, socklen_t optlen) throw (errno_error) { return s.setsockopt(level, optname, optval, optlen); } template <typename T> void setsockopt(int level, int optname, const T &optval) throw (errno_error) { return s.setsockopt(level, optname, optval); } void close() { s.close(); } virtual int dial(const char *addr, uint16_t port, unsigned timeout_ms=0) __attribute__((warn_unused_result)) = 0; virtual int connect(const address &addr, unsigned ms=0) __attribute__((warn_unused_result)) = 0; virtual int accept(address &addr, int flags=0, unsigned ms=0) __attribute__((warn_unused_result)) = 0; virtual ssize_t recv(void *buf, size_t len, int flags=0, unsigned ms=0) __attribute__((warn_unused_result)) = 0; virtual ssize_t send(const void *buf, size_t len, int flags=0, unsigned ms=0) __attribute__((warn_unused_result)) = 0; }; class netsock : public sockbase { public: netsock(int fd=-1) throw (errno_error) : sockbase(fd) {} netsock(int domain, int type, int protocol=0) throw (errno_error) : sockbase(domain, type, protocol) {} #ifdef __GXX_EXPERIMENTAL_CXX0X__ // C++0x move stuff netsock(netsock &&other) : sockbase() { std::swap(s, other.s); } netsock &operator = (netsock &&other) { if (this != &other) { std::swap(s, other.s); } return *this; } #endif //! dial requires a large 8MB stack size for getaddrinfo int dial(const char *addr, uint16_t port, unsigned timeout_ms=0) __attribute__((warn_unused_result)); int connect(const address &addr, unsigned timeout_ms=0) __attribute__((warn_unused_result)) { return netconnect(s.fd, addr, timeout_ms); } int accept(address &addr, int flags=0, unsigned timeout_ms=0) __attribute__((warn_unused_result)) { return netaccept(s.fd, addr, flags, timeout_ms); } ssize_t recv(void *buf, size_t len, int flags=0, unsigned timeout_ms=0) __attribute__((warn_unused_result)) { return netrecv(s.fd, buf, len, flags, timeout_ms); } ssize_t send(const void *buf, size_t len, int flags=0, unsigned timeout_ms=0) __attribute__((warn_unused_result)) { return netsend(s.fd, buf, len, flags, timeout_ms); } }; class netsock_server { public: netsock_server(const std::string &protocol_name_, size_t stacksize_=default_stacksize, int timeout_ms_=-1) : protocol_name(protocol_name_), stacksize(stacksize_), timeout_ms(timeout_ms_) { } netsock_server(const netsock_server &) = delete; netsock_server &operator=(const netsock_server &) = delete; //! listen and accept connections void serve(const std::string &ipaddr, uint16_t port) { address baddr(ipaddr.c_str(), port); serve(baddr); } //! listen and accept connections void serve(address &baddr) { sock = netsock(baddr.family(), SOCK_STREAM); sock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1); sock.bind(baddr); sock.getsockname(baddr); LOG(INFO) << "listening for " << protocol_name << " on " << baddr; sock.listen(); try { for (;;) { address client_addr; int fd; while ((fd = sock.accept(client_addr, 0)) > 0) { taskspawn(std::bind(&netsock_server::client_task, this, fd), stacksize); } } } catch (...) { // do any cleanup to free memory etc... // for example if your callbacks hold a reference to this server // this would be the place to release that circular reference on_shutdown(); throw; } } protected: netsock sock; std::string protocol_name; size_t stacksize; int timeout_ms; virtual void on_shutdown() {} virtual void on_connection(netsock &s) = 0; void client_task(int fd) { netsock s(fd); try { on_connection(s); } catch (std::exception &e) { LOG(ERROR) << "unhandled client task error: " << e.what(); } } }; } // end namespace ten #endif // NETSOCK_HH
#ifndef NETSOCK_HH #define NETSOCK_HH #include "descriptors.hh" #include "task.hh" namespace ten { int netconnect(int fd, const address &addr, unsigned ms); int netdial(int fd, const char *addr, uint16_t port); int netaccept(int fd, address &addr, int flags, unsigned ms); ssize_t netrecv(int fd, void *buf, size_t len, int flags, unsigned ms); ssize_t netsend(int fd, const void *buf, size_t len, int flags, unsigned ms); class sockbase : boost::noncopyable { public: socket_fd s; sockbase(int fd=-1) throw (errno_error) : s(fd) {} sockbase(int domain, int type, int protocol=0) throw (errno_error) : s(domain, type | SOCK_NONBLOCK, protocol) {} virtual ~sockbase() {} void bind(address &addr) throw (errno_error) { s.bind(addr); } void listen(int backlog=128) throw (errno_error) { s.listen(backlog); } bool getpeername(address &addr) throw (errno_error) __attribute__((warn_unused_result)) { return s.getpeername(addr); } void getsockname(address &addr) throw (errno_error) { return s.getsockname(addr); } template <typename T> void getsockopt(int level, int optname, T &optval, socklen_t &optlen) throw (errno_error) { return s.getsockopt(level, optname, optval, optlen); } template <typename T> void setsockopt(int level, int optname, const T &optval, socklen_t optlen) throw (errno_error) { return s.setsockopt(level, optname, optval, optlen); } template <typename T> void setsockopt(int level, int optname, const T &optval) throw (errno_error) { return s.setsockopt(level, optname, optval); } void close() { s.close(); } virtual int dial(const char *addr, uint16_t port, unsigned timeout_ms=0) __attribute__((warn_unused_result)) = 0; virtual int connect(const address &addr, unsigned ms=0) __attribute__((warn_unused_result)) = 0; virtual int accept(address &addr, int flags=0, unsigned ms=0) __attribute__((warn_unused_result)) = 0; virtual ssize_t recv(void *buf, size_t len, int flags=0, unsigned ms=0) __attribute__((warn_unused_result)) = 0; virtual ssize_t send(const void *buf, size_t len, int flags=0, unsigned ms=0) __attribute__((warn_unused_result)) = 0; ssize_t recvall(void *buf, size_t len, unsigned ms=0) { size_t pos = 0; ssize_t left = len; while (pos != len) { ssize_t nr = recv(&((char *)buf)[pos], left, 0, ms); if (nr > 0) { pos += nr; left -= nr; } else { break; } } return pos; } }; class netsock : public sockbase { public: netsock(int fd=-1) throw (errno_error) : sockbase(fd) {} netsock(int domain, int type, int protocol=0) throw (errno_error) : sockbase(domain, type, protocol) {} #ifdef __GXX_EXPERIMENTAL_CXX0X__ // C++0x move stuff netsock(netsock &&other) : sockbase() { std::swap(s, other.s); } netsock &operator = (netsock &&other) { if (this != &other) { std::swap(s, other.s); } return *this; } #endif //! dial requires a large 8MB stack size for getaddrinfo int dial(const char *addr, uint16_t port, unsigned timeout_ms=0) __attribute__((warn_unused_result)); int connect(const address &addr, unsigned timeout_ms=0) __attribute__((warn_unused_result)) { return netconnect(s.fd, addr, timeout_ms); } int accept(address &addr, int flags=0, unsigned timeout_ms=0) __attribute__((warn_unused_result)) { return netaccept(s.fd, addr, flags, timeout_ms); } ssize_t recv(void *buf, size_t len, int flags=0, unsigned timeout_ms=0) __attribute__((warn_unused_result)) { return netrecv(s.fd, buf, len, flags, timeout_ms); } ssize_t send(const void *buf, size_t len, int flags=0, unsigned timeout_ms=0) __attribute__((warn_unused_result)) { return netsend(s.fd, buf, len, flags, timeout_ms); } }; class netsock_server { public: netsock_server(const std::string &protocol_name_, size_t stacksize_=default_stacksize, int timeout_ms_=-1) : protocol_name(protocol_name_), stacksize(stacksize_), timeout_ms(timeout_ms_) { } netsock_server(const netsock_server &) = delete; netsock_server &operator=(const netsock_server &) = delete; //! listen and accept connections void serve(const std::string &ipaddr, uint16_t port) { address baddr(ipaddr.c_str(), port); serve(baddr); } //! listen and accept connections void serve(address &baddr) { sock = netsock(baddr.family(), SOCK_STREAM); sock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1); sock.bind(baddr); sock.getsockname(baddr); LOG(INFO) << "listening for " << protocol_name << " on " << baddr; sock.listen(); try { for (;;) { address client_addr; int fd; while ((fd = sock.accept(client_addr, 0)) > 0) { taskspawn(std::bind(&netsock_server::client_task, this, fd), stacksize); } } } catch (...) { // do any cleanup to free memory etc... // for example if your callbacks hold a reference to this server // this would be the place to release that circular reference on_shutdown(); throw; } } protected: netsock sock; std::string protocol_name; size_t stacksize; int timeout_ms; virtual void on_shutdown() {} virtual void on_connection(netsock &s) = 0; void client_task(int fd) { netsock s(fd); try { on_connection(s); } catch (std::exception &e) { LOG(ERROR) << "unhandled client task error: " << e.what(); } } }; } // end namespace ten #endif // NETSOCK_HH
add recvall
add recvall
C++
apache-2.0
toffaletti/libten,toffaletti/libten,toffaletti/libten,toffaletti/libten,toffaletti/libten
ab9447707d1a7a85945f1c6f775d7da960294f7f
CCJson.cpp
CCJson.cpp
/**************************************************************************** Copyright (c) Yassy https://github.com/yassy0413/cocos2dx-3.x-util ****************************************************************************/ #include "CCJson.h" #include <sstream> #include <iomanip> #include <external/json/writer.h> #include <external/json/prettywriter.h> NS_CC_EXT_BEGIN Json* Json::createFromStr(const char* str){ auto p = new (std::nothrow) Json(); if( p->initFromStr(str, false) ){ p->autorelease(); return p; } delete p; return nullptr; } Json* Json::createFromStrInsitu(const char* str){ auto p = new (std::nothrow) Json(); if( p->initFromStr(str, true) ){ p->autorelease(); return p; } delete p; return nullptr; } Json* Json::createFromValue(const Value& value){ auto p = new (std::nothrow) Json(); if( p->initFromValue(value) ){ p->autorelease(); return p; } delete p; return nullptr; } Json::Json() : _document(nullptr) , _stringBuffer(nullptr) {} Json::~Json(){ delete _stringBuffer; delete _document; } bool Json::initFromStr(const char* str, bool insitu){ delete _document; _document = new (std::nothrow) rapidjson::Document(); if( insitu ){ _document->ParseInsitu<rapidjson::kParseDefaultFlags>(const_cast<char*>(str)); }else{ _document->Parse<rapidjson::kParseDefaultFlags>(str); } if( _document->HasParseError() ){ CCLOG("JsonParseError [%d]", _document->GetParseError()); return false; } return true; } bool Json::initFromValue(const Value& value){ static const std::function<void(rapidjson::Document& document, const Value& in, rapidjson::Value& out)> convert[] = { // NONE [](rapidjson::Document& document, const Value& in, rapidjson::Value& out){ out.SetNull(); }, // BYTE [](rapidjson::Document& document, const Value& in, rapidjson::Value& out){ out.SetInt( in.asByte() ); }, // INTEGER [](rapidjson::Document& document, const Value& in, rapidjson::Value& out){ out.SetInt( in.asInt() ); }, // UNSIGNED [](rapidjson::Document& document, const Value& in, rapidjson::Value& out){ out.SetUint( in.asUnsignedInt() ); }, // FLOAT [](rapidjson::Document& document, const Value& in, rapidjson::Value& out){ out.SetDouble( in.asFloat() ); }, // DOUBLE [](rapidjson::Document& document, const Value& in, rapidjson::Value& out){ out.SetDouble( in.asDouble() ); }, // BOOLEAN [](rapidjson::Document& document, const Value& in, rapidjson::Value& out){ out.SetBool( in.asBool() ); }, // STRING [](rapidjson::Document& document, const Value& in, rapidjson::Value& out){ out.SetString( in.asString().c_str(), static_cast<rapidjson::SizeType>(in.asString().length()) ); }, // VECTOR [](rapidjson::Document& document, const Value& in, rapidjson::Value& out){ out.SetArray(); for( const auto& vv : in.asValueVector() ){ rapidjson::Value v; convert[ static_cast<int>(vv.getType()) ]( document, vv, v ); out.PushBack( v, document.GetAllocator() ); } }, // MAP [](rapidjson::Document& document, const Value& in, rapidjson::Value& out){ out.SetObject(); for( const auto& vv : in.asValueMap() ){ rapidjson::Value v; convert[ static_cast<int>(vv.second.getType()) ]( document, vv.second, v ); out.AddMember( rapidjson::StringRef(vv.first.c_str()), v, document.GetAllocator() ); } }, // INT_KEY_MAP [](rapidjson::Document& document, const Value& in, rapidjson::Value& out){ CCASSERT(0, "Not supported."); }, }; // std::vector<char> buffer; // buffer.resize( 4*1024*1024 ); // rapidjson::MemoryPoolAllocator<> allocator( &buffer.front(), buffer.size() ); delete _document; _document = new (std::nothrow) rapidjson::Document(); convert[ static_cast<int>(value.getType()) ]( *_document, value, *_document ); return true; } const char* Json::getString(){ CC_ASSERT(_document); delete _stringBuffer; _stringBuffer = new (std::nothrow) rapidjson::StringBuffer(); rapidjson::Writer<rapidjson::StringBuffer> writer( *_stringBuffer ); _document->Accept( writer ); return _stringBuffer->GetString(); } const char* Json::getPrettyString(char indentChar, uint32_t indentCharCount){ CC_ASSERT(_document); delete _stringBuffer; _stringBuffer = new (std::nothrow) rapidjson::StringBuffer(); rapidjson::PrettyWriter<rapidjson::StringBuffer> writer( *_stringBuffer ); writer.SetIndent( indentChar, indentCharCount ); _document->Accept( writer ); return _stringBuffer->GetString(); } Value Json::getValue() const { CC_ASSERT(_document); static std::function<Value(const rapidjson::Value& in)> convert[] = { // kNullType [](const rapidjson::Value& in){ return Value(); }, // kFalseType [](const rapidjson::Value& in){ return Value(false); }, // kTrueType [](const rapidjson::Value& in){ return Value(true); }, // kObjectType [](const rapidjson::Value& in){ ValueMap result; for( auto it = in.MemberBegin(); it != in.MemberEnd(); ++it ){ result.emplace( it->name.GetString(), convert[ it->value.GetType() ]( it->value ) ); } return Value( std::move(result) ); }, // kArrayType [](const rapidjson::Value& in){ ValueVector result; const rapidjson::SizeType size = in.Size(); result.reserve( size ); for( rapidjson::SizeType lp = 0; lp < size; ++lp ){ result.emplace_back( convert[ in.GetType() ]( in[lp] ) ); } return Value( std::move(result) ); }, // kStringType [](const rapidjson::Value& in){ return Value( in.GetString() ); }, // kNumberType [](const rapidjson::Value& in){ return in.IsDouble()? Value(in.GetDouble()) : Value(in.GetInt()) ; }, }; return convert[ _document->GetType() ]( *_document ); } NS_CC_EXT_END
/**************************************************************************** Copyright (c) Yassy https://github.com/yassy0413/cocos2dx-3.x-util ****************************************************************************/ #include "CCJson.h" #include <sstream> #include <iomanip> #include <external/json/writer.h> #include <external/json/prettywriter.h> NS_CC_EXT_BEGIN Json* Json::createFromStr(const char* str){ auto p = new (std::nothrow) Json(); if( p->initFromStr(str, false) ){ p->autorelease(); return p; } delete p; return nullptr; } Json* Json::createFromStrInsitu(const char* str){ auto p = new (std::nothrow) Json(); if( p->initFromStr(str, true) ){ p->autorelease(); return p; } delete p; return nullptr; } Json* Json::createFromValue(const Value& value){ auto p = new (std::nothrow) Json(); if( p->initFromValue(value) ){ p->autorelease(); return p; } delete p; return nullptr; } Json::Json() : _document(nullptr) , _stringBuffer(nullptr) {} Json::~Json(){ delete _stringBuffer; delete _document; } bool Json::initFromStr(const char* str, bool insitu){ delete _document; _document = new (std::nothrow) rapidjson::Document(); if( insitu ){ _document->ParseInsitu<rapidjson::kParseDefaultFlags>(const_cast<char*>(str)); }else{ _document->Parse<rapidjson::kParseDefaultFlags>(str); } if( _document->HasParseError() ){ CCLOG("JsonParseError [%d]", _document->GetParseError()); return false; } return true; } bool Json::initFromValue(const Value& value){ static const std::function<void(rapidjson::Document& document, const Value& in, rapidjson::Value& out)> convert[] = { // NONE [](rapidjson::Document& document, const Value& in, rapidjson::Value& out){ out.SetNull(); }, // BYTE [](rapidjson::Document& document, const Value& in, rapidjson::Value& out){ out.SetInt( in.asByte() ); }, // INTEGER [](rapidjson::Document& document, const Value& in, rapidjson::Value& out){ out.SetInt( in.asInt() ); }, // UNSIGNED [](rapidjson::Document& document, const Value& in, rapidjson::Value& out){ out.SetUint( in.asUnsignedInt() ); }, // FLOAT [](rapidjson::Document& document, const Value& in, rapidjson::Value& out){ out.SetDouble( in.asFloat() ); }, // DOUBLE [](rapidjson::Document& document, const Value& in, rapidjson::Value& out){ out.SetDouble( in.asDouble() ); }, // BOOLEAN [](rapidjson::Document& document, const Value& in, rapidjson::Value& out){ out.SetBool( in.asBool() ); }, // STRING [](rapidjson::Document& document, const Value& in, rapidjson::Value& out){ out.SetString( in.asString().c_str(), static_cast<rapidjson::SizeType>(in.asString().length()) ); }, // VECTOR [](rapidjson::Document& document, const Value& in, rapidjson::Value& out){ out.SetArray(); for( const auto& vv : in.asValueVector() ){ rapidjson::Value v; convert[ static_cast<int>(vv.getType()) ]( document, vv, v ); out.PushBack( v, document.GetAllocator() ); } }, // MAP [](rapidjson::Document& document, const Value& in, rapidjson::Value& out){ out.SetObject(); for( const auto& vv : in.asValueMap() ){ rapidjson::Value v; convert[ static_cast<int>(vv.second.getType()) ]( document, vv.second, v ); out.AddMember( rapidjson::StringRef(vv.first.c_str()), v, document.GetAllocator() ); } }, // INT_KEY_MAP [](rapidjson::Document& document, const Value& in, rapidjson::Value& out){ CCASSERT(0, "Not supported."); }, }; // std::vector<char> buffer; // buffer.resize( 4*1024*1024 ); // rapidjson::MemoryPoolAllocator<> allocator( &buffer.front(), buffer.size() ); delete _document; _document = new (std::nothrow) rapidjson::Document(); convert[ static_cast<int>(value.getType()) ]( *_document, value, *_document ); return true; } const char* Json::getString(){ CC_ASSERT(_document); delete _stringBuffer; _stringBuffer = new (std::nothrow) rapidjson::StringBuffer(); rapidjson::Writer<rapidjson::StringBuffer> writer( *_stringBuffer ); _document->Accept( writer ); return _stringBuffer->GetString(); } const char* Json::getPrettyString(char indentChar, uint32_t indentCharCount){ CC_ASSERT(_document); delete _stringBuffer; _stringBuffer = new (std::nothrow) rapidjson::StringBuffer(); rapidjson::PrettyWriter<rapidjson::StringBuffer> writer( *_stringBuffer ); writer.SetIndent( indentChar, indentCharCount ); _document->Accept( writer ); return _stringBuffer->GetString(); } Value Json::getValue() const { CC_ASSERT(_document); static std::function<Value(const rapidjson::Value& in)> convert[] = { // kNullType [](const rapidjson::Value& in){ return Value(); }, // kFalseType [](const rapidjson::Value& in){ return Value(false); }, // kTrueType [](const rapidjson::Value& in){ return Value(true); }, // kObjectType [](const rapidjson::Value& in){ ValueMap result; for( auto it = in.MemberBegin(); it != in.MemberEnd(); ++it ){ result.emplace( it->name.GetString(), convert[ it->value.GetType() ]( it->value ) ); } return Value( std::move(result) ); }, // kArrayType [](const rapidjson::Value& in){ ValueVector result; const rapidjson::SizeType size = in.Size(); result.reserve( size ); for( rapidjson::SizeType lp = 0; lp < size; ++lp ){ result.emplace_back( convert[ in.GetType() ]( in[lp] ) ); } return Value( std::move(result) ); }, // kStringType [](const rapidjson::Value& in){ return Value( in.GetString() ); }, // kNumberType [](const rapidjson::Value& in){ return in.IsDouble()? Value(in.GetDouble()) : (in.IsUint()? Value(in.GetUint()) : Value(in.GetInt())) ; }, }; return convert[ _document->GetType() ]( *_document ); } NS_CC_EXT_END
add uint ccjson
add uint ccjson
C++
mit
yassy0413/cocos2dx-3.x-util,yassy0413/cocos2dx-3.x-util
9dff7e90b885d8bf16bdcedec8b07a3cd3d2f496
src/fmi4cpp/fmi2/import/FmiLibraryHelper.hpp
src/fmi4cpp/fmi2/import/FmiLibraryHelper.hpp
// // Created by laht on 24.09.18. // #ifndef FMI4CPP_FMILIBRARYHELPER_HPP #define FMI4CPP_FMILIBRARYHELPER_HPP #include <fmi4cpp/fmi2/import/FmiLibrary.hpp> namespace { DLL_HANDLE loadLibrary(const std::string libName) { #ifdef WIN32 return LoadLibrary(libName.c_str()); #else return dlopen(libName.c_str(), RTLD_NOW | RTLD_LOCAL); #endif } template<class T> T loadFunction(DLL_HANDLE handle, const char *function_name) { #ifdef WIN32 return (T) GetProcAddress(handle, function_name); #else return (T) dlsym(handle, function_name); #endif } } #endif //FMI4CPP_FMILIBRARYHELPER_HPP
/* * The MIT License * * Copyright 2017-2018 Norwegian University of Technology * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #ifndef FMI4CPP_FMILIBRARYHELPER_HPP #define FMI4CPP_FMILIBRARYHELPER_HPP #include <fmi4cpp/fmi2/import/FmiLibrary.hpp> namespace { DLL_HANDLE loadLibrary(const std::string libName) { #ifdef WIN32 return LoadLibrary(libName.c_str()); #else return dlopen(libName.c_str(), RTLD_NOW | RTLD_LOCAL); #endif } template<class T> T loadFunction(DLL_HANDLE handle, const char *function_name) { #ifdef WIN32 return (T) GetProcAddress(handle, function_name); #else return (T) dlsym(handle, function_name); #endif } } #endif //FMI4CPP_FMILIBRARYHELPER_HPP
add license header
add license header
C++
mit
NTNU-IHB/FMI4cpp,NTNU-IHB/FMI4cpp,NTNU-IHB/FMI4cpp
b6b238dcefc1db60d0d1741606619e6cd3a79362
Source/ModernGL-Framebuffer.cpp
Source/ModernGL-Framebuffer.cpp
#include "ModernGL.hpp" #include "OpenGL.hpp" PyObject * NewFramebuffer(PyObject * self, PyObject * args, PyObject * kwargs) { int width = 0; int height = 0; static const char * kwlist[] = {"width", "height", 0}; if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ii:NewFramebuffer", (char **)kwlist, &width, &height)) { return 0; } int framebuffer = 0; int color = 0; int depth = 0; OpenGL::glGenFramebuffers(1, (OpenGL::GLuint *)&framebuffer); OpenGL::glBindFramebuffer(OpenGL::GL_FRAMEBUFFER, framebuffer); if (!width && !height) { width = activeViewportWidth; height = activeViewportHeight; } OpenGL::glGenTextures(1, (OpenGL::GLuint *)&color); OpenGL::glBindTexture(OpenGL::GL_TEXTURE_2D, color); OpenGL::glTexParameteri(OpenGL::GL_TEXTURE_2D, OpenGL::GL_TEXTURE_MIN_FILTER, OpenGL::GL_LINEAR); OpenGL::glTexParameteri(OpenGL::GL_TEXTURE_2D, OpenGL::GL_TEXTURE_MAG_FILTER, OpenGL::GL_LINEAR); OpenGL::glTexImage2D(OpenGL::GL_TEXTURE_2D, 0, OpenGL::GL_RGBA, width, height, 0, OpenGL::GL_RGBA, OpenGL::GL_FLOAT, 0); OpenGL::glFramebufferTexture2D(OpenGL::GL_FRAMEBUFFER, OpenGL::GL_COLOR_ATTACHMENT0, OpenGL::GL_TEXTURE_2D, color, 0); OpenGL::glGenTextures(1, (OpenGL::GLuint *)&depth); OpenGL::glBindTexture(OpenGL::GL_TEXTURE_2D, depth); OpenGL::glTexParameteri(OpenGL::GL_TEXTURE_2D, OpenGL::GL_TEXTURE_MIN_FILTER, OpenGL::GL_LINEAR); OpenGL::glTexParameteri(OpenGL::GL_TEXTURE_2D, OpenGL::GL_TEXTURE_MAG_FILTER, OpenGL::GL_LINEAR); OpenGL::glTexImage2D(OpenGL::GL_TEXTURE_2D, 0, OpenGL::GL_DEPTH_COMPONENT, width, height, 0, OpenGL::GL_DEPTH_COMPONENT, OpenGL::GL_FLOAT, 0); OpenGL::glFramebufferTexture2D(OpenGL::GL_FRAMEBUFFER, OpenGL::GL_DEPTH_ATTACHMENT, OpenGL::GL_TEXTURE_2D, depth, 0); OpenGL::glBindFramebuffer(OpenGL::GL_FRAMEBUFFER, defaultFramebuffer); PyObject * fbo = CreateFramebufferType(framebuffer, color, depth); PyObject * colorTexture = CreateTextureType(color, width, height, 4); PyObject * depthTexture = CreateTextureType(depth, width, height, 1); return Py_BuildValue("OOO", fbo, colorTexture, depthTexture); } PyObject * DeleteFramebuffer(PyObject * self, PyObject * args) { Framebuffer * fbo; if (!PyArg_ParseTuple(args, "O:DeleteFramebuffer", &fbo)) { return 0; } CHECK_AND_REPORT_ARG_TYPE_ERROR("fbo", fbo, FramebufferType); OpenGL::glDeleteFramebuffers(1, (OpenGL::GLuint *)&fbo->fbo); OpenGL::glDeleteTextures(1, (OpenGL::GLuint *)&fbo->color); OpenGL::glDeleteTextures(1, (OpenGL::GLuint *)&fbo->depth); Py_RETURN_NONE; } PyObject * UseFramebuffer(PyObject * self, PyObject * args) { Framebuffer * fbo; if (!PyArg_ParseTuple(args, "O:UseFramebuffer", &fbo)) { return 0; } CHECK_AND_REPORT_ARG_TYPE_ERROR("fbo", fbo, FramebufferType); OpenGL::glBindFramebuffer(OpenGL::GL_FRAMEBUFFER, fbo->fbo); activeProgram = fbo->fbo; Py_RETURN_NONE; } PyObject * GetDefaultFramebuffer(PyObject * self) { OpenGL::glGetIntegerv(OpenGL::GL_DRAW_FRAMEBUFFER_BINDING, (OpenGL::GLint *)&defaultFramebuffer); Py_RETURN_NONE; } PyObject * UseDefaultFramebuffer(PyObject * self) { OpenGL::glBindFramebuffer(OpenGL::GL_FRAMEBUFFER, defaultFramebuffer); Py_RETURN_NONE; } PyObject * ReadPixels(PyObject * self, PyObject * args, PyObject * kwargs) { int x; int y; int width; int height; int components = 3; static const char * kwlist[] = {"x", "y", "width", "height", "components", 0}; if (!PyArg_ParseTupleAndKeywords(args, kwargs, "iiii|i:ReadPixels", (char **)kwlist, &x, &y, &width, &height, &components)) { return 0; } if (components < 1 || components > 4) { PyErr_Format(ModuleError, "ReadPixels() argument `components` must be in range 1 to 4, not %d", components); return 0; } int size = height * ((width * components + 3) & ~3); const int formats[] = {0, OpenGL::GL_RED, OpenGL::GL_RG, OpenGL::GL_RGB, OpenGL::GL_RGBA}; int format = formats[components]; PyObject * bytes = PyBytes_FromStringAndSize(0, size); char * data = PyBytes_AS_STRING(bytes); OpenGL::glReadPixels(x, y, width, height, format, OpenGL::GL_UNSIGNED_BYTE, data); data[size] = 0; return bytes; } PyObject * ReadDepthPixels(PyObject * self, PyObject * args, PyObject * kwargs) { PyErr_SetString(ModuleError, "No Imp."); return 0; // int x; // int y; // int width; // int height; // static const char * kwlist[] = {"x", "y", "width", "height", 0}; // if (!PyArg_ParseTupleAndKeywords(args, kwargs, "iiii:ReadDepthPixels", (char **)kwlist, &x, &y, &width, &height)) { // return 0; // } // int size = height * height * 4; // float * pixels = ModernGL::ReadDepthPixels(x, y, width, height); // PyObject * data = PyBytes_FromStringAndSize((const char *)pixels, size); // free(pixels); // return data; } PyObject * ReadPixel(PyObject * self, PyObject * args, PyObject * kwargs) { PyErr_SetString(ModuleError, "No Imp."); return 0; // int x; // int y; // static const char * kwlist[] = {"x", "y", 0}; // if (!PyArg_ParseTupleAndKeywords(args, kwargs, "ii:ReadPixel", (char **)kwlist, &x, &y)) { // return 0; // } // return PyLong_FromUnsignedLong(ModernGL::ReadPixel(x, y)); } PyObject * ReadDepthPixel(PyObject * self, PyObject * args, PyObject * kwargs) { PyErr_SetString(ModuleError, "No Imp."); return 0; // int x; // int y; // static const char * kwlist[] = {"x", "y", 0}; // if (!PyArg_ParseTupleAndKeywords(args, kwargs, "ii:ReadDepthPixel", (char **)kwlist, &x, &y)) { // return 0; // } // return PyFloat_FromDouble(ModernGL::ReadDepthPixel(x, y)); }
#include "ModernGL.hpp" #include "OpenGL.hpp" PyObject * NewFramebuffer(PyObject * self, PyObject * args, PyObject * kwargs) { int width = 0; int height = 0; static const char * kwlist[] = {"width", "height", 0}; if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ii:NewFramebuffer", (char **)kwlist, &width, &height)) { return 0; } int framebuffer = 0; int color = 0; int depth = 0; OpenGL::glGenFramebuffers(1, (OpenGL::GLuint *)&framebuffer); OpenGL::glBindFramebuffer(OpenGL::GL_FRAMEBUFFER, framebuffer); if (!width && !height) { width = activeViewportWidth; height = activeViewportHeight; } OpenGL::glGenTextures(1, (OpenGL::GLuint *)&color); OpenGL::glBindTexture(OpenGL::GL_TEXTURE_2D, color); OpenGL::glTexParameteri(OpenGL::GL_TEXTURE_2D, OpenGL::GL_TEXTURE_MIN_FILTER, OpenGL::GL_LINEAR); OpenGL::glTexParameteri(OpenGL::GL_TEXTURE_2D, OpenGL::GL_TEXTURE_MAG_FILTER, OpenGL::GL_LINEAR); OpenGL::glTexImage2D(OpenGL::GL_TEXTURE_2D, 0, OpenGL::GL_RGBA, width, height, 0, OpenGL::GL_RGBA, OpenGL::GL_FLOAT, 0); OpenGL::glFramebufferTexture2D(OpenGL::GL_FRAMEBUFFER, OpenGL::GL_COLOR_ATTACHMENT0, OpenGL::GL_TEXTURE_2D, color, 0); OpenGL::glGenTextures(1, (OpenGL::GLuint *)&depth); OpenGL::glBindTexture(OpenGL::GL_TEXTURE_2D, depth); OpenGL::glTexParameteri(OpenGL::GL_TEXTURE_2D, OpenGL::GL_TEXTURE_MIN_FILTER, OpenGL::GL_LINEAR); OpenGL::glTexParameteri(OpenGL::GL_TEXTURE_2D, OpenGL::GL_TEXTURE_MAG_FILTER, OpenGL::GL_LINEAR); OpenGL::glTexImage2D(OpenGL::GL_TEXTURE_2D, 0, OpenGL::GL_DEPTH_COMPONENT, width, height, 0, OpenGL::GL_DEPTH_COMPONENT, OpenGL::GL_FLOAT, 0); OpenGL::glFramebufferTexture2D(OpenGL::GL_FRAMEBUFFER, OpenGL::GL_DEPTH_ATTACHMENT, OpenGL::GL_TEXTURE_2D, depth, 0); OpenGL::glBindFramebuffer(OpenGL::GL_FRAMEBUFFER, defaultFramebuffer); PyObject * fbo = CreateFramebufferType(framebuffer, color, depth); PyObject * colorTexture = CreateTextureType(color, width, height, 4); PyObject * depthTexture = CreateTextureType(depth, width, height, 1); return Py_BuildValue("OOO", fbo, colorTexture, depthTexture); } PyObject * DeleteFramebuffer(PyObject * self, PyObject * args) { Framebuffer * fbo; if (!PyArg_ParseTuple(args, "O:DeleteFramebuffer", &fbo)) { return 0; } CHECK_AND_REPORT_ARG_TYPE_ERROR("fbo", fbo, FramebufferType); OpenGL::glDeleteFramebuffers(1, (OpenGL::GLuint *)&fbo->fbo); OpenGL::glDeleteTextures(1, (OpenGL::GLuint *)&fbo->color); OpenGL::glDeleteTextures(1, (OpenGL::GLuint *)&fbo->depth); Py_RETURN_NONE; } PyObject * UseFramebuffer(PyObject * self, PyObject * args) { Framebuffer * fbo; if (!PyArg_ParseTuple(args, "O:UseFramebuffer", &fbo)) { return 0; } CHECK_AND_REPORT_ARG_TYPE_ERROR("fbo", fbo, FramebufferType); OpenGL::glBindFramebuffer(OpenGL::GL_FRAMEBUFFER, fbo->fbo); activeProgram = fbo->fbo; Py_RETURN_NONE; } PyObject * GetDefaultFramebuffer(PyObject * self) { OpenGL::glGetIntegerv(OpenGL::GL_DRAW_FRAMEBUFFER_BINDING, (OpenGL::GLint *)&defaultFramebuffer); Py_RETURN_NONE; } PyObject * UseDefaultFramebuffer(PyObject * self) { OpenGL::glBindFramebuffer(OpenGL::GL_FRAMEBUFFER, defaultFramebuffer); Py_RETURN_NONE; } PyObject * ReadPixels(PyObject * self, PyObject * args, PyObject * kwargs) { int x; int y; int width; int height; int components = 3; static const char * kwlist[] = {"x", "y", "width", "height", "components", 0}; if (!PyArg_ParseTupleAndKeywords(args, kwargs, "iiii|i:ReadPixels", (char **)kwlist, &x, &y, &width, &height, &components)) { return 0; } CHECK_AND_REPORT_ARG_VALUE_ERROR(width < 1, "width", width); CHECK_AND_REPORT_ARG_VALUE_ERROR(height < 1, "height", height); CHECK_AND_REPORT_ARG_VALUE_ERROR(components < 1 || components > 4, "components", components); int size = height * ((width * components + 3) & ~3); const int formats[] = {0, OpenGL::GL_RED, OpenGL::GL_RG, OpenGL::GL_RGB, OpenGL::GL_RGBA}; int format = formats[components]; PyObject * bytes = PyBytes_FromStringAndSize(0, size); char * data = PyBytes_AS_STRING(bytes); OpenGL::glReadPixels(x, y, width, height, format, OpenGL::GL_UNSIGNED_BYTE, data); data[size] = 0; return bytes; } PyObject * ReadDepthPixels(PyObject * self, PyObject * args, PyObject * kwargs) { int x; int y; int width; int height; static const char * kwlist[] = {"x", "y", "width", "height", 0}; if (!PyArg_ParseTupleAndKeywords(args, kwargs, "iiii:ReadDepthPixels", (char **)kwlist, &x, &y, &width, &height)) { return 0; } CHECK_AND_REPORT_ARG_VALUE_ERROR(width < 1, "width", width); CHECK_AND_REPORT_ARG_VALUE_ERROR(height < 1, "height", height); int size = height * height * 4; float * pixels = ModernGL::ReadDepthPixels(x, y, width, height); PyObject * data = PyBytes_FromStringAndSize((const char *)pixels, size); free(pixels); PyObject * bytes = PyBytes_FromStringAndSize(0, size); char * data = PyBytes_AS_STRING(bytes); OpenGL::glReadPixels(x, y, width, height, OpenGL::GL_DEPTH_COMPONENT, OpenGL::GL_FLOAT, data); data[size] = 0; return bytes; } PyObject * ReadPixel(PyObject * self, PyObject * args, PyObject * kwargs) { int x; int y; static const char * kwlist[] = {"x", "y", 0}; if (!PyArg_ParseTupleAndKeywords(args, kwargs, "ii:ReadPixel", (char **)kwlist, &x, &y)) { return 0; } unsigned rgba = 0; OpenGL::glReadPixels(x, y, 1, 1, OpenGL::GL_RGBA, OpenGL::GL_UNSIGNED_BYTE, &rgba); return PyLong_FromUnsignedLong(rgba); } PyObject * ReadDepthPixel(PyObject * self, PyObject * args, PyObject * kwargs) { int x; int y; static const char * kwlist[] = {"x", "y", 0}; if (!PyArg_ParseTupleAndKeywords(args, kwargs, "ii:ReadDepthPixel", (char **)kwlist, &x, &y)) { return 0; } float depth = 0.0; OpenGL::glReadPixels(x, y, 1, 1, OpenGL::GL_DEPTH_COMPONENT, OpenGL::GL_FLOAT, &depth); return PyFloat_FromDouble(depth); }
read imp #8 + checks
read imp #8 + checks
C++
mit
cprogrammer1994/ModernGL,cprogrammer1994/ModernGL,cprogrammer1994/ModernGL
829fa6db38c43d468ce08359defa2762292c5efa
src/Setup/UpdateRunner.cpp
src/Setup/UpdateRunner.cpp
#include "stdafx.h" #include "unzip.h" #include "Resource.h" #include "UpdateRunner.h" #include <vector> void CUpdateRunner::DisplayErrorMessage(CString& errorMessage, wchar_t* logFile) { CTaskDialog dlg; TASKDIALOG_BUTTON buttons[] = { { 1, L"Open Setup Log", }, { 2, L"Close", }, }; // TODO: Something about contacting support? if (logFile == NULL) { dlg.SetButtons(&buttons[1], 1, 1); } else { dlg.SetButtons(buttons, 2, 1); } dlg.SetMainInstructionText(L"Installation has failed"); dlg.SetContentText(errorMessage); dlg.SetMainIcon(TD_ERROR_ICON); int nButton; if (FAILED(dlg.DoModal(::GetActiveWindow(), &nButton))) { return; } if (nButton == 1 && logFile != NULL) { ShellExecute(NULL, NULL, logFile, NULL, NULL, SW_SHOW); } } HRESULT CUpdateRunner::AreWeUACElevated() { HANDLE hProcess = GetCurrentProcess(); HANDLE hToken = 0; HRESULT hr; if (!OpenProcessToken(hProcess, TOKEN_QUERY, &hToken)) { hr = HRESULT_FROM_WIN32(GetLastError()); goto out; } TOKEN_ELEVATION_TYPE elevType; DWORD dontcare; if (!GetTokenInformation(hToken, TokenElevationType, &elevType, sizeof(TOKEN_ELEVATION_TYPE), &dontcare)) { hr = HRESULT_FROM_WIN32(GetLastError()); goto out; } hr = (elevType == TokenElevationTypeFull ? S_OK : S_FALSE); out: if (hToken) { CloseHandle(hToken); } return hr; } HRESULT FindDesktopFolderView(REFIID riid, void **ppv) { HRESULT hr; CComPtr<IShellWindows> spShellWindows; spShellWindows.CoCreateInstance(CLSID_ShellWindows); CComVariant vtLoc(CSIDL_DESKTOP); CComVariant vtEmpty; long lhwnd; CComPtr<IDispatch> spdisp; hr = spShellWindows->FindWindowSW( &vtLoc, &vtEmpty, SWC_DESKTOP, &lhwnd, SWFO_NEEDDISPATCH, &spdisp); if (FAILED(hr)) return hr; CComPtr<IShellBrowser> spBrowser; hr = CComQIPtr<IServiceProvider>(spdisp)->QueryService(SID_STopLevelBrowser, IID_PPV_ARGS(&spBrowser)); if (FAILED(hr)) return hr; CComPtr<IShellView> spView; hr = spBrowser->QueryActiveShellView(&spView); if (FAILED(hr)) return hr; hr = spView->QueryInterface(riid, ppv); if (FAILED(hr)) return hr; return S_OK; } HRESULT GetDesktopAutomationObject(REFIID riid, void **ppv) { HRESULT hr; CComPtr<IShellView> spsv; hr = FindDesktopFolderView(IID_PPV_ARGS(&spsv)); if (FAILED(hr)) return hr; CComPtr<IDispatch> spdispView; hr = spsv->GetItemObject(SVGIO_BACKGROUND, IID_PPV_ARGS(&spdispView)); if (FAILED(hr)) return hr; return spdispView->QueryInterface(riid, ppv); } HRESULT CUpdateRunner::ShellExecuteFromExplorer(LPWSTR pszFile, LPWSTR pszParameters) { HRESULT hr; CComPtr<IShellFolderViewDual> spFolderView; hr = GetDesktopAutomationObject(IID_PPV_ARGS(&spFolderView)); if (FAILED(hr)) return hr; CComPtr<IDispatch> spdispShell; hr = spFolderView->get_Application(&spdispShell); if (FAILED(hr)) return hr; return CComQIPtr<IShellDispatch2>(spdispShell)->ShellExecute( CComBSTR(pszFile), CComVariant(pszParameters ? pszParameters : L""), CComVariant(L""), CComVariant(L""), CComVariant(SW_SHOWDEFAULT)); } bool CUpdateRunner::DirectoryExists(wchar_t* szPath) { DWORD dwAttrib = GetFileAttributes(szPath); return (dwAttrib != INVALID_FILE_ATTRIBUTES && (dwAttrib & FILE_ATTRIBUTE_DIRECTORY)); } bool CUpdateRunner::DirectoryIsWritable(wchar_t * szPath) { wchar_t szTempFileName[MAX_PATH]; UINT uRetVal = GetTempFileNameW(szPath, L"Squirrel", 0, szTempFileName); if (uRetVal == 0) { return false; } DeleteFile(szTempFileName); return true; } int CUpdateRunner::ExtractUpdaterAndRun(wchar_t* lpCommandLine, bool useFallbackDir) { PROCESS_INFORMATION pi = { 0 }; STARTUPINFO si = { 0 }; CResource zipResource; wchar_t targetDir[MAX_PATH] = { 0 }; wchar_t logFile[MAX_PATH]; std::vector<CString> to_delete; wchar_t* envSquirrelTemp = _wgetenv(L"SQUIRREL_TEMP"); if (envSquirrelTemp && DirectoryExists(envSquirrelTemp) && DirectoryIsWritable(envSquirrelTemp) && !PathIsUNCW(envSquirrelTemp)) { _swprintf_c(targetDir, _countof(targetDir), L"%s", envSquirrelTemp); goto gotADir; } if (!useFallbackDir) { SHGetFolderPath(NULL, CSIDL_LOCAL_APPDATA, NULL, SHGFP_TYPE_CURRENT, targetDir); goto gotADir; } wchar_t username[512]; wchar_t uid[128]; wchar_t appDataDir[MAX_PATH]; ULONG unameSize = _countof(username); SHGetFolderPath(NULL, CSIDL_COMMON_APPDATA, NULL, SHGFP_TYPE_CURRENT, appDataDir); GetUserName(username, &unameSize); _swprintf_c(targetDir, _countof(targetDir), L"%s\\%s", appDataDir, username); if (!CreateDirectory(targetDir, NULL) && GetLastError() != ERROR_ALREADY_EXISTS) { wchar_t err[4096]; _swprintf_c(err, _countof(err), L"Unable to write to %s - IT policies may be restricting access to this folder", targetDir); DisplayErrorMessage(CString(err), NULL); return -1; } gotADir: wcscat_s(targetDir, _countof(targetDir), L"\\SquirrelTemp"); if (!CreateDirectory(targetDir, NULL) && GetLastError() != ERROR_ALREADY_EXISTS) { wchar_t err[4096]; _swprintf_c(err, _countof(err), L"Unable to write to %s - IT policies may be restricting access to this folder", targetDir); if (useFallbackDir) { DisplayErrorMessage(CString(err), NULL); } goto failedExtract; } swprintf_s(logFile, L"%s\\SquirrelSetup.log", targetDir); if (!zipResource.Load(L"DATA", IDR_UPDATE_ZIP)) { goto failedExtract; } DWORD dwSize = zipResource.GetSize(); if (dwSize < 0x100) { goto failedExtract; } BYTE* pData = (BYTE*)zipResource.Lock(); HZIP zipFile = OpenZip(pData, dwSize, NULL); SetUnzipBaseDir(zipFile, targetDir); // NB: This library is kind of a disaster ZRESULT zr; int index = 0; do { ZIPENTRY zentry; wchar_t targetFile[MAX_PATH]; zr = GetZipItem(zipFile, index, &zentry); if (zr != ZR_OK && zr != ZR_MORE) { break; } // NB: UnzipItem won't overwrite data, we need to do it ourselves swprintf_s(targetFile, L"%s\\%s", targetDir, zentry.name); DeleteFile(targetFile); if (UnzipItem(zipFile, index, zentry.name) != ZR_OK) break; to_delete.push_back(CString(targetFile)); index++; } while (zr == ZR_MORE || zr == ZR_OK); CloseZip(zipFile); zipResource.Release(); // nfi if the zip extract actually worked, check for Update.exe wchar_t updateExePath[MAX_PATH]; swprintf_s(updateExePath, L"%s\\%s", targetDir, L"Update.exe"); if (GetFileAttributes(updateExePath) == INVALID_FILE_ATTRIBUTES) { goto failedExtract; } // Run Update.exe si.cb = sizeof(STARTUPINFO); si.wShowWindow = SW_SHOW; si.dwFlags = STARTF_USESHOWWINDOW; if (!lpCommandLine || wcsnlen_s(lpCommandLine, MAX_PATH) < 1) { lpCommandLine = L""; } wchar_t cmd[MAX_PATH]; swprintf_s(cmd, L"\"%s\" --install . %s", updateExePath, lpCommandLine); if (!CreateProcess(NULL, cmd, NULL, NULL, false, 0, NULL, targetDir, &si, &pi)) { goto failedExtract; } WaitForSingleObject(pi.hProcess, INFINITE); DWORD dwExitCode; if (!GetExitCodeProcess(pi.hProcess, &dwExitCode)) { dwExitCode = (DWORD)-1; } if (dwExitCode != 0) { DisplayErrorMessage(CString( L"There was an error while installing the application. " L"Check the setup log for more information and contact the author."), logFile); } for (unsigned int i = 0; i < to_delete.size(); i++) { DeleteFile(to_delete[i]); } CloseHandle(pi.hProcess); CloseHandle(pi.hThread); return (int) dwExitCode; failedExtract: if (!useFallbackDir) { // Take another pass at it, using C:\ProgramData instead return ExtractUpdaterAndRun(lpCommandLine, true); } DisplayErrorMessage(CString(L"Failed to extract installer"), NULL); return (int) dwExitCode; }
#include "stdafx.h" #include "unzip.h" #include "Resource.h" #include "UpdateRunner.h" #include <vector> void CUpdateRunner::DisplayErrorMessage(CString& errorMessage, wchar_t* logFile) { CTaskDialog dlg; TASKDIALOG_BUTTON buttons[] = { { 1, L"Open Setup Log", }, { 2, L"Close", }, }; // TODO: Something about contacting support? if (logFile == NULL) { dlg.SetButtons(&buttons[1], 1, 1); } else { dlg.SetButtons(buttons, 2, 1); } dlg.SetMainInstructionText(L"Installation has failed"); dlg.SetContentText(errorMessage); dlg.SetMainIcon(TD_ERROR_ICON); int nButton; if (FAILED(dlg.DoModal(::GetActiveWindow(), &nButton))) { return; } if (nButton == 1 && logFile != NULL) { ShellExecute(NULL, NULL, logFile, NULL, NULL, SW_SHOW); } } HRESULT CUpdateRunner::AreWeUACElevated() { HANDLE hProcess = GetCurrentProcess(); HANDLE hToken = 0; HRESULT hr; if (!OpenProcessToken(hProcess, TOKEN_QUERY, &hToken)) { hr = HRESULT_FROM_WIN32(GetLastError()); goto out; } TOKEN_ELEVATION_TYPE elevType; DWORD dontcare; if (!GetTokenInformation(hToken, TokenElevationType, &elevType, sizeof(TOKEN_ELEVATION_TYPE), &dontcare)) { hr = HRESULT_FROM_WIN32(GetLastError()); goto out; } hr = (elevType == TokenElevationTypeFull ? S_OK : S_FALSE); out: if (hToken) { CloseHandle(hToken); } return hr; } HRESULT FindDesktopFolderView(REFIID riid, void **ppv) { HRESULT hr; CComPtr<IShellWindows> spShellWindows; spShellWindows.CoCreateInstance(CLSID_ShellWindows); CComVariant vtLoc(CSIDL_DESKTOP); CComVariant vtEmpty; long lhwnd; CComPtr<IDispatch> spdisp; hr = spShellWindows->FindWindowSW( &vtLoc, &vtEmpty, SWC_DESKTOP, &lhwnd, SWFO_NEEDDISPATCH, &spdisp); if (FAILED(hr)) return hr; CComPtr<IShellBrowser> spBrowser; hr = CComQIPtr<IServiceProvider>(spdisp)->QueryService(SID_STopLevelBrowser, IID_PPV_ARGS(&spBrowser)); if (FAILED(hr)) return hr; CComPtr<IShellView> spView; hr = spBrowser->QueryActiveShellView(&spView); if (FAILED(hr)) return hr; hr = spView->QueryInterface(riid, ppv); if (FAILED(hr)) return hr; return S_OK; } HRESULT GetDesktopAutomationObject(REFIID riid, void **ppv) { HRESULT hr; CComPtr<IShellView> spsv; hr = FindDesktopFolderView(IID_PPV_ARGS(&spsv)); if (FAILED(hr)) return hr; CComPtr<IDispatch> spdispView; hr = spsv->GetItemObject(SVGIO_BACKGROUND, IID_PPV_ARGS(&spdispView)); if (FAILED(hr)) return hr; return spdispView->QueryInterface(riid, ppv); } HRESULT CUpdateRunner::ShellExecuteFromExplorer(LPWSTR pszFile, LPWSTR pszParameters) { HRESULT hr; CComPtr<IShellFolderViewDual> spFolderView; hr = GetDesktopAutomationObject(IID_PPV_ARGS(&spFolderView)); if (FAILED(hr)) return hr; CComPtr<IDispatch> spdispShell; hr = spFolderView->get_Application(&spdispShell); if (FAILED(hr)) return hr; return CComQIPtr<IShellDispatch2>(spdispShell)->ShellExecute( CComBSTR(pszFile), CComVariant(pszParameters ? pszParameters : L""), CComVariant(L""), CComVariant(L""), CComVariant(SW_SHOWDEFAULT)); } bool CUpdateRunner::DirectoryExists(wchar_t* szPath) { DWORD dwAttrib = GetFileAttributes(szPath); return (dwAttrib != INVALID_FILE_ATTRIBUTES && (dwAttrib & FILE_ATTRIBUTE_DIRECTORY)); } bool CUpdateRunner::DirectoryIsWritable(wchar_t * szPath) { wchar_t szTempFileName[MAX_PATH]; UINT uRetVal = GetTempFileNameW(szPath, L"Squirrel", 0, szTempFileName); if (uRetVal == 0) { return false; } DeleteFile(szTempFileName); return true; } int CUpdateRunner::ExtractUpdaterAndRun(wchar_t* lpCommandLine, bool useFallbackDir) { PROCESS_INFORMATION pi = { 0 }; STARTUPINFO si = { 0 }; CResource zipResource; wchar_t targetDir[MAX_PATH] = { 0 }; wchar_t logFile[MAX_PATH]; std::vector<CString> to_delete; wchar_t* envSquirrelTemp = _wgetenv(L"SQUIRREL_TEMP"); if (envSquirrelTemp && DirectoryExists(envSquirrelTemp) && DirectoryIsWritable(envSquirrelTemp) && !PathIsUNCW(envSquirrelTemp)) { _swprintf_c(targetDir, _countof(targetDir), L"%s", envSquirrelTemp); goto gotADir; } if (!useFallbackDir) { SHGetFolderPath(NULL, CSIDL_LOCAL_APPDATA, NULL, SHGFP_TYPE_CURRENT, targetDir); goto gotADir; } wchar_t username[512]; wchar_t appDataDir[MAX_PATH]; ULONG unameSize = _countof(username); SHGetFolderPath(NULL, CSIDL_COMMON_APPDATA, NULL, SHGFP_TYPE_CURRENT, appDataDir); GetUserName(username, &unameSize); _swprintf_c(targetDir, _countof(targetDir), L"%s\\%s", appDataDir, username); if (!CreateDirectory(targetDir, NULL) && GetLastError() != ERROR_ALREADY_EXISTS) { wchar_t err[4096]; _swprintf_c(err, _countof(err), L"Unable to write to %s - IT policies may be restricting access to this folder", targetDir); DisplayErrorMessage(CString(err), NULL); return -1; } gotADir: wcscat_s(targetDir, _countof(targetDir), L"\\SquirrelTemp"); if (!CreateDirectory(targetDir, NULL) && GetLastError() != ERROR_ALREADY_EXISTS) { wchar_t err[4096]; _swprintf_c(err, _countof(err), L"Unable to write to %s - IT policies may be restricting access to this folder", targetDir); if (useFallbackDir) { DisplayErrorMessage(CString(err), NULL); } goto failedExtract; } swprintf_s(logFile, L"%s\\SquirrelSetup.log", targetDir); if (!zipResource.Load(L"DATA", IDR_UPDATE_ZIP)) { goto failedExtract; } DWORD dwSize = zipResource.GetSize(); if (dwSize < 0x100) { goto failedExtract; } BYTE* pData = (BYTE*)zipResource.Lock(); HZIP zipFile = OpenZip(pData, dwSize, NULL); SetUnzipBaseDir(zipFile, targetDir); // NB: This library is kind of a disaster ZRESULT zr; int index = 0; do { ZIPENTRY zentry; wchar_t targetFile[MAX_PATH]; zr = GetZipItem(zipFile, index, &zentry); if (zr != ZR_OK && zr != ZR_MORE) { break; } // NB: UnzipItem won't overwrite data, we need to do it ourselves swprintf_s(targetFile, L"%s\\%s", targetDir, zentry.name); DeleteFile(targetFile); if (UnzipItem(zipFile, index, zentry.name) != ZR_OK) break; to_delete.push_back(CString(targetFile)); index++; } while (zr == ZR_MORE || zr == ZR_OK); CloseZip(zipFile); zipResource.Release(); // nfi if the zip extract actually worked, check for Update.exe wchar_t updateExePath[MAX_PATH]; swprintf_s(updateExePath, L"%s\\%s", targetDir, L"Update.exe"); if (GetFileAttributes(updateExePath) == INVALID_FILE_ATTRIBUTES) { goto failedExtract; } // Run Update.exe si.cb = sizeof(STARTUPINFO); si.wShowWindow = SW_SHOW; si.dwFlags = STARTF_USESHOWWINDOW; if (!lpCommandLine || wcsnlen_s(lpCommandLine, MAX_PATH) < 1) { lpCommandLine = L""; } wchar_t cmd[MAX_PATH]; swprintf_s(cmd, L"\"%s\" --install . %s", updateExePath, lpCommandLine); if (!CreateProcess(NULL, cmd, NULL, NULL, false, 0, NULL, targetDir, &si, &pi)) { goto failedExtract; } WaitForSingleObject(pi.hProcess, INFINITE); DWORD dwExitCode; if (!GetExitCodeProcess(pi.hProcess, &dwExitCode)) { dwExitCode = (DWORD)-1; } if (dwExitCode != 0) { DisplayErrorMessage(CString( L"There was an error while installing the application. " L"Check the setup log for more information and contact the author."), logFile); } for (unsigned int i = 0; i < to_delete.size(); i++) { DeleteFile(to_delete[i]); } CloseHandle(pi.hProcess); CloseHandle(pi.hThread); return (int) dwExitCode; failedExtract: if (!useFallbackDir) { // Take another pass at it, using C:\ProgramData instead return ExtractUpdaterAndRun(lpCommandLine, true); } DisplayErrorMessage(CString(L"Failed to extract installer"), NULL); return (int) dwExitCode; }
Fix C4101: Remove unreferenced local variable
Fix C4101: Remove unreferenced local variable
C++
mit
punker76/Squirrel.Windows,kenbailey/Squirrel.Windows,JonMartinTx/AS400Report,JonMartinTx/AS400Report,punker76/Squirrel.Windows,kenbailey/Squirrel.Windows,Squirrel/Squirrel.Windows,BloomBooks/Squirrel.Windows,JonMartinTx/AS400Report,kenbailey/Squirrel.Windows,punker76/Squirrel.Windows,Squirrel/Squirrel.Windows,BloomBooks/Squirrel.Windows,BloomBooks/Squirrel.Windows,Squirrel/Squirrel.Windows
6ffef287348b75262139a4aa7ac221146e30132f
src/hex/noise.cpp
src/hex/noise.cpp
#include "common.h" #include "hex/noise.h" static float interpolate(float x1, float x2, float w) { return (1.0f - w) * x1 + w * x2; } PerlinNoise::PerlinNoise(int width, int height): grid_width(width), grid_height(height) { gradients = new float_vector *[height + 1]; for (int i = 0; i <= height; i++) { gradients[i] = new float_vector[width + 1]; } for (int i = 0; i <= height; i++) { for (int j = 0; j <= width; j++) { float dx, dy; float a; do { dx = ((rand() % 2000) - 1000) / 1000.0f; dy = ((rand() % 2000) - 1000) / 1000.0f; a = dx*dx + dy*dy; } while (a > 1.0f || a < 0.9f); float a2 = sqrtf(a); gradients[i][j][0] = dx / a2; gradients[i][j][1] = dy / a2; } } } PerlinNoise::~PerlinNoise() { for (int i = 0; i <= grid_height; i++) { delete[] gradients[i]; } delete[] gradients; } float PerlinNoise::dot_product(int ix, int iy, float x, float y) { float dx = x - ix; float dy = y - iy; return dx * gradients[iy][ix][0] + dy * gradients[iy][ix][1]; } float PerlinNoise::value(float x, float y) { x *= grid_width; y *= grid_height; int x0 = (int) x; int x1 = x0 + 1; int y0 = (int) y; int y1 = y0 + 1; if (x0 < 0 || x1 > grid_width || y0 < 0 || y1 > grid_height) return 0.0f; float sx = x - (float) x0; float sy = y - (float) y0; // Interpolate between grid point gradients float n0, n1, ix0, ix1, value; n0 = dot_product(x0, y0, x, y); n1 = dot_product(x1, y0, x, y); ix0 = interpolate(n0, n1, sx); n0 = dot_product(x0, y1, x, y); n1 = dot_product(x1, y1, x, y); ix1 = interpolate(n0, n1, sx); value = interpolate(ix0, ix1, sy); return value; }
#include "common.h" #include "hex/noise.h" static float interpolate(float x1, float x2, float w) { return (1.0f - w) * x1 + w * x2; } static float fade(float t) { // Approximate sigmoid function: 6t^5 - 15t^4 + 10t^3 return t * t * t * (t * (t * 6 - 15) + 10); } PerlinNoise::PerlinNoise(int width, int height): grid_width(width), grid_height(height) { gradients = new float_vector *[height + 1]; for (int i = 0; i <= height; i++) { gradients[i] = new float_vector[width + 1]; } for (int i = 0; i <= height; i++) { for (int j = 0; j <= width; j++) { float dx, dy; float a; do { dx = ((rand() % 2000) - 1000) / 1000.0f; dy = ((rand() % 2000) - 1000) / 1000.0f; a = dx*dx + dy*dy; } while (a > 1.0f || a < 0.9f); float a2 = sqrtf(a); gradients[i][j][0] = dx / a2; gradients[i][j][1] = dy / a2; } } } PerlinNoise::~PerlinNoise() { for (int i = 0; i <= grid_height; i++) { delete[] gradients[i]; } delete[] gradients; } float PerlinNoise::dot_product(int ix, int iy, float x, float y) { float dx = x - ix; float dy = y - iy; return dx * gradients[iy][ix][0] + dy * gradients[iy][ix][1]; } float PerlinNoise::value(float x, float y) { x *= grid_width; y *= grid_height; int x0 = (int) x; int x1 = x0 + 1; int y0 = (int) y; int y1 = y0 + 1; if (x0 < 0 || x1 > grid_width || y0 < 0 || y1 > grid_height) return 0.0f; float sx = x - (float) x0; float sy = y - (float) y0; sx = fade(sx); sy = fade(sy); // Interpolate between grid point gradients float n0, n1, ix0, ix1, value; n0 = dot_product(x0, y0, x, y); n1 = dot_product(x1, y0, x, y); ix0 = interpolate(n0, n1, sx); n0 = dot_product(x0, y1, x, y); n1 = dot_product(x1, y1, x, y); ix1 = interpolate(n0, n1, sx); value = interpolate(ix0, ix1, sy); return value; }
Add fading to noise.
Add fading to noise.
C++
mit
ejrh/hex,ejrh/hex
9a72cd32901f88380e5e6f4818357f8926b23173
Source/core/dom/SelectorQuery.cpp
Source/core/dom/SelectorQuery.cpp
/* * Copyright (C) 2011 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS 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 APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "core/dom/SelectorQuery.h" #include "core/css/CSSParser.h" #include "core/css/CSSSelectorList.h" #include "core/css/SelectorChecker.h" #include "core/css/SelectorCheckerFastPath.h" #include "core/css/SiblingTraversalStrategies.h" #include "core/dom/Document.h" #include "core/dom/StaticNodeList.h" namespace WebCore { void SelectorDataList::initialize(const CSSSelectorList& selectorList) { ASSERT(m_selectors.isEmpty()); unsigned selectorCount = 0; for (const CSSSelector* selector = selectorList.first(); selector; selector = CSSSelectorList::next(selector)) selectorCount++; m_selectors.reserveInitialCapacity(selectorCount); for (const CSSSelector* selector = selectorList.first(); selector; selector = CSSSelectorList::next(selector)) m_selectors.uncheckedAppend(SelectorData(selector, SelectorCheckerFastPath::canUse(selector))); } inline bool SelectorDataList::selectorMatches(const SelectorData& selectorData, Element* element, const Node* rootNode) const { if (selectorData.isFastCheckable && !element->isSVGElement()) { SelectorCheckerFastPath selectorCheckerFastPath(selectorData.selector, element); if (!selectorCheckerFastPath.matchesRightmostSelector(SelectorChecker::VisitedMatchDisabled)) return false; return selectorCheckerFastPath.matches(); } SelectorChecker selectorChecker(element->document(), SelectorChecker::QueryingRules); SelectorChecker::SelectorCheckingContext selectorCheckingContext(selectorData.selector, element, SelectorChecker::VisitedMatchDisabled); selectorCheckingContext.behaviorAtBoundary = SelectorChecker::StaysWithinTreeScope; selectorCheckingContext.scope = !rootNode->isDocumentNode() && rootNode->isContainerNode() ? toContainerNode(rootNode) : 0; PseudoId ignoreDynamicPseudo = NOPSEUDO; return selectorChecker.match(selectorCheckingContext, ignoreDynamicPseudo, DOMSiblingTraversalStrategy()) == SelectorChecker::SelectorMatches; } bool SelectorDataList::matches(Element* targetElement) const { ASSERT(targetElement); unsigned selectorCount = m_selectors.size(); for (unsigned i = 0; i < selectorCount; ++i) { if (selectorMatches(m_selectors[i], targetElement, targetElement)) return true; } return false; } PassRefPtr<NodeList> SelectorDataList::queryAll(Node* rootNode) const { Vector<RefPtr<Node> > result; execute<false>(rootNode, result); return StaticNodeList::adopt(result); } PassRefPtr<Element> SelectorDataList::queryFirst(Node* rootNode) const { Vector<RefPtr<Node> > result; execute<true>(rootNode, result); if (result.isEmpty()) return 0; ASSERT(result.size() == 1); ASSERT(result.first()->isElementNode()); return toElement(result.first().get()); } static inline bool isTreeScopeRoot(Node* node) { ASSERT(node); return node->isDocumentNode() || node->isShadowRoot(); } // If the first pair value is true, the returned Node is the single Element that may match the selector query. // // If the first value is false, the returned Node is the rootNode parameter or a descendant of rootNode representing // the subtree for which we can limit the querySelector traversal. // // The returned Node may be 0, regardless of the returned bool value, if this method finds that the selectors won't // match any element. std::pair<bool, Node*> SelectorDataList::findTraverseRoot(Node* rootNode) const { // We need to return the matches in document order. To use id lookup while there is possiblity of multiple matches // we would need to sort the results. For now, just traverse the document in that case. if (m_selectors.size() != 1) return std::make_pair(false, rootNode); if (!rootNode->inDocument()) return std::make_pair(false, rootNode); if (rootNode->document()->inQuirksMode()) return std::make_pair(false, rootNode); bool matchSingleNode = true; bool startFromParent = false; for (const CSSSelector* selector = m_selectors[0].selector; selector; selector = selector->tagHistory()) { if (selector->m_match == CSSSelector::Id && !rootNode->document()->containsMultipleElementsWithId(selector->value())) { Element* element = rootNode->treeScope()->getElementById(selector->value()); if (element && (isTreeScopeRoot(rootNode) || element->isDescendantOf(rootNode))) rootNode = element; else if (!element || matchSingleNode) rootNode = 0; if (matchSingleNode) return std::make_pair(true, rootNode); if (startFromParent && rootNode) rootNode = rootNode->parentNode(); return std::make_pair(false, rootNode); } if (selector->relation() == CSSSelector::SubSelector) continue; matchSingleNode = false; if (selector->relation() == CSSSelector::DirectAdjacent || selector->relation() == CSSSelector::IndirectAdjacent) startFromParent = true; else startFromParent = false; } return std::make_pair(false, rootNode); } template <bool firstMatchOnly> void SelectorDataList::execute(Node* rootNode, Vector<RefPtr<Node> >& matchedElements) const { std::pair<bool, Node*> traverseRoot = findTraverseRoot(rootNode); if (!traverseRoot.second) return; Node* traverseRootNode = traverseRoot.second; if (traverseRoot.first) { ASSERT(m_selectors.size() == 1); ASSERT(traverseRootNode->isElementNode()); Element* element = toElement(traverseRootNode); if (selectorMatches(m_selectors[0], element, rootNode)) matchedElements.append(element); return; } unsigned selectorCount = m_selectors.size(); Node* n = traverseRootNode->firstChild(); while (n) { if (n->isElementNode()) { Element* element = toElement(n); for (unsigned i = 0; i < selectorCount; ++i) { if (selectorMatches(m_selectors[i], element, rootNode)) { matchedElements.append(element); if (firstMatchOnly) return; break; } } if (element->firstChild()) { n = element->firstChild(); continue; } } while (!n->nextSibling()) { n = n->parentNode(); if (n == traverseRootNode) return; } n = n->nextSibling(); } } SelectorQuery::SelectorQuery(const CSSSelectorList& selectorList) : m_selectorList(selectorList) { m_selectors.initialize(m_selectorList); } bool SelectorQuery::matches(Element* element) const { return m_selectors.matches(element); } PassRefPtr<NodeList> SelectorQuery::queryAll(Node* rootNode) const { return m_selectors.queryAll(rootNode); } PassRefPtr<Element> SelectorQuery::queryFirst(Node* rootNode) const { return m_selectors.queryFirst(rootNode); } SelectorQuery* SelectorQueryCache::add(const AtomicString& selectors, Document* document, ExceptionCode& ec) { HashMap<AtomicString, OwnPtr<SelectorQuery> >::iterator it = m_entries.find(selectors); if (it != m_entries.end()) return it->value.get(); CSSParser parser(document); CSSSelectorList selectorList; parser.parseSelector(selectors, selectorList); if (!selectorList.first() || selectorList.hasInvalidSelector()) { ec = SYNTAX_ERR; return 0; } // throw a NAMESPACE_ERR if the selector includes any namespace prefixes. if (selectorList.selectorsNeedNamespaceResolution()) { ec = NAMESPACE_ERR; return 0; } const int maximumSelectorQueryCacheSize = 256; if (m_entries.size() == maximumSelectorQueryCacheSize) m_entries.remove(m_entries.begin()); OwnPtr<SelectorQuery> selectorQuery = adoptPtr(new SelectorQuery(selectorList)); SelectorQuery* rawSelectorQuery = selectorQuery.get(); m_entries.add(selectors, selectorQuery.release()); return rawSelectorQuery; } void SelectorQueryCache::invalidate() { m_entries.clear(); } }
/* * Copyright (C) 2011 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS 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 APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "core/dom/SelectorQuery.h" #include "core/css/CSSParser.h" #include "core/css/CSSSelectorList.h" #include "core/css/SelectorChecker.h" #include "core/css/SelectorCheckerFastPath.h" #include "core/css/SiblingTraversalStrategies.h" #include "core/dom/Document.h" #include "core/dom/NodeTraversal.h" #include "core/dom/StaticNodeList.h" namespace WebCore { void SelectorDataList::initialize(const CSSSelectorList& selectorList) { ASSERT(m_selectors.isEmpty()); unsigned selectorCount = 0; for (const CSSSelector* selector = selectorList.first(); selector; selector = CSSSelectorList::next(selector)) selectorCount++; m_selectors.reserveInitialCapacity(selectorCount); for (const CSSSelector* selector = selectorList.first(); selector; selector = CSSSelectorList::next(selector)) m_selectors.uncheckedAppend(SelectorData(selector, SelectorCheckerFastPath::canUse(selector))); } inline bool SelectorDataList::selectorMatches(const SelectorData& selectorData, Element* element, const Node* rootNode) const { if (selectorData.isFastCheckable && !element->isSVGElement()) { SelectorCheckerFastPath selectorCheckerFastPath(selectorData.selector, element); if (!selectorCheckerFastPath.matchesRightmostSelector(SelectorChecker::VisitedMatchDisabled)) return false; return selectorCheckerFastPath.matches(); } SelectorChecker selectorChecker(element->document(), SelectorChecker::QueryingRules); SelectorChecker::SelectorCheckingContext selectorCheckingContext(selectorData.selector, element, SelectorChecker::VisitedMatchDisabled); selectorCheckingContext.behaviorAtBoundary = SelectorChecker::StaysWithinTreeScope; selectorCheckingContext.scope = !rootNode->isDocumentNode() && rootNode->isContainerNode() ? toContainerNode(rootNode) : 0; PseudoId ignoreDynamicPseudo = NOPSEUDO; return selectorChecker.match(selectorCheckingContext, ignoreDynamicPseudo, DOMSiblingTraversalStrategy()) == SelectorChecker::SelectorMatches; } bool SelectorDataList::matches(Element* targetElement) const { ASSERT(targetElement); unsigned selectorCount = m_selectors.size(); for (unsigned i = 0; i < selectorCount; ++i) { if (selectorMatches(m_selectors[i], targetElement, targetElement)) return true; } return false; } PassRefPtr<NodeList> SelectorDataList::queryAll(Node* rootNode) const { Vector<RefPtr<Node> > result; execute<false>(rootNode, result); return StaticNodeList::adopt(result); } PassRefPtr<Element> SelectorDataList::queryFirst(Node* rootNode) const { Vector<RefPtr<Node> > result; execute<true>(rootNode, result); if (result.isEmpty()) return 0; ASSERT(result.size() == 1); ASSERT(result.first()->isElementNode()); return toElement(result.first().get()); } static inline bool isTreeScopeRoot(Node* node) { ASSERT(node); return node->isDocumentNode() || node->isShadowRoot(); } // If the first pair value is true, the returned Node is the single Element that may match the selector query. // // If the first value is false, the returned Node is the rootNode parameter or a descendant of rootNode representing // the subtree for which we can limit the querySelector traversal. // // The returned Node may be 0, regardless of the returned bool value, if this method finds that the selectors won't // match any element. std::pair<bool, Node*> SelectorDataList::findTraverseRoot(Node* rootNode) const { // We need to return the matches in document order. To use id lookup while there is possiblity of multiple matches // we would need to sort the results. For now, just traverse the document in that case. if (m_selectors.size() != 1) return std::make_pair(false, rootNode); if (!rootNode->inDocument()) return std::make_pair(false, rootNode); if (rootNode->document()->inQuirksMode()) return std::make_pair(false, rootNode); bool matchSingleNode = true; bool startFromParent = false; for (const CSSSelector* selector = m_selectors[0].selector; selector; selector = selector->tagHistory()) { if (selector->m_match == CSSSelector::Id && !rootNode->document()->containsMultipleElementsWithId(selector->value())) { Element* element = rootNode->treeScope()->getElementById(selector->value()); if (element && (isTreeScopeRoot(rootNode) || element->isDescendantOf(rootNode))) rootNode = element; else if (!element || matchSingleNode) rootNode = 0; if (matchSingleNode) return std::make_pair(true, rootNode); if (startFromParent && rootNode) rootNode = rootNode->parentNode(); return std::make_pair(false, rootNode); } if (selector->relation() == CSSSelector::SubSelector) continue; matchSingleNode = false; if (selector->relation() == CSSSelector::DirectAdjacent || selector->relation() == CSSSelector::IndirectAdjacent) startFromParent = true; else startFromParent = false; } return std::make_pair(false, rootNode); } template <bool firstMatchOnly> void SelectorDataList::execute(Node* rootNode, Vector<RefPtr<Node> >& matchedElements) const { std::pair<bool, Node*> traverseRoot = findTraverseRoot(rootNode); if (!traverseRoot.second) return; Node* traverseRootNode = traverseRoot.second; if (traverseRoot.first) { ASSERT(m_selectors.size() == 1); ASSERT(traverseRootNode->isElementNode()); Element* element = toElement(traverseRootNode); if (selectorMatches(m_selectors[0], element, rootNode)) matchedElements.append(element); return; } for (Element* element = ElementTraversal::firstWithin(rootNode); element; element = ElementTraversal::next(element, rootNode)) { for (unsigned i = 0; i < m_selectors.size(); ++i) { if (selectorMatches(m_selectors[i], element, rootNode)) { matchedElements.append(element); if (firstMatchOnly) return; break; } } } } SelectorQuery::SelectorQuery(const CSSSelectorList& selectorList) : m_selectorList(selectorList) { m_selectors.initialize(m_selectorList); } bool SelectorQuery::matches(Element* element) const { return m_selectors.matches(element); } PassRefPtr<NodeList> SelectorQuery::queryAll(Node* rootNode) const { return m_selectors.queryAll(rootNode); } PassRefPtr<Element> SelectorQuery::queryFirst(Node* rootNode) const { return m_selectors.queryFirst(rootNode); } SelectorQuery* SelectorQueryCache::add(const AtomicString& selectors, Document* document, ExceptionCode& ec) { HashMap<AtomicString, OwnPtr<SelectorQuery> >::iterator it = m_entries.find(selectors); if (it != m_entries.end()) return it->value.get(); CSSParser parser(document); CSSSelectorList selectorList; parser.parseSelector(selectors, selectorList); if (!selectorList.first() || selectorList.hasInvalidSelector()) { ec = SYNTAX_ERR; return 0; } // throw a NAMESPACE_ERR if the selector includes any namespace prefixes. if (selectorList.selectorsNeedNamespaceResolution()) { ec = NAMESPACE_ERR; return 0; } const int maximumSelectorQueryCacheSize = 256; if (m_entries.size() == maximumSelectorQueryCacheSize) m_entries.remove(m_entries.begin()); OwnPtr<SelectorQuery> selectorQuery = adoptPtr(new SelectorQuery(selectorList)); SelectorQuery* rawSelectorQuery = selectorQuery.get(); m_entries.add(selectors, selectorQuery.release()); return rawSelectorQuery; } void SelectorQueryCache::invalidate() { m_entries.clear(); } }
Use ElementTraversal in SelectorDataList::execute
Use ElementTraversal in SelectorDataList::execute Using ElementTraversal::firstWithin and ElementTraversal::next simplifies the code. This is a backport from WebKit 150099. Patch by Ryosuke Niwa. [email protected] Review URL: https://chromiumcodereview.appspot.com/15857007 git-svn-id: bf5cd6ccde378db821296732a091cfbcf5285fbd@151620 bbb929c8-8fbe-4397-9dbb-9b2b20218538
C++
bsd-3-clause
primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs
59ca4484ab03c6fed9d485f002c14ffa4a895f76
src/Win32/Config-win32.cpp
src/Win32/Config-win32.cpp
#include "../USB.h" #include "resource.h" #include "Config-win32.h" #include "../deviceproxy.h" #include "../usb-pad/padproxy.h" #include "../usb-mic/audiodeviceproxy.h" #include "../configuration.h" extern HINSTANCE hInst; extern bool configChanged; void SysMessageA(const char *fmt, ...) { va_list list; char tmp[512]; va_start(list, fmt); vsprintf_s(tmp, 512, fmt, list); va_end(list); MessageBoxA(0, tmp, "Qemu USB Msg", 0); } void SysMessageW(const wchar_t *fmt, ...) { va_list list; wchar_t tmp[512]; va_start(list, fmt); vswprintf_s(tmp, 512, fmt, list); va_end(list); MessageBoxW(0, tmp, L"Qemu USB Msg", 0); } void SelChangedAPI(HWND hW, int port) { int sel = SendDlgItemMessage(hW, port ? IDC_COMBO_API1 : IDC_COMBO_API2, CB_GETCURSEL, 0, 0); int devtype = SendDlgItemMessage(hW, port ? IDC_COMBO1 : IDC_COMBO2, CB_GETCURSEL, 0, 0); if (devtype == 0) return; devtype--; auto& rd = RegisterDevice::instance(); auto devName = rd.Name(devtype); auto apis = rd.Device(devtype)->ListAPIs(); auto it = apis.begin(); std::advance(it, sel); changedAPIs[std::make_pair(port, devName)] = *it; } void PopulateAPIs(HWND hW, int port) { OSDebugOut(TEXT("Populate api %d\n"), port); SendDlgItemMessage(hW, port ? IDC_COMBO_API1 : IDC_COMBO_API2, CB_RESETCONTENT, 0, 0); int devtype = SendDlgItemMessage(hW, port ? IDC_COMBO1 : IDC_COMBO2, CB_GETCURSEL, 0, 0); if (devtype == 0) return; devtype--; auto& rd = RegisterDevice::instance(); auto dev = rd.Device(devtype); auto devName = rd.Name(devtype); auto apis = dev->ListAPIs(); std::string selApi = GetSelectedAPI(std::make_pair(port, devName)); CONFIGVARIANT var(N_DEVICE_API, CONFIG_TYPE_CHAR); if(LoadSetting(port, rd.Name(devtype), var)) OSDebugOut(L"Current API: %S\n", var.strValue.c_str()); else { if (apis.begin() != apis.end()) { selApi = *apis.begin(); changedAPIs[std::make_pair(port, devName)] = selApi; } } int i = 0, sel = 0; for (auto& api : apis) { auto name = dev->LongAPIName(api); SendDlgItemMessageW(hW, port ? IDC_COMBO_API1 : IDC_COMBO_API2, CB_ADDSTRING, 0, (LPARAM)name); if (api == var.strValue) sel = i; i++; } SendDlgItemMessage(hW, port ? IDC_COMBO_API1 : IDC_COMBO_API2, CB_SETCURSEL, sel, 0); } BOOL CALLBACK ConfigureDlgProc(HWND hW, UINT uMsg, WPARAM wParam, LPARAM lParam) { int port; switch(uMsg) { case WM_INITDIALOG: SendDlgItemMessageA(hW, IDC_BUILD_DATE, WM_SETTEXT, 0, (LPARAM)__DATE__ " " __TIME__); LoadConfig(); CheckDlgButton(hW, IDC_LOGGING, conf.Log); CheckDlgButton(hW, IDC_DFP_PASS, conf.DFPPass); //Selected emulated devices. SendDlgItemMessageA(hW, IDC_COMBO1, CB_ADDSTRING, 0, (LPARAM)"None"); SendDlgItemMessageA(hW, IDC_COMBO2, CB_ADDSTRING, 0, (LPARAM)"None"); { auto& rd = RegisterDevice::instance(); int i = 0, p1 = 0, p2 = 0; for (auto& name : rd.Names()) { i++; //jump over "None" auto dev = rd.Device(name); SendDlgItemMessageW(hW, IDC_COMBO1, CB_ADDSTRING, 0, (LPARAM)dev->TypeName()); SendDlgItemMessageW(hW, IDC_COMBO2, CB_ADDSTRING, 0, (LPARAM)dev->TypeName()); //Port 1 aka device/player 1 if (conf.Port[1] == name) p1 = i; //Port 0 aka device/player 2 if (conf.Port[0] == name) p2 = i; } SendDlgItemMessage(hW, IDC_COMBO1, CB_SETCURSEL, p1, 0); SendDlgItemMessage(hW, IDC_COMBO2, CB_SETCURSEL, p2, 0); PopulateAPIs(hW, 0); PopulateAPIs(hW, 1); } SendDlgItemMessageA(hW, IDC_COMBO_WHEEL_TYPE1, CB_ADDSTRING, 0, (LPARAM)"Driving Force / Generic Logitech Wheel"); SendDlgItemMessageA(hW, IDC_COMBO_WHEEL_TYPE1, CB_ADDSTRING, 0, (LPARAM)"Driving Force Pro"); SendDlgItemMessageA(hW, IDC_COMBO_WHEEL_TYPE1, CB_ADDSTRING, 0, (LPARAM)"GT Force"); SendDlgItemMessage(hW, IDC_COMBO_WHEEL_TYPE1, CB_SETCURSEL, conf.WheelType[0], 0); SendDlgItemMessageA(hW, IDC_COMBO_WHEEL_TYPE2, CB_ADDSTRING, 0, (LPARAM)"Driving Force / Generic Logitech Wheel"); SendDlgItemMessageA(hW, IDC_COMBO_WHEEL_TYPE2, CB_ADDSTRING, 0, (LPARAM)"Driving Force Pro"); SendDlgItemMessageA(hW, IDC_COMBO_WHEEL_TYPE2, CB_ADDSTRING, 0, (LPARAM)"GT Force"); SendDlgItemMessage(hW, IDC_COMBO_WHEEL_TYPE2, CB_SETCURSEL, conf.WheelType[1], 0); return TRUE; break; case WM_COMMAND: switch (HIWORD(wParam)) { case CBN_SELCHANGE: switch (LOWORD(wParam)) { case IDC_COMBO_API1: case IDC_COMBO_API2: port = (LOWORD(wParam) == IDC_COMBO_API1) ? 1 : 0; SelChangedAPI(hW, port); break; case IDC_COMBO1: case IDC_COMBO2: port = (LOWORD(wParam) == IDC_COMBO1) ? 1 : 0; PopulateAPIs(hW, port); break; } break; case BN_CLICKED: switch(LOWORD(wParam)) { case IDC_CONFIGURE1: case IDC_CONFIGURE2: { LRESULT devtype, apitype; port = (LOWORD(wParam) == IDC_CONFIGURE1) ? 1 : 0; devtype = SendDlgItemMessage(hW, port ? IDC_COMBO1 : IDC_COMBO2, CB_GETCURSEL, 0, 0); apitype = SendDlgItemMessage(hW, port ? IDC_COMBO_API1 : IDC_COMBO_API2, CB_GETCURSEL, 0, 0); if (devtype > 0) { devtype--; auto device = RegisterDevice::instance().Device(devtype); if (device) { auto list = device->ListAPIs(); auto it = list.begin(); std::advance(it, apitype); if (it == list.end()) break; std::string api = *it; Win32Handles handles(hInst, hW); if (device->Configure(port, api, &handles) == RESULT_FAILED) SysMessage(TEXT("Some settings may have not been saved!")); } } } break; case IDCANCEL: EndDialog(hW, TRUE); return TRUE; case IDOK: conf.Log = IsDlgButtonChecked(hW, IDC_LOGGING); conf.DFPPass = IsDlgButtonChecked(hW, IDC_DFP_PASS); { auto& regInst = RegisterDevice::instance(); int i; //device type i = SendDlgItemMessage(hW, IDC_COMBO1, CB_GETCURSEL, 0, 0); conf.Port[1] = regInst.Name(i - 1); i = SendDlgItemMessage(hW, IDC_COMBO2, CB_GETCURSEL, 0, 0); conf.Port[0] = regInst.Name(i - 1); } //wheel type conf.WheelType[0] = SendDlgItemMessage(hW, IDC_COMBO_WHEEL_TYPE1, CB_GETCURSEL, 0, 0); conf.WheelType[1] = SendDlgItemMessage(hW, IDC_COMBO_WHEEL_TYPE2, CB_GETCURSEL, 0, 0); SaveConfig(); CreateDevices(); EndDialog(hW, RESULT_OK); configChanged = true; return TRUE; } } } return FALSE; } EXPORT_C_(BOOL) AboutDlgProc(HWND hW, UINT uMsg, WPARAM wParam, LPARAM lParam) { switch(uMsg) { case WM_INITDIALOG: return TRUE; case WM_COMMAND: switch(LOWORD(wParam)) { case IDOK: EndDialog(hW, FALSE); return TRUE; } } return FALSE; } EXPORT_C_(void) USBconfigure() { DialogBox(hInst, MAKEINTRESOURCE(IDD_CONFIG), GetActiveWindow(), (DLGPROC)ConfigureDlgProc); } EXPORT_C_(void) USBabout() { DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUT), GetActiveWindow(), (DLGPROC)AboutDlgProc); } BOOL APIENTRY DllMain(HANDLE hModule, DWORD dwReason, LPVOID lpReserved) { hInst = (HINSTANCE)hModule; return TRUE; }
#include "../USB.h" #include "resource.h" #include "Config-win32.h" #include "../deviceproxy.h" #include "../usb-pad/padproxy.h" #include "../usb-mic/audiodeviceproxy.h" #include "../configuration.h" extern HINSTANCE hInst; extern bool configChanged; void SysMessageA(const char *fmt, ...) { va_list list; char tmp[512]; va_start(list, fmt); vsprintf_s(tmp, 512, fmt, list); va_end(list); MessageBoxA(0, tmp, "Qemu USB Msg", 0); } void SysMessageW(const wchar_t *fmt, ...) { va_list list; wchar_t tmp[512]; va_start(list, fmt); vswprintf_s(tmp, 512, fmt, list); va_end(list); MessageBoxW(0, tmp, L"Qemu USB Msg", 0); } void SelChangedAPI(HWND hW, int port) { int sel = SendDlgItemMessage(hW, port ? IDC_COMBO_API1 : IDC_COMBO_API2, CB_GETCURSEL, 0, 0); int devtype = SendDlgItemMessage(hW, port ? IDC_COMBO1 : IDC_COMBO2, CB_GETCURSEL, 0, 0); if (devtype == 0) return; devtype--; auto& rd = RegisterDevice::instance(); auto devName = rd.Name(devtype); auto apis = rd.Device(devtype)->ListAPIs(); auto it = apis.begin(); std::advance(it, sel); changedAPIs[std::make_pair(port, devName)] = *it; } void PopulateAPIs(HWND hW, int port) { OSDebugOut(TEXT("Populate api %d\n"), port); SendDlgItemMessage(hW, port ? IDC_COMBO_API1 : IDC_COMBO_API2, CB_RESETCONTENT, 0, 0); int devtype = SendDlgItemMessage(hW, port ? IDC_COMBO1 : IDC_COMBO2, CB_GETCURSEL, 0, 0); if (devtype == 0) return; devtype--; auto& rd = RegisterDevice::instance(); auto dev = rd.Device(devtype); auto devName = rd.Name(devtype); auto apis = dev->ListAPIs(); std::string selApi = GetSelectedAPI(std::make_pair(port, devName)); CONFIGVARIANT var(N_DEVICE_API, CONFIG_TYPE_CHAR); if(LoadSetting(port, rd.Name(devtype), var)) OSDebugOut(L"Current API: %S\n", var.strValue.c_str()); else { if (apis.begin() != apis.end()) { selApi = *apis.begin(); changedAPIs[std::make_pair(port, devName)] = selApi; } } int i = 0, sel = 0; for (auto& api : apis) { auto name = dev->LongAPIName(api); SendDlgItemMessageW(hW, port ? IDC_COMBO_API1 : IDC_COMBO_API2, CB_ADDSTRING, 0, (LPARAM)name); if (api == var.strValue) sel = i; i++; } SendDlgItemMessage(hW, port ? IDC_COMBO_API1 : IDC_COMBO_API2, CB_SETCURSEL, sel, 0); } BOOL CALLBACK ConfigureDlgProc(HWND hW, UINT uMsg, WPARAM wParam, LPARAM lParam) { int port; switch(uMsg) { case WM_INITDIALOG: SendDlgItemMessageA(hW, IDC_BUILD_DATE, WM_SETTEXT, 0, (LPARAM)__DATE__ " " __TIME__); LoadConfig(); CheckDlgButton(hW, IDC_LOGGING, conf.Log); CheckDlgButton(hW, IDC_DFP_PASS, conf.DFPPass); //Selected emulated devices. SendDlgItemMessageA(hW, IDC_COMBO1, CB_ADDSTRING, 0, (LPARAM)"None"); SendDlgItemMessageA(hW, IDC_COMBO2, CB_ADDSTRING, 0, (LPARAM)"None"); { auto& rd = RegisterDevice::instance(); int i = 0, p1 = 0, p2 = 0; for (auto& name : rd.Names()) { i++; //jump over "None" auto dev = rd.Device(name); SendDlgItemMessageW(hW, IDC_COMBO1, CB_ADDSTRING, 0, (LPARAM)dev->Name()); SendDlgItemMessageW(hW, IDC_COMBO2, CB_ADDSTRING, 0, (LPARAM)dev->Name()); //Port 1 aka device/player 1 if (conf.Port[1] == name) p1 = i; //Port 0 aka device/player 2 if (conf.Port[0] == name) p2 = i; } SendDlgItemMessage(hW, IDC_COMBO1, CB_SETCURSEL, p1, 0); SendDlgItemMessage(hW, IDC_COMBO2, CB_SETCURSEL, p2, 0); PopulateAPIs(hW, 0); PopulateAPIs(hW, 1); } SendDlgItemMessageA(hW, IDC_COMBO_WHEEL_TYPE1, CB_ADDSTRING, 0, (LPARAM)"Driving Force / Generic Logitech Wheel"); SendDlgItemMessageA(hW, IDC_COMBO_WHEEL_TYPE1, CB_ADDSTRING, 0, (LPARAM)"Driving Force Pro"); SendDlgItemMessageA(hW, IDC_COMBO_WHEEL_TYPE1, CB_ADDSTRING, 0, (LPARAM)"GT Force"); SendDlgItemMessage(hW, IDC_COMBO_WHEEL_TYPE1, CB_SETCURSEL, conf.WheelType[0], 0); SendDlgItemMessageA(hW, IDC_COMBO_WHEEL_TYPE2, CB_ADDSTRING, 0, (LPARAM)"Driving Force / Generic Logitech Wheel"); SendDlgItemMessageA(hW, IDC_COMBO_WHEEL_TYPE2, CB_ADDSTRING, 0, (LPARAM)"Driving Force Pro"); SendDlgItemMessageA(hW, IDC_COMBO_WHEEL_TYPE2, CB_ADDSTRING, 0, (LPARAM)"GT Force"); SendDlgItemMessage(hW, IDC_COMBO_WHEEL_TYPE2, CB_SETCURSEL, conf.WheelType[1], 0); return TRUE; break; case WM_COMMAND: switch (HIWORD(wParam)) { case CBN_SELCHANGE: switch (LOWORD(wParam)) { case IDC_COMBO_API1: case IDC_COMBO_API2: port = (LOWORD(wParam) == IDC_COMBO_API1) ? 1 : 0; SelChangedAPI(hW, port); break; case IDC_COMBO1: case IDC_COMBO2: port = (LOWORD(wParam) == IDC_COMBO1) ? 1 : 0; PopulateAPIs(hW, port); break; } break; case BN_CLICKED: switch(LOWORD(wParam)) { case IDC_CONFIGURE1: case IDC_CONFIGURE2: { LRESULT devtype, apitype; port = (LOWORD(wParam) == IDC_CONFIGURE1) ? 1 : 0; devtype = SendDlgItemMessage(hW, port ? IDC_COMBO1 : IDC_COMBO2, CB_GETCURSEL, 0, 0); apitype = SendDlgItemMessage(hW, port ? IDC_COMBO_API1 : IDC_COMBO_API2, CB_GETCURSEL, 0, 0); if (devtype > 0) { devtype--; auto device = RegisterDevice::instance().Device(devtype); if (device) { auto list = device->ListAPIs(); auto it = list.begin(); std::advance(it, apitype); if (it == list.end()) break; std::string api = *it; Win32Handles handles(hInst, hW); if (device->Configure(port, api, &handles) == RESULT_FAILED) SysMessage(TEXT("Some settings may have not been saved!")); } } } break; case IDCANCEL: EndDialog(hW, TRUE); return TRUE; case IDOK: conf.Log = IsDlgButtonChecked(hW, IDC_LOGGING); conf.DFPPass = IsDlgButtonChecked(hW, IDC_DFP_PASS); { auto& regInst = RegisterDevice::instance(); int i; //device type i = SendDlgItemMessage(hW, IDC_COMBO1, CB_GETCURSEL, 0, 0); conf.Port[1] = regInst.Name(i - 1); i = SendDlgItemMessage(hW, IDC_COMBO2, CB_GETCURSEL, 0, 0); conf.Port[0] = regInst.Name(i - 1); } //wheel type conf.WheelType[0] = SendDlgItemMessage(hW, IDC_COMBO_WHEEL_TYPE1, CB_GETCURSEL, 0, 0); conf.WheelType[1] = SendDlgItemMessage(hW, IDC_COMBO_WHEEL_TYPE2, CB_GETCURSEL, 0, 0); SaveConfig(); CreateDevices(); EndDialog(hW, RESULT_OK); configChanged = true; return TRUE; } } } return FALSE; } EXPORT_C_(BOOL) AboutDlgProc(HWND hW, UINT uMsg, WPARAM wParam, LPARAM lParam) { switch(uMsg) { case WM_INITDIALOG: return TRUE; case WM_COMMAND: switch(LOWORD(wParam)) { case IDOK: EndDialog(hW, FALSE); return TRUE; } } return FALSE; } EXPORT_C_(void) USBconfigure() { DialogBox(hInst, MAKEINTRESOURCE(IDD_CONFIG), GetActiveWindow(), (DLGPROC)ConfigureDlgProc); } EXPORT_C_(void) USBabout() { DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUT), GetActiveWindow(), (DLGPROC)AboutDlgProc); } BOOL APIENTRY DllMain(HANDLE hModule, DWORD dwReason, LPVOID lpReserved) { hInst = (HINSTANCE)hModule; return TRUE; }
fix device list names
win32: fix device list names
C++
unlicense
jackun/USBqemu-wheel,jackun/USBqemu-wheel,jackun/USBqemu-wheel
0208df968ae68d0f9b6a9903b31411b331e9fe78
src/pow.cpp
src/pow.cpp
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2017 The BitCore Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "pow.h" #include "arith_uint256.h" #include "chain.h" #include "primitives/block.h" #include "uint256.h" #include "util.h" #include <math.h> unsigned int static DUAL_KGW3(const CBlockIndex* pindexLast, const Consensus::Params& params, const CBlockHeader *pblock) { // current difficulty formula, ERC3 - DUAL_KGW3, written by Bitcoin Talk Limx Dev // BitSend and Eropecoin Developer const CBlockIndex *BlockLastSolved = pindexLast; const CBlockIndex *BlockReading = pindexLast; bool kgwdebug=false; uint64_t PastBlocksMass = 0; int64_t PastRateActualSeconds = 0; int64_t PastRateTargetSeconds = 0; double PastRateAdjustmentRatio = double(1); arith_uint256 PastDifficultyAverage; arith_uint256 PastDifficultyAveragePrev; double EventHorizonDeviation; double EventHorizonDeviationFast; double EventHorizonDeviationSlow; //DUAL_KGW3 SETUP static const uint64_t Blocktime = 9.6 * 60; // 9.6 = 10 min (Value = Value*0.96) Limx DEV 23.04.2017 static const unsigned int timeDaySeconds = 60 * 60 * 24; uint64_t pastSecondsMin = timeDaySeconds * 0.025; uint64_t pastSecondsMax = timeDaySeconds * 7; uint64_t PastBlocksMin = pastSecondsMin / Blocktime; uint64_t PastBlocksMax = pastSecondsMax / Blocktime; const arith_uint256 bnPowLimit = UintToArith256(params.powLimit); if (BlockLastSolved == NULL || BlockLastSolved->nHeight == 0 || (uint64_t)BlockLastSolved->nHeight < PastBlocksMin) { return bnPowLimit.GetCompact(); } for (unsigned int i = 1; BlockReading && BlockReading->nHeight > 0; i++) { if (PastBlocksMax > 0 && i > PastBlocksMax) { break; } PastBlocksMass++; PastDifficultyAverage.SetCompact(BlockReading->nBits); if (i > 1) { if(PastDifficultyAverage >= PastDifficultyAveragePrev) PastDifficultyAverage = ((PastDifficultyAverage - PastDifficultyAveragePrev) / i) + PastDifficultyAveragePrev; else PastDifficultyAverage = PastDifficultyAveragePrev - ((PastDifficultyAveragePrev - PastDifficultyAverage) / i); } PastDifficultyAveragePrev = PastDifficultyAverage; PastRateActualSeconds = BlockLastSolved->GetBlockTime() - BlockReading->GetBlockTime(); PastRateTargetSeconds = Blocktime * PastBlocksMass; PastRateAdjustmentRatio = double(1); if (PastRateActualSeconds < 0) { PastRateActualSeconds = 0; } if (PastRateActualSeconds != 0 && PastRateTargetSeconds != 0) { PastRateAdjustmentRatio = double(PastRateTargetSeconds) / double(PastRateActualSeconds); } EventHorizonDeviation = 1 + (0.7084 * pow((double(PastBlocksMass)/double(72)), -1.228)); //28.2 and 144 possible EventHorizonDeviationFast = EventHorizonDeviation; EventHorizonDeviationSlow = 1 / EventHorizonDeviation; if (PastBlocksMass >= PastBlocksMin) { if ((PastRateAdjustmentRatio <= EventHorizonDeviationSlow) || (PastRateAdjustmentRatio >= EventHorizonDeviationFast)) { assert(BlockReading); break; } } if (BlockReading->pprev == NULL) { assert(BlockReading); break; } BlockReading = BlockReading->pprev; } //KGW Original arith_uint256 kgw_dual1(PastDifficultyAverage); arith_uint256 kgw_dual2; kgw_dual2.SetCompact(pindexLast->nBits); if (PastRateActualSeconds != 0 && PastRateTargetSeconds != 0) { kgw_dual1 *= PastRateActualSeconds; kgw_dual1 /= PastRateTargetSeconds; } int64_t nActualTime1 = pindexLast->GetBlockTime() - pindexLast->pprev->GetBlockTime(); int64_t nActualTimespanshort = nActualTime1; // Retarget BTC Original ...not exactly // Small Fix if(nActualTime1 < 0) nActualTime1 = Blocktime; if (nActualTime1 < Blocktime / 3) nActualTime1 = Blocktime / 3; if (nActualTime1 > Blocktime * 3) nActualTime1 = Blocktime * 3; kgw_dual2 *= nActualTime1; kgw_dual2 /= Blocktime; //Fusion from Retarget and Classic KGW3 (BitSend=) arith_uint256 bnNew; bnNew = ((kgw_dual2 + kgw_dual1)/2); // DUAL KGW3 increased rapidly the Diff if Blocktime to last block under Blocktime/6 sec. if(kgwdebug)LogPrintf("nActualTimespanshort = %d \n", nActualTimespanshort ); if( nActualTimespanshort < Blocktime/6 ) { if(kgwdebug)LogPrintf("Vordiff:%08x %s bnNew first \n", bnNew.GetCompact(), bnNew.ToString().c_str()); const int nLongShortNew1 = 85; const int nLongShortNew2 = 100; bnNew = bnNew * nLongShortNew1; bnNew = bnNew / nLongShortNew2; if(kgwdebug)LogPrintf("Erhöhte Diff:\n %08x %s bnNew second \n", bnNew.GetCompact(), bnNew.ToString().c_str() ); } //BitBreak BitSend // Reduce difficulty if current block generation time has already exceeded maximum time limit. // Diffbreak 12 Hours const int nLongTimeLimit = 12 * 60 * 60; if(kgwdebug) { LogPrintf("Prediff %08x %s\n", bnNew.GetCompact(), bnNew.ToString().c_str()); LogPrintf("Vordiff %d \n", nLongTimeLimit); LogPrintf(" %d Block", BlockReading->nHeight ); } if ((pblock-> nTime - pindexLast->GetBlockTime()) > nLongTimeLimit) //block.nTime { bnNew = bnPowLimit; if(kgwdebug)LogPrintf("<BSD> Maximum block time hit - cute diff %08x %s\n", bnNew.GetCompact(), bnNew.ToString().c_str()); } if (bnNew > bnPowLimit) { bnNew = bnPowLimit; } return bnNew.GetCompact(); } unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlockHeader *pblock, const Consensus::Params& params) { int fork1 = 10000; int fork2 = 21000; if (pindexLast->nHeight+1 <= fork1) { return DUAL_KGW3(pindexLast, params, pblock); } unsigned int nProofOfWorkLimit = UintToArith256(params.powLimit).GetCompact(); if (pindexLast->nHeight+1 <= fork2) { // Genesis block if (pindexLast == NULL) return nProofOfWorkLimit; // Only change once per difficulty adjustment interval if ((pindexLast->nHeight+1) % params.DifficultyAdjustmentInterval() != 0) { if (params.fPowAllowMinDifficultyBlocks) { // Special difficulty rule for testnet: // If the new block's timestamp is more than 2* 10 minutes // then allow mining of a min-difficulty block. if (pblock->GetBlockTime() > pindexLast->GetBlockTime() + params.nPowTargetSpacing*2) return nProofOfWorkLimit; else { // Return the last non-special-min-difficulty-rules-block const CBlockIndex* pindex = pindexLast; while (pindex->pprev && pindex->nHeight % params.DifficultyAdjustmentInterval() != 0 && pindex->nBits == nProofOfWorkLimit) pindex = pindex->pprev; return pindex->nBits; } } return pindexLast->nBits; } // Go back by what we want to be 14 days worth of blocks // Litecoin: This fixes an issue where a 51% attack can change difficulty at will. // Go back the full period unless it's the first retarget after genesis. Code courtesy of Art Forz int blockstogoback = params.DifficultyAdjustmentInterval()-1; if ((pindexLast->nHeight+1) != params.DifficultyAdjustmentInterval()) blockstogoback = params.DifficultyAdjustmentInterval(); // Go back by what we want to be 14 days worth of blocks const CBlockIndex* pindexFirst = pindexLast; for (int i = 0; pindexFirst && i < blockstogoback; i++) pindexFirst = pindexFirst->pprev; assert(pindexFirst); return CalculateNextWorkRequired(pindexLast, pindexFirst->GetBlockTime(), params); } else { // Genesis block if (pindexLast == NULL) return nProofOfWorkLimit; // Only change once per difficulty adjustment interval if ((pindexLast->nHeight+1) % params.DifficultyAdjustmentIntervalV2() != 0) { if (params.fPowAllowMinDifficultyBlocks) { // Special difficulty rule for testnet: // If the new block's timestamp is more than 2* 10 minutes // then allow mining of a min-difficulty block. if (pblock->GetBlockTime() > pindexLast->GetBlockTime() + params.nPowTargetSpacing*2) return nProofOfWorkLimit; else { // Return the last non-special-min-difficulty-rules-block const CBlockIndex* pindex = pindexLast; while (pindex->pprev && pindex->nHeight % params.DifficultyAdjustmentIntervalV2() != 0 && pindex->nBits == nProofOfWorkLimit) pindex = pindex->pprev; return pindex->nBits; } } //LogPrintf("difficulty adjustment interval %d \n",(pindexLast->nHeight+1) % params.DifficultyAdjustmentIntervalV2()); return pindexLast->nBits; } // Go back by what we want to be 14 days worth of blocks // Litecoin: This fixes an issue where a 51% attack can change difficulty at will. // Go back the full period unless it's the first retarget after genesis. Code courtesy of Art Forz int blockstogoback2 = params.DifficultyAdjustmentIntervalV2()-1; if ((pindexLast->nHeight+1) != params.DifficultyAdjustmentIntervalV2()) blockstogoback2 = params.DifficultyAdjustmentIntervalV2(); // Go back by what we want to be 14 days worth of blocks const CBlockIndex* pindexFirst = pindexLast; for (int i = 0; pindexFirst && i < blockstogoback2; i++) pindexFirst = pindexFirst->pprev; assert(pindexFirst); return CalculateNextWorkRequired(pindexLast, pindexFirst->GetBlockTime(), params); } } //For Tet POW unsigned int CalculateNextWorkRequired(const CBlockIndex* pindexLast, int64_t nFirstBlockTime, const Consensus::Params& params) { int fork2 = 21000; if (params.fPowNoRetargeting) return pindexLast->nBits; // Limit adjustment step int64_t nActualTimespan = pindexLast->GetBlockTime() - nFirstBlockTime; const arith_uint256 bnPowLimit = UintToArith256(params.powLimit); arith_uint256 bnNew; if (pindexLast->nHeight+1 <= fork2) { //Retarget with 400 % if (nActualTimespan < params.nPowTargetTimespan/4) nActualTimespan = params.nPowTargetTimespan/4; if (nActualTimespan > params.nPowTargetTimespan*4) nActualTimespan = params.nPowTargetTimespan*4; bnNew.SetCompact(pindexLast->nBits); bnNew *= nActualTimespan; bnNew /= params.nPowTargetTimespan; if (bnNew > bnPowLimit) bnNew = bnPowLimit; return bnNew.GetCompact(); } else { //Low Retarget with 15 % if (nActualTimespan < params.nPowTargetTimespanV2/(115/100)) nActualTimespan = params.nPowTargetTimespanV2/(115/100); if (nActualTimespan > params.nPowTargetTimespanV2*(115/100)) nActualTimespan = params.nPowTargetTimespanV2*(115/100); bnNew.SetCompact(pindexLast->nBits); bnNew *= nActualTimespan; bnNew /= params.nPowTargetTimespanV2; if (bnNew > bnPowLimit) bnNew = bnPowLimit; return bnNew.GetCompact(); } // Retarget } bool CheckProofOfWork(uint256 hash, unsigned int nBits, const Consensus::Params& params) { bool fNegative; bool fOverflow; arith_uint256 bnTarget; bnTarget.SetCompact(nBits, &fNegative, &fOverflow); // Check range if (fNegative || bnTarget == 0 || fOverflow || bnTarget > UintToArith256(params.powLimit)) return false; // Check proof of work matches claimed amount if (UintToArith256(hash) > bnTarget) return false; return true; }
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2017 The BitCore Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "pow.h" #include "arith_uint256.h" #include "chain.h" #include "primitives/block.h" #include "uint256.h" #include "util.h" #include <math.h> unsigned int static DUAL_KGW3(const CBlockIndex* pindexLast, const Consensus::Params& params, const CBlockHeader *pblock) { // current difficulty formula, ERC3 - DUAL_KGW3, written by Bitcoin Talk Limx Dev // BitSend and Europecoin Developer const CBlockIndex *BlockLastSolved = pindexLast; const CBlockIndex *BlockReading = pindexLast; bool kgwdebug=false; uint64_t PastBlocksMass = 0; int64_t PastRateActualSeconds = 0; int64_t PastRateTargetSeconds = 0; double PastRateAdjustmentRatio = double(1); arith_uint256 PastDifficultyAverage; arith_uint256 PastDifficultyAveragePrev; double EventHorizonDeviation; double EventHorizonDeviationFast; double EventHorizonDeviationSlow; //DUAL_KGW3 SETUP static const uint64_t Blocktime = 9.6 * 60; // 9.6 = 10 min (Value = Value*0.96) Limx DEV 23.04.2017 static const unsigned int timeDaySeconds = 60 * 60 * 24; uint64_t pastSecondsMin = timeDaySeconds * 0.025; uint64_t pastSecondsMax = timeDaySeconds * 7; uint64_t PastBlocksMin = pastSecondsMin / Blocktime; uint64_t PastBlocksMax = pastSecondsMax / Blocktime; const arith_uint256 bnPowLimit = UintToArith256(params.powLimit); if (BlockLastSolved == NULL || BlockLastSolved->nHeight == 0 || (uint64_t)BlockLastSolved->nHeight < PastBlocksMin) { return bnPowLimit.GetCompact(); } for (unsigned int i = 1; BlockReading && BlockReading->nHeight > 0; i++) { if (PastBlocksMax > 0 && i > PastBlocksMax) { break; } PastBlocksMass++; PastDifficultyAverage.SetCompact(BlockReading->nBits); if (i > 1) { if(PastDifficultyAverage >= PastDifficultyAveragePrev) PastDifficultyAverage = ((PastDifficultyAverage - PastDifficultyAveragePrev) / i) + PastDifficultyAveragePrev; else PastDifficultyAverage = PastDifficultyAveragePrev - ((PastDifficultyAveragePrev - PastDifficultyAverage) / i); } PastDifficultyAveragePrev = PastDifficultyAverage; PastRateActualSeconds = BlockLastSolved->GetBlockTime() - BlockReading->GetBlockTime(); PastRateTargetSeconds = Blocktime * PastBlocksMass; PastRateAdjustmentRatio = double(1); if (PastRateActualSeconds < 0) { PastRateActualSeconds = 0; } if (PastRateActualSeconds != 0 && PastRateTargetSeconds != 0) { PastRateAdjustmentRatio = double(PastRateTargetSeconds) / double(PastRateActualSeconds); } EventHorizonDeviation = 1 + (0.7084 * pow((double(PastBlocksMass)/double(72)), -1.228)); //28.2 and 144 possible EventHorizonDeviationFast = EventHorizonDeviation; EventHorizonDeviationSlow = 1 / EventHorizonDeviation; if (PastBlocksMass >= PastBlocksMin) { if ((PastRateAdjustmentRatio <= EventHorizonDeviationSlow) || (PastRateAdjustmentRatio >= EventHorizonDeviationFast)) { assert(BlockReading); break; } } if (BlockReading->pprev == NULL) { assert(BlockReading); break; } BlockReading = BlockReading->pprev; } //KGW Original arith_uint256 kgw_dual1(PastDifficultyAverage); arith_uint256 kgw_dual2; kgw_dual2.SetCompact(pindexLast->nBits); if (PastRateActualSeconds != 0 && PastRateTargetSeconds != 0) { kgw_dual1 *= PastRateActualSeconds; kgw_dual1 /= PastRateTargetSeconds; } int64_t nActualTime1 = pindexLast->GetBlockTime() - pindexLast->pprev->GetBlockTime(); int64_t nActualTimespanshort = nActualTime1; // Retarget BTC Original ...not exactly // Small Fix if(nActualTime1 < 0) nActualTime1 = Blocktime; if (nActualTime1 < Blocktime / 3) nActualTime1 = Blocktime / 3; if (nActualTime1 > Blocktime * 3) nActualTime1 = Blocktime * 3; kgw_dual2 *= nActualTime1; kgw_dual2 /= Blocktime; //Fusion from Retarget and Classic KGW3 (BitSend=) arith_uint256 bnNew; bnNew = ((kgw_dual2 + kgw_dual1)/2); // DUAL KGW3 increased rapidly the Diff if Blocktime to last block under Blocktime/6 sec. if(kgwdebug)LogPrintf("nActualTimespanshort = %d \n", nActualTimespanshort ); if( nActualTimespanshort < Blocktime/6 ) { if(kgwdebug)LogPrintf("Vordiff:%08x %s bnNew first \n", bnNew.GetCompact(), bnNew.ToString().c_str()); const int nLongShortNew1 = 85; const int nLongShortNew2 = 100; bnNew = bnNew * nLongShortNew1; bnNew = bnNew / nLongShortNew2; if(kgwdebug)LogPrintf("Erhöhte Diff:\n %08x %s bnNew second \n", bnNew.GetCompact(), bnNew.ToString().c_str() ); } //BitBreak BitSend // Reduce difficulty if current block generation time has already exceeded maximum time limit. // Diffbreak 12 Hours const int nLongTimeLimit = 12 * 60 * 60; if(kgwdebug) { LogPrintf("Prediff %08x %s\n", bnNew.GetCompact(), bnNew.ToString().c_str()); LogPrintf("Vordiff %d \n", nLongTimeLimit); LogPrintf(" %d Block", BlockReading->nHeight ); } if ((pblock-> nTime - pindexLast->GetBlockTime()) > nLongTimeLimit) //block.nTime { bnNew = bnPowLimit; if(kgwdebug)LogPrintf("<BSD> Maximum block time hit - cute diff %08x %s\n", bnNew.GetCompact(), bnNew.ToString().c_str()); } if (bnNew > bnPowLimit) { bnNew = bnPowLimit; } return bnNew.GetCompact(); } unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlockHeader *pblock, const Consensus::Params& params) { int fork1 = 10000; int fork2 = 21000; if (pindexLast->nHeight+1 <= fork1) { return DUAL_KGW3(pindexLast, params, pblock); } unsigned int nProofOfWorkLimit = UintToArith256(params.powLimit).GetCompact(); if (pindexLast->nHeight+1 <= fork2) { // Genesis block if (pindexLast == NULL) return nProofOfWorkLimit; // Only change once per difficulty adjustment interval if ((pindexLast->nHeight+1) % params.DifficultyAdjustmentInterval() != 0) { if (params.fPowAllowMinDifficultyBlocks) { // Special difficulty rule for testnet: // If the new block's timestamp is more than 2* 10 minutes // then allow mining of a min-difficulty block. if (pblock->GetBlockTime() > pindexLast->GetBlockTime() + params.nPowTargetSpacing*2) return nProofOfWorkLimit; else { // Return the last non-special-min-difficulty-rules-block const CBlockIndex* pindex = pindexLast; while (pindex->pprev && pindex->nHeight % params.DifficultyAdjustmentInterval() != 0 && pindex->nBits == nProofOfWorkLimit) pindex = pindex->pprev; return pindex->nBits; } } return pindexLast->nBits; } // Go back by what we want to be 14 days worth of blocks // Litecoin: This fixes an issue where a 51% attack can change difficulty at will. // Go back the full period unless it's the first retarget after genesis. Code courtesy of Art Forz int blockstogoback = params.DifficultyAdjustmentInterval()-1; if ((pindexLast->nHeight+1) != params.DifficultyAdjustmentInterval()) blockstogoback = params.DifficultyAdjustmentInterval(); // Go back by what we want to be 14 days worth of blocks const CBlockIndex* pindexFirst = pindexLast; for (int i = 0; pindexFirst && i < blockstogoback; i++) pindexFirst = pindexFirst->pprev; assert(pindexFirst); return CalculateNextWorkRequired(pindexLast, pindexFirst->GetBlockTime(), params); } else { // Genesis block if (pindexLast == NULL) return nProofOfWorkLimit; // Only change once per difficulty adjustment interval if ((pindexLast->nHeight+1) % params.DifficultyAdjustmentIntervalV2() != 0) { if (params.fPowAllowMinDifficultyBlocks) { // Special difficulty rule for testnet: // If the new block's timestamp is more than 2* 10 minutes // then allow mining of a min-difficulty block. if (pblock->GetBlockTime() > pindexLast->GetBlockTime() + params.nPowTargetSpacing*2) return nProofOfWorkLimit; else { // Return the last non-special-min-difficulty-rules-block const CBlockIndex* pindex = pindexLast; while (pindex->pprev && pindex->nHeight % params.DifficultyAdjustmentIntervalV2() != 0 && pindex->nBits == nProofOfWorkLimit) pindex = pindex->pprev; return pindex->nBits; } } //LogPrintf("difficulty adjustment interval %d \n",(pindexLast->nHeight+1) % params.DifficultyAdjustmentIntervalV2()); return pindexLast->nBits; } // Go back by what we want to be 14 days worth of blocks // Litecoin: This fixes an issue where a 51% attack can change difficulty at will. // Go back the full period unless it's the first retarget after genesis. Code courtesy of Art Forz int blockstogoback2 = params.DifficultyAdjustmentIntervalV2()-1; if ((pindexLast->nHeight+1) != params.DifficultyAdjustmentIntervalV2()) blockstogoback2 = params.DifficultyAdjustmentIntervalV2(); // Go back by what we want to be 14 days worth of blocks const CBlockIndex* pindexFirst = pindexLast; for (int i = 0; pindexFirst && i < blockstogoback2; i++) pindexFirst = pindexFirst->pprev; assert(pindexFirst); return CalculateNextWorkRequired(pindexLast, pindexFirst->GetBlockTime(), params); } } //For Tet POW unsigned int CalculateNextWorkRequired(const CBlockIndex* pindexLast, int64_t nFirstBlockTime, const Consensus::Params& params) { int fork2 = 21000; if (params.fPowNoRetargeting) return pindexLast->nBits; // Limit adjustment step int64_t nActualTimespan = pindexLast->GetBlockTime() - nFirstBlockTime; const arith_uint256 bnPowLimit = UintToArith256(params.powLimit); arith_uint256 bnNew; if (pindexLast->nHeight+1 <= fork2) { //Retarget with 400 % if (nActualTimespan < params.nPowTargetTimespan/4) nActualTimespan = params.nPowTargetTimespan/4; if (nActualTimespan > params.nPowTargetTimespan*4) nActualTimespan = params.nPowTargetTimespan*4; bnNew.SetCompact(pindexLast->nBits); bnNew *= nActualTimespan; bnNew /= params.nPowTargetTimespan; if (bnNew > bnPowLimit) bnNew = bnPowLimit; return bnNew.GetCompact(); } else { //Low Retarget with 15 % if (nActualTimespan < params.nPowTargetTimespanV2/(115/100)) nActualTimespan = params.nPowTargetTimespanV2/(115/100); if (nActualTimespan > params.nPowTargetTimespanV2*(115/100)) nActualTimespan = params.nPowTargetTimespanV2*(115/100); bnNew.SetCompact(pindexLast->nBits); bnNew *= nActualTimespan; bnNew /= params.nPowTargetTimespanV2; if (bnNew > bnPowLimit) bnNew = bnPowLimit; return bnNew.GetCompact(); } // Retarget } bool CheckProofOfWork(uint256 hash, unsigned int nBits, const Consensus::Params& params) { bool fNegative; bool fOverflow; arith_uint256 bnTarget; bnTarget.SetCompact(nBits, &fNegative, &fOverflow); // Check range if (fNegative || bnTarget == 0 || fOverflow || bnTarget > UintToArith256(params.powLimit)) return false; // Check proof of work matches claimed amount if (UintToArith256(hash) > bnTarget) return false; return true; }
Update pow.cpp
Update pow.cpp
C++
mit
LIMXTEC/BitCore,LIMXTEC/BitCore,LIMXTEC/BitCore,LIMXTEC/BitCore,LIMXTEC/BitCore,LIMXTEC/BitCore
a613f0fc17a47bbf433a3778d35147ebf22beb99
src/http_util.cxx
src/http_util.cxx
/* * Various utilities for working with HTTP objects. * * author: Max Kellermann <[email protected]> */ #include "http_util.hxx" #include "pool.hxx" #include "util/CharUtil.hxx" #include "util/StringView.hxx" #include <string.h> char ** http_list_split(struct pool *pool, const char *p) { enum { MAX_ITEMS = 64 }; char *tmp[MAX_ITEMS + 1]; /* XXX dynamic allocation */ size_t num = 0; do { const char *comma, *end; /* skip whitespace */ while (IsWhitespaceNotNull(*p)) ++p; if (*p == 0) break; /* find the next delimiter */ end = comma = strchr(p, ','); if (end == nullptr) /* last element */ end = p + strlen(p); /* delete trailing whitespace */ while (end > p && IsWhitespaceFast(end[-1])) --end; /* append new list item */ tmp[num++] = p_strdup_lower(*pool, StringView(p, end)); if (comma == nullptr) /* this was the last element */ break; /* continue after the comma */ p = comma + 1; } while (num < MAX_ITEMS); tmp[num++] = nullptr; return (char**)p_memdup(pool, tmp, num * sizeof(tmp[0])); } static void http_trim(const char **pp, size_t *length_p) { const char *p = *pp; size_t length = *length_p; /* trim whitespace */ while (length > 0 && IsWhitespaceOrNull(p[length - 1])) --length; while (length > 0 && IsWhitespaceOrNull(p[0])) { ++p; --length; } /* remove quotes from quoted-string */ if (length >= 2 && p[0] == '"' && p[length - 1] == '"') { ++p; length -= 2; } /* return */ *pp = p; *length_p = length; } static bool http_equals(const char *a, size_t a_length, const char *b, size_t b_length) { http_trim(&a, &a_length); http_trim(&b, &b_length); return a_length == b_length && memcmp(a, b, a_length) == 0; } bool http_list_contains(const char *list, const char *item) { const char *comma; size_t item_length = strlen(item); while (*list != 0) { /* XXX what if the comma is within an quoted-string? */ comma = strchr(list, ','); if (comma == nullptr) return http_equals(list, strlen(list), item, item_length); if (http_equals(list, comma - list, item, item_length)) return true; list = comma + 1; } return false; } static bool http_equals_i(const char *a, size_t a_length, const char *b, size_t b_length) { http_trim(&a, &a_length); return a_length == b_length && strncasecmp(a, b, a_length) == 0; } bool http_list_contains_i(const char *list, const char *item) { const char *comma; size_t item_length = strlen(item); while (*list != 0) { /* XXX what if the comma is within an quoted-string? */ comma = strchr(list, ','); if (comma == nullptr) return http_equals_i(list, strlen(list), item, item_length); if (http_equals_i(list, comma - list, item, item_length)) return true; list = comma + 1; } return false; } StringView http_header_param(const char *value, const char *name) { /* XXX this implementation only supports one param */ const char *p = strchr(value, ';'), *q; if (p == nullptr) return nullptr; ++p; while (IsWhitespaceNotNull(*p)) ++p; q = strchr(p, '='); if (q == nullptr || (size_t)(q - p) != strlen(name) || memcmp(p, name, q - p) != 0) return nullptr; p = q + 1; if (*p == '"') { ++p; q = strchr(p, '"'); if (q == nullptr) return p; else return {p, size_t(q - p)}; } else { return p; } }
/* * Various utilities for working with HTTP objects. * * author: Max Kellermann <[email protected]> */ #include "http_util.hxx" #include "pool.hxx" #include "util/CharUtil.hxx" #include "util/StringView.hxx" #include <string.h> char ** http_list_split(struct pool *pool, const char *p) { enum { MAX_ITEMS = 64 }; char *tmp[MAX_ITEMS + 1]; /* XXX dynamic allocation */ size_t num = 0; do { const char *comma, *end; /* skip whitespace */ while (IsWhitespaceNotNull(*p)) ++p; if (*p == 0) break; /* find the next delimiter */ end = comma = strchr(p, ','); if (end == nullptr) /* last element */ end = p + strlen(p); /* delete trailing whitespace */ while (end > p && IsWhitespaceFast(end[-1])) --end; /* append new list item */ tmp[num++] = p_strdup_lower(*pool, StringView(p, end)); if (comma == nullptr) /* this was the last element */ break; /* continue after the comma */ p = comma + 1; } while (num < MAX_ITEMS); tmp[num++] = nullptr; return (char**)p_memdup(pool, tmp, num * sizeof(tmp[0])); } static StringView http_trim(StringView s) { /* trim whitespace */ s.Strip(); /* remove quotes from quoted-string */ if (s.size >= 2 && s.front() == '"' && s.back() == '"') { s.pop_front(); s.pop_back(); } /* return */ return s; } static bool http_equals(StringView a, StringView b) { return http_trim(a).Equals(http_trim(b)); } bool http_list_contains(const char *list, const char *_item) { const StringView item(_item); while (*list != 0) { /* XXX what if the comma is within an quoted-string? */ const char *comma = strchr(list, ','); if (comma == nullptr) return http_equals(list, item); if (http_equals({list, comma}, item)) return true; list = comma + 1; } return false; } static bool http_equals_i(StringView a, StringView b) { return http_trim(a).EqualsIgnoreCase(b); } bool http_list_contains_i(const char *list, const char *_item) { const StringView item(_item); while (*list != 0) { /* XXX what if the comma is within an quoted-string? */ const char *comma = strchr(list, ','); if (comma == nullptr) return http_equals_i(list, item); if (http_equals_i({list, comma}, item)) return true; list = comma + 1; } return false; } StringView http_header_param(const char *value, const char *name) { /* XXX this implementation only supports one param */ const char *p = strchr(value, ';'), *q; if (p == nullptr) return nullptr; ++p; while (IsWhitespaceNotNull(*p)) ++p; q = strchr(p, '='); if (q == nullptr || (size_t)(q - p) != strlen(name) || memcmp(p, name, q - p) != 0) return nullptr; p = q + 1; if (*p == '"') { ++p; q = strchr(p, '"'); if (q == nullptr) return p; else return {p, size_t(q - p)}; } else { return p; } }
use struct StringView
http_util: use struct StringView
C++
bsd-2-clause
CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy
4f84af0856e7621c728e5a39addf9002097b6025
src/io/file-0.cpp
src/io/file-0.cpp
// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp: /* The MIT License Copyright (c) 2008, 2009 Flusspferd contributors (see "CONTRIBUTORS" or http://flusspferd.org/contributors.txt) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "flusspferd/io/file-0.hpp" #include "flusspferd.hpp" #include <boost/foreach.hpp> #include <boost/lexical_cast.hpp> #include <boost/filesystem/fstream.hpp> #ifdef WIN32 #include <stdio.h> #else #include <unistd.h> #endif using namespace flusspferd; namespace file0 = flusspferd::io::file0; namespace fs = boost::filesystem; void flusspferd::load_file_0_module(object container) { object exports = container.get_property_object("exports"); create_native_function(exports, "canonical", &file0::canonical); create_native_function(exports, "lastModified", &file0::last_modified); create_native_function(exports, "touch", &file0::touch); create_native_function(exports, "size", &file0::size); create_native_function(exports, "exists", &file0::exists); create_native_function(exports, "isFile", &file0::is_file); create_native_function(exports, "isDirectory", &file0::is_directory); create_native_function(exports, "isLink", &file0::is_link); create_native_function(exports, "isReadable", &file0::is_readable); create_native_function(exports, "isWriteable", &file0::is_writeable); create_native_function(exports, "link", &file0::link); create_native_function(exports, "hardLink", &file0::hard_link); create_native_function(exports, "readLink", &file0::read_link); } string file0::canonical(string path) { return canonicalize(path.to_string()).string(); } // Resolve symlinks fs::path file0::canonicalize(fs::path in) { fs::path accum; char buff[PATH_MAX]; if (!in.has_root_path()) { // dir is relative! accum = fs::system_complete("."); if (*--accum.end() == ".") accum.remove_filename(); } BOOST_FOREACH(fs::path seg, in) { if (seg == ".") continue; // We've already canon'd the path's parent, so just remove the last dir if (seg == "..") { accum = accum.remove_filename(); continue; } accum /= seg; if (fs::is_symlink(accum)) { ssize_t len = readlink(accum.string().c_str(), buff, PATH_MAX); if (len == -1) { //TODO: How do i use boost to get a nicer errmessage? Also should actually use errno throw std::string("Path too long"); } fs::path link_path = std::string(buff, len); // An absolute link if (link_path.has_root_path()) accum = canonicalize(link_path); else { accum.remove_filename(); accum = canonicalize(accum / link_path); } } } // This trickery forces a trailing / onto the dir accum /= "."; accum.remove_filename(); return accum; } value file0::last_modified(string path) { std::time_t last_mod = fs::last_write_time(path.to_string()); // TODO: Is there any way that isn't so truely horrible? std::string js = "new Date("; return evaluate(js + boost::lexical_cast<std::string>(last_mod*1000.0) + ")"); } void file0::touch(string str, object mtime_o) { object date = global().get_property_object("Date"); value ctor; if (mtime_o.is_null() || !(ctor = mtime_o.get_property("constructor")).is_object() || ctor.get_object() != date) { throw exception("touch expects a Date as it's second argument", "TypeError"); } double msecs = mtime_o.call("valueOf").to_number(); std::time_t mtime = msecs/1000; fs::path p(str.to_string()); if (!fs::exists(p)) { // File doesn't exist, create fs::ofstream f(p); } fs::last_write_time(p, mtime); } // JS has no concept of unit, and double has a 53 bit mantissa, which means we // can store up to 9*10^E15 (2^53, 8192TB ) without loosing precisions. Much // better than only 30bits == 1gb! eek double file0::size(string file) { uintmax_t fsize = fs::file_size(file.to_string()); return fsize; } bool file0::exists(string p) { return fs::exists(p.to_string()); } bool file0::is_file(string p) { return fs::is_regular_file(p.to_string()); } bool file0::is_directory(string p) { return fs::is_directory(p.to_string()); } bool file0::is_link(string p) { return fs::is_symlink(p.to_string()); } bool file0::is_readable(string p) { return access(p.to_string().c_str(), R_OK) != -1; } bool file0::is_writeable(string str) { fs::path p(str.to_string()); if (access(p.string().c_str(), W_OK) != -1) return true; // Might be false because it doesn't exist, in which case check we can write // to the dir its in if (!fs::exists(p)) { p.remove_filename(); p = canonicalize(p); return access(p.string().c_str(), W_OK) != -1; } return false; } void file0::link(string source, string target) { if (symlink(source.to_string().c_str(), target.to_string().c_str()) == 0) return; // TODO: paths and system error message! throw exception("Error creating symbolic link"); } void file0::hard_link(string source, string target) { if (::link(source.to_string().c_str(), target.to_string().c_str()) == 0) return; // TODO: paths and system error message! throw exception("Error creating hard link"); } string file0::read_link(string link) { std::string s = link.to_string(); if (!fs::is_symlink(s)) { throw exception("Cannot readLink: " + s + " is not a link"); } char buff[PATH_MAX]; ssize_t len = readlink(s.c_str(), buff, PATH_MAX); if (len == -1) { //TODO: How do i use boost to get a nicer errmessage? Also should actually use errno throw std::string("Path too long"); } return string(buff, len); }
// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp: /* The MIT License Copyright (c) 2008, 2009 Flusspferd contributors (see "CONTRIBUTORS" or http://flusspferd.org/contributors.txt) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "flusspferd/io/file-0.hpp" #include "flusspferd.hpp" #include <boost/foreach.hpp> #include <boost/lexical_cast.hpp> #include <boost/filesystem/fstream.hpp> #ifdef WIN32 #include <stdio.h> #else #include <unistd.h> #endif using namespace flusspferd; namespace file0 = flusspferd::io::file0; namespace fs = boost::filesystem; void flusspferd::load_file_0_module(object container) { object exports = container.get_property_object("exports"); create_native_function(exports, "canonical", &file0::canonical); create_native_function(exports, "lastModified", &file0::last_modified); create_native_function(exports, "touch", &file0::touch); create_native_function(exports, "size", &file0::size); create_native_function(exports, "exists", &file0::exists); create_native_function(exports, "isFile", &file0::is_file); create_native_function(exports, "isDirectory", &file0::is_directory); create_native_function(exports, "isLink", &file0::is_link); create_native_function(exports, "isReadable", &file0::is_readable); create_native_function(exports, "isWriteable", &file0::is_writeable); create_native_function(exports, "link", &file0::link); create_native_function(exports, "hardLink", &file0::hard_link); create_native_function(exports, "readLink", &file0::read_link); } string file0::canonical(string path) { return canonicalize(path.to_string()).string(); } // Resolve symlinks fs::path file0::canonicalize(fs::path in) { fs::path accum; char buff[PATH_MAX]; if (!in.has_root_path()) { // dir is relative! accum = fs::system_complete("."); if (*--accum.end() == ".") accum.remove_filename(); } BOOST_FOREACH(fs::path seg, in) { if (seg == ".") continue; // We've already canon'd the path's parent, so just remove the last dir if (seg == "..") { accum = accum.remove_filename(); continue; } accum /= seg; if (fs::is_symlink(accum)) { ssize_t len = readlink(accum.string().c_str(), buff, PATH_MAX); if (len == -1) { //TODO: How do i use boost to get a nicer errmessage? Also should actually use errno throw std::string("Path too long"); } fs::path link_path = std::string(buff, len); // An absolute link if (link_path.has_root_path()) accum = canonicalize(link_path); else { accum.remove_filename(); accum = canonicalize(accum / link_path); } } } // This trickery forces a trailing / onto the dir accum /= "."; accum.remove_filename(); return accum; } value file0::last_modified(string path) { std::time_t last_mod = fs::last_write_time(path.to_string()); // TODO: Is there any way that isn't so truely horrible? std::string js = "new Date("; return evaluate(js + boost::lexical_cast<std::string>(last_mod*1000.0) + ")"); } void file0::touch(string str, object mtime_o) { object date = global().get_property_object("Date"); value ctor; std::size_t mtime; if (!mtime_o.is_null()) { if (!(ctor = mtime_o.get_property("constructor")).is_object() || ctor.get_object() != date) { throw exception("touch expects a Date as it's second argument if present", "TypeError"); } double msecs = mtime_o.call("valueOf").to_number(); mtime = msecs/1000; } else { mtime = time(NULL); } fs::path p(str.to_string()); if (!fs::exists(p)) { // File doesn't exist, create fs::ofstream f(p); } fs::last_write_time(p, mtime); } // JS has no concept of unit, and double has a 53 bit mantissa, which means we // can store up to 9*10^E15 (2^53, 8192TB ) without loosing precisions. Much // better than only 30bits == 1gb! eek double file0::size(string file) { uintmax_t fsize = fs::file_size(file.to_string()); return fsize; } bool file0::exists(string p) { return fs::exists(p.to_string()); } bool file0::is_file(string p) { return fs::is_regular_file(p.to_string()); } bool file0::is_directory(string p) { return fs::is_directory(p.to_string()); } bool file0::is_link(string p) { return fs::is_symlink(p.to_string()); } bool file0::is_readable(string p) { return access(p.to_string().c_str(), R_OK) != -1; } bool file0::is_writeable(string str) { fs::path p(str.to_string()); if (access(p.string().c_str(), W_OK) != -1) return true; // Might be false because it doesn't exist, in which case check we can write // to the dir its in if (!fs::exists(p)) { p.remove_filename(); p = canonicalize(p); return access(p.string().c_str(), W_OK) != -1; } return false; } void file0::link(string source, string target) { if (symlink(source.to_string().c_str(), target.to_string().c_str()) == 0) return; // TODO: paths and system error message! throw exception("Error creating symbolic link"); } void file0::hard_link(string source, string target) { if (::link(source.to_string().c_str(), target.to_string().c_str()) == 0) return; // TODO: paths and system error message! throw exception("Error creating hard link"); } string file0::read_link(string link) { std::string s = link.to_string(); if (!fs::is_symlink(s)) { throw exception("Cannot readLink: " + s + " is not a link"); } char buff[PATH_MAX]; ssize_t len = readlink(s.c_str(), buff, PATH_MAX); if (len == -1) { //TODO: How do i use boost to get a nicer errmessage? Also should actually use errno throw std::string("Path too long"); } return string(buff, len); }
fix bug with touch() - mtime is optional argument
core/file-0: fix bug with touch() - mtime is optional argument
C++
mit
Flusspferd/flusspferd,Flusspferd/flusspferd,Flusspferd/flusspferd,Flusspferd/flusspferd,Flusspferd/flusspferd
b08387613bd177c36c0740f9702c6ba3b4c5c520
src/label_data.cc
src/label_data.cc
/****************************************************************************** * Copyright (c) 2015 Jamis Hoo * Distributed under the MIT license * (See accompanying file LICENSE or copy at http://opensource.org/licenses/MIT) * * Project: * Filename: label_data.cc * Version: 1.0 * Author: Jamis Hoo * E-mail: [email protected] * Date: Jul 19, 2015 * Time: 17:58:55 * Description: *****************************************************************************/
/****************************************************************************** * Copyright (c) 2015 Jamis Hoo * Distributed under the MIT license * (See accompanying file LICENSE or copy at http://opensource.org/licenses/MIT) * * Project: * Filename: label_data.cc * Version: 1.0 * Author: Jamis Hoo * E-mail: [email protected] * Date: Jul 19, 2015 * Time: 17:58:55 * Description: *****************************************************************************/ #include <iostream> #include <fstream> #include <cassert> #include "hadoop/Pipes.hh" #include "hadoop/TemplateFactory.hh" #include "hadoop/StringUtils.hh" #include "netflix_movie.h" constexpr size_t canopy_threshold = 2; const std::string canopy_centers_path = "jamis_canopy_output/part-00000"; inline std::string to_hex_string(const size_t x) { char buff[32] = { 0 }; sprintf(buff, "%zx", x); return buff; } class LabelDataMapper: public HadoopPipes::Mapper { public: LabelDataMapper(HadoopPipes::TaskContext& /* context */) { load_canopy_centers(); } // emit key: movie id // emit value: canopy id1, canopy id2, canopy id3 ...; user_id1, rating1, user_id2, rating2, ... // without any spaces void map(HadoopPipes::MapContext& context) { Movie movie = context.getInputValue(); std::string emit_value; for (const auto& mv: canopy_centers) if (movie.user_match_count(mv) > canopy_threshold) emit_value += to_hex_string(mv.movie_id()) + ','; if (emit_value.length() == 0) return; emit_value.back() = ';'; size_t pos = context.getInputValue().find_first_of('\t'); std::string emit_key = context.getInputValue().substr(0, pos); emit_value += context.getInputValue().substr(pos + 1); context.emit(emit_key, emit_value); } private: void load_canopy_centers() { std::ifstream fin(canopy_centers_path); std::string line; while (std::getline(fin, line)) canopy_centers.emplace_back(line); } std::vector<Movie> canopy_centers; }; class DoNothingReducer: public HadoopPipes::Reducer { public: DoNothingReducer(const HadoopPipes::TaskContext& /* context */) { } void reduce(HadoopPipes::ReduceContext& context) { bool once_flag = false; while (context.nextValue()) { assert(once_flag == false); once_flag = true; context.emit(context.getInputKey(), context.getInputValue()); } } }; int main(int, char**) { return HadoopPipes::runTask(HadoopPipes::TemplateFactory<LabelDataMapper, DoNothingReducer>()); }
add label data program
add label data program
C++
mit
JamisHoo/k-Means-with-Canopy-Clustering-MapReduce,JamisHoo/k-Means-with-Canopy-Clustering-MapReduce,JamisHoo/k-Means-with-Canopy-Clustering-MapReduce
362046685c63ea77ca62ff99fc9184573a51389c
src/libcsg/map.cc
src/libcsg/map.cc
/* * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org) * * 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. * */ // Standard includes #include <numeric> #include <string> // VOTCA includes #include <votca/tools/eigen.h> #include <votca/tools/tokenizer.h> // Local VOTCA includes #include "votca/csg/bead.h" #include "votca/csg/map.h" #include "votca/csg/topology.h" namespace votca { namespace csg { class Molecule; } // namespace csg namespace tools { class Property; } // namespace tools } // namespace votca namespace votca { namespace csg { using namespace tools; using namespace std; Map::~Map() { for (auto &_map : _maps) { delete _map; } _maps.clear(); } void Map::Apply(const BoundaryCondition &bc) { for (auto &_map : _maps) { _map->Apply(bc); } } void Map_Sphere::Initialize(Molecule *in, Bead *out, Property *opts_bead, Property *opts_map) { BeadMap::Initialize(in, out, opts_bead, opts_map); vector<string> beads; vector<double> weights; vector<double> fweights; // get the beads string s(_opts_bead->get("beads").value()); Tokenizer tok_beads(s, " \n\t"); tok_beads.ToVector(beads); // get vector of weights Tokenizer tok_weights(_opts_map->get("weights").value(), " \n\t"); tok_weights.ConvertToVector<double>(weights); // check weather weights and # beads matches if (beads.size() != weights.size()) { throw runtime_error( string("number of subbeads in " + opts_bead->get("name").as<string>() + " and number of weights in map " + opts_map->get("name").as<string>() + " do not match")); } // normalize the weights double norm = 1. / std::accumulate(weights.begin(), weights.end(), 0.); transform(weights.begin(), weights.end(), weights.begin(), bind2nd(multiplies<double>(), norm)); // get the d vector if exists or initialize same as weights vector<double> d; if (_opts_map->exists("d")) { Tokenizer tok_weights2(_opts_map->get("d").value(), " \n\t"); tok_weights2.ConvertToVector(d); // normalize d coefficients norm = 1. / std::accumulate(d.begin(), d.end(), 0.); transform(d.begin(), d.end(), d.begin(), bind2nd(multiplies<double>(), norm)); } else { // initialize force-weights with weights d.resize(weights.size()); copy(weights.begin(), weights.end(), d.begin()); } // check weather number of d coeffs is correct if (beads.size() != d.size()) { throw runtime_error( string("number of subbeads in " + opts_bead->get("name").as<string>() + " and number of d-coefficients in map " + opts_map->get("name").as<string>() + " do not match")); } fweights.resize(weights.size()); // calculate force weights by d_i/w_i for (size_t i = 0; i < weights.size(); ++i) { if (weights[i] == 0 && d[i] != 0) { throw runtime_error( "A d coefficient is nonzero while weights is zero in mapping " + opts_map->get("name").as<string>()); } if (weights[i] != 0) { fweights[i] = d[i] / weights[i]; } else { fweights[i] = 0; } } for (size_t i = 0; i < beads.size(); ++i) { Index iin = in->getBeadByName(beads[i]); if (iin < 0) { throw std::runtime_error( string("mapping error: molecule " + beads[i] + " does not exist")); } AddElem(in->getBead(iin), weights[i], fweights[i]); } } void Map_Sphere::Apply(const BoundaryCondition &bc) { assert(_matrix.size() > 0 && "Cannot map to sphere there are no beads"); bool bPos, bVel, bF; bPos = bVel = bF = false; _out->ClearParentBeads(); // the following is needed for pbc treatment Eigen::Vector3d r0 = Eigen::Vector3d::Zero(); string name0; Index id0 = 0; if (_matrix.size() > 0) { if (_matrix.front()._in->HasPos()) { r0 = _matrix.front()._in->getPos(); name0 = _matrix.front()._in->getName(); id0 = _matrix.front()._in->getId(); } } double M = 0; Eigen::Vector3d cg = Eigen::Vector3d::Zero(); Eigen::Vector3d f = Eigen::Vector3d::Zero(); Eigen::Vector3d vel = Eigen::Vector3d::Zero(); Bead *bead_max_dist = _matrix.at(0)._in; double max_bead_dist = bc.BCShortestConnection(r0, bead_max_dist->getPos()).norm(); for (auto &iter : _matrix) { Bead *bead = iter._in; _out->AddParentBead(bead->getId()); M += bead->getMass(); if (bead->HasPos()) { Eigen::Vector3d r = bc.BCShortestConnection(r0, bead->getPos()); if (r.norm() > max_bead_dist) { max_bead_dist = r.norm(); bead_max_dist = bead; } cg += iter._weight * (r + r0); bPos = true; } } /// Safety check, if box is not open check if the bead is larger than the /// boundaries if (bc.getBoxType() != BoundaryCondition::eBoxtype::typeOpen) { double max_dist = 0.5 * bc.getShortestBoxDimension(); if (max_bead_dist > max_dist) { cout << r0 << " " << bead_max_dist->getPos() << endl; throw std::runtime_error( "coarse-grained bead is bigger than half the box \n " "(atoms " + name0 + " (id " + boost::lexical_cast<string>(id0 + 1) + ")" + ", " + bead_max_dist->getName() + " (id " + boost::lexical_cast<string>(bead_max_dist->getId() + 1) + ")" + +" , molecule " + boost::lexical_cast<string>(bead_max_dist->getMoleculeId() + 1) + ")"); } } for (auto &iter : _matrix) { Bead *bead = iter._in; if (bead->HasVel()) { vel += iter._weight * bead->getVel(); bVel = true; } if (bead->HasF()) { f += iter._force_weight * bead->getF(); bF = true; } } _out->setMass(M); if (bPos) { _out->setPos(cg); } if (bVel) { _out->setVel(vel); } if (bF) { _out->setF(f); } } /// \todo implement this function void Map_Ellipsoid::Apply(const BoundaryCondition &bc) { assert(_matrix.size() > 0 && "Cannot map to ellipsoid there are no beads"); bool bPos, bVel, bF; bPos = bVel = bF = false; // the following is needed for pbc treatment Eigen::Vector3d r0 = Eigen::Vector3d::Zero(); string name0; Index id0 = 0; if (_matrix.size() > 0) { if (_matrix.front()._in->HasPos()) { r0 = _matrix.front()._in->getPos(); name0 = _matrix.front()._in->getName(); id0 = _matrix.front()._in->getId(); } } Eigen::Vector3d cg = Eigen::Vector3d::Zero(); Eigen::Vector3d c = Eigen::Vector3d::Zero(); Eigen::Vector3d f = Eigen::Vector3d::Zero(); Eigen::Vector3d vel = Eigen::Vector3d::Zero(); Index n; n = 0; _out->ClearParentBeads(); Bead *bead_max_dist = _matrix.at(0)._in; double max_bead_dist = bc.BCShortestConnection(r0, bead_max_dist->getPos()).norm(); for (auto &iter : _matrix) { Bead *bead = iter._in; _out->AddParentBead(bead->getId()); if (bead->HasPos()) { Eigen::Vector3d r = bc.BCShortestConnection(r0, bead->getPos()); if (r.norm() > max_bead_dist) { max_bead_dist = r.norm(); bead_max_dist = bead; } cg += iter._weight * (r + r0); bPos = true; } } /// Safety check, if box is not open check if the bead is larger than the /// boundaries if (bc.getBoxType() != BoundaryCondition::eBoxtype::typeOpen) { double max_dist = 0.5 * bc.getShortestBoxDimension(); if (max_bead_dist > max_dist) { cout << r0 << " " << bead_max_dist->getPos() << endl; throw std::runtime_error( "coarse-grained bead is bigger than half the box \n " "(atoms " + name0 + " (id " + boost::lexical_cast<string>(id0 + 1) + ")" + ", " + bead_max_dist->getName() + " (id " + boost::lexical_cast<string>(bead_max_dist->getId() + 1) + ")" + +" , molecule " + boost::lexical_cast<string>(bead_max_dist->getMoleculeId() + 1) + ")"); } } for (auto &iter : _matrix) { Bead *bead = iter._in; if (bead->HasVel() == true) { vel += iter._weight * bead->getVel(); bVel = true; } if (bead->HasF()) { /// \todo fix me, right calculation should be F_i = m_cg / sum(w_i) * /// sum(w_i/m_i*F_i) // f += (*iter)._weight * _in->getBeadF((*iter)._in); f += iter._force_weight * bead->getF(); bF = true; } if (iter._weight > 0 && bead->HasPos()) { c += bead->getPos(); n++; } } if (bPos) { _out->setPos(cg); } if (bVel) { _out->setVel(vel); } if (bF) { _out->setF(f); } if (!_matrix[0]._in->HasPos()) { _out->setU(Eigen::Vector3d::UnitX()); _out->setV(Eigen::Vector3d::UnitY()); _out->setW(Eigen::Vector3d::UnitZ()); return; } Eigen::Matrix3d m = Eigen::Matrix3d::Zero(); // calculate the tensor of gyration c = c / (double)n; for (auto &iter : _matrix) { if (iter._weight == 0) { continue; } Bead *bead = iter._in; Eigen::Vector3d v = bead->getPos() - c; // v = vec(1, 0.5, 0) * 0.*(drand48()-0.5) // + vec(0.5, -1, 0) * (drand48()-0.5) // + vec(0, 0, 1) * (drand48()-0.5); // Normalize the tensor with 1/number_of_atoms_per_bead m += v * v.transpose() / (double)_matrix.size(); } Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d> eig; eig.computeDirect(m); Eigen::Vector3d u = eig.eigenvectors().col(0); Eigen::Vector3d v = _matrix[1]._in->getPos() - _matrix[0]._in->getPos(); v.normalize(); _out->setV(v); Eigen::Vector3d w = _matrix[2]._in->getPos() - _matrix[0]._in->getPos(); w.normalize(); if (v.cross(w).dot(u) < 0) { u = -u; } _out->setU(u); // write out w w = u.cross(v); w.normalize(); _out->setW(w); } } // namespace csg } // namespace votca
/* * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org) * * 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. * */ // Standard includes #include <numeric> #include <string> // VOTCA includes #include <votca/tools/eigen.h> #include <votca/tools/tokenizer.h> // Local VOTCA includes #include "votca/csg/bead.h" #include "votca/csg/map.h" #include "votca/csg/topology.h" namespace votca { namespace csg { class Molecule; } // namespace csg namespace tools { class Property; } // namespace tools } // namespace votca namespace votca { namespace csg { using namespace tools; using namespace std; Map::~Map() { for (auto &_map : _maps) { delete _map; } _maps.clear(); } void Map::Apply(const BoundaryCondition &bc) { for (auto &_map : _maps) { _map->Apply(bc); } } void Map_Sphere::Initialize(Molecule *in, Bead *out, Property *opts_bead, Property *opts_map) { BeadMap::Initialize(in, out, opts_bead, opts_map); vector<string> beads; vector<double> weights; vector<double> fweights; // get the beads string s(_opts_bead->get("beads").value()); Tokenizer tok_beads(s, " \n\t"); tok_beads.ToVector(beads); // get vector of weights Tokenizer tok_weights(_opts_map->get("weights").value(), " \n\t"); tok_weights.ConvertToVector<double>(weights); // check weather weights and # beads matches if (beads.size() != weights.size()) { throw runtime_error( string("number of subbeads in " + opts_bead->get("name").as<string>() + " and number of weights in map " + opts_map->get("name").as<string>() + " do not match")); } // normalize the weights double norm = 1. / std::accumulate(weights.begin(), weights.end(), 0.); transform(weights.begin(), weights.end(), weights.begin(), bind2nd(multiplies<double>(), norm)); // get the d vector if exists or initialize same as weights vector<double> d; if (_opts_map->exists("d")) { Tokenizer tok_weights2(_opts_map->get("d").value(), " \n\t"); tok_weights2.ConvertToVector(d); // normalize d coefficients norm = 1. / std::accumulate(d.begin(), d.end(), 0.); transform(d.begin(), d.end(), d.begin(), bind2nd(multiplies<double>(), norm)); } else { // initialize force-weights with weights d.resize(weights.size()); copy(weights.begin(), weights.end(), d.begin()); } // check weather number of d coeffs is correct if (beads.size() != d.size()) { throw runtime_error( string("number of subbeads in " + opts_bead->get("name").as<string>() + " and number of d-coefficients in map " + opts_map->get("name").as<string>() + " do not match")); } fweights.resize(weights.size()); // calculate force weights by d_i/w_i for (size_t i = 0; i < weights.size(); ++i) { if (weights[i] == 0 && d[i] != 0) { throw runtime_error( "A d coefficient is nonzero while weights is zero in mapping " + opts_map->get("name").as<string>()); } if (weights[i] != 0) { fweights[i] = d[i] / weights[i]; } else { fweights[i] = 0; } } for (size_t i = 0; i < beads.size(); ++i) { Index iin = in->getBeadByName(beads[i]); if (iin < 0) { throw std::runtime_error( string("mapping error: molecule " + beads[i] + " does not exist")); } AddElem(in->getBead(iin), weights[i], fweights[i]); } } void Map_Sphere::Apply(const BoundaryCondition &bc) { assert(_matrix.size() > 0 && "Cannot map to sphere there are no beads"); bool bPos, bVel, bF; bPos = bVel = bF = false; _out->ClearParentBeads(); // the following is needed for pbc treatment Eigen::Vector3d r0 = Eigen::Vector3d::Zero(); string name0; Index id0 = 0; if (_matrix.size() > 0) { if (_matrix.front()._in->HasPos()) { r0 = _matrix.front()._in->getPos(); name0 = _matrix.front()._in->getName(); id0 = _matrix.front()._in->getId(); } } double M = 0; Eigen::Vector3d cg = Eigen::Vector3d::Zero(); Eigen::Vector3d f = Eigen::Vector3d::Zero(); Eigen::Vector3d vel = Eigen::Vector3d::Zero(); Bead *bead_max_dist = _matrix.at(0)._in; double max_bead_dist = 0; if (bead_max_dist->HasPos()) { max_bead_dist = bc.BCShortestConnection(r0, bead_max_dist->getPos()).norm(); } for (auto &iter : _matrix) { Bead *bead = iter._in; _out->AddParentBead(bead->getId()); M += bead->getMass(); if (bead->HasPos()) { Eigen::Vector3d r = bc.BCShortestConnection(r0, bead->getPos()); if (r.norm() > max_bead_dist) { max_bead_dist = r.norm(); bead_max_dist = bead; } cg += iter._weight * (r + r0); bPos = true; } } /// Safety check, if box is not open check if the bead is larger than the /// boundaries if (bc.getBoxType() != BoundaryCondition::eBoxtype::typeOpen) { double max_dist = 0.5 * bc.getShortestBoxDimension(); if (max_bead_dist > max_dist) { cout << r0 << " " << bead_max_dist->getPos() << endl; throw std::runtime_error( "coarse-grained bead is bigger than half the box \n " "(atoms " + name0 + " (id " + boost::lexical_cast<string>(id0 + 1) + ")" + ", " + bead_max_dist->getName() + " (id " + boost::lexical_cast<string>(bead_max_dist->getId() + 1) + ")" + +" , molecule " + boost::lexical_cast<string>(bead_max_dist->getMoleculeId() + 1) + ")"); } } for (auto &iter : _matrix) { Bead *bead = iter._in; if (bead->HasVel()) { vel += iter._weight * bead->getVel(); bVel = true; } if (bead->HasF()) { f += iter._force_weight * bead->getF(); bF = true; } } _out->setMass(M); if (bPos) { _out->setPos(cg); } if (bVel) { _out->setVel(vel); } if (bF) { _out->setF(f); } } /// \todo implement this function void Map_Ellipsoid::Apply(const BoundaryCondition &bc) { assert(_matrix.size() > 0 && "Cannot map to ellipsoid there are no beads"); bool bPos, bVel, bF; bPos = bVel = bF = false; // the following is needed for pbc treatment Eigen::Vector3d r0 = Eigen::Vector3d::Zero(); string name0; Index id0 = 0; if (_matrix.size() > 0) { if (_matrix.front()._in->HasPos()) { r0 = _matrix.front()._in->getPos(); name0 = _matrix.front()._in->getName(); id0 = _matrix.front()._in->getId(); } } Eigen::Vector3d cg = Eigen::Vector3d::Zero(); Eigen::Vector3d c = Eigen::Vector3d::Zero(); Eigen::Vector3d f = Eigen::Vector3d::Zero(); Eigen::Vector3d vel = Eigen::Vector3d::Zero(); Index n; n = 0; _out->ClearParentBeads(); Bead *bead_max_dist = _matrix.at(0)._in; double max_bead_dist = 0; if (bead_max_dist->HasPos()) { max_bead_dist = bc.BCShortestConnection(r0, bead_max_dist->getPos()).norm(); } for (auto &iter : _matrix) { Bead *bead = iter._in; _out->AddParentBead(bead->getId()); if (bead->HasPos()) { Eigen::Vector3d r = bc.BCShortestConnection(r0, bead->getPos()); if (r.norm() > max_bead_dist) { max_bead_dist = r.norm(); bead_max_dist = bead; } cg += iter._weight * (r + r0); bPos = true; } } /// Safety check, if box is not open check if the bead is larger than the /// boundaries if (bc.getBoxType() != BoundaryCondition::eBoxtype::typeOpen) { double max_dist = 0.5 * bc.getShortestBoxDimension(); if (max_bead_dist > max_dist) { cout << r0 << " " << bead_max_dist->getPos() << endl; throw std::runtime_error( "coarse-grained bead is bigger than half the box \n " "(atoms " + name0 + " (id " + boost::lexical_cast<string>(id0 + 1) + ")" + ", " + bead_max_dist->getName() + " (id " + boost::lexical_cast<string>(bead_max_dist->getId() + 1) + ")" + +" , molecule " + boost::lexical_cast<string>(bead_max_dist->getMoleculeId() + 1) + ")"); } } for (auto &iter : _matrix) { Bead *bead = iter._in; if (bead->HasVel() == true) { vel += iter._weight * bead->getVel(); bVel = true; } if (bead->HasF()) { /// \todo fix me, right calculation should be F_i = m_cg / sum(w_i) * /// sum(w_i/m_i*F_i) // f += (*iter)._weight * _in->getBeadF((*iter)._in); f += iter._force_weight * bead->getF(); bF = true; } if (iter._weight > 0 && bead->HasPos()) { c += bead->getPos(); n++; } } if (bPos) { _out->setPos(cg); } if (bVel) { _out->setVel(vel); } if (bF) { _out->setF(f); } if (!_matrix[0]._in->HasPos()) { _out->setU(Eigen::Vector3d::UnitX()); _out->setV(Eigen::Vector3d::UnitY()); _out->setW(Eigen::Vector3d::UnitZ()); return; } Eigen::Matrix3d m = Eigen::Matrix3d::Zero(); // calculate the tensor of gyration c = c / (double)n; for (auto &iter : _matrix) { if (iter._weight == 0) { continue; } Bead *bead = iter._in; Eigen::Vector3d v = bead->getPos() - c; // v = vec(1, 0.5, 0) * 0.*(drand48()-0.5) // + vec(0.5, -1, 0) * (drand48()-0.5) // + vec(0, 0, 1) * (drand48()-0.5); // Normalize the tensor with 1/number_of_atoms_per_bead m += v * v.transpose() / (double)_matrix.size(); } Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d> eig; eig.computeDirect(m); Eigen::Vector3d u = eig.eigenvectors().col(0); Eigen::Vector3d v = _matrix[1]._in->getPos() - _matrix[0]._in->getPos(); v.normalize(); _out->setV(v); Eigen::Vector3d w = _matrix[2]._in->getPos() - _matrix[0]._in->getPos(); w.normalize(); if (v.cross(w).dot(u) < 0) { u = -u; } _out->setU(u); // write out w w = u.cross(v); w.normalize(); _out->setW(w); } } // namespace csg } // namespace votca
fix max_bead_dist calc without positions
map: fix max_bead_dist calc without positions
C++
apache-2.0
votca/csg,votca/csg,votca/csg,votca/csg
949a1139096b9212ff2aee3ae1ee7cb1fb18b245
src/lts_remote.hh
src/lts_remote.hh
/* * 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 __lts_remote_hh__ #define __lts_remote_hh__ #include "lts.hh" class Lts_remote: public Lts { public: Lts_remote(Log&l, std::string params): Lts(l, params) {} virtual bool init(); }; #endif
/* * 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 __lts_remote_hh__ #define __lts_remote_hh__ #include "lts.hh" class Lts_remote: public Lts { public: Lts_remote(Log&l, std::string params): Lts(l, params) {} virtual ~Lts_remote() {} virtual bool init(); }; #endif
Add missing virtual destructor
Add missing virtual destructor
C++
lgpl-2.1
giantpinkwalrus/fMBT,giantpinkwalrus/fMBT,rseymour/fMBT,pablovirolainen/fMBT,violep01/fMBT,acozzette/fMBT,rseymour/fMBT,pyykkis/fMBT,acozzette/fMBT,CosminNiculae/fMBT,yoonkiss/fMBT,mlq/fMBT,yoonkiss/fMBT,yoonkiss/fMBT,pyykkis/fMBT,heivi/fMBT,violep01/fMBT,CosminNiculae/fMBT,violep01/fMBT,rseymour/fMBT,OMKR/fMBT,heivi/fMBT,acozzette/fMBT,pyykkis/fMBT,mixu-/fMBT,pombreda/fMBT,01org/fMBT,pyykkis/fMBT,mixu-/fMBT,01org/fMBT,pablovirolainen/fMBT,acozzette/fMBT,mlq/fMBT,pablovirolainen/fMBT,pablovirolainen/fMBT,CosminNiculae/fMBT,OMKR/fMBT,CosminNiculae/fMBT,CosminNiculae/fMBT,mlq/fMBT,OMKR/fMBT,OMKR/fMBT,mixu-/fMBT,heivi/fMBT,rseymour/fMBT,giantpinkwalrus/fMBT,mlq/fMBT,rseymour/fMBT,01org/fMBT,pombreda/fMBT,mixu-/fMBT,OMKR/fMBT,violep01/fMBT,mixu-/fMBT,pablovirolainen/fMBT,CosminNiculae/fMBT,mlq/fMBT,yoonkiss/fMBT,mlq/fMBT,rseymour/fMBT,pyykkis/fMBT,yoonkiss/fMBT,pombreda/fMBT,rseymour/fMBT,pombreda/fMBT,pablovirolainen/fMBT,CosminNiculae/fMBT,mlq/fMBT,violep01/fMBT,01org/fMBT,giantpinkwalrus/fMBT,heivi/fMBT,pombreda/fMBT,01org/fMBT,pyykkis/fMBT,pombreda/fMBT,acozzette/fMBT,heivi/fMBT,OMKR/fMBT,heivi/fMBT,heivi/fMBT,giantpinkwalrus/fMBT,pombreda/fMBT
faeaf3b0569508fa1c95b608fdc4b2ffa090cd03
Tutorial/Tutorial2/HelloWorld2.cpp
Tutorial/Tutorial2/HelloWorld2.cpp
#include "HelloWorld2.h" #include "NFComm/NFCore/NFCObject.h" bool HelloWorld2::Init() { //ʼ std::cout << "Hello, world2, Init" << std::endl; return true; } int HelloWorld2::OnPropertyCallBackEvent( const NFIDENTID& self, const std::string& strProperty, const NFIDataList& oldVarList, const NFIDataList& newVarList ) { //Իص¼ֻҪֵб仯ͻᱻص std::cout << "OnPropertyCallBackEvent Property: " << strProperty << " OldValue: " << oldVarList.Int(0) << " NewValue: " << newVarList.Int(0) << std::endl; return 0; } bool HelloWorld2::AfterInit() { // #ifdef NF_USE_ACTOR // if(pPluginManager->GetActorID() == NFIActorManager::EACTOR_MAIN) // #endif { //ʼ std::cout << "Hello, world2, AfterInit" << std::endl; NFIObject* pObject = new NFCObject(NFIDENTID(0, 1), pPluginManager); pObject->GetPropertyManager()->AddProperty(pObject->Self(), "Hello", TDATA_STRING, true, true, true, true, 0, ""); pObject->GetPropertyManager()->AddProperty(pObject->Self(), "World", TDATA_INT, true, true, true, true, 0, ""); pObject->SetPropertyInt("World", 1111); const int nProperty1 = pObject->GetPropertyInt("World"); std::cout << "Property World:" << nProperty1 << std::endl; //¼ pObject->AddPropertyCallBack("World", this, &HelloWorld2::OnPropertyCallBackEvent); pObject->SetPropertyInt("World", 2222); const int nProperty2 = pObject->GetPropertyInt("World"); std::cout << "Property World:" << nProperty2 << std::endl; } return true; } bool HelloWorld2::Execute( const float fLasFrametime, const float fStartedTime ) { //ÿִ֡ //std::cout << "Hello, world2, Execute" << std::endl; return true; } bool HelloWorld2::BeforeShut() { //ʼ֮ǰ std::cout << "Hello, world2, BeforeShut" << std::endl; return true; } bool HelloWorld2::Shut() { //ʼ std::cout << "Hello, world2, Shut" << std::endl; return true; }
#include "HelloWorld2.h" #include "NFComm/NFCore/NFCObject.h" bool HelloWorld2::Init() { //ʼ std::cout << "Hello, world2, Init" << std::endl; return true; } int HelloWorld2::OnPropertyCallBackEvent( const NFIDENTID& self, const std::string& strProperty, const NFIDataList& oldVarList, const NFIDataList& newVarList ) { //Իص¼ֻҪֵб仯ͻᱻص std::cout << "OnPropertyCallBackEvent Property: " << strProperty << " OldValue: " << oldVarList.Int(0) << " NewValue: " << newVarList.Int(0) << std::endl; return 0; } bool HelloWorld2::AfterInit() { // #ifdef NF_USE_ACTOR // if(pPluginManager->GetActorID() == NFIActorManager::EACTOR_MAIN) // #endif { std::cout << "Hello, world2, AfterInit" << std::endl; //created a object for this test NFIObject* pObject = new NFCObject(NFIDENTID(0, 1), pPluginManager); //add a property name is "Hello" of this object pObject->GetPropertyManager()->AddProperty(pObject->Self(), "Hello", TDATA_STRING, true, true, true, true, 0, ""); //add a property name is "World" of this object pObject->GetPropertyManager()->AddProperty(pObject->Self(), "World", TDATA_INT, true, true, true, true, 0, ""); //set the "world" property value as 1111 pObject->SetPropertyInt("World", 1111); //get the "world" property value and printf it const int nProperty1 = pObject->GetPropertyInt("World"); std::cout << "Property World:" << nProperty1 << std::endl; //add a call back functin for "world" property pObject->AddPropertyCallBack("World", this, &HelloWorld2::OnPropertyCallBackEvent); ////set the "world" property value as 2222[than the function "HelloWorld2::OnPropertyCallBackEvent" will be called] pObject->SetPropertyInt("World", 2222); //get the "world" property value and printf it const int nProperty2 = pObject->GetPropertyInt("World"); std::cout << "Property World:" << nProperty2 << std::endl; } return true; } bool HelloWorld2::Execute( const float fLasFrametime, const float fStartedTime ) { //ÿִ֡ //std::cout << "Hello, world2, Execute" << std::endl; return true; } bool HelloWorld2::BeforeShut() { //ʼ֮ǰ std::cout << "Hello, world2, BeforeShut" << std::endl; return true; } bool HelloWorld2::Shut() { //ʼ std::cout << "Hello, world2, Shut" << std::endl; return true; }
add comments for tutorial2
add comments for tutorial2
C++
apache-2.0
zh423328/NFServer,zh423328/NFServer,xinst/NoahGameFrame,zh423328/NFServer,xinst/NoahGameFrame,xinst/NoahGameFrame,xinst/NoahGameFrame,xinst/NoahGameFrame,xinst/NoahGameFrame,xinst/NoahGameFrame,zh423328/NFServer,zh423328/NFServer,xinst/NoahGameFrame,zh423328/NFServer,zh423328/NFServer,zh423328/NFServer,xinst/NoahGameFrame
0cd31d39d353ac0ec418ccbef60f82a77aab7300
src/abc-testing/runner.cxx
src/abc-testing/runner.cxx
/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*- Copyright 2013 Raffaello D. Di Napoli This file is part of Application-Building Components (henceforth referred to as ABC). ABC is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. ABC is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with ABC. If not, see <http://www.gnu.org/licenses/>. --------------------------------------------------------------------------------------------------*/ #include <abc/testing/core.hxx> #include <abc/testing/runner.hxx> #include <abc/testing/test_case.hxx> #include <abc/trace.hxx> //////////////////////////////////////////////////////////////////////////////////////////////////// // abc::testing::assertion_error namespace abc { namespace testing { assertion_error::assertion_error() : exception() { m_pszWhat = "abc::assertion_error"; } } //namespace testing } //namespace abc //////////////////////////////////////////////////////////////////////////////////////////////////// // abc::testing::runner namespace abc { namespace testing { runner::runner(std::shared_ptr<ostream> posOut) : m_pos(std::move(posOut)), m_cTotalTestCases(0), m_cPassedTestCases(0), m_cTotalAssertions(0), m_cPassedAssertions(0) { } runner::~runner() { // TODO: currently abc::*vector containers don’t support move-only types; remove this manual // cleanup code when std::unique_ptr becomes supported. for (auto it(m_vptc.begin()); it != m_vptc.end(); ++it) { delete *it; } } void runner::load_registered_test_cases() { ABC_TRACE_FN((this)); for ( test_case_factory_impl::list_item * pli(test_case_factory_impl::get_factory_list_head()); pli; pli = pli->pliNext ) { // Instantiate the test case. auto ptc(pli->pfnFactory(this)); // TODO: currently abc::*vector containers don’t support move-only types; change to use // std::unique_ptr when that becomes supported. m_vptc.append(ptc.release()); // m_vptc.append(std::move(ptc)); } } void runner::log_assertion( bool bSuccess, istr const & sExpr, istr const & sExpected /*= istr()*/, istr const & sActual /*= istr()*/ ) { ABC_TRACE_FN((this, bSuccess, sExpr, sExpected, sActual)); if (!bSuccess) { m_pos->print( SL("Assertion failed: {}; expected: {}, actual: {}\n"), sExpr, sExpected, sActual ); } else if (false /*|| verbose*/) { m_pos->print(SL("Assertion passed: {}\n"), sExpr); } if (bSuccess) { ++m_cPassedAssertions; } ++m_cTotalAssertions; } bool runner::log_summary() { ABC_TRACE_FN((this)); if (m_cTotalAssertions == 0) { m_pos->write(SL("No tests performed\n")); } else { m_pos->print( SL("Test cases: {} executed, {} passed ({}%), {} failed ({}%)\n"), m_cTotalTestCases, m_cPassedTestCases, m_cPassedTestCases * 100 / m_cTotalTestCases, m_cTotalTestCases - m_cPassedTestCases, ((m_cTotalTestCases - m_cPassedTestCases) * 100 + 1) / m_cTotalTestCases ); m_pos->print( SL("Assertions: {} performed, {} passed ({}%), {} failed ({}%)\n"), m_cTotalAssertions, m_cPassedAssertions, m_cPassedAssertions * 100 / m_cTotalAssertions, m_cTotalAssertions - m_cPassedAssertions, ((m_cTotalAssertions - m_cPassedAssertions) * 100 + 1) / m_cTotalAssertions ); } return m_cPassedAssertions == m_cTotalAssertions; } void runner::run() { ABC_TRACE_FN((this)); for (auto it(m_vptc.begin()); it != m_vptc.end(); ++it) { run_test_case(**it); } } void runner::run_test_case(test_case & tc) { ABC_TRACE_FN((this/*, u*/)); m_pos->print(SL("Test case: {}: running...\n"), tc.title()); // Save the current total and passed counts, so we can compare them after running the test case. unsigned cPrevTotalAssertions(m_cTotalAssertions), cPrevPassedAssertions(m_cPassedAssertions); bool bPassed(false); try { tc.run(); // If both the total and the passed count increased, the test case passed. if ( cPrevTotalAssertions - m_cTotalAssertions == cPrevPassedAssertions - m_cPassedAssertions ) { bPassed = true; ++m_cPassedTestCases; } } catch (assertion_error const &) { // This exception type is only used to interrupt abc::testing::test_case::run(). m_pos->write(SL("Test case execution interrupted\n")); } catch (std::exception const & x) { exception::write_with_scope_trace(m_pos.get(), &x); } catch (...) { exception::write_with_scope_trace(m_pos.get()); } ++m_cTotalTestCases; m_pos->print(SL("Test case: {}: {}\n"), tc.title(), bPassed ? SL("pass") : SL("fail")); } } //namespace testing } //namespace abc ////////////////////////////////////////////////////////////////////////////////////////////////////
/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*- Copyright 2013 Raffaello D. Di Napoli This file is part of Application-Building Components (henceforth referred to as ABC). ABC is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. ABC is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with ABC. If not, see <http://www.gnu.org/licenses/>. --------------------------------------------------------------------------------------------------*/ #include <abc/testing/core.hxx> #include <abc/testing/runner.hxx> #include <abc/testing/test_case.hxx> #include <abc/trace.hxx> //////////////////////////////////////////////////////////////////////////////////////////////////// // abc::testing::assertion_error namespace abc { namespace testing { assertion_error::assertion_error() : exception() { m_pszWhat = "abc::assertion_error"; } } //namespace testing } //namespace abc //////////////////////////////////////////////////////////////////////////////////////////////////// // abc::testing::runner namespace abc { namespace testing { runner::runner(std::shared_ptr<ostream> posOut) : m_pos(std::move(posOut)), m_cTotalTestCases(0), m_cPassedTestCases(0), m_cTotalAssertions(0), m_cPassedAssertions(0) { } runner::~runner() { // TODO: currently abc::*vector containers don’t support move-only types; remove this manual // cleanup code when std::unique_ptr becomes supported. for (auto it(m_vptc.begin()); it != m_vptc.end(); ++it) { delete *it; } } void runner::load_registered_test_cases() { ABC_TRACE_FN((this)); for ( test_case_factory_impl::list_item * pli(test_case_factory_impl::get_factory_list_head()); pli; pli = pli->pliNext ) { // Instantiate the test case. auto ptc(pli->pfnFactory(this)); // TODO: currently abc::*vector containers don’t support move-only types; change to use // std::unique_ptr when that becomes supported. m_vptc.append(ptc.release()); // m_vptc.append(std::move(ptc)); } } void runner::log_assertion( bool bSuccess, istr const & sExpr, istr const & sExpected /*= istr()*/, istr const & sActual /*= istr()*/ ) { ABC_TRACE_FN((this, bSuccess, sExpr, sExpected, sActual)); ++m_cTotalAssertions; if (bSuccess) { ++m_cPassedAssertions; m_pos->print(SL("ABCMK-TEST-ASSERT-PASS {}\n"), sExpr); } else { m_pos->print( SL("ABCMK-TEST-ASSERT-FAIL {}\n") SL(" expected: {}\n") SL(" actual: {}\n"), sExpr, sExpected, sActual ); } } bool runner::log_summary() { ABC_TRACE_FN((this)); /*if (m_cTotalAssertions == 0) { m_pos->write(SL("No tests performed\n")); } else { m_pos->print( SL("Test cases: {} executed, {} passed ({}%), {} failed ({}%)\n"), m_cTotalTestCases, m_cPassedTestCases, m_cPassedTestCases * 100 / m_cTotalTestCases, m_cTotalTestCases - m_cPassedTestCases, ((m_cTotalTestCases - m_cPassedTestCases) * 100 + 1) / m_cTotalTestCases ); m_pos->print( SL("Assertions: {} performed, {} passed ({}%), {} failed ({}%)\n"), m_cTotalAssertions, m_cPassedAssertions, m_cPassedAssertions * 100 / m_cTotalAssertions, m_cTotalAssertions - m_cPassedAssertions, ((m_cTotalAssertions - m_cPassedAssertions) * 100 + 1) / m_cTotalAssertions ); }*/ return m_cPassedAssertions == m_cTotalAssertions; } void runner::run() { ABC_TRACE_FN((this)); for (auto it(m_vptc.begin()); it != m_vptc.end(); ++it) { run_test_case(**it); } } void runner::run_test_case(test_case & tc) { ABC_TRACE_FN((this/*, u*/)); m_pos->print(SL("ABCMK-TEST-CASE-START {}\n"), tc.title()); // Save the current total and passed counts, so we can compare them after running the test case. unsigned cPrevTotalAssertions(m_cTotalAssertions), cPrevPassedAssertions(m_cPassedAssertions); try { tc.run(); // If both the total and the passed count increased, the test case passed. if ( cPrevTotalAssertions - m_cTotalAssertions == cPrevPassedAssertions - m_cPassedAssertions ) { ++m_cPassedTestCases; } } catch (assertion_error const &) { // This exception type is only used to interrupt abc::testing::test_case::run(). m_pos->write(SL("test case execution interrupted\n")); } catch (std::exception const & x) { exception::write_with_scope_trace(m_pos.get(), &x); } catch (...) { exception::write_with_scope_trace(m_pos.get()); } ++m_cTotalTestCases; m_pos->print(SL("ABCMK-TEST-CASE-END\n")); } } //namespace testing } //namespace abc ////////////////////////////////////////////////////////////////////////////////////////////////////
Integrate abc::testing and ABC Make
Integrate abc::testing and ABC Make
C++
lgpl-2.1
raffaellod/lofty,raffaellod/lofty
ef66e176141408b558a14b66c1355268a638264f
tascore/services/interactionhandlers/eventgenerator/tastoucheventgenerator.cpp
tascore/services/interactionhandlers/eventgenerator/tastoucheventgenerator.cpp
/*************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of Testability Driver Qt Agent ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected] . ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation ** and appearing in the file LICENSE.LGPL included in the packaging ** of this file. ** ****************************************************************************/ #include <QtTest/qtestspontaneevent.h> #include <QDesktopWidget> #include "tascoreutils.h" #include "tastoucheventgenerator.h" #include "taslogger.h" int TasTouchEventGenerator::mTouchPointCounter = 0; TasTouchEventGenerator::TasTouchEventGenerator(QObject* parent) :QObject(parent) { } TasTouchEventGenerator::~TasTouchEventGenerator() { } void TasTouchEventGenerator::doTouchBegin(QWidget* target, QPoint point, bool primary, QString identifier) { doTouchBegin(target, toTouchPoints(point,primary), identifier); } void TasTouchEventGenerator::doTouchUpdate(QWidget* target, QPoint point, bool primary, QString identifier) { doTouchUpdate(target, toTouchPoints(point,primary), identifier); } void TasTouchEventGenerator::doTouchEnd(QWidget* target, QPoint point, bool primary, QString identifier) { doTouchEnd(target, toTouchPoints(point,primary), identifier); } void TasTouchEventGenerator::doTouchBegin(QWidget* target, QList<TasTouchPoints> points, QString identifier) { QList<QTouchEvent::TouchPoint> touchPoints = convertToTouchPoints(target, Qt::TouchPointPressed, points, identifier); QTouchEvent* touchPress = new QTouchEvent(QEvent::TouchBegin, QTouchEvent::TouchScreen, Qt::NoModifier, Qt::TouchPointPressed, touchPoints); touchPress->setWidget(target); sendTouchEvent(target, touchPress); } void TasTouchEventGenerator::doTouchUpdate(QWidget* target, QList<TasTouchPoints> points, QString identifier) { QList<QTouchEvent::TouchPoint> touchPoints = convertToTouchPoints(target, Qt::TouchPointMoved, points, identifier); QTouchEvent* touchMove = new QTouchEvent(QEvent::TouchUpdate, QTouchEvent::TouchScreen, Qt::NoModifier, Qt::TouchPointMoved, touchPoints); touchMove->setWidget(target); sendTouchEvent(target, touchMove); } void TasTouchEventGenerator::doTouchEnd(QWidget* target, QList<TasTouchPoints> points, QString identifier) { QList<QTouchEvent::TouchPoint> touchPoints = convertToTouchPoints(target, Qt::TouchPointReleased, points, identifier); QTouchEvent *touchRelease = new QTouchEvent(QEvent::TouchEnd, QTouchEvent::TouchScreen, Qt::NoModifier, Qt::TouchPointReleased, touchPoints); touchRelease->setWidget(target); sendTouchEvent(target, touchRelease); } void TasTouchEventGenerator::sendTouchEvent(QWidget* target, QTouchEvent* event) { QSpontaneKeyEvent::setSpontaneous(event); qApp->postEvent(target, event); qApp->processEvents(); } QList<QTouchEvent::TouchPoint> TasTouchEventGenerator::convertToTouchPoints(TargetData targetData, Qt::TouchPointState state) { return convertToTouchPoints(targetData.target, state, toTouchPoints(targetData.targetPoint, false), TasCoreUtils::pointerId(targetData.targetItem)); } QList<QTouchEvent::TouchPoint> TasTouchEventGenerator::convertToTouchPoints(QWidget* target, Qt::TouchPointState state, QList<TasTouchPoints> points, QString identifier) { bool store = true; QList<QVariant> pointIds; if(!identifier.isEmpty()) { QVariant pointStore = qApp->property(identifier.toAscii()); if(pointStore.isValid()){ pointIds = pointStore.toList(); } if(state == Qt::TouchPointReleased){ //set invalid to remove the list qApp->setProperty(identifier.toAscii(), QVariant()); store = false; } } else{ store = false; } QList<QTouchEvent::TouchPoint> touchPoints; if(!points.isEmpty()){ for(int i = 0 ; i < points.size() ; i++){ if(pointIds.size() <= i ){ mTouchPointCounter++; pointIds.append(QVariant(mTouchPointCounter)); } touchPoints.append(makeTouchPoint(target, points.at(i), state, pointIds.at(i).toInt())); } } if(store && !identifier.isEmpty()){ //we store the point id to the app as property //this allows new gestures to use the ids when needed qApp->setProperty(identifier.toAscii(), QVariant(pointIds)); } return touchPoints; } QTouchEvent::TouchPoint TasTouchEventGenerator::makeTouchPoint(QWidget* target, TasTouchPoints points, Qt::TouchPointState state, int id) { QTouchEvent::TouchPoint touchPoint(id); Qt::TouchPointStates states = state; if(points.isPrimary){ states |= Qt::TouchPointPrimary; } touchPoint.setPressure(1.0); touchPoint.setState(states); touchPoint.setPos(target->mapFromGlobal(points.screenPoint)); touchPoint.setScreenPos(points.screenPoint); QRect screenGeometry = QApplication::desktop()->screenGeometry(points.screenPoint); touchPoint.setNormalizedPos(QPointF(points.screenPoint.x() / screenGeometry.width(), points.screenPoint.y() / screenGeometry.height())); //in addition to the position we also need to set last and start positions as //some gesture may depend on them if(!points.lastScreenPoint.isNull()){ touchPoint.setLastPos(target->mapFromGlobal(points.lastScreenPoint)); touchPoint.setLastScreenPos(points.lastScreenPoint); touchPoint.setLastNormalizedPos(QPointF(points.lastScreenPoint.x() / screenGeometry.width(), points.lastScreenPoint.y() / screenGeometry.height())); } if(!points.startScreenPoint.isNull()){ touchPoint.setStartPos(target->mapFromGlobal(points.startScreenPoint)); touchPoint.setStartScreenPos(points.startScreenPoint); touchPoint.setStartNormalizedPos(QPointF(points.startScreenPoint.x() / screenGeometry.width(), points.startScreenPoint.y() / screenGeometry.height())); } return touchPoint; } QList<TasTouchPoints> TasTouchEventGenerator::toTouchPoints(QPoint point, bool primary) { QList<TasTouchPoints> points; points.append(toTouchPoint(point, primary)); return points; } TasTouchPoints TasTouchEventGenerator::toTouchPoint(QPoint point, bool primary) { TasTouchPoints touchPoint; touchPoint.screenPoint = point; touchPoint.isPrimary = primary; return touchPoint; } bool TasTouchEventGenerator::areIdentical(QList<TasTouchPoints> points1, QList<TasTouchPoints> points2) { if(points1.size() != points2.size()){ return false; } //loop points to detect differences for(int i = 0 ; i < points1.size() ; i++){ TasTouchPoints t = points1.at(i); TasTouchPoints p = points2.at(i); if(p.screenPoint != t.screenPoint || t.lastScreenPoint != p.lastScreenPoint || p.startScreenPoint != t.startScreenPoint){ return false; } } return true; }
/*************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of Testability Driver Qt Agent ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected] . ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation ** and appearing in the file LICENSE.LGPL included in the packaging ** of this file. ** ****************************************************************************/ #include <QtTest/qtestspontaneevent.h> #include <QDesktopWidget> #include "tascoreutils.h" #include "tastoucheventgenerator.h" #include "taslogger.h" int TasTouchEventGenerator::mTouchPointCounter = 0; TasTouchEventGenerator::TasTouchEventGenerator(QObject* parent) :QObject(parent) { } TasTouchEventGenerator::~TasTouchEventGenerator() { } void TasTouchEventGenerator::doTouchBegin(QWidget* target, QPoint point, bool primary, QString identifier) { doTouchBegin(target, toTouchPoints(point,primary), identifier); } void TasTouchEventGenerator::doTouchUpdate(QWidget* target, QPoint point, bool primary, QString identifier) { doTouchUpdate(target, toTouchPoints(point,primary), identifier); } void TasTouchEventGenerator::doTouchEnd(QWidget* target, QPoint point, bool primary, QString identifier) { doTouchEnd(target, toTouchPoints(point,primary), identifier); } void TasTouchEventGenerator::doTouchBegin(QWidget* target, QList<TasTouchPoints> points, QString identifier) { QList<QTouchEvent::TouchPoint> touchPoints = convertToTouchPoints(target, Qt::TouchPointPressed, points, identifier); QTouchEvent* touchPress = new QTouchEvent(QEvent::TouchBegin, QTouchEvent::TouchScreen, Qt::NoModifier, Qt::TouchPointPressed, touchPoints); touchPress->setWidget(target); sendTouchEvent(target, touchPress); } void TasTouchEventGenerator::doTouchUpdate(QWidget* target, QList<TasTouchPoints> points, QString identifier) { QList<QTouchEvent::TouchPoint> touchPoints = convertToTouchPoints(target, Qt::TouchPointMoved, points, identifier); QTouchEvent* touchMove = new QTouchEvent(QEvent::TouchUpdate, QTouchEvent::TouchScreen, Qt::NoModifier, Qt::TouchPointMoved, touchPoints); touchMove->setWidget(target); sendTouchEvent(target, touchMove); } void TasTouchEventGenerator::doTouchEnd(QWidget* target, QList<TasTouchPoints> points, QString identifier) { QList<QTouchEvent::TouchPoint> touchPoints = convertToTouchPoints(target, Qt::TouchPointReleased, points, identifier); QTouchEvent *touchRelease = new QTouchEvent(QEvent::TouchEnd, QTouchEvent::TouchScreen, Qt::NoModifier, Qt::TouchPointReleased, touchPoints); touchRelease->setWidget(target); sendTouchEvent(target, touchRelease); } void TasTouchEventGenerator::sendTouchEvent(QWidget* target, QTouchEvent* event) { QSpontaneKeyEvent::setSpontaneous(event); qApp->postEvent(target, event); qApp->processEvents(); } QList<QTouchEvent::TouchPoint> TasTouchEventGenerator::convertToTouchPoints(TargetData targetData, Qt::TouchPointState state) { return convertToTouchPoints(targetData.target, state, toTouchPoints(targetData.targetPoint, false), TasCoreUtils::pointerId(targetData.targetItem)); } QList<QTouchEvent::TouchPoint> TasTouchEventGenerator::convertToTouchPoints(QWidget* target, Qt::TouchPointState state, QList<TasTouchPoints> points, QString identifier) { QList<QVariant> pointIds; if(!identifier.isEmpty()) { QVariant pointStore = qApp->property(identifier.toAscii()); if(pointStore.isValid()){ pointIds = pointStore.toList(); } } QList<QTouchEvent::TouchPoint> touchPoints; if(!points.isEmpty()){ for(int i = 0 ; i < points.size() ; i++){ if(pointIds.size() <= i ){ mTouchPointCounter++; pointIds.append(QVariant(mTouchPointCounter)); } touchPoints.append(makeTouchPoint(target, points.at(i), state, pointIds.at(i).toInt())); } } if(state == Qt::TouchPointReleased){ qApp->setProperty(identifier.toAscii(), QVariant()); mTouchPointCounter = 0; } else if(!identifier.isEmpty()){ //we store the point id to the app as property //this allows new gestures to use the ids when needed qApp->setProperty(identifier.toAscii(), QVariant(pointIds)); } return touchPoints; } QTouchEvent::TouchPoint TasTouchEventGenerator::makeTouchPoint(QWidget* target, TasTouchPoints points, Qt::TouchPointState state, int id) { QTouchEvent::TouchPoint touchPoint(id); Qt::TouchPointStates states = state; if(points.isPrimary){ states |= Qt::TouchPointPrimary; } touchPoint.setPressure(1.0); touchPoint.setState(states); touchPoint.setPos(target->mapFromGlobal(points.screenPoint)); touchPoint.setScreenPos(points.screenPoint); QRect screenGeometry = QApplication::desktop()->screenGeometry(points.screenPoint); touchPoint.setNormalizedPos(QPointF(points.screenPoint.x() / screenGeometry.width(), points.screenPoint.y() / screenGeometry.height())); //in addition to the position we also need to set last and start positions as //some gesture may depend on them if(!points.lastScreenPoint.isNull()){ touchPoint.setLastPos(target->mapFromGlobal(points.lastScreenPoint)); touchPoint.setLastScreenPos(points.lastScreenPoint); touchPoint.setLastNormalizedPos(QPointF(points.lastScreenPoint.x() / screenGeometry.width(), points.lastScreenPoint.y() / screenGeometry.height())); } if(!points.startScreenPoint.isNull()){ touchPoint.setStartPos(target->mapFromGlobal(points.startScreenPoint)); touchPoint.setStartScreenPos(points.startScreenPoint); touchPoint.setStartNormalizedPos(QPointF(points.startScreenPoint.x() / screenGeometry.width(), points.startScreenPoint.y() / screenGeometry.height())); } return touchPoint; } QList<TasTouchPoints> TasTouchEventGenerator::toTouchPoints(QPoint point, bool primary) { QList<TasTouchPoints> points; points.append(toTouchPoint(point, primary)); return points; } TasTouchPoints TasTouchEventGenerator::toTouchPoint(QPoint point, bool primary) { TasTouchPoints touchPoint; touchPoint.screenPoint = point; touchPoint.isPrimary = primary; return touchPoint; } bool TasTouchEventGenerator::areIdentical(QList<TasTouchPoints> points1, QList<TasTouchPoints> points2) { if(points1.size() != points2.size()){ return false; } //loop points to detect differences for(int i = 0 ; i < points1.size() ; i++){ TasTouchPoints t = points1.at(i); TasTouchPoints p = points2.at(i); if(p.screenPoint != t.screenPoint || t.lastScreenPoint != p.lastScreenPoint || p.startScreenPoint != t.startScreenPoint){ return false; } } return true; }
reset counter when touch point ends
reset counter when touch point ends
C++
lgpl-2.1
rferrazz/cutedriver-agent_qt,mer-tools/qttas,ration/agent_qt,mer-tools/qttas,d0b3rm4n/agent_qt,ration/agent_qt,d0b3rm4n/agent_qt,rferrazz/cutedriver-agent_qt,rasjani/cutedriver-agent_qt,ration/agent_qt,mer-tools/qttas,rasjani/cutedriver-agent_qt,nomovok-opensource/cutedriver-agent_qt,ration/agent_qt,d0b3rm4n/agent_qt,mer-tools/qttas,d0b3rm4n/agent_qt,nomovok-opensource/cutedriver-agent_qt,rasjani/cutedriver-agent_qt,nomovok-opensource/cutedriver-agent_qt,rferrazz/cutedriver-agent_qt
4da4e41e0e171e8f8204ee573a04d2170de173de
tensorflow/compiler/mlir/tools/kernel_gen/transforms/buffer_reuse_pass.cc
tensorflow/compiler/mlir/tools/kernel_gen/transforms/buffer_reuse_pass.cc
/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include <cstddef> #include <vector> #include "llvm/ADT/EquivalenceClasses.h" #include "llvm/ADT/None.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/SmallVector.h" #include "mlir/Analysis/BufferAliasAnalysis.h" // from @llvm-project #include "mlir/Analysis/Liveness.h" // from @llvm-project #include "mlir/Dialect/Linalg/IR/LinalgOps.h" // from @llvm-project #include "mlir/Dialect/StandardOps/IR/Ops.h" // from @llvm-project #include "mlir/IR/AffineMap.h" // from @llvm-project #include "mlir/IR/Function.h" // from @llvm-project #include "mlir/IR/Operation.h" // from @llvm-project #include "mlir/IR/StandardTypes.h" // from @llvm-project #include "tensorflow/compiler/mlir/hlo/include/mlir-hlo/Dialect/mhlo/IR/lhlo_ops.h" #include "tensorflow/compiler/mlir/tools/kernel_gen/ir/tf_framework_ops.h" #include "tensorflow/compiler/mlir/tools/kernel_gen/transforms/passes.h" #include "tensorflow/compiler/mlir/tools/kernel_gen/transforms/rewriters.h" // Needed to build `llvm::EquivalenceClasses` of `mlir::Value`s. namespace mlir { static bool operator<(const Value &lhs, const Value &rhs) { return lhs.getAsOpaquePointer() < rhs.getAsOpaquePointer(); } } // namespace mlir namespace mlir { namespace kernel_gen { namespace transforms { namespace { // TODO(frgossen): Move this to MLIR. static void walkBlocks(Operation *op, std::function<void(Block &)> callback) { for (Region &region : op->getRegions()) { for (Block &block : region) { callback(block); for (Operation &nested_op : block) walkBlocks(&nested_op, callback); } } } /// A temporary buffer size analysis that is correct but may be incomplete. class BufferSizeAnalysis { public: explicit BufferSizeAnalysis(FuncOp f) { build(f); } bool is_same_size(Value a, Value b) { return ecs_.isEquivalent(a, b); } private: void build(FuncOp &f) { auto buffers = find_buffer_values(f); // Memrefs with statically known same shape must be of the same size. int n = buffers.size(); for (int i = 0; i < n; ++i) { for (int j = i + 1; j < n; ++j) { Value a = buffers[i]; Value b = buffers[j]; auto a_ty = a.getType().dyn_cast<MemRefType>(); auto b_ty = b.getType().dyn_cast<MemRefType>(); if (a_ty && b_ty && a_ty.hasStaticShape() && b_ty.hasStaticShape() && a_ty.getSizeInBits() == b_ty.getSizeInBits() && a_ty.getAffineMaps() == b_ty.getAffineMaps()) { ecs_.unionSets(a, b); } } } // Operands to `linalg.generic` with equal affine maps must be of same size. f.walk([&](linalg::GenericOp genericOp) { auto operand_buffers = genericOp.getInputsAndOutputBuffers(); int n = operand_buffers.size(); for (int i = 0; i < n; ++i) { for (int j = i + 1; j < n; ++j) { Value a = operand_buffers[i]; Value b = operand_buffers[j]; auto a_ty = a.getType().dyn_cast<MemRefType>(); auto b_ty = b.getType().dyn_cast<MemRefType>(); if (a_ty && b_ty && a_ty.getElementType() == b_ty.getElementType() && a_ty.getAffineMaps() == b_ty.getAffineMaps()) { AffineMap map_i = genericOp.getIndexingMap(i); AffineMap map_j = genericOp.getIndexingMap(j); if (map_i == map_j && map_i.isPermutation()) ecs_.unionSets(a, b); } } } }); // Operand and result of `reshape_memref_cast` must be of same size. f.walk([&](lmhlo::ReshapeMemRefCastOp reshapeOp) { ecs_.unionSets(reshapeOp.result(), reshapeOp.operand()); }); } llvm::SmallVector<Value, 8> find_buffer_values(FuncOp f) { llvm::SmallVector<Value, 8> buffers; f.walk([&](Operation *op) { for (Value val : op->getResults()) if (val.getType().isa<BaseMemRefType>()) buffers.push_back(val); }); walkBlocks(f.getOperation(), [&](Block &block) { for (Value val : block.getArguments()) { if (val.getType().isa<BaseMemRefType>()) buffers.push_back(val); } }); return buffers; } llvm::EquivalenceClasses<Value> ecs_; }; class BufferReuseAnalysis { public: explicit BufferReuseAnalysis(FuncOp f) { build(f); } static constexpr int kIndexAmbiguous = -1; Optional<SmallVector<int64_t, 2>> get_reuse_candiates(AllocOp op) { auto it = reuse_candidates_.find(op); if (it == reuse_candidates_.end()) return llvm::None; return it->second; } Optional<int64_t> get_output_index(AllocOp op) { auto it = output_indices_.find(op); if (it == output_indices_.end()) return llvm::None; return it->second; } private: void build(FuncOp &f) { BufferAliasAnalysis aliases(f); find_output_indices(f, aliases); find_reuse_candiates(f, aliases); } void find_output_indices(FuncOp &f, BufferAliasAnalysis &aliases) { f.walk([&](AllocOp alloc_op) { int64_t output_index = kIndexAmbiguous; int count_return_uses = 0; auto buffer_aliases = aliases.resolve(alloc_op.getResult()); for (Value alias : buffer_aliases) { for (auto &use : alias.getUses()) { if (isa<ReturnOp>(use.getOwner())) { int64_t index = use.getOperandNumber(); if (count_return_uses++ == 0) output_index = index; else if (output_index != index) output_index = kIndexAmbiguous; } } } output_indices_[alloc_op] = output_index; }); } void find_reuse_candiates(FuncOp &f, BufferAliasAnalysis &aliases) { Liveness liveness(f); BufferSizeAnalysis size_equivalences(f); walkBlocks(f.getOperation(), [&](Block &block) { find_reuse_candiates(block, aliases, liveness.getLiveness(&block), size_equivalences, f.getArguments()); }); } void find_reuse_candiates(Block &block, BufferAliasAnalysis &aliases, const LivenessBlockInfo *liveness, BufferSizeAnalysis &size_equivalences, ArrayRef<BlockArgument> arguments) { for (Operation &op : block) { auto alloc_op = dyn_cast<AllocOp>(op); if (!alloc_op) continue; // Find first use of the newly allocated buffer within this block. Value new_buffer = alloc_op.getResult(); Operation *first_reuse = find_first_use_in_block( new_buffer, alloc_op.getOperation()->getBlock()); // Find reuse candidates for the regarded allocation. SmallVector<int64_t, 2> local_reuse_candidates; for (auto it : llvm::enumerate(arguments)) { int64_t old_buffer_index = it.index(); Value old_buffer = it.value(); if (!old_buffer.getType().isa<BaseMemRefType>()) continue; // Will not reuse buffers of different size as they may be too small. if (!size_equivalences.is_same_size(new_buffer, old_buffer)) continue; // Only reuse buffers that are no longer used on first reuse, i.e. they // are no longer alive. bool livetimes_compatible = true; for (Value old_buffer_alias : aliases.resolve(old_buffer)) { if (first_reuse == nullptr) { // If the first use is beyond the end of this block we look at the // block end. An argument buffer that is already reusable there is // certainly reusable at any later actual use. if (liveness->isLiveOut(old_buffer_alias)) { livetimes_compatible = false; break; } } else { // A buffer is *not* reusable if // i) its last use is after the point of reuse, or // ii) its last use is also its first reuse but the operation // does not allow for local reuse. Operation *last_use = liveness->getEndOperation( old_buffer_alias, liveness->getStartOperation(old_buffer_alias)); if (first_reuse->isBeforeInBlock(last_use)) { livetimes_compatible = false; break; } if (first_reuse == last_use && !can_reuse_locally(first_reuse, old_buffer_alias, new_buffer)) { livetimes_compatible = false; break; } } } // All criteria are fulfilled 🙂. if (livetimes_compatible) local_reuse_candidates.push_back(old_buffer_index); } reuse_candidates_[&op] = local_reuse_candidates; } } Operation *find_first_use_in_block(Value value, Block *block) { Operation *first_use = nullptr; for (Operation *op : value.getUsers()) { Operation *ancestor_op = block->findAncestorOpInBlock(*op); if (ancestor_op == nullptr) continue; if (first_use == nullptr || ancestor_op->isBeforeInBlock(first_use)) first_use = ancestor_op; } return first_use; } std::vector<Value> get_buffer_arguments(FuncOp &f) { std::vector<Value> buffer_arguments; for (BlockArgument arg : f.getArguments()) { if (arg.getType().isa<BaseMemRefType>()) buffer_arguments.push_back(arg); } return buffer_arguments; } bool can_reuse_locally(Operation *op, Value old_buffer, Value new_buffer) { // For now, we support only memrefs with the same memory layout. auto old_buffer_ty = old_buffer.getType().dyn_cast<MemRefType>(); auto new_buffer_ty = old_buffer.getType().dyn_cast<MemRefType>(); if (!old_buffer_ty || !new_buffer_ty || old_buffer_ty.getAffineMaps() != new_buffer_ty.getAffineMaps()) return false; if (auto generic_op = dyn_cast<linalg::GenericOp>(op)) { assert(llvm::find(op->getOperands(), old_buffer) != op->getOperands().end() && llvm::find(op->getOperands(), new_buffer) != op->getOperands().end() && "expect `old/new_buffer` to be operand of `op`"); // If `linalg.generic` indexing maps are the same for input and output // buffer then the last use of the input buffer happens before its first // reuse (per memory location). auto operand_buffers = generic_op.getInputsAndOutputBuffers(); int old_index = llvm::find(operand_buffers, old_buffer) - operand_buffers.begin(); int new_index = llvm::find(operand_buffers, new_buffer) - operand_buffers.begin(); AffineMap old_indexing_map = generic_op.getIndexingMap(old_index); AffineMap new_indexing_map = generic_op.getIndexingMap(new_index); return old_indexing_map == new_indexing_map && old_indexing_map.isPermutation(); } return false; } DenseMap<Operation *, SmallVector<int64_t, 2>> reuse_candidates_; DenseMap<Operation *, int64_t> output_indices_; }; #define GEN_PASS_CLASSES #include "tensorflow/compiler/mlir/tools/kernel_gen/transforms/kernel_gen_passes.h.inc" struct BufferReusePass : public BufferReusePassBase<BufferReusePass> { void runOnFunction() override { if (!getFunction().getAttrOfType<UnitAttr>( tf_framework::TFFrameworkDialect::kTFEntryAttrName)) return; BufferReuseAnalysis analysis(getFunction()); // Annotate IR with reuse candidates and output indices per allocation. Builder builder(&getContext()); auto reuse_output_attr_name = tf_framework::TFAllocOp::kReuseOutputAttrName; auto reuse_input_candidates_attr_name = tf_framework::TFAllocOp::kReuseInputCandidatesAttrName; getFunction().walk([&](AllocOp op) { if (auto output_index = analysis.get_output_index(op)) { auto attr = builder.getIndexAttr(*output_index); op.getOperation()->setAttr(reuse_output_attr_name, attr); } if (auto reuse_candiates = analysis.get_reuse_candiates(op)) { auto attr = builder.getIndexArrayAttr(*reuse_candiates); op.getOperation()->setAttr(reuse_input_candidates_attr_name, attr); } }); } }; } // namespace std::unique_ptr<FunctionPass> CreateBufferReusePass() { return std::make_unique<BufferReusePass>(); } } // namespace transforms } // namespace kernel_gen } // namespace mlir
/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include <cstddef> #include <vector> #include "llvm/ADT/EquivalenceClasses.h" #include "llvm/ADT/None.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/SmallVector.h" #include "mlir/Analysis/BufferAliasAnalysis.h" // from @llvm-project #include "mlir/Analysis/Liveness.h" // from @llvm-project #include "mlir/Dialect/Linalg/IR/LinalgOps.h" // from @llvm-project #include "mlir/Dialect/StandardOps/IR/Ops.h" // from @llvm-project #include "mlir/IR/AffineMap.h" // from @llvm-project #include "mlir/IR/Function.h" // from @llvm-project #include "mlir/IR/Operation.h" // from @llvm-project #include "mlir/IR/StandardTypes.h" // from @llvm-project #include "tensorflow/compiler/mlir/hlo/include/mlir-hlo/Dialect/mhlo/IR/lhlo_ops.h" #include "tensorflow/compiler/mlir/tools/kernel_gen/ir/tf_framework_ops.h" #include "tensorflow/compiler/mlir/tools/kernel_gen/transforms/passes.h" #include "tensorflow/compiler/mlir/tools/kernel_gen/transforms/rewriters.h" // Needed to build `llvm::EquivalenceClasses` of `mlir::Value`s. namespace mlir { static bool operator<(const Value &lhs, const Value &rhs) { return lhs.getAsOpaquePointer() < rhs.getAsOpaquePointer(); } } // namespace mlir constexpr llvm::StringRef mlir::kernel_gen::tf_framework::TFAllocOp::kReuseOutputAttrName; constexpr llvm::StringRef mlir::kernel_gen::tf_framework::TFAllocOp::kReuseInputCandidatesAttrName; constexpr llvm::StringRef mlir::kernel_gen::tf_framework::TFFrameworkDialect::kTFEntryAttrName; namespace mlir { namespace kernel_gen { namespace transforms { namespace { // TODO(frgossen): Move this to MLIR. static void walkBlocks(Operation *op, std::function<void(Block &)> callback) { for (Region &region : op->getRegions()) { for (Block &block : region) { callback(block); for (Operation &nested_op : block) walkBlocks(&nested_op, callback); } } } /// A temporary buffer size analysis that is correct but may be incomplete. class BufferSizeAnalysis { public: explicit BufferSizeAnalysis(FuncOp f) { build(f); } bool is_same_size(Value a, Value b) { return ecs_.isEquivalent(a, b); } private: void build(FuncOp &f) { auto buffers = find_buffer_values(f); // Memrefs with statically known same shape must be of the same size. int n = buffers.size(); for (int i = 0; i < n; ++i) { for (int j = i + 1; j < n; ++j) { Value a = buffers[i]; Value b = buffers[j]; auto a_ty = a.getType().dyn_cast<MemRefType>(); auto b_ty = b.getType().dyn_cast<MemRefType>(); if (a_ty && b_ty && a_ty.hasStaticShape() && b_ty.hasStaticShape() && a_ty.getSizeInBits() == b_ty.getSizeInBits() && a_ty.getAffineMaps() == b_ty.getAffineMaps()) { ecs_.unionSets(a, b); } } } // Operands to `linalg.generic` with equal affine maps must be of same size. f.walk([&](linalg::GenericOp genericOp) { auto operand_buffers = genericOp.getInputsAndOutputBuffers(); int n = operand_buffers.size(); for (int i = 0; i < n; ++i) { for (int j = i + 1; j < n; ++j) { Value a = operand_buffers[i]; Value b = operand_buffers[j]; auto a_ty = a.getType().dyn_cast<MemRefType>(); auto b_ty = b.getType().dyn_cast<MemRefType>(); if (a_ty && b_ty && a_ty.getElementType() == b_ty.getElementType() && a_ty.getAffineMaps() == b_ty.getAffineMaps()) { AffineMap map_i = genericOp.getIndexingMap(i); AffineMap map_j = genericOp.getIndexingMap(j); if (map_i == map_j && map_i.isPermutation()) ecs_.unionSets(a, b); } } } }); // Operand and result of `reshape_memref_cast` must be of same size. f.walk([&](lmhlo::ReshapeMemRefCastOp reshapeOp) { ecs_.unionSets(reshapeOp.result(), reshapeOp.operand()); }); } llvm::SmallVector<Value, 8> find_buffer_values(FuncOp f) { llvm::SmallVector<Value, 8> buffers; f.walk([&](Operation *op) { for (Value val : op->getResults()) if (val.getType().isa<BaseMemRefType>()) buffers.push_back(val); }); walkBlocks(f.getOperation(), [&](Block &block) { for (Value val : block.getArguments()) { if (val.getType().isa<BaseMemRefType>()) buffers.push_back(val); } }); return buffers; } llvm::EquivalenceClasses<Value> ecs_; }; class BufferReuseAnalysis { public: explicit BufferReuseAnalysis(FuncOp f) { build(f); } static constexpr int kIndexAmbiguous = -1; Optional<SmallVector<int64_t, 2>> get_reuse_candiates(AllocOp op) { auto it = reuse_candidates_.find(op); if (it == reuse_candidates_.end()) return llvm::None; return it->second; } Optional<int64_t> get_output_index(AllocOp op) { auto it = output_indices_.find(op); if (it == output_indices_.end()) return llvm::None; return it->second; } private: void build(FuncOp &f) { BufferAliasAnalysis aliases(f); find_output_indices(f, aliases); find_reuse_candiates(f, aliases); } void find_output_indices(FuncOp &f, BufferAliasAnalysis &aliases) { f.walk([&](AllocOp alloc_op) { int64_t output_index = kIndexAmbiguous; int count_return_uses = 0; auto buffer_aliases = aliases.resolve(alloc_op.getResult()); for (Value alias : buffer_aliases) { for (auto &use : alias.getUses()) { if (isa<ReturnOp>(use.getOwner())) { int64_t index = use.getOperandNumber(); if (count_return_uses++ == 0) output_index = index; else if (output_index != index) output_index = kIndexAmbiguous; } } } output_indices_[alloc_op] = output_index; }); } void find_reuse_candiates(FuncOp &f, BufferAliasAnalysis &aliases) { Liveness liveness(f); BufferSizeAnalysis size_equivalences(f); walkBlocks(f.getOperation(), [&](Block &block) { find_reuse_candiates(block, aliases, liveness.getLiveness(&block), size_equivalences, f.getArguments()); }); } void find_reuse_candiates(Block &block, BufferAliasAnalysis &aliases, const LivenessBlockInfo *liveness, BufferSizeAnalysis &size_equivalences, ArrayRef<BlockArgument> arguments) { for (Operation &op : block) { auto alloc_op = dyn_cast<AllocOp>(op); if (!alloc_op) continue; // Find first use of the newly allocated buffer within this block. Value new_buffer = alloc_op.getResult(); Operation *first_reuse = find_first_use_in_block( new_buffer, alloc_op.getOperation()->getBlock()); // Find reuse candidates for the regarded allocation. SmallVector<int64_t, 2> local_reuse_candidates; for (auto it : llvm::enumerate(arguments)) { int64_t old_buffer_index = it.index(); Value old_buffer = it.value(); if (!old_buffer.getType().isa<BaseMemRefType>()) continue; // Will not reuse buffers of different size as they may be too small. if (!size_equivalences.is_same_size(new_buffer, old_buffer)) continue; // Only reuse buffers that are no longer used on first reuse, i.e. they // are no longer alive. bool livetimes_compatible = true; for (Value old_buffer_alias : aliases.resolve(old_buffer)) { if (first_reuse == nullptr) { // If the first use is beyond the end of this block we look at the // block end. An argument buffer that is already reusable there is // certainly reusable at any later actual use. if (liveness->isLiveOut(old_buffer_alias)) { livetimes_compatible = false; break; } } else { // A buffer is *not* reusable if // i) its last use is after the point of reuse, or // ii) its last use is also its first reuse but the operation // does not allow for local reuse. Operation *last_use = liveness->getEndOperation( old_buffer_alias, liveness->getStartOperation(old_buffer_alias)); if (first_reuse->isBeforeInBlock(last_use)) { livetimes_compatible = false; break; } if (first_reuse == last_use && !can_reuse_locally(first_reuse, old_buffer_alias, new_buffer)) { livetimes_compatible = false; break; } } } // All criteria are fulfilled 🙂. if (livetimes_compatible) local_reuse_candidates.push_back(old_buffer_index); } reuse_candidates_[&op] = local_reuse_candidates; } } Operation *find_first_use_in_block(Value value, Block *block) { Operation *first_use = nullptr; for (Operation *op : value.getUsers()) { Operation *ancestor_op = block->findAncestorOpInBlock(*op); if (ancestor_op == nullptr) continue; if (first_use == nullptr || ancestor_op->isBeforeInBlock(first_use)) first_use = ancestor_op; } return first_use; } std::vector<Value> get_buffer_arguments(FuncOp &f) { std::vector<Value> buffer_arguments; for (BlockArgument arg : f.getArguments()) { if (arg.getType().isa<BaseMemRefType>()) buffer_arguments.push_back(arg); } return buffer_arguments; } bool can_reuse_locally(Operation *op, Value old_buffer, Value new_buffer) { // For now, we support only memrefs with the same memory layout. auto old_buffer_ty = old_buffer.getType().dyn_cast<MemRefType>(); auto new_buffer_ty = old_buffer.getType().dyn_cast<MemRefType>(); if (!old_buffer_ty || !new_buffer_ty || old_buffer_ty.getAffineMaps() != new_buffer_ty.getAffineMaps()) return false; if (auto generic_op = dyn_cast<linalg::GenericOp>(op)) { assert(llvm::find(op->getOperands(), old_buffer) != op->getOperands().end() && llvm::find(op->getOperands(), new_buffer) != op->getOperands().end() && "expect `old/new_buffer` to be operand of `op`"); // If `linalg.generic` indexing maps are the same for input and output // buffer then the last use of the input buffer happens before its first // reuse (per memory location). auto operand_buffers = generic_op.getInputsAndOutputBuffers(); int old_index = llvm::find(operand_buffers, old_buffer) - operand_buffers.begin(); int new_index = llvm::find(operand_buffers, new_buffer) - operand_buffers.begin(); AffineMap old_indexing_map = generic_op.getIndexingMap(old_index); AffineMap new_indexing_map = generic_op.getIndexingMap(new_index); return old_indexing_map == new_indexing_map && old_indexing_map.isPermutation(); } return false; } DenseMap<Operation *, SmallVector<int64_t, 2>> reuse_candidates_; DenseMap<Operation *, int64_t> output_indices_; }; #define GEN_PASS_CLASSES #include "tensorflow/compiler/mlir/tools/kernel_gen/transforms/kernel_gen_passes.h.inc" struct BufferReusePass : public BufferReusePassBase<BufferReusePass> { void runOnFunction() override { if (!getFunction().getAttrOfType<UnitAttr>( tf_framework::TFFrameworkDialect::kTFEntryAttrName)) return; BufferReuseAnalysis analysis(getFunction()); // Annotate IR with reuse candidates and output indices per allocation. Builder builder(&getContext()); getFunction().walk([&](AllocOp op) { if (auto output_index = analysis.get_output_index(op)) { auto attr = builder.getIndexAttr(*output_index); op.getOperation()->setAttr( tf_framework::TFAllocOp::kReuseOutputAttrName, attr); } if (auto reuse_candiates = analysis.get_reuse_candiates(op)) { auto attr = builder.getIndexArrayAttr(*reuse_candiates); op.getOperation()->setAttr( tf_framework::TFAllocOp::kReuseInputCandidatesAttrName, attr); } }); } }; } // namespace std::unique_ptr<FunctionPass> CreateBufferReusePass() { return std::make_unique<BufferReusePass>(); } } // namespace transforms } // namespace kernel_gen } // namespace mlir
Use constexpr in a C++14-compliant way
[MLIR][KernelGen] Use constexpr in a C++14-compliant way PiperOrigin-RevId: 339883324 Change-Id: I9b8cbe92bfa2bd279be4d72ca9a40b894f7fcaa7
C++
apache-2.0
frreiss/tensorflow-fred,annarev/tensorflow,karllessard/tensorflow,Intel-Corporation/tensorflow,Intel-tensorflow/tensorflow,gautam1858/tensorflow,tensorflow/tensorflow-pywrap_saved_model,cxxgtxy/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow-pywrap_saved_model,petewarden/tensorflow,tensorflow/tensorflow,petewarden/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,paolodedios/tensorflow,annarev/tensorflow,paolodedios/tensorflow,tensorflow/tensorflow,tensorflow/tensorflow-pywrap_saved_model,karllessard/tensorflow,paolodedios/tensorflow,gautam1858/tensorflow,freedomtan/tensorflow,Intel-tensorflow/tensorflow,tensorflow/tensorflow,Intel-tensorflow/tensorflow,frreiss/tensorflow-fred,tensorflow/tensorflow,paolodedios/tensorflow,freedomtan/tensorflow,yongtang/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow-pywrap_tf_optimizer,Intel-tensorflow/tensorflow,freedomtan/tensorflow,frreiss/tensorflow-fred,yongtang/tensorflow,sarvex/tensorflow,frreiss/tensorflow-fred,karllessard/tensorflow,tensorflow/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow-pywrap_tf_optimizer,petewarden/tensorflow,gautam1858/tensorflow,cxxgtxy/tensorflow,petewarden/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow-experimental_link_static_libraries_once,karllessard/tensorflow,cxxgtxy/tensorflow,paolodedios/tensorflow,gautam1858/tensorflow,gautam1858/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,yongtang/tensorflow,freedomtan/tensorflow,karllessard/tensorflow,cxxgtxy/tensorflow,Intel-tensorflow/tensorflow,freedomtan/tensorflow,Intel-Corporation/tensorflow,karllessard/tensorflow,petewarden/tensorflow,tensorflow/tensorflow-pywrap_saved_model,freedomtan/tensorflow,annarev/tensorflow,sarvex/tensorflow,yongtang/tensorflow,Intel-tensorflow/tensorflow,tensorflow/tensorflow,tensorflow/tensorflow,petewarden/tensorflow,annarev/tensorflow,tensorflow/tensorflow,yongtang/tensorflow,petewarden/tensorflow,gautam1858/tensorflow,Intel-tensorflow/tensorflow,annarev/tensorflow,frreiss/tensorflow-fred,tensorflow/tensorflow-pywrap_saved_model,paolodedios/tensorflow,Intel-tensorflow/tensorflow,cxxgtxy/tensorflow,petewarden/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,frreiss/tensorflow-fred,sarvex/tensorflow,sarvex/tensorflow,annarev/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,petewarden/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,yongtang/tensorflow,yongtang/tensorflow,frreiss/tensorflow-fred,yongtang/tensorflow,karllessard/tensorflow,karllessard/tensorflow,tensorflow/tensorflow-pywrap_saved_model,gautam1858/tensorflow,frreiss/tensorflow-fred,Intel-Corporation/tensorflow,annarev/tensorflow,annarev/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,annarev/tensorflow,tensorflow/tensorflow-pywrap_saved_model,karllessard/tensorflow,Intel-Corporation/tensorflow,tensorflow/tensorflow,freedomtan/tensorflow,tensorflow/tensorflow-pywrap_saved_model,freedomtan/tensorflow,gautam1858/tensorflow,karllessard/tensorflow,karllessard/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,sarvex/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,paolodedios/tensorflow,tensorflow/tensorflow,frreiss/tensorflow-fred,paolodedios/tensorflow,gautam1858/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,Intel-Corporation/tensorflow,petewarden/tensorflow,yongtang/tensorflow,yongtang/tensorflow,paolodedios/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,gautam1858/tensorflow,Intel-Corporation/tensorflow,gautam1858/tensorflow,freedomtan/tensorflow,cxxgtxy/tensorflow,Intel-Corporation/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,freedomtan/tensorflow,cxxgtxy/tensorflow,frreiss/tensorflow-fred,Intel-tensorflow/tensorflow,paolodedios/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow-pywrap_saved_model,Intel-tensorflow/tensorflow,Intel-Corporation/tensorflow,frreiss/tensorflow-fred,gautam1858/tensorflow,tensorflow/tensorflow-pywrap_saved_model,frreiss/tensorflow-fred,tensorflow/tensorflow-pywrap_tf_optimizer,petewarden/tensorflow,sarvex/tensorflow,yongtang/tensorflow,paolodedios/tensorflow,petewarden/tensorflow,sarvex/tensorflow,cxxgtxy/tensorflow,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow,annarev/tensorflow,Intel-tensorflow/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,annarev/tensorflow,sarvex/tensorflow,freedomtan/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,freedomtan/tensorflow
a92fa56b4de87acf4f90cc93ff2697035209c3a1
TelepathyQt/Farstream/channel.cpp
TelepathyQt/Farstream/channel.cpp
/** * This file is part of TelepathyQt * * Copyright © 2009-2012 Collabora Ltd. <http://www.collabora.co.uk/> * Copyright © 2009 Nokia Corporation * * 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 */ #include <TelepathyQt/Farstream/Channel> #include "TelepathyQt/Farstream/_gen/channel.moc.hpp" #include "TelepathyQt/debug-internal.h" #include <TelepathyQt/CallChannel> #include <TelepathyQt/Connection> #include <telepathy-farstream/telepathy-farstream.h> #include <telepathy-glib/channel.h> #include <telepathy-glib/connection.h> #include <telepathy-glib/dbus.h> namespace Tp { namespace Farstream { struct TP_QT_FS_NO_EXPORT PendingChannel::Private { Private() : mTfChannel(0) { } static void onTfChannelNewFinish(GObject *sourceObject, GAsyncResult *res, gpointer userData); TfChannel *mTfChannel; }; PendingChannel::PendingChannel(const CallChannelPtr &channel) : Tp::PendingOperation(channel), mPriv(new PendingChannel::Private) { if (!channel->handlerStreamingRequired()) { setFinishedWithError(TP_QT_ERROR_NOT_AVAILABLE, QLatin1String("Handler streaming not required")); return; } TpDBusDaemon *dbus = tp_dbus_daemon_dup(0); if (!dbus) { setFinishedWithError(TP_QT_ERROR_NOT_AVAILABLE, QLatin1String("Unable to connect to D-Bus")); return; } Tp::ConnectionPtr connection = channel->connection(); if (connection.isNull()) { setFinishedWithError(TP_QT_ERROR_NOT_AVAILABLE, QLatin1String("Connection not available")); g_object_unref(dbus); return; } TpConnection *gconnection = tp_connection_new(dbus, connection->busName().toAscii(), connection->objectPath().toAscii(), 0); g_object_unref(dbus); dbus = 0; if (!gconnection) { setFinishedWithError(TP_QT_ERROR_NOT_AVAILABLE, QLatin1String("Unable to construct TpConnection")); return; } TpChannel *gchannel = tp_channel_new(gconnection, channel->objectPath().toAscii(), TP_QT_IFACE_CHANNEL_TYPE_CALL.latin1(), (TpHandleType) channel->targetHandleType(), channel->targetHandle(), 0); g_object_unref(gconnection); gconnection = 0; if (!gchannel) { setFinishedWithError(TP_QT_ERROR_NOT_AVAILABLE, QLatin1String("Unable to construct TpChannel")); return; } tf_channel_new_async(gchannel, PendingChannel::Private::onTfChannelNewFinish, this); g_object_unref(gchannel); } PendingChannel::~PendingChannel() { delete mPriv; } void PendingChannel::Private::onTfChannelNewFinish(GObject *sourceObject, GAsyncResult *res, gpointer userData) { PendingChannel *self = reinterpret_cast<PendingChannel *>(userData); GError *error = NULL; TfChannel *ret = tf_channel_new_finish(sourceObject, res, &error); if (error) { debug() << "Fs::PendingChannel::Private::onTfChannelNewFinish: error " << error->message; self->setFinishedWithError(TP_QT_ERROR_NOT_AVAILABLE, QLatin1String(error->message)); g_clear_error(&error); return; } self->mPriv->mTfChannel = ret; self->setFinished(); } TfChannel *PendingChannel::tfChannel() const { return mPriv->mTfChannel; } CallChannelPtr PendingChannel::callChannel() const { return CallChannelPtr::staticCast(object()); } PendingChannel *createChannel(const CallChannelPtr &channel) { PendingChannel *ptf = new PendingChannel(channel); return ptf; } } // Farstream } // Tp
/** * This file is part of TelepathyQt * * Copyright © 2009-2012 Collabora Ltd. <http://www.collabora.co.uk/> * Copyright © 2009 Nokia Corporation * * 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 */ #include <TelepathyQt/Farstream/Channel> #include "TelepathyQt/Farstream/_gen/channel.moc.hpp" #include "TelepathyQt/debug-internal.h" #include <TelepathyQt/CallChannel> #include <TelepathyQt/Connection> #include <telepathy-farstream/telepathy-farstream.h> #include <telepathy-glib/channel.h> #include <telepathy-glib/connection.h> #include <telepathy-glib/dbus.h> namespace Tp { namespace Farstream { struct TP_QT_FS_NO_EXPORT PendingChannel::Private { Private() : mTfChannel(0) { } static void onTfChannelNewFinish(GObject *sourceObject, GAsyncResult *res, gpointer userData); TfChannel *mTfChannel; }; PendingChannel::PendingChannel(const CallChannelPtr &channel) : Tp::PendingOperation(channel), mPriv(new PendingChannel::Private) { if (!channel->handlerStreamingRequired()) { warning() << "Handler streaming not required"; setFinishedWithError(TP_QT_ERROR_NOT_AVAILABLE, QLatin1String("Handler streaming not required")); return; } TpDBusDaemon *dbus = tp_dbus_daemon_dup(0); if (!dbus) { warning() << "Unable to connect to D-Bus"; setFinishedWithError(TP_QT_ERROR_NOT_AVAILABLE, QLatin1String("Unable to connect to D-Bus")); return; } Tp::ConnectionPtr connection = channel->connection(); if (connection.isNull()) { warning() << "Connection not available"; setFinishedWithError(TP_QT_ERROR_NOT_AVAILABLE, QLatin1String("Connection not available")); g_object_unref(dbus); return; } TpConnection *gconnection = tp_connection_new(dbus, connection->busName().toAscii(), connection->objectPath().toAscii(), 0); g_object_unref(dbus); dbus = 0; if (!gconnection) { warning() << "Unable to construct TpConnection"; setFinishedWithError(TP_QT_ERROR_NOT_AVAILABLE, QLatin1String("Unable to construct TpConnection")); return; } TpChannel *gchannel = tp_channel_new(gconnection, channel->objectPath().toAscii(), TP_QT_IFACE_CHANNEL_TYPE_CALL.latin1(), (TpHandleType) channel->targetHandleType(), channel->targetHandle(), 0); g_object_unref(gconnection); gconnection = 0; if (!gchannel) { warning() << "Unable to construct TpChannel"; setFinishedWithError(TP_QT_ERROR_NOT_AVAILABLE, QLatin1String("Unable to construct TpChannel")); return; } tf_channel_new_async(gchannel, PendingChannel::Private::onTfChannelNewFinish, this); g_object_unref(gchannel); } PendingChannel::~PendingChannel() { delete mPriv; } void PendingChannel::Private::onTfChannelNewFinish(GObject *sourceObject, GAsyncResult *res, gpointer userData) { PendingChannel *self = reinterpret_cast<PendingChannel *>(userData); GError *error = NULL; TfChannel *ret = tf_channel_new_finish(sourceObject, res, &error); if (error) { warning() << "Fs::PendingChannel::Private::onTfChannelNewFinish: error " << error->message; self->setFinishedWithError(TP_QT_ERROR_NOT_AVAILABLE, QLatin1String(error->message)); g_clear_error(&error); return; } self->mPriv->mTfChannel = ret; self->setFinished(); } TfChannel *PendingChannel::tfChannel() const { return mPriv->mTfChannel; } CallChannelPtr PendingChannel::callChannel() const { return CallChannelPtr::staticCast(object()); } PendingChannel *createChannel(const CallChannelPtr &channel) { PendingChannel *ptf = new PendingChannel(channel); return ptf; } } // Farstream } // Tp
Add some debug warnings in early returns
farstream: Add some debug warnings in early returns
C++
lgpl-2.1
freedesktop-unofficial-mirror/telepathy__telepathy-qt,freedesktop-unofficial-mirror/telepathy__telepathy-qt,TelepathyQt/telepathy-qt,special/telepathy-qt-upstream,tiagosh/telepathy-qt,TelepathyQt/telepathy-qt,special/telepathy-qt-upstream,TelepathyIM/telepathy-qt,tiagosh/telepathy-qt,TelepathyQt/telepathy-qt,freedesktop-unofficial-mirror/telepathy__telepathy-qt,anantkamath/telepathy-qt,freedesktop-unofficial-mirror/telepathy__telepathy-qt,freedesktop-unofficial-mirror/telepathy__telepathy-qt4,anantkamath/telepathy-qt,TelepathyIM/telepathy-qt,detrout/telepathy-qt,tiagosh/telepathy-qt,detrout/telepathy-qt,TelepathyIM/telepathy-qt,TelepathyIM/telepathy-qt,anantkamath/telepathy-qt,detrout/telepathy-qt,tiagosh/telepathy-qt,TelepathyQt/telepathy-qt,freedesktop-unofficial-mirror/telepathy__telepathy-qt4,special/telepathy-qt-upstream,freedesktop-unofficial-mirror/telepathy__telepathy-qt4,freedesktop-unofficial-mirror/telepathy__telepathy-qt4,TelepathyIM/telepathy-qt
1cdac50af215da6d033099ded414716fd08f3c26
src/Nazara/Network/Win32/SocketPollerImpl.cpp
src/Nazara/Network/Win32/SocketPollerImpl.cpp
// Copyright (C) 2017 Jérôme Leclercq // This file is part of the "Nazara Engine - Network module" // For conditions of distribution and use, see copyright notice in Config.hpp #include <Nazara/Network/Win32/SocketPollerImpl.hpp> #include <Nazara/Network/Debug.hpp> namespace Nz { SocketPollerImpl::SocketPollerImpl() { #if !NAZARA_NETWORK_POLL_SUPPORT FD_ZERO(&m_readSockets); FD_ZERO(&m_readyToReadSockets); FD_ZERO(&m_readyToWriteSockets); FD_ZERO(&m_writeSockets); #endif } void SocketPollerImpl::Clear() { #if NAZARA_NETWORK_POLL_SUPPORT m_allSockets.clear(); m_readyToReadSockets.clear(); m_readyToWriteSockets.clear(); m_sockets.clear(); #else FD_ZERO(&m_readSockets); FD_ZERO(&m_readyToReadSockets); FD_ZERO(&m_readyToWriteSockets); FD_ZERO(&m_writeSockets); #endif } bool SocketPollerImpl::IsReadyToRead(SocketHandle socket) const { #if NAZARA_NETWORK_POLL_SUPPORT return m_readyToReadSockets.count(socket) != 0; #else return FD_ISSET(socket, &m_readyToReadSockets) != 0; #endif } bool SocketPollerImpl::IsReadyToWrite(SocketHandle socket) const { #if NAZARA_NETWORK_POLL_SUPPORT return m_readyToWriteSockets.count(socket) != 0; #else return FD_ISSET(socket, &m_readyToWriteSockets) != 0; #endif } bool SocketPollerImpl::IsRegistered(SocketHandle socket) const { #if NAZARA_NETWORK_POLL_SUPPORT return m_allSockets.count(socket) != 0; #else return FD_ISSET(socket, &m_readSockets) != 0 || FD_ISSET(socket, &m_writeSockets) != 0; #endif } bool SocketPollerImpl::RegisterSocket(SocketHandle socket, SocketPollEventFlags eventFlags) { NazaraAssert(!IsRegistered(socket), "Socket is already registered"); #if NAZARA_NETWORK_POLL_SUPPORT PollSocket entry = { socket, 0, 0 }; if (eventFlags & SocketPollEvent_Read) entry.events |= POLLRDNORM; if (eventFlags & SocketPollEvent_Write) entry.events |= POLLWRNORM; m_allSockets[socket] = m_sockets.size(); m_sockets.emplace_back(entry); #else for (std::size_t i = 0; i < 2; ++i) { if (eventFlags & ((i == 0) ? SocketPollEvent_Read : SocketPollEvent_Write) == 0) continue; fd_set& targetSet = (i == 0) ? m_readSockets : m_writeSockets; if (targetSet.fd_count > FD_SETSIZE) { NazaraError("Socket count exceeding hard-coded FD_SETSIZE (" + String::Number(FD_SETSIZE) + ")"); return false; } FD_SET(socket, &targetSet); } #endif return true; } void SocketPollerImpl::UnregisterSocket(SocketHandle socket) { NazaraAssert(IsRegistered(socket), "Socket is not registered"); #if NAZARA_NETWORK_POLL_SUPPORT if (m_sockets.size() > 1U) { // Instead of using vector::erase, let's move the last element to the now unoccupied position std::size_t entry = m_allSockets[socket]; // Get the last element and update it's position const PollSocket& lastElement = m_sockets.back(); m_allSockets[lastElement.fd] = entry; // Now move it properly (lastElement is invalid after the following line) and pop it m_sockets[entry] = std::move(m_sockets.back()); } m_sockets.pop_back(); m_allSockets.erase(socket); m_readyToReadSockets.erase(socket); m_readyToWriteSockets.erase(socket); #else FD_CLR(socket, &m_readSockets); FD_CLR(socket, &m_readyToReadSockets); FD_CLR(socket, &m_readyToWriteSockets); FD_CLR(socket, &m_writeSockets); #endif } int SocketPollerImpl::Wait(UInt64 msTimeout, SocketError* error) { int activeSockets; #if NAZARA_NETWORK_POLL_SUPPORT activeSockets = SocketImpl::Poll(m_sockets.data(), m_sockets.size(), static_cast<int>(msTimeout), error); x #else m_readyToReadSockets = m_readSockets; m_readyToWriteSockets = m_writeSockets; timeval tv; tv.tv_sec = static_cast<long>(msTimeout / 1000ULL); tv.tv_usec = static_cast<long>((msTimeout % 1000ULL) * 1000ULL); activeSockets = ::select(0xDEADBEEF, &m_readyToReadSockets, &m_readyToWriteSockets, nullptr, (msTimeout > 0) ? &tv : nullptr); //< The first argument is ignored on Windows if (activeSockets == SOCKET_ERROR) { if (error) *error = SocketImpl::TranslateWSAErrorToSocketError(WSAGetLastError()); return 0; } if (error) *error = SocketError_NoError; #endif return activeSockets; } }
// Copyright (C) 2017 Jérôme Leclercq // This file is part of the "Nazara Engine - Network module" // For conditions of distribution and use, see copyright notice in Config.hpp #include <Nazara/Network/Win32/SocketPollerImpl.hpp> #include <Nazara/Network/Debug.hpp> namespace Nz { SocketPollerImpl::SocketPollerImpl() { #if !NAZARA_NETWORK_POLL_SUPPORT FD_ZERO(&m_readSockets); FD_ZERO(&m_readyToReadSockets); FD_ZERO(&m_readyToWriteSockets); FD_ZERO(&m_writeSockets); #endif } void SocketPollerImpl::Clear() { #if NAZARA_NETWORK_POLL_SUPPORT m_allSockets.clear(); m_readyToReadSockets.clear(); m_readyToWriteSockets.clear(); m_sockets.clear(); #else FD_ZERO(&m_readSockets); FD_ZERO(&m_readyToReadSockets); FD_ZERO(&m_readyToWriteSockets); FD_ZERO(&m_writeSockets); #endif } bool SocketPollerImpl::IsReadyToRead(SocketHandle socket) const { #if NAZARA_NETWORK_POLL_SUPPORT return m_readyToReadSockets.count(socket) != 0; #else return FD_ISSET(socket, &m_readyToReadSockets) != 0; #endif } bool SocketPollerImpl::IsReadyToWrite(SocketHandle socket) const { #if NAZARA_NETWORK_POLL_SUPPORT return m_readyToWriteSockets.count(socket) != 0; #else return FD_ISSET(socket, &m_readyToWriteSockets) != 0; #endif } bool SocketPollerImpl::IsRegistered(SocketHandle socket) const { #if NAZARA_NETWORK_POLL_SUPPORT return m_allSockets.count(socket) != 0; #else return FD_ISSET(socket, &m_readSockets) != 0 || FD_ISSET(socket, &m_writeSockets) != 0; #endif } bool SocketPollerImpl::RegisterSocket(SocketHandle socket, SocketPollEventFlags eventFlags) { NazaraAssert(!IsRegistered(socket), "Socket is already registered"); #if NAZARA_NETWORK_POLL_SUPPORT PollSocket entry = { socket, 0, 0 }; if (eventFlags & SocketPollEvent_Read) entry.events |= POLLRDNORM; if (eventFlags & SocketPollEvent_Write) entry.events |= POLLWRNORM; m_allSockets[socket] = m_sockets.size(); m_sockets.emplace_back(entry); #else for (std::size_t i = 0; i < 2; ++i) { if ((eventFlags & ((i == 0) ? SocketPollEvent_Read : SocketPollEvent_Write)) == 0) continue; fd_set& targetSet = (i == 0) ? m_readSockets : m_writeSockets; if (targetSet.fd_count > FD_SETSIZE) { NazaraError("Socket count exceeding hard-coded FD_SETSIZE (" + String::Number(FD_SETSIZE) + ")"); return false; } FD_SET(socket, &targetSet); } #endif return true; } void SocketPollerImpl::UnregisterSocket(SocketHandle socket) { NazaraAssert(IsRegistered(socket), "Socket is not registered"); #if NAZARA_NETWORK_POLL_SUPPORT if (m_sockets.size() > 1U) { // Instead of using vector::erase, let's move the last element to the now unoccupied position std::size_t entry = m_allSockets[socket]; // Get the last element and update it's position const PollSocket& lastElement = m_sockets.back(); m_allSockets[lastElement.fd] = entry; // Now move it properly (lastElement is invalid after the following line) and pop it m_sockets[entry] = std::move(m_sockets.back()); } m_sockets.pop_back(); m_allSockets.erase(socket); m_readyToReadSockets.erase(socket); m_readyToWriteSockets.erase(socket); #else FD_CLR(socket, &m_readSockets); FD_CLR(socket, &m_readyToReadSockets); FD_CLR(socket, &m_readyToWriteSockets); FD_CLR(socket, &m_writeSockets); #endif } int SocketPollerImpl::Wait(UInt64 msTimeout, SocketError* error) { int activeSockets; #if NAZARA_NETWORK_POLL_SUPPORT activeSockets = SocketImpl::Poll(m_sockets.data(), m_sockets.size(), static_cast<int>(msTimeout), error); #else m_readyToReadSockets = m_readSockets; m_readyToWriteSockets = m_writeSockets; timeval tv; tv.tv_sec = static_cast<long>(msTimeout / 1000ULL); tv.tv_usec = static_cast<long>((msTimeout % 1000ULL) * 1000ULL); activeSockets = ::select(0xDEADBEEF, &m_readyToReadSockets, &m_readyToWriteSockets, nullptr, (msTimeout > 0) ? &tv : nullptr); //< The first argument is ignored on Windows if (activeSockets == SOCKET_ERROR) { if (error) *error = SocketImpl::TranslateWSAErrorToSocketError(WSAGetLastError()); return 0; } if (error) *error = SocketError_NoError; #endif return activeSockets; } }
Fix RegisterSocket on Windows
Network/SocketPoller: Fix RegisterSocket on Windows
C++
mit
DigitalPulseSoftware/NazaraEngine
d839f60367b86489f22b229144c9794db6370ce5
factory.cpp
factory.cpp
/* This file is part of the KDE project Copyright (C) 2004-2005 Matthias Kretz <[email protected]> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License version 2 as published by the Free Software Foundation. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include "factory.h" #include "ifaces/audiopath.h" #include "ifaces/audioeffect.h" #include "ifaces/volumefadereffect.h" #include "ifaces/audiooutput.h" #include "ifaces/audiodataoutput.h" #include "ifaces/videopath.h" #include "ifaces/videoeffect.h" #include "ifaces/backend.h" #include "ifaces/mediaobject.h" #include "ifaces/avcapture.h" #include "ifaces/bytestream.h" #include "base_p.h" #include <ktrader.h> #include <kservice.h> #include <klibloader.h> #include <kmessagebox.h> #include <QFile> #include <QList> #include <klocale.h> #include <kmimetype.h> #include <kdebug.h> #include <kstaticdeleter.h> static KStaticDeleter<Phonon::Factory> sd; namespace Phonon { class Factory::Private { public: Private() : backend( 0 ) { createBackend(); } void createBackend() { KTrader::OfferList offers = KTrader::self()->query( "PhononBackend", "Type == 'Service' AND [X-KDE-PhononBackendInfo-InterfaceVersion] == 1" ); KTrader::OfferListIterator it = offers.begin(); KTrader::OfferListIterator end = offers.end(); QStringList errormsg; for( ; it != end; ++it ) { KService::Ptr ptr = *it; KLibFactory * factory = KLibLoader::self()->factory( QFile::encodeName( ptr->library() ) ); if( factory ) { backend = ( Ifaces::Backend* )factory->create( 0, "Multimedia Backend", "Phonon::Ifaces::Backend" ); if( 0 == backend ) { QString e = i18n( "create method returned 0" ); errormsg.append( e ); kDebug( 600 ) << "Error getting backend from factory for " << ptr->name() << ":\n" << e << endl; } else { service = ptr; kDebug( 600 ) << "using backend: " << ptr->name() << endl; break; } } else { QString e = KLibLoader::self()->lastErrorMessage(); errormsg.append( e ); kDebug( 600 ) << "Error getting factory for " << ptr->name() << ":\n" << e << endl; } } if( 0 == backend ) { if( offers.size() == 0 ) KMessageBox::error( 0, i18n( "Unable to find a Multimedia Backend" ) ); else { QString details = "<qt><table>"; QStringList::Iterator eit = errormsg.begin(); QStringList::Iterator eend = errormsg.end(); KTrader::OfferListIterator oit = offers.begin(); KTrader::OfferListIterator oend = offers.end(); for( ; eit != eend || oit != oend; ++eit, ++oit ) details += QString( "<tr><td><b>%1</b></td><td>%2</td></tr>" ) .arg( ( *oit )->name() ).arg( *eit ); details += "</table></qt>"; KMessageBox::detailedError( 0, i18n( "Unable to use any of the available Multimedia Backends" ), details ); } } } Ifaces::Backend * backend; KService::Ptr service; QList<QObject*> objects; QList<BasePrivate*> basePrivateList; }; Factory * Factory::m_self = 0; Factory * Factory::self() { if( ! m_self ) { m_self = new Factory(); ::sd.setObject( m_self, m_self ); } return m_self; } Factory::Factory() : DCOPObject( "PhononFactory" ) , d( new Private ) { connectDCOPSignal( 0, 0, "phononBackendChanged()", "phononBackendChanged()", false); } Factory::~Factory() { //kDebug( 600 ) << k_funcinfo << endl; emit deleteYourObjects(); foreach( BasePrivate* bp, d->basePrivateList ) bp->deleteIface(); foreach( QObject* o, d->objects ) { //kDebug( 600 ) << "delete " << o << endl; delete o; } delete d->backend; delete d; } void Factory::registerFrontendObject( BasePrivate* bp ) { d->basePrivateList.append( bp ); } void Factory::deregisterFrontendObject( BasePrivate* bp ) { d->basePrivateList.removeAll( bp ); } void Factory::phononBackendChanged() { if( d->backend ) { emit deleteYourObjects(); foreach( BasePrivate* bp, d->basePrivateList ) bp->deleteIface(); if( d->objects.size() > 0 ) { kWarning( 600 ) << "we were asked to change the backend but the application did\n" "not free all references to objects created by the factory. Therefore we can not\n" "change the backend without crashing. Now we have to wait for a restart to make\n" "backendswitching possible." << endl; // in case there were objects deleted give 'em a chance to recreate // them now emit recreateObjects(); foreach( BasePrivate* bp, d->basePrivateList ) bp->createIface(); return; } delete d->backend; d->backend = 0; } d->createBackend(); emit recreateObjects(); foreach( BasePrivate* bp, d->basePrivateList ) bp->createIface(); emit backendChanged(); } //X void Factory::freeSoundcardDevices() //X { //X if( d->backend ) //X { //X d->backend->freeSoundcardDevices(); //X } //X } void Factory::objectDestroyed( QObject * obj ) { //kDebug( 600 ) << k_funcinfo << obj << endl; d->objects.removeAll( obj ); } #define FACTORY_IMPL( classname ) \ Ifaces::classname* Factory::create ## classname( QObject* parent ) \ { \ return d->backend ? registerObject( d->backend->create ## classname( parent ) ) : 0; \ } FACTORY_IMPL( MediaObject ) FACTORY_IMPL( AvCapture ) FACTORY_IMPL( ByteStream ) FACTORY_IMPL( AudioPath ) FACTORY_IMPL( AudioEffect ) FACTORY_IMPL( VolumeFaderEffect ) FACTORY_IMPL( AudioOutput ) FACTORY_IMPL( AudioDataOutput ) FACTORY_IMPL( VideoPath ) FACTORY_IMPL( VideoEffect ) #undef FACTORY_IMPL const Ifaces::Backend* Factory::backend() const { return d->backend; } const char* Factory::uiLibrary() const { if( !d->backend ) return 0; return d->backend->uiLibrary(); } const char* Factory::uiSymbol() const { if( !d->backend ) return 0; return d->backend->uiSymbol(); } #if 0 bool Factory::isMimeTypePlayable( const QString & type ) const { if( d->backend ) { KMimeType::Ptr mimetype = KMimeType::mimeType( type ); QStringList mimetypes = playableMimeTypes(); for( QStringList::ConstIterator i=mimetypes.begin(); i!=mimetypes.end(); i++ ) if( mimetype->is( *i ) ) return true; } return false; } #endif QString Factory::backendName() const { if( d->service ) return d->service->name(); else return QString(); } QString Factory::backendComment() const { if( d->service ) return d->service->comment(); else return QString(); } QString Factory::backendVersion() const { if( d->service ) return d->service->property( "X-KDE-PhononBackendInfo-Version" ).toString(); else return QString(); } QString Factory::backendIcon() const { if( d->service ) return d->service->icon(); else return QString(); } QString Factory::backendWebsite() const { if( d->service ) return d->service->property( "X-KDE-PhononBackendInfo-Website" ).toString(); else return QString(); } template<class T> inline T* Factory::registerObject( T* o ) { registerQObject( o->qobject() ); return o; } void Factory::registerQObject( QObject* o ) { connect( o, SIGNAL( destroyed( QObject* ) ), SLOT( objectDestroyed( QObject* ) ) ); d->objects.append( o ); } } //namespace Phonon #include "factory.moc" // vim: sw=4 ts=4 noet
/* This file is part of the KDE project Copyright (C) 2004-2005 Matthias Kretz <[email protected]> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License version 2 as published by the Free Software Foundation. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include "factory.h" #include "ifaces/audiopath.h" #include "ifaces/audioeffect.h" #include "ifaces/volumefadereffect.h" #include "ifaces/audiooutput.h" #include "ifaces/audiodataoutput.h" #include "ifaces/videopath.h" #include "ifaces/videoeffect.h" #include "ifaces/backend.h" #include "ifaces/mediaobject.h" #include "ifaces/avcapture.h" #include "ifaces/bytestream.h" #include "base_p.h" #include <ktrader.h> #include <kservice.h> #include <klibloader.h> #include <kmessagebox.h> #include <QFile> #include <QList> #include <klocale.h> #include <kmimetype.h> #include <kdebug.h> #include <kstaticdeleter.h> static KStaticDeleter<Phonon::Factory> sd; namespace Phonon { class Factory::Private { public: Private() : backend( 0 ) { createBackend(); } void createBackend() { KTrader::OfferList offers = KTrader::self()->query( "PhononBackend", "Type == 'Service' and [X-KDE-PhononBackendInfo-InterfaceVersion] == 1" ); KTrader::OfferListIterator it = offers.begin(); KTrader::OfferListIterator end = offers.end(); QStringList errormsg; for( ; it != end; ++it ) { KService::Ptr ptr = *it; KLibFactory * factory = KLibLoader::self()->factory( QFile::encodeName( ptr->library() ) ); if( factory ) { backend = ( Ifaces::Backend* )factory->create( 0, "Multimedia Backend", "Phonon::Ifaces::Backend" ); if( 0 == backend ) { QString e = i18n( "create method returned 0" ); errormsg.append( e ); kDebug( 600 ) << "Error getting backend from factory for " << ptr->name() << ":\n" << e << endl; } else { service = ptr; kDebug( 600 ) << "using backend: " << ptr->name() << endl; break; } } else { QString e = KLibLoader::self()->lastErrorMessage(); errormsg.append( e ); kDebug( 600 ) << "Error getting factory for " << ptr->name() << ":\n" << e << endl; } } if( 0 == backend ) { if( offers.size() == 0 ) KMessageBox::error( 0, i18n( "Unable to find a Multimedia Backend" ) ); else { QString details = "<qt><table>"; QStringList::Iterator eit = errormsg.begin(); QStringList::Iterator eend = errormsg.end(); KTrader::OfferListIterator oit = offers.begin(); KTrader::OfferListIterator oend = offers.end(); for( ; eit != eend || oit != oend; ++eit, ++oit ) details += QString( "<tr><td><b>%1</b></td><td>%2</td></tr>" ) .arg( ( *oit )->name() ).arg( *eit ); details += "</table></qt>"; KMessageBox::detailedError( 0, i18n( "Unable to use any of the available Multimedia Backends" ), details ); } } } Ifaces::Backend * backend; KService::Ptr service; QList<QObject*> objects; QList<BasePrivate*> basePrivateList; }; Factory * Factory::m_self = 0; Factory * Factory::self() { if( ! m_self ) { m_self = new Factory(); ::sd.setObject( m_self, m_self ); } return m_self; } Factory::Factory() : DCOPObject( "PhononFactory" ) , d( new Private ) { connectDCOPSignal( 0, 0, "phononBackendChanged()", "phononBackendChanged()", false); } Factory::~Factory() { //kDebug( 600 ) << k_funcinfo << endl; emit deleteYourObjects(); foreach( BasePrivate* bp, d->basePrivateList ) bp->deleteIface(); foreach( QObject* o, d->objects ) { //kDebug( 600 ) << "delete " << o << endl; delete o; } delete d->backend; delete d; } void Factory::registerFrontendObject( BasePrivate* bp ) { d->basePrivateList.append( bp ); } void Factory::deregisterFrontendObject( BasePrivate* bp ) { d->basePrivateList.removeAll( bp ); } void Factory::phononBackendChanged() { if( d->backend ) { emit deleteYourObjects(); foreach( BasePrivate* bp, d->basePrivateList ) bp->deleteIface(); if( d->objects.size() > 0 ) { kWarning( 600 ) << "we were asked to change the backend but the application did\n" "not free all references to objects created by the factory. Therefore we can not\n" "change the backend without crashing. Now we have to wait for a restart to make\n" "backendswitching possible." << endl; // in case there were objects deleted give 'em a chance to recreate // them now emit recreateObjects(); foreach( BasePrivate* bp, d->basePrivateList ) bp->createIface(); return; } delete d->backend; d->backend = 0; } d->createBackend(); emit recreateObjects(); foreach( BasePrivate* bp, d->basePrivateList ) bp->createIface(); emit backendChanged(); } //X void Factory::freeSoundcardDevices() //X { //X if( d->backend ) //X { //X d->backend->freeSoundcardDevices(); //X } //X } void Factory::objectDestroyed( QObject * obj ) { //kDebug( 600 ) << k_funcinfo << obj << endl; d->objects.removeAll( obj ); } #define FACTORY_IMPL( classname ) \ Ifaces::classname* Factory::create ## classname( QObject* parent ) \ { \ return d->backend ? registerObject( d->backend->create ## classname( parent ) ) : 0; \ } FACTORY_IMPL( MediaObject ) FACTORY_IMPL( AvCapture ) FACTORY_IMPL( ByteStream ) FACTORY_IMPL( AudioPath ) FACTORY_IMPL( AudioEffect ) FACTORY_IMPL( VolumeFaderEffect ) FACTORY_IMPL( AudioOutput ) FACTORY_IMPL( AudioDataOutput ) FACTORY_IMPL( VideoPath ) FACTORY_IMPL( VideoEffect ) #undef FACTORY_IMPL const Ifaces::Backend* Factory::backend() const { return d->backend; } const char* Factory::uiLibrary() const { if( !d->backend ) return 0; return d->backend->uiLibrary(); } const char* Factory::uiSymbol() const { if( !d->backend ) return 0; return d->backend->uiSymbol(); } #if 0 bool Factory::isMimeTypePlayable( const QString & type ) const { if( d->backend ) { KMimeType::Ptr mimetype = KMimeType::mimeType( type ); QStringList mimetypes = playableMimeTypes(); for( QStringList::ConstIterator i=mimetypes.begin(); i!=mimetypes.end(); i++ ) if( mimetype->is( *i ) ) return true; } return false; } #endif QString Factory::backendName() const { if( d->service ) return d->service->name(); else return QString(); } QString Factory::backendComment() const { if( d->service ) return d->service->comment(); else return QString(); } QString Factory::backendVersion() const { if( d->service ) return d->service->property( "X-KDE-PhononBackendInfo-Version" ).toString(); else return QString(); } QString Factory::backendIcon() const { if( d->service ) return d->service->icon(); else return QString(); } QString Factory::backendWebsite() const { if( d->service ) return d->service->property( "X-KDE-PhononBackendInfo-Website" ).toString(); else return QString(); } template<class T> inline T* Factory::registerObject( T* o ) { registerQObject( o->qobject() ); return o; } void Factory::registerQObject( QObject* o ) { connect( o, SIGNAL( destroyed( QObject* ) ), SLOT( objectDestroyed( QObject* ) ) ); d->objects.append( o ); } } //namespace Phonon #include "factory.moc" // vim: sw=4 ts=4 noet
correct trader syntax
correct trader syntax svn path=/trunk/KDE/kdelibs/phonon/; revision=525245
C++
lgpl-2.1
sandsmark/phonon-visualization-gsoc,sandsmark/phonon-visualization-gsoc,sandsmark/phonon-visualization-gsoc,sandsmark/phonon-visualization-gsoc
ee1036e988ffe0260a88a9665a7d7ab05e64e478
src/algebra/MatrixBase.cpp
src/algebra/MatrixBase.cpp
/*********************************************** * Author: Jun Jiang - [email protected] * Create: 2017-07-25 16:33 * Last modified : 2017-07-25 16:33 * Filename : Matrix.h * Description : Base Data Structure **********************************************/ #include "algebra/Matrix.h" #include "algebra/MatrixHelper.h" #include "utils/ParallelOperator.h" #include <random> #include <string.h> #include <iostream> #include <stdio.h> using abcdl::utils::ParallelOperator; namespace abcdl{ namespace algebra{ template<class T> Matrix<T>::Matrix(){ _rows = 0; _cols = 0; _data = nullptr; } template<class T> Matrix<T>::Matrix(const Matrix<T>& mat){ _rows = mat.rows(); _cols = mat.cols(); _data = new T[_rows * _cols]; memcpy(_data, mat.data(), sizeof(T) * _rows * _cols); } template<class T> Matrix<T>::Matrix(const size_t rows, const size_t cols){ _rows = rows; _cols = cols; _data = new T[_rows * _cols]; memset(_data, 0, sizeof(T) * _rows * _cols); } template<class T> Matrix<T>::Matrix(const T& value, const size_t rows, const size_t cols){ _rows = rows; _cols = cols; _data = new T[_rows * _cols]; if(value == 0 || value == -1){ memset(_data, value, sizeof(T) * _rows * _cols); }else{ auto lamda = [](T* a, const T& b){ *a = b; }; ParallelOperator po; po.parallel_mul2one<T>(_data, get_size(), value, lamda); } } template<class T> Matrix<T>::Matrix(const T* data, const size_t rows, const size_t cols){ _rows = rows; _cols = cols; _data = new T[_rows * _cols]; memcpy(_data, data, sizeof(T) * _rows * _cols); } template<class T> Matrix<T>::~Matrix(){ if(_data != nullptr){ delete[] _data; _data = nullptr; } } template<class T> void Matrix<T>::set_shallow_data(T* data, const size_t rows, const size_t cols){ if(_data != nullptr){ delete[] _data; } _data = data; _rows = rows; _cols = cols; } template<class T> Matrix<T> Matrix<T>::get_row(const size_t row_id, const size_t row_size) const{ Matrix<T> mat; get_row(&mat, row_id, _cols); return mat; } template<class T> void Matrix<T>::get_row(Matrix<T>* mat, const size_t row_id, const size_t row_size) const{ CHECK(row_id + row_size <= _rows); T* data = new T[row_size * _cols]; memcpy(data, &_data[row_id * _cols], sizeof(T) * row_size * _cols); mat->set_shallow_data(data, row_size, _cols); } template<class T> void Matrix<T>::set_row(const Matrix<T>& mat){ set_row(0, mat); } template<class T> void Matrix<T>::set_row(const size_t row_id, const Matrix<T>& mat){ CHECK(_cols == mat.cols()); CHECK(row_id + mat.rows() <= _rows); memcpy(&_data[row_id * _cols], mat.data(), sizeof(T) * mat.get_size()); } template<class T> void Matrix<T>::insert_row(const Matrix<T>& mat){ insert_row(_rows, mat); } template<class T> void Matrix<T>::insert_row(const size_t row_id, const Matrix<T>& mat){ if(get_size() == 0){ set_data(mat.data(), mat.rows(), mat.cols()); return; } CHECK(_cols == mat.cols()); T* data = new T[(_rows + mat.rows()) * _cols]; if(row_id > 0){ memcpy(data, _data, sizeof(T) * row_id * _cols); } memcpy(&data[row_id * _cols], mat.data(), sizeof(T) * mat.get_size()); if(row_id < _rows){ memcpy(&data[(row_id + mat.rows()) * _cols], &_data[row_id * _cols], sizeof(T) * (_rows - row_id) * _cols); } set_shallow_data(data, _rows + mat.rows(), _cols); } template<class T> Matrix<T> Matrix<T>::get_col(const size_t col_id, const size_t col_size) const{ Matrix<T> mat; get_col(&mat, col_id, col_size); return mat; } template<class T> void Matrix<T>::get_col(Matrix<T>* mat, const size_t col_id, const size_t col_size) const{ CHECK(col_id + col_size <= _cols); T* data = new T[_rows * col_size]; for(size_t i = 0; i != _rows; i++){ memcpy(&data[i * col_size], &_data[i * col_size + col_id], sizeof(T) * col_size); } mat->set_shallow_data(data, _rows, col_size); } template<class T> void Matrix<T>::set_col(const Matrix<T>& mat){ set_col(0, mat); } template<class T> void Matrix<T>::set_col(const size_t col_id, const Matrix<T>& mat){ CHECK(mat.rows() == _rows); CHECK(col_id + mat.cols() <= _cols); T* sub_data = mat.data(); size_t sub_cols = mat.cols(); for(size_t i = 0; i != _rows; i++){ memcpy(&_data[i * _cols + col_id], &sub_data[i * sub_cols], sizeof(T) * sub_cols); } } template<class T> void Matrix<T>::insert_col(const Matrix<T>& mat){ set_col(0, mat); } template<class T> void Matrix<T>::insert_col(const size_t col_id, const Matrix<T>& mat){ CHECK(mat.rows() == _rows); CHECK(col_id <= _cols); size_t sub_cols = mat.cols(); size_t new_cols = _cols + sub_cols; T* sub_data = mat.data(); T* data = new T[_rows * new_cols]; for(size_t i = 0; i != _rows; i++){ if(col_id > 0){ memcpy(&data[i * new_cols], &_data[i * _cols], sizeof(T) * sub_cols); } memcpy(&data[i * new_cols + sub_cols], &sub_data[i * sub_cols], sizeof(T) * sub_cols); if(col_id != _cols){ memcpy(&data[i * new_cols + col_id + sub_cols], &_data[i * _cols + col_id], sizeof(T) * (_cols - col_id)); } } set_shallow_data(data, _rows, new_cols); } template<class T> Matrix<T>* Matrix<T>::clone() const{ return new Matrix<T>(_data, _rows, _cols); } template<class T> void Matrix<T>::clone(Matrix<T>& mat) const{ mat.set_data(_data, _rows, _cols); } template<class T> void Matrix<T>::reset(const T& value){ reset(value, _rows, _cols); } template<class T> void Matrix<T>::reset(const T& value, const size_t rows, const size_t cols){ if(get_size() != rows * cols){ if(_data != nullptr){ delete[] _data; _data = nullptr; } _data = new T[rows * cols]; _rows = rows; _cols = cols; } size_t size = rows * cols; if(value == 0 || value == -1){ memset(_data, value, sizeof(T) * size); }else{ auto lamda = [](T* a, const T& b){ *a = b; }; ParallelOperator po; po.parallel_mul2one<T>(_data, size, value, lamda); } } template<class T> Matrix<T> Matrix<T>::Ts(){ MatrixHelper<T> mh; Matrix<T> mat; mh.transpose(mat, *this); return mat; } template<class T> void Matrix<T>::transpose(){ MatrixHelper<T> mh; mh.transpose(*this, *this); } template<class T> void Matrix<T>::display(const std::string& split){ printf("[%ld*%ld][\n", _rows, _cols); for(size_t i = 0; i != _rows; i++){ printf("row[%ld][", i); for(size_t j = 0; j != _cols; j++){ printf("%s", std::to_string(_data[i * _cols + j]).c_str()); if(j != this->_cols - 1){ printf("%s", split.c_str()); } } printf("]\n"); } printf("]\n"); } template<class T> RandomMatrix<T>::RandomMatrix(size_t rows, size_t cols, const T& mean_value, const T& stddev, const T& min, const T& max) : Matrix<T>(rows, cols){ _mean_value = mean_value; _stddev = stddev; _min = min; _max = max; reset(); } template<class T> void RandomMatrix<T>::reset(){ T scale = _max - _min; T min = _min; T max = _max; ParallelOperator po; size_t size = this->_rows * this->_cols; T* data = this->_data; size_t block_size = po.get_block_size(size); size_t num_thread = po.get_num_thread(size, block_size); std::vector<std::thread> threads(num_thread); std::default_random_engine engine(std::chrono::system_clock::now().time_since_epoch().count()); std::normal_distribution<T> distribution(_mean_value, _stddev); for(size_t i = 0; i != num_thread; i++){ threads[i] = std::thread( [&data, max, min, scale, &distribution, &engine](size_t start_idx, size_t end_idx){ for(size_t ti = start_idx; ti != end_idx; ti++){ T value = static_cast<T>(distribution(engine)); if(value > max){ real step = (value - min)/scale; value = min + (step - (int)step) * scale; }else if(value < min){ real step = (max - value)/scale; value = min + (step - (int)step) * scale; } data[ti] = value; } }, i * block_size, std::min(size, (i + 1) * block_size) ); } for(auto& thread : threads){ thread.join(); } } template<class T> void RandomMatrix<T>::reset(size_t rows, size_t cols, const T& mean_value, const T& stddev, const T& min, const T& max){ if(rows * cols != this->_rows * this->_cols){ if(this->_data != nullptr){ delete this->_data; } this->_data = new T[rows * cols]; } this->_rows = rows; this->_cols = cols; _mean_value = mean_value; _stddev = stddev; _min = min; _max = max; reset(); } template class Matrix<int>; template class Matrix<float>; template class Matrix<double>; template class RandomMatrix<float>; }//namespace algebra }//namespace abcdl
/*********************************************** * Author: Jun Jiang - [email protected] * Create: 2017-07-25 16:33 * Last modified : 2017-07-25 16:33 * Filename : Matrix.h * Description : Base Data Structure **********************************************/ #include "algebra/Matrix.h" #include "algebra/MatrixHelper.h" #include "utils/ParallelOperator.h" #include <random> #include <string.h> #include <iostream> #include <stdio.h> using abcdl::utils::ParallelOperator; namespace abcdl{ namespace algebra{ template<class T> Matrix<T>::Matrix(){ _rows = 0; _cols = 0; _data = nullptr; } template<class T> Matrix<T>::Matrix(const Matrix<T>& mat){ _rows = mat.rows(); _cols = mat.cols(); _data = new T[_rows * _cols]; memcpy(_data, mat.data(), sizeof(T) * _rows * _cols); } template<class T> Matrix<T>::Matrix(const size_t rows, const size_t cols){ _rows = rows; _cols = cols; _data = new T[_rows * _cols]; memset(_data, 0, sizeof(T) * _rows * _cols); } template<class T> Matrix<T>::Matrix(const T& value, const size_t rows, const size_t cols){ _rows = rows; _cols = cols; _data = new T[_rows * _cols]; if(value == 0 || value == -1){ memset(_data, value, sizeof(T) * _rows * _cols); }else{ auto lamda = [](T* a, const T& b){ *a = b; }; ParallelOperator po; po.parallel_mul2one<T>(_data, get_size(), value, lamda); } } template<class T> Matrix<T>::Matrix(const T* data, const size_t rows, const size_t cols){ _rows = rows; _cols = cols; _data = new T[_rows * _cols]; memcpy(_data, data, sizeof(T) * _rows * _cols); } template<class T> Matrix<T>::~Matrix(){ if(_data != nullptr){ delete[] _data; _data = nullptr; } } template<class T> void Matrix<T>::set_shallow_data(T* data, const size_t rows, const size_t cols){ if(_data != nullptr){ delete[] _data; } _data = data; _rows = rows; _cols = cols; } template<class T> Matrix<T> Matrix<T>::get_row(const size_t row_id, const size_t row_size) const{ Matrix<T> mat; get_row(&mat, row_id, _cols); return mat; } template<class T> void Matrix<T>::get_row(Matrix<T>* mat, const size_t row_id, const size_t row_size) const{ CHECK(row_id + row_size <= _rows); T* data = new T[row_size * _cols]; memcpy(data, &_data[row_id * _cols], sizeof(T) * row_size * _cols); mat->set_shallow_data(data, row_size, _cols); } template<class T> void Matrix<T>::set_row(const Matrix<T>& mat){ set_row(0, mat); } template<class T> void Matrix<T>::set_row(const size_t row_id, const Matrix<T>& mat){ CHECK(_cols == mat.cols()); CHECK(row_id + mat.rows() <= _rows); memcpy(&_data[row_id * _cols], mat.data(), sizeof(T) * mat.get_size()); } template<class T> void Matrix<T>::insert_row(const Matrix<T>& mat){ insert_row(_rows, mat); } template<class T> void Matrix<T>::insert_row(const size_t row_id, const Matrix<T>& mat){ if(get_size() == 0){ set_data(mat.data(), mat.rows(), mat.cols()); return; } CHECK(_cols == mat.cols()); T* data = new T[(_rows + mat.rows()) * _cols]; if(row_id > 0){ memcpy(data, _data, sizeof(T) * row_id * _cols); } memcpy(&data[row_id * _cols], mat.data(), sizeof(T) * mat.get_size()); if(row_id < _rows){ memcpy(&data[(row_id + mat.rows()) * _cols], &_data[row_id * _cols], sizeof(T) * (_rows - row_id) * _cols); } set_shallow_data(data, _rows + mat.rows(), _cols); } template<class T> Matrix<T> Matrix<T>::get_col(const size_t col_id, const size_t col_size) const{ Matrix<T> mat; get_col(&mat, col_id, col_size); return mat; } template<class T> void Matrix<T>::get_col(Matrix<T>* mat, const size_t col_id, const size_t col_size) const{ CHECK(col_id + col_size <= _cols); T* data = new T[_rows * col_size]; for(size_t i = 0; i != _rows; i++){ memcpy(&data[i * col_size], &_data[i * col_size + col_id], sizeof(T) * col_size); } mat->set_shallow_data(data, _rows, col_size); } template<class T> void Matrix<T>::set_col(const Matrix<T>& mat){ set_col(0, mat); } template<class T> void Matrix<T>::set_col(const size_t col_id, const Matrix<T>& mat){ CHECK(mat.rows() == _rows); CHECK(col_id + mat.cols() <= _cols); T* sub_data = mat.data(); size_t sub_cols = mat.cols(); for(size_t i = 0; i != _rows; i++){ memcpy(&_data[i * _cols + col_id], &sub_data[i * sub_cols], sizeof(T) * sub_cols); } } template<class T> void Matrix<T>::insert_col(const Matrix<T>& mat){ set_col(0, mat); } template<class T> void Matrix<T>::insert_col(const size_t col_id, const Matrix<T>& mat){ CHECK(mat.rows() == _rows); CHECK(col_id <= _cols); size_t sub_cols = mat.cols(); size_t new_cols = _cols + sub_cols; T* sub_data = mat.data(); T* data = new T[_rows * new_cols]; for(size_t i = 0; i != _rows; i++){ if(col_id > 0){ memcpy(&data[i * new_cols], &_data[i * _cols], sizeof(T) * sub_cols); } memcpy(&data[i * new_cols + sub_cols], &sub_data[i * sub_cols], sizeof(T) * sub_cols); if(col_id != _cols){ memcpy(&data[i * new_cols + col_id + sub_cols], &_data[i * _cols + col_id], sizeof(T) * (_cols - col_id)); } } set_shallow_data(data, _rows, new_cols); } template<class T> Matrix<T>* Matrix<T>::clone() const{ return new Matrix<T>(_data, _rows, _cols); } template<class T> void Matrix<T>::clone(Matrix<T>& mat) const{ mat.set_data(_data, _rows, _cols); } template<class T> void Matrix<T>::reset(const T& value){ reset(value, _rows, _cols); } template<class T> void Matrix<T>::reset(const T& value, const size_t rows, const size_t cols){ if(get_size() != rows * cols){ if(_data != nullptr){ delete[] _data; _data = nullptr; } _data = new T[rows * cols]; _rows = rows; _cols = cols; } size_t size = rows * cols; if(value == 0 || value == -1){ memset(_data, value, sizeof(T) * size); }else{ auto lamda = [](T* a, const T& b){ *a = b; }; ParallelOperator po; po.parallel_mul2one<T>(_data, size, value, lamda); } } template<class T> Matrix<T> Matrix<T>::Ts(){ MatrixHelper<T> mh; Matrix<T> mat; mh.transpose(mat, *this); return mat; } template<class T> void Matrix<T>::transpose(){ MatrixHelper<T> mh; mh.transpose(*this, *this); } template<class T> void Matrix<T>::display(const std::string& split){ printf("[%ld*%ld][\n", _rows, _cols); for(size_t i = 0; i != _rows; i++){ printf("row[%ld][", i); for(size_t j = 0; j != _cols; j++){ printf("%s", std::to_string(_data[i * _cols + j]).c_str()); if(j != this->_cols - 1){ printf("%s", split.c_str()); } } printf("]\n"); } printf("]\n"); } template<class T> RandomMatrix<T>::RandomMatrix(size_t rows, size_t cols, const T& mean_value, const T& stddev, const T& min, const T& max) : Matrix<T>(rows, cols){ _mean_value = mean_value; _stddev = stddev; _min = min; _max = max; reset(); } template<class T> void RandomMatrix<T>::reset(){ T scale = _max - _min; T min = _min; T max = _max; ParallelOperator po; size_t size = this->_rows * this->_cols; T* data = this->_data; size_t block_size = po.get_block_size(size); size_t num_thread = po.get_num_thread(size, block_size); std::vector<std::thread> threads(num_thread); std::default_random_engine engine(std::chrono::system_clock::now().time_since_epoch().count()); std::normal_distribution<T> distribution(_mean_value, _stddev); for(size_t i = 0; i != num_thread; i++){ threads[i] = std::thread( [&data, max, min, scale, &distribution, &engine](size_t start_idx, size_t end_idx){ for(size_t ti = start_idx; ti != end_idx; ti++){ T value = static_cast<T>(distribution(engine)); if(max == min || value == max || value == min){ data[ti] = value; }else if(value > max){ real step = (value - min)/scale; value = min + (step - (int)step) * scale; }else{ real step = (max - value)/scale; value = min + (step - (int)step) * scale; } } }, i * block_size, std::min(size, (i + 1) * block_size) ); } for(auto& thread : threads){ thread.join(); } } template<class T> void RandomMatrix<T>::reset(size_t rows, size_t cols, const T& mean_value, const T& stddev, const T& min, const T& max){ if(rows * cols != this->_rows * this->_cols){ if(this->_data != nullptr){ delete[] this->_data; } this->_data = new T[rows * cols]; } this->_rows = rows; this->_cols = cols; _mean_value = mean_value; _stddev = stddev; _min = min; _max = max; reset(); } template class Matrix<int>; template class Matrix<float>; template class Matrix<double>; template class RandomMatrix<float>; }//namespace algebra }//namespace abcdl
fix RandomMatrix bug
fix RandomMatrix bug
C++
apache-2.0
btbujiangjun/abcdl
f919c1253c2db0f2b2b26edc92a5f68c8702829f
examples/echo/testecho.cpp
examples/echo/testecho.cpp
#include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <semaphore.h> #include <unistd.h> #include "EchoIndicationWrapper.h" #include "EchoRequestProxy.h" #include "GeneratedTypes.h" #include "SwallowProxy.h" #define LOOP_COUNT 50 //1000 #define SEPARATE_EVENT_THREAD //#define USE_MUTEX_SYNC EchoRequestProxy *echoRequestProxy = 0; #ifndef SEPARATE_EVENT_THREAD typedef int SEM_TYPE; #define SEMPOST(A) (*(A))++ #define SEMWAIT pthread_worker #elif defined(USE_MUTEX_SYNC) typedef pthread_mutex_t SEM_TYPE; #define SEMINIT(A) pthread_mutex_lock(A); #define SEMWAIT(A) pthread_mutex_lock(A); #define SEMPOST(A) pthread_mutex_unlock(A); #else // use semaphores typedef sem_t SEM_TYPE; #define SEMINIT(A) sem_init(A, 0, 0); #define SEMWAIT(A) sem_wait(A); #define SEMPOST(A) sem_post(A) #endif #ifdef SEPARATE_EVENT_THREAD #define PREPAREWAIT(A) #define CHECKSEM(A) 1 #else // use inline sync #define PREPAREWAIT(A) (A) = 0 #define CHECKSEM(A) (!(A)) #endif static SEM_TYPE sem_heard2; PortalPoller *poller = 0; static void *pthread_worker(void *p) { void *rc = NULL; while (CHECKSEM(sem_heard2) && !rc && !poller->stopping) rc = poller->portalExec_event(poller->portalExec_timeout); return rc; } static void init_thread() { #ifdef SEPARATE_EVENT_THREAD pthread_t threaddata; SEMINIT(&sem_heard2); pthread_create(&threaddata, NULL, &pthread_worker, (void*)poller); #endif } class EchoIndication : public EchoIndicationWrapper { public: virtual void heard(uint32_t v) { fprintf(stderr, "heard an echo: %d\n", v); echoRequestProxy->say2(v, 2*v); } virtual void heard2(uint32_t a, uint32_t b) { catch_timer(20); SEMPOST(&sem_heard2); //fprintf(stderr, "heard an echo2: %ld %ld\n", a, b); //catch_timer(25); } EchoIndication(unsigned int id, PortalPoller *poller) : EchoIndicationWrapper(id, poller) {} }; static void call_say(int v) { printf("[%s:%d] %d\n", __FUNCTION__, __LINE__, v); start_timer(0); PREPAREWAIT(sem_heard2); echoRequestProxy->say(v); SEMWAIT(&sem_heard2); printf("call_say: elapsed %zd\n", lap_timer(0)); } static void call_say2(int v, int v2) { start_timer(0); PREPAREWAIT(sem_heard2); catch_timer(0); echoRequestProxy->say2(v, v2); catch_timer(19); SEMWAIT(&sem_heard2); catch_timer(30); } int main(int argc, const char **argv) { poller = new PortalPoller(); EchoIndication *echoIndication = new EchoIndication(IfcNames_EchoIndication, poller); // these use the default poller SwallowProxy *swallowProxy = new SwallowProxy(IfcNames_Swallow); echoRequestProxy = new EchoRequestProxy(IfcNames_EchoRequest); poller->portalExec_init(); init_thread(); portalExec_start(); int v = 42; fprintf(stderr, "Saying %d\n", v); call_say(v); call_say(v*5); call_say(v*17); call_say(v*93); printf("[%s:%d] run %d loops\n\n", __FUNCTION__, __LINE__, LOOP_COUNT); init_timer(); start_timer(1); printf("[%s:%d] sleep2\n", __FUNCTION__, __LINE__); sleep(2); for (int i = 0; i < LOOP_COUNT; i++) call_say2(v, v*3); uint64_t elapsed = lap_timer(1); printf("TEST TYPE: " #ifndef SEPARATE_EVENT_THREAD "INLINE" #elif defined(USE_MUTEX_SYNC) "MUTEX" #else "SEM" #endif "\n"); print_timer(LOOP_COUNT); printf("call_say: elapsed %g average %g\n", (double) elapsed, (double) elapsed/ (double) LOOP_COUNT); echoRequestProxy->setLeds(9); poller->portalExec_end(); portalExec_end(); return 0; }
#include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <semaphore.h> #include <unistd.h> #include "EchoIndicationWrapper.h" #include "EchoRequestProxy.h" #include "GeneratedTypes.h" #include "SwallowProxy.h" #define LOOP_COUNT 50 //1000 //#define SEPARATE_EVENT_THREAD //#define USE_MUTEX_SYNC EchoRequestProxy *echoRequestProxy = 0; #ifndef SEPARATE_EVENT_THREAD typedef int SEM_TYPE; #define SEMPOST(A) (*(A))++ #define SEMWAIT pthread_worker #elif defined(USE_MUTEX_SYNC) typedef pthread_mutex_t SEM_TYPE; #define SEMINIT(A) pthread_mutex_lock(A); #define SEMWAIT(A) pthread_mutex_lock(A); #define SEMPOST(A) pthread_mutex_unlock(A); #else // use semaphores typedef sem_t SEM_TYPE; #define SEMINIT(A) sem_init(A, 0, 0); #define SEMWAIT(A) sem_wait(A); #define SEMPOST(A) sem_post(A) #endif #ifdef SEPARATE_EVENT_THREAD #define PREPAREWAIT(A) #define CHECKSEM(A) 1 #else // use inline sync #define PREPAREWAIT(A) (A) = 0 #define CHECKSEM(A) (!(A)) #endif static SEM_TYPE sem_heard2; PortalPoller *poller = 0; static void *pthread_worker(void *p) { void *rc = NULL; while (CHECKSEM(sem_heard2) && !rc && !poller->stopping) rc = poller->portalExec_event(poller->portalExec_timeout); return rc; } static void init_thread() { #ifdef SEPARATE_EVENT_THREAD pthread_t threaddata; SEMINIT(&sem_heard2); pthread_create(&threaddata, NULL, &pthread_worker, (void*)poller); #endif } class EchoIndication : public EchoIndicationWrapper { public: virtual void heard(uint32_t v) { fprintf(stderr, "heard an echo: %d\n", v); echoRequestProxy->say2(v, 2*v); } virtual void heard2(uint32_t a, uint32_t b) { catch_timer(20); SEMPOST(&sem_heard2); //fprintf(stderr, "heard an echo2: %ld %ld\n", a, b); //catch_timer(25); } EchoIndication(unsigned int id, PortalPoller *poller) : EchoIndicationWrapper(id, poller) {} }; static void call_say(int v) { printf("[%s:%d] %d\n", __FUNCTION__, __LINE__, v); start_timer(0); PREPAREWAIT(sem_heard2); echoRequestProxy->say(v); SEMWAIT(&sem_heard2); printf("call_say: elapsed %zd\n", lap_timer(0)); } static void call_say2(int v, int v2) { start_timer(0); PREPAREWAIT(sem_heard2); catch_timer(0); echoRequestProxy->say2(v, v2); catch_timer(19); SEMWAIT(&sem_heard2); catch_timer(30); } int main(int argc, const char **argv) { poller = new PortalPoller(); EchoIndication *echoIndication = new EchoIndication(IfcNames_EchoIndication, poller); // these use the default poller SwallowProxy *swallowProxy = new SwallowProxy(IfcNames_Swallow); echoRequestProxy = new EchoRequestProxy(IfcNames_EchoRequest); poller->portalExec_init(); init_thread(); portalExec_start(); printf("Timer tests\n"); init_timer(); for (int i = 0; i < 1000; i++) { start_timer(0); catch_timer(1); catch_timer(2); catch_timer(3); catch_timer(4); catch_timer(5); catch_timer(6); catch_timer(7); catch_timer(8); } print_timer(1000); int v = 42; fprintf(stderr, "Saying %d\n", v); call_say(v); call_say(v*5); call_say(v*17); call_say(v*93); printf("[%s:%d] run %d loops\n\n", __FUNCTION__, __LINE__, LOOP_COUNT); init_timer(); printf("[%s:%d] sleep2\n", __FUNCTION__, __LINE__); sleep(2); start_timer(1); for (int i = 0; i < LOOP_COUNT; i++) call_say2(v, v*3); uint64_t elapsed = lap_timer(1); printf("TEST TYPE: " #ifndef SEPARATE_EVENT_THREAD "INLINE" #elif defined(USE_MUTEX_SYNC) "MUTEX" #else "SEM" #endif "\n"); print_timer(LOOP_COUNT); printf("call_say: elapsed %g average %g\n", (double) elapsed, (double) elapsed/ (double) LOOP_COUNT); echoRequestProxy->setLeds(9); poller->portalExec_end(); portalExec_end(); return 0; }
add pure timer test
add pure timer test
C++
mit
8l/connectal,cambridgehackers/connectal,csail-csg/connectal,chenm001/connectal,hanw/connectal,cambridgehackers/connectal,chenm001/connectal,csail-csg/connectal,csail-csg/connectal,cambridgehackers/connectal,chenm001/connectal,csail-csg/connectal,chenm001/connectal,8l/connectal,8l/connectal,cambridgehackers/connectal,hanw/connectal,hanw/connectal,8l/connectal,hanw/connectal,cambridgehackers/connectal,8l/connectal,csail-csg/connectal,hanw/connectal,chenm001/connectal
a8c0f04697c5397c52b4b340b16b6a29b1338794
Tests/tests/gapi/directx_test.cpp
Tests/tests/gapi/directx_test.cpp
#include <Tempest/DirectX12Api> #include <Tempest/Except> #include <Tempest/Device> #include <Tempest/Fence> #include <Tempest/Pixmap> #include <Tempest/Log> #include <gtest/gtest.h> #include <gmock/gmock-matchers.h> #include "gapi_test_common.h" using namespace testing; using namespace Tempest; struct Vertex { float x,y; }; namespace Tempest { template<> inline VertexBufferDecl vertexBufferDecl<::Vertex>() { return {Decl::float2}; } } static const Vertex vboData[3] = {{-1,-1},{1,-1},{1,1}}; static const uint16_t iboData[3] = {0,1,2}; TEST(DirectX12Api,DirectX12Api) { #if defined(_MSC_VER) GapiTestCommon::init<DirectX12Api>(); #endif } TEST(DirectX12Api,Vbo) { #if defined(_MSC_VER) GapiTestCommon::vbo<DirectX12Api>(); #endif } TEST(DirectX12Api,Shader) { #if defined(_MSC_VER) GapiTestCommon::shader<DirectX12Api>(); #endif } TEST(DirectX12Api,Pso) { #if defined(_MSC_VER) GapiTestCommon::pso<DirectX12Api>(); #endif } TEST(DirectX12Api,Fbo) { #if defined(_MSC_VER) GapiTestCommon::fbo<DirectX12Api>("DirectX12Api_Fbo.png"); #endif } TEST(DirectX12Api,Draw) { #if defined(_MSC_VER) GapiTestCommon::draw<DirectX12Api,TextureFormat::RGBA8> ("DirectX12Api_Draw_RGBA8.png"); GapiTestCommon::draw<DirectX12Api,TextureFormat::RG8> ("DirectX12Api_Draw_RG8.png"); GapiTestCommon::draw<DirectX12Api,TextureFormat::R8> ("DirectX12Api_Draw_R8.png"); GapiTestCommon::draw<DirectX12Api,TextureFormat::RGBA16> ("DirectX12Api_Draw_RGBA16.png"); GapiTestCommon::draw<DirectX12Api,TextureFormat::RG16> ("DirectX12Api_Draw_RG16.png"); GapiTestCommon::draw<DirectX12Api,TextureFormat::R16> ("DirectX12Api_Draw_R16.png"); GapiTestCommon::draw<DirectX12Api,TextureFormat::RGBA32F>("DirectX12Api_Draw_RGBA32F.png"); GapiTestCommon::draw<DirectX12Api,TextureFormat::RG32F> ("DirectX12Api_Draw_RG32F.png"); GapiTestCommon::draw<DirectX12Api,TextureFormat::R32F> ("DirectX12Api_Draw_R32F.png"); #endif } TEST(DirectX12Api,Compute) { #if defined(_MSC_VER) GapiTestCommon::ssboDispath<DirectX12Api>(); #endif } TEST(DirectX12Api,ComputeImage) { #if defined(_MSC_VER) GapiTestCommon::imageCompute<DirectX12Api>("DirectX12Api_Compute.png"); #endif } TEST(DirectX12Api,MipMaps) { #if defined(_MSC_VER) GapiTestCommon::mipMaps<DirectX12Api,TextureFormat::RGBA8> ("DirectX12Api_MipMaps_RGBA8.png"); GapiTestCommon::mipMaps<DirectX12Api,TextureFormat::RGBA16> ("DirectX12Api_MipMaps_RGBA16.png"); GapiTestCommon::mipMaps<DirectX12Api,TextureFormat::RGBA32F>("DirectX12Api_MipMaps_RGBA32.png"); #endif } TEST(DirectX12Api,S3TC) { #if defined(_MSC_VER) try { DirectX12Api api{ApiFlags::Validation}; Device device(api); auto tex = device.loadTexture("data/img/tst-dxt5.dds"); EXPECT_EQ(tex.format(),TextureFormat::DXT5); } catch(std::system_error& e) { if(e.code()==Tempest::GraphicsErrc::NoDevice) Log::d("Skipping directx testcase: ", e.what()); else throw; } #endif }
#include <Tempest/DirectX12Api> #include <Tempest/Except> #include <Tempest/Device> #include <Tempest/Fence> #include <Tempest/Pixmap> #include <Tempest/Log> #include <gtest/gtest.h> #include <gmock/gmock-matchers.h> #include "gapi_test_common.h" using namespace testing; using namespace Tempest; struct Vertex { float x,y; }; namespace Tempest { template<> inline VertexBufferDecl vertexBufferDecl<::Vertex>() { return {Decl::float2}; } } TEST(DirectX12Api,DirectX12Api) { #if defined(_MSC_VER) GapiTestCommon::init<DirectX12Api>(); #endif } TEST(DirectX12Api,Vbo) { #if defined(_MSC_VER) GapiTestCommon::vbo<DirectX12Api>(); #endif } TEST(DirectX12Api,Shader) { #if defined(_MSC_VER) GapiTestCommon::shader<DirectX12Api>(); #endif } TEST(DirectX12Api,Pso) { #if defined(_MSC_VER) GapiTestCommon::pso<DirectX12Api>(); #endif } TEST(DirectX12Api,Fbo) { #if defined(_MSC_VER) GapiTestCommon::fbo<DirectX12Api>("DirectX12Api_Fbo.png"); #endif } TEST(DirectX12Api,Draw) { #if defined(_MSC_VER) GapiTestCommon::draw<DirectX12Api,TextureFormat::RGBA8> ("DirectX12Api_Draw_RGBA8.png"); GapiTestCommon::draw<DirectX12Api,TextureFormat::RG8> ("DirectX12Api_Draw_RG8.png"); GapiTestCommon::draw<DirectX12Api,TextureFormat::R8> ("DirectX12Api_Draw_R8.png"); GapiTestCommon::draw<DirectX12Api,TextureFormat::RGBA16> ("DirectX12Api_Draw_RGBA16.png"); GapiTestCommon::draw<DirectX12Api,TextureFormat::RG16> ("DirectX12Api_Draw_RG16.png"); GapiTestCommon::draw<DirectX12Api,TextureFormat::R16> ("DirectX12Api_Draw_R16.png"); GapiTestCommon::draw<DirectX12Api,TextureFormat::RGBA32F>("DirectX12Api_Draw_RGBA32F.png"); GapiTestCommon::draw<DirectX12Api,TextureFormat::RG32F> ("DirectX12Api_Draw_RG32F.png"); GapiTestCommon::draw<DirectX12Api,TextureFormat::R32F> ("DirectX12Api_Draw_R32F.png"); #endif } TEST(DirectX12Api,Compute) { #if defined(_MSC_VER) GapiTestCommon::ssboDispath<DirectX12Api>(); #endif } TEST(DirectX12Api,ComputeImage) { #if defined(_MSC_VER) GapiTestCommon::imageCompute<DirectX12Api>("DirectX12Api_Compute.png"); #endif } TEST(DirectX12Api,MipMaps) { #if defined(_MSC_VER) GapiTestCommon::mipMaps<DirectX12Api,TextureFormat::RGBA8> ("DirectX12Api_MipMaps_RGBA8.png"); GapiTestCommon::mipMaps<DirectX12Api,TextureFormat::RGBA16> ("DirectX12Api_MipMaps_RGBA16.png"); GapiTestCommon::mipMaps<DirectX12Api,TextureFormat::RGBA32F>("DirectX12Api_MipMaps_RGBA32.png"); #endif } TEST(DirectX12Api,S3TC) { #if defined(_MSC_VER) try { DirectX12Api api{ApiFlags::Validation}; Device device(api); auto tex = device.loadTexture("data/img/tst-dxt5.dds"); EXPECT_EQ(tex.format(),TextureFormat::DXT5); } catch(std::system_error& e) { if(e.code()==Tempest::GraphicsErrc::NoDevice) Log::d("Skipping directx testcase: ", e.what()); else throw; } #endif }
remove unused variables in test
remove unused variables in test
C++
mit
Try/Tempest,Try/Tempest,Try/Tempest,Try/Tempest
0753b08e1c7a25836f18f29558638aac1bf7ad67
examples/lennard_jones.cpp
examples/lennard_jones.cpp
// Petter Strandmark 2012. // // See http://doye.chem.ox.ac.uk/jon/structures/LJ/tables.150.html // for best known minima for N <= 150. // #include <functional> #include <iomanip> #include <iostream> #include <random> #include <spii/auto_diff_term.h> #include <spii/solver.h> #include <spii/solver-callbacks.h> using namespace spii; struct LennardJonesTerm { template<typename R> R operator()(const R* const p1, const R* const p2) const { R dx = p1[0] - p2[0]; R dy = p1[1] - p2[1]; R dz = p1[2] - p2[2]; R r2 = dx*dx + dy*dy + dz*dz; R r6 = r2*r2*r2; R r12 = r6*r6; return 1.0 / r12 - 2.0 / r6; } }; int main() { std::mt19937 prng(1); std::normal_distribution<double> normal; auto randn = std::bind(normal, prng); int N = -1; std::cout << "Enter N = "; std::cin >> N; Function potential; std::vector<Eigen::Vector3d> points(N); int n = int(std::ceil(std::pow(double(N), 1.0/3.0))); // Initial position is a cubic grid with random pertubations. for (int i = 0; i < N; ++i) { int x = i % n; int y = (i / n) % n; int z = (i / n) / n; potential.add_variable(&points[i][0], 3); points[i][0] = x + 0.05 * randn(); points[i][1] = y + 0.05 * randn(); points[i][2] = z + 0.05 * randn(); } for (int i = 0; i < N; ++i) { for (int j = i + 1; j < N; ++j) { potential.add_term<AutoDiffTerm<LennardJonesTerm, 3, 3>>( &points[i][0], &points[j][0]); } } LBFGSSolver solver; //solver.sparsity_mode = Solver::DENSE; // For NewtonSolver. solver.maximum_iterations = 3000; std::ofstream file("convergence.data"); FileCallback callback(file); solver.callback_function = callback; SolverResults results; solver.solve(potential, &results); std::cerr << results; potential.print_timing_information(std::cout); std::cout << "Energy = " << std::setprecision(10) << potential.evaluate() << std::endl; }
// Petter Strandmark 2012. // // See http://doye.chem.ox.ac.uk/jon/structures/LJ/tables.150.html // for best known minima for N <= 150. // #include <functional> #include <iomanip> #include <iostream> #include <random> #include <spii/auto_diff_term.h> #include <spii/solver.h> #include <spii/solver-callbacks.h> using namespace spii; struct LennardJonesTerm { template<typename R> R operator()(const R* const p1, const R* const p2) const { R dx = p1[0] - p2[0]; R dy = p1[1] - p2[1]; R dz = p1[2] - p2[2]; R r2 = dx*dx + dy*dy + dz*dz; R r6 = r2*r2*r2; R r12 = r6*r6; return 1.0 / r12 - 2.0 / r6; } }; int main() { using namespace std; mt19937 prng(1); normal_distribution<double> normal; auto randn = bind(normal, ref(prng)); int N = -1; cout << "Enter N = "; cin >> N; Function potential; vector<Eigen::Vector3d> points(N); int n = int(ceil(pow(double(N), 1.0/3.0))); // Initial position is a cubic grid with random pertubations. for (int i = 0; i < N; ++i) { int x = i % n; int y = (i / n) % n; int z = (i / n) / n; potential.add_variable(&points[i][0], 3); points[i][0] = x + 0.05 * randn(); points[i][1] = y + 0.05 * randn(); points[i][2] = z + 0.05 * randn(); } for (int i = 0; i < N; ++i) { for (int j = i + 1; j < N; ++j) { potential.add_term<AutoDiffTerm<LennardJonesTerm, 3, 3>>( &points[i][0], &points[j][0]); } } LBFGSSolver solver; //solver.sparsity_mode = Solver::DENSE; // For NewtonSolver. solver.maximum_iterations = 3000; ofstream file("convergence.data"); FileCallback callback(file); solver.callback_function = callback; SolverResults results; solver.solve(potential, &results); cerr << results; potential.print_timing_information(cout); cout << "Energy = " << setprecision(10) << potential.evaluate() << endl; }
Remove std:: from L-J example.
Remove std:: from L-J example.
C++
bsd-2-clause
yuhangwang/spii,PetterS/spii
1f4ca64074849757c387f5284056d42faa24afdd
Geometry/sign_test.cpp
Geometry/sign_test.cpp
#include "glog/logging.h" #include "gtest/gtest.h" #include "Geometry/Sign.hpp" namespace principia { namespace geometry { class SignTest : public testing::Test { protected: Sign const positive_ = Sign(1); Sign const negative_ = Sign(-1); }; TEST_F(SignTest, Integer) { LOG(INFO) << "JE SUIS LA!"; Sign const positive(1); Sign const negative(-1); EXPECT_TRUE(positive.Positive()); EXPECT_FALSE(positive.Negative()); EXPECT_FALSE(negative.Positive()); EXPECT_TRUE(negative.Negative()); } TEST_F(SignTest, SignMultiplication) { Sign const positive(1); Sign const negative(-1); EXPECT_TRUE((positive * positive).Positive()); EXPECT_TRUE((positive * negative).Negative()); EXPECT_TRUE((negative * positive).Negative()); EXPECT_TRUE((negative * negative).Positive()); } TEST_F(SignTest, ScalarMultiplication) { Sign const positive(1); Sign const negative(-1); EXPECT_EQ(3, positive * 3); EXPECT_EQ(-3, positive * -3); EXPECT_EQ(-3, negative * 3); EXPECT_EQ(3, negative * -3); } } // namespace geometry } // namespace principia
#include "glog/logging.h" #include "gtest/gtest.h" #include "Geometry/Sign.hpp" namespace principia { namespace geometry { class SignTest : public testing::Test { protected: Sign const positive_ = Sign(1); Sign const negative_ = Sign(-1); }; TEST_F(SignTest, Integer) { Sign const positive(1); Sign const negative(-1); EXPECT_TRUE(positive.Positive()); EXPECT_FALSE(positive.Negative()); EXPECT_FALSE(negative.Positive()); EXPECT_TRUE(negative.Negative()); } TEST_F(SignTest, SignMultiplication) { Sign const positive(1); Sign const negative(-1); EXPECT_TRUE((positive * positive).Positive()); EXPECT_TRUE((positive * negative).Negative()); EXPECT_TRUE((negative * positive).Negative()); EXPECT_TRUE((negative * negative).Positive()); } TEST_F(SignTest, ScalarMultiplication) { Sign const positive(1); Sign const negative(-1); EXPECT_EQ(3, positive * 3); EXPECT_EQ(-3, positive * -3); EXPECT_EQ(-3, negative * 3); EXPECT_EQ(3, negative * -3); } } // namespace geometry } // namespace principia
Remove silly trace.
Remove silly trace.
C++
mit
eggrobin/Principia,mockingbirdnest/Principia,Norgg/Principia,mockingbirdnest/Principia,eggrobin/Principia,Norgg/Principia,Norgg/Principia,mockingbirdnest/Principia,eggrobin/Principia,pleroy/Principia,Norgg/Principia,pleroy/Principia,pleroy/Principia,mockingbirdnest/Principia,pleroy/Principia
61eae72ac7c187aeb4bcc10b275a00fc1d4fdcd8
src/medGui/database/medDatabaseNavigator.cpp
src/medGui/database/medDatabaseNavigator.cpp
/* medDatabaseNavigator.cpp --- * * Author: Julien Wintz * Copyright (C) 2008 - Julien Wintz, Inria. * Created: Tue Dec 15 09:38:39 2009 (+0100) * Version: $Id$ * Last-Updated: Mon Jun 28 14:21:37 2010 (+0200) * By: Julien Wintz * Update #: 59 */ /* Commentary: * */ /* Change log: * */ #include "medDatabaseNavigator.h" #include <dtkCore/dtkGlobal.h> #include <QtCore> #include <QtGui> #include <medCore/medAbstractDbController.h> #include <medCore/medDataManager.h> #include <medCore/medMetaDataKeys.h> #include <medCore/medStorage.h> #include "medDatabaseNavigatorController.h" #include "medDatabaseNavigatorItem.h" #include "medDatabaseNavigatorItemGroup.h" #include "medDatabaseNavigatorScene.h" #include "medDatabaseNavigatorView.h" namespace { // These small classes are used to determine if patients from different DBs are the same. // At present it is just based on the name. struct PatientDataKey{ QString name; bool operator==(const PatientDataKey & other) const { return this->name == other.name; } bool operator!=(const PatientDataKey & other) const { return !this->operator==(other); } }; struct StudyDataKey{ QString name; bool operator==(const StudyDataKey & other) const { return this->name == other.name; } bool operator!=(const StudyDataKey & other) const { return !this->operator==(other); } bool operator<(const StudyDataKey & other) const { return this->name < other.name; } }; } // namespace class medDatabaseNavigatorPrivate { public: medDatabaseNavigatorScene *scene; medDatabaseNavigatorView *view; int currentPatient ; Qt::Orientation orientation; }; medDatabaseNavigator::medDatabaseNavigator(QWidget *parent) : QFrame(parent), d(new medDatabaseNavigatorPrivate) { d->currentPatient = -1; d->orientation = medDatabaseNavigatorController::instance()->orientation(); d->scene = new medDatabaseNavigatorScene(this); d->scene->setOrientation (d->orientation); d->view = new medDatabaseNavigatorView(this); d->view->setOrientation (d->orientation); d->view->setScene(d->scene); d->view->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); d->view->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); QVBoxLayout *layout = new QVBoxLayout(this); layout->setContentsMargins(0, 0, 0, 0); layout->setSpacing(0); layout->addWidget(d->view); // medDatabaseNavigatorController::instance()->setOrientation(Qt::Vertical); medDatabaseNavigatorController::instance()->setItemSize(128, 128); d->orientation == Qt::Horizontal ? this->setFixedHeight(medDatabaseNavigatorController::instance()->groupHeight() + medDatabaseNavigatorController::instance()->itemSpacing() + 36) // 26 pixels for the scroller : this->setFixedWidth(medDatabaseNavigatorController::instance()->groupWidth() + medDatabaseNavigatorController::instance()->itemSpacing() + 36); // 26 pixels for the scroller } medDatabaseNavigator::~medDatabaseNavigator(void) { delete d; d = NULL; } void medDatabaseNavigator::reset(void) { d->scene->reset(); } void medDatabaseNavigator::onItemClicked(const medDataIndex& index) { if ( index.isValidForPatient() ) this->onPatientClicked(index); } void medDatabaseNavigator::updateNavigator(const medDataIndex& index) { if (index.isValidForPatient() && index.patientId() == d->currentPatient) { onPatientClicked(index); } } void medDatabaseNavigator::onPatientClicked(const medDataIndex& index) { // qDebug()<< "resetting Navigator"; this->reset(); if (!index.isValidForPatient()) { return; } d->currentPatient = index.patientId(); typedef QSet<medDataIndex> IndexSet; typedef QList<int> IntList; typedef QList<medDataIndex> IndexList; medDataManager *dataManager = medDataManager::instance(); IntList dataSources = dataManager->dataSourceIds(); QMap<StudyDataKey, medDatabaseNavigatorItemGroup*> groupMap; medAbstractDbController *dbc = dataManager->controllerForDataSource(index.dataSourceId()); if ( !dbc ) return; PatientDataKey referencePatientKey; referencePatientKey.name = dbc->metaData(index,medMetaDataKeys::PatientName); foreach (const int dataSourceId, dataSources ) { // qDebug() << "dataSource:" << dataSourceId; medAbstractDbController *dbc = dataManager->controllerForDataSource(dataSourceId); if ( !dbc ) continue; IndexList patientsForSource; if ( dataSourceId == index.dataSourceId() ) { patientsForSource.push_back(index); } else { patientsForSource = dbc->patients(); } foreach (const medDataIndex& patient, patientsForSource ) { // qDebug() << "patient:" << patient; IndexList studiesForSource = dbc->studies(patient); QString patientName = dbc->metaData(patient,medMetaDataKeys::PatientName); PatientDataKey patientKey; patientKey.name = patientName; if ( patientKey != referencePatientKey ) { continue; } foreach (const medDataIndex& study, studiesForSource ) { // qDebug() << "study:" << study; QString studyName = dbc->metaData(study,medMetaDataKeys::StudyDescription); StudyDataKey studyKey; studyKey.name = studyName; medDatabaseNavigatorItemGroup *group = NULL; // qDebug() << "groups"; if ( groupMap.contains(studyKey) ) { qDebug() << "group contains" << studyKey.name; group = groupMap.find(studyKey).value(); } else { // qDebug() << "new group"; group = new medDatabaseNavigatorItemGroup; group->setOrientation (d->orientation); group->setName(studyName); groupMap[studyKey] = group; } IndexList seriesForSource = dbc->series(study); foreach (const medDataIndex& series, seriesForSource ) { // qDebug() << "Creating new item for series:" << series; medDatabaseNavigatorItem *item = new medDatabaseNavigatorItem( medDataIndex(series) ); connect(item, SIGNAL(itemClicked(const medDataIndex&)), this, SIGNAL(itemClicked(const medDataIndex&))); group->addItem(item); } } } } foreach(medDatabaseNavigatorItemGroup *group, groupMap) { // qDebug() << "add group to groupMap"; d->scene->addGroup(group); } } void medDatabaseNavigator::onStudyClicked(const medDataIndex& id) { qDebug() << DTK_PRETTY_FUNCTION << id; } void medDatabaseNavigator::onSeriesClicked(const medDataIndex& id) { qDebug() << DTK_PRETTY_FUNCTION << id; } void medDatabaseNavigator::onImageClicked(const medDataIndex& id) { qDebug() << DTK_PRETTY_FUNCTION << id; } void medDatabaseNavigator::setOrientation (Qt::Orientation orientation) { d->orientation = orientation; if (d->orientation == Qt::Horizontal) { this->setFixedHeight(medDatabaseNavigatorController::instance()->groupHeight() + medDatabaseNavigatorController::instance()->itemSpacing() + 36); // 26 pixels for the scroller this->setFixedWidth(QWIDGETSIZE_MAX); } else { this->setFixedWidth(medDatabaseNavigatorController::instance()->groupWidth() + medDatabaseNavigatorController::instance()->itemSpacing() + 36); // 26 pixels for the scroller this->setFixedHeight(QWIDGETSIZE_MAX); } d->view->setOrientation (d->orientation); d->scene->setOrientation (d->orientation); } Qt::Orientation medDatabaseNavigator::orientation (void) const { return d->orientation; }
/* medDatabaseNavigator.cpp --- * * Author: Julien Wintz * Copyright (C) 2008 - Julien Wintz, Inria. * Created: Tue Dec 15 09:38:39 2009 (+0100) * Version: $Id$ * Last-Updated: Mon Jun 28 14:21:37 2010 (+0200) * By: Julien Wintz * Update #: 59 */ /* Commentary: * */ /* Change log: * */ #include "medDatabaseNavigator.h" #include <dtkCore/dtkGlobal.h> #include <QtCore> #include <QtGui> #include <medCore/medAbstractDbController.h> #include <medCore/medDataManager.h> #include <medCore/medMetaDataKeys.h> #include <medCore/medStorage.h> #include "medDatabaseNavigatorController.h" #include "medDatabaseNavigatorItem.h" #include "medDatabaseNavigatorItemGroup.h" #include "medDatabaseNavigatorScene.h" #include "medDatabaseNavigatorView.h" namespace { // These small classes are used to determine if patients from different DBs are the same. // At present it is just based on the name. struct PatientDataKey{ QString name; bool operator==(const PatientDataKey & other) const { return this->name == other.name; } bool operator!=(const PatientDataKey & other) const { return !this->operator==(other); } }; struct StudyDataKey{ QString name; bool operator==(const StudyDataKey & other) const { return this->name == other.name; } bool operator!=(const StudyDataKey & other) const { return !this->operator==(other); } bool operator<(const StudyDataKey & other) const { return this->name < other.name; } }; } // namespace class medDatabaseNavigatorPrivate { public: medDatabaseNavigatorScene *scene; medDatabaseNavigatorView *view; int currentPatient ; Qt::Orientation orientation; }; medDatabaseNavigator::medDatabaseNavigator(QWidget *parent) : QFrame(parent), d(new medDatabaseNavigatorPrivate) { d->currentPatient = -1; d->orientation = medDatabaseNavigatorController::instance()->orientation(); d->scene = new medDatabaseNavigatorScene(this); d->scene->setOrientation (d->orientation); d->view = new medDatabaseNavigatorView(this); d->view->setOrientation (d->orientation); d->view->setScene(d->scene); d->view->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); d->view->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); QVBoxLayout *layout = new QVBoxLayout(this); layout->setContentsMargins(0, 0, 0, 0); layout->setSpacing(0); layout->addWidget(d->view); // medDatabaseNavigatorController::instance()->setOrientation(Qt::Vertical); medDatabaseNavigatorController::instance()->setItemSize(128, 128); d->orientation == Qt::Horizontal ? this->setFixedHeight(medDatabaseNavigatorController::instance()->groupHeight() + medDatabaseNavigatorController::instance()->itemSpacing() + 36) // 26 pixels for the scroller : this->setFixedWidth(medDatabaseNavigatorController::instance()->groupWidth() + medDatabaseNavigatorController::instance()->itemSpacing() + 36); // 26 pixels for the scroller } medDatabaseNavigator::~medDatabaseNavigator(void) { delete d; d = NULL; } void medDatabaseNavigator::reset(void) { d->scene->reset(); } void medDatabaseNavigator::onItemClicked(const medDataIndex& index) { if ( index.isValidForPatient() ) this->onPatientClicked(index); } void medDatabaseNavigator::updateNavigator(const medDataIndex& index) { if (index.isValidForPatient() && index.patientId() == d->currentPatient) { onPatientClicked(index); } } void medDatabaseNavigator::onPatientClicked(const medDataIndex& index) { //qDebug()<< "resetting Navigator" << index; // Small trick so that when a patient image gets deleted, we're still able to find all other images of that patient medDataIndex baseIndex = index; baseIndex.setSeriesId(-1); this->reset(); if (!baseIndex.isValidForPatient()) { return; } d->currentPatient = baseIndex.patientId(); typedef QSet<medDataIndex> IndexSet; typedef QList<int> IntList; typedef QList<medDataIndex> IndexList; medDataManager *dataManager = medDataManager::instance(); IntList dataSources = dataManager->dataSourceIds(); QMap<StudyDataKey, medDatabaseNavigatorItemGroup*> groupMap; medAbstractDbController *dbc = dataManager->controllerForDataSource(baseIndex.dataSourceId()); if ( !dbc ) return; PatientDataKey referencePatientKey; referencePatientKey.name = dbc->metaData(baseIndex,medMetaDataKeys::PatientName); foreach (const int dataSourceId, dataSources ) { //qDebug() << "dataSource:" << dataSourceId; medAbstractDbController *dbc = dataManager->controllerForDataSource(dataSourceId); if ( !dbc ) continue; IndexList patientsForSource; if ( dataSourceId == baseIndex.dataSourceId() ) { patientsForSource.push_back(baseIndex); } else { patientsForSource = dbc->patients(); } //qDebug() << "patients for source" << patientsForSource; foreach (const medDataIndex& patient, patientsForSource ) { //qDebug() << "patient:" << patient; IndexList studiesForSource = dbc->studies(patient); QString patientName = dbc->metaData(patient,medMetaDataKeys::PatientName); PatientDataKey patientKey; patientKey.name = patientName; if ( patientKey != referencePatientKey ) { continue; } foreach (const medDataIndex& study, studiesForSource ) { //qDebug() << "study:" << study; QString studyName = dbc->metaData(study,medMetaDataKeys::StudyDescription); StudyDataKey studyKey; studyKey.name = studyName; medDatabaseNavigatorItemGroup *group = NULL; //qDebug() << "groups"; if ( groupMap.contains(studyKey) ) { //qDebug() << "group contains" << studyKey.name; group = groupMap.find(studyKey).value(); } else { //qDebug() << "new group"; group = new medDatabaseNavigatorItemGroup; group->setOrientation (d->orientation); group->setName(studyName); groupMap[studyKey] = group; } IndexList seriesForSource = dbc->series(study); foreach (const medDataIndex& series, seriesForSource ) { //qDebug() << "Creating new item for series:" << series; medDatabaseNavigatorItem *item = new medDatabaseNavigatorItem( medDataIndex(series) ); connect(item, SIGNAL(itemClicked(const medDataIndex&)), this, SIGNAL(itemClicked(const medDataIndex&))); group->addItem(item); } } } } foreach(medDatabaseNavigatorItemGroup *group, groupMap) { // qDebug() << "add group to groupMap"; d->scene->addGroup(group); } } void medDatabaseNavigator::onStudyClicked(const medDataIndex& id) { qDebug() << DTK_PRETTY_FUNCTION << id; } void medDatabaseNavigator::onSeriesClicked(const medDataIndex& id) { qDebug() << DTK_PRETTY_FUNCTION << id; } void medDatabaseNavigator::onImageClicked(const medDataIndex& id) { qDebug() << DTK_PRETTY_FUNCTION << id; } void medDatabaseNavigator::setOrientation (Qt::Orientation orientation) { d->orientation = orientation; if (d->orientation == Qt::Horizontal) { this->setFixedHeight(medDatabaseNavigatorController::instance()->groupHeight() + medDatabaseNavigatorController::instance()->itemSpacing() + 36); // 26 pixels for the scroller this->setFixedWidth(QWIDGETSIZE_MAX); } else { this->setFixedWidth(medDatabaseNavigatorController::instance()->groupWidth() + medDatabaseNavigatorController::instance()->itemSpacing() + 36); // 26 pixels for the scroller this->setFixedHeight(QWIDGETSIZE_MAX); } d->view->setOrientation (d->orientation); d->scene->setOrientation (d->orientation); } Qt::Orientation medDatabaseNavigator::orientation (void) const { return d->orientation; }
Correct patient menu disappearing when data removed from overlay buttons
Correct patient menu disappearing when data removed from overlay buttons
C++
bsd-3-clause
aabadie/medInria-public,aabadie/medInria-public,rdebroiz/medInria-public,aabadie/medInria-public,NicolasSchnitzler/medInria-public,rdebroiz/medInria-public,NicolasSchnitzler/medInria-public,NicolasSchnitzler/medInria-public,rdebroiz/medInria-public
b871dfa33c23ffe225edc4bf1c533909bfa7e54e
src/media/media_stream_devices_controller.cc
src/media/media_stream_devices_controller.cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/nw/src/media/media_stream_devices_controller.h" #include "base/values.h" #include "content/nw/src/media/media_capture_devices_dispatcher.h" #include "content/nw/src/media/media_internals.h" #include "content/public/browser/browser_thread.h" #include "content/public/common/media_stream_request.h" using content::BrowserThread; namespace { bool HasAnyAvailableDevice() { MediaCaptureDevicesDispatcher* dispatcher = MediaInternals::GetInstance()->GetMediaCaptureDevicesDispatcher(); const content::MediaStreamDevices& audio_devices = dispatcher->GetAudioCaptureDevices(); const content::MediaStreamDevices& video_devices = dispatcher->GetVideoCaptureDevices(); return !audio_devices.empty() || !video_devices.empty(); }; const char kAudioKey[] = "audio"; const char kVideoKey[] = "video"; } // namespace MediaStreamDevicesController::MediaStreamDevicesController( const content::MediaStreamRequest& request, const content::MediaResponseCallback& callback) : request_(request), callback_(callback), has_audio_(content::IsAudioMediaType(request.audio_type) && !IsAudioDeviceBlockedByPolicy()), has_video_(content::IsVideoMediaType(request.video_type) && !IsVideoDeviceBlockedByPolicy()) { } MediaStreamDevicesController::~MediaStreamDevicesController() {} #if 0 // static void MediaStreamDevicesController::RegisterUserPrefs( PrefServiceSyncable* prefs) { prefs->RegisterBooleanPref(prefs::kVideoCaptureAllowed, true, PrefServiceSyncable::UNSYNCABLE_PREF); prefs->RegisterBooleanPref(prefs::kAudioCaptureAllowed, true, PrefServiceSyncable::UNSYNCABLE_PREF); } #endif bool MediaStreamDevicesController::DismissInfoBarAndTakeActionOnSettings() { // If this is a no UI check for policies only go straight to accept - policy // check will be done automatically on the way. if (request_.request_type == content::MEDIA_OPEN_DEVICE) { Accept(false); return true; } if (request_.audio_type == content::MEDIA_TAB_AUDIO_CAPTURE || request_.video_type == content::MEDIA_TAB_VIDEO_CAPTURE || request_.video_type == content::MEDIA_DESKTOP_VIDEO_CAPTURE) { HandleTapMediaRequest(); return true; } #if 0 // Deny the request if the security origin is empty, this happens with // file access without |--allow-file-access-from-files| flag. if (request_.security_origin.is_empty()) { Deny(false); return true; } #endif // Deny the request if there is no device attached to the OS. if (!HasAnyAvailableDevice()) { Deny(false); return true; } // Check if any allow exception has been made for this request. if (IsRequestAllowedByDefault()) { Accept(false); return true; } #if 0 // Check if any block exception has been made for this request. if (IsRequestBlockedByDefault()) { Deny(false); return true; } // Check if the media default setting is set to block. if (IsDefaultMediaAccessBlocked()) { Deny(false); return true; } #endif // Don't show the infobar. return true; } const std::string& MediaStreamDevicesController::GetSecurityOriginSpec() const { return request_.security_origin.spec(); } void MediaStreamDevicesController::Accept(bool update_content_setting) { // Get the default devices for the request. content::MediaStreamDevices devices; MediaCaptureDevicesDispatcher* dispatcher = MediaInternals::GetInstance()->GetMediaCaptureDevicesDispatcher(); switch (request_.request_type) { case content::MEDIA_OPEN_DEVICE: { const content::MediaStreamDevice* device = NULL; // For open device request pick the desired device or fall back to the // first available of the given type. if (request_.audio_type == content::MEDIA_DEVICE_AUDIO_CAPTURE) { device = dispatcher-> GetRequestedAudioDevice(request_.requested_audio_device_id); // TODO(wjia): Confirm this is the intended behavior. if (!device) { device = dispatcher->GetFirstAvailableAudioDevice(); } } else if (request_.video_type == content::MEDIA_DEVICE_VIDEO_CAPTURE) { // Pepper API opens only one device at a time. device = dispatcher->GetRequestedVideoDevice(request_.requested_video_device_id); // TODO(wjia): Confirm this is the intended behavior. if (!device) { device = dispatcher->GetFirstAvailableVideoDevice(); } } if (device) devices.push_back(*device); break; } case content::MEDIA_GENERATE_STREAM: { bool needs_audio_device = has_audio_; bool needs_video_device = has_video_; // Get the exact audio or video device if an id is specified. if (!request_.requested_audio_device_id.empty()) { const content::MediaStreamDevice* audio_device = dispatcher->GetRequestedAudioDevice(request_.requested_audio_device_id); if (audio_device) { devices.push_back(*audio_device); needs_audio_device = false; } } if (!request_.requested_video_device_id.empty()) { const content::MediaStreamDevice* video_device = dispatcher->GetRequestedVideoDevice(request_.requested_video_device_id); if (video_device) { devices.push_back(*video_device); needs_video_device = false; } } // If either or both audio and video devices were requested but not // specified by id, get the default devices. if (needs_audio_device || needs_video_device) { media::GetDefaultDevicesForProfile( needs_audio_device, needs_video_device, &devices); } break; } case content::MEDIA_DEVICE_ACCESS: // Get the default devices for the request. media::GetDefaultDevicesForProfile( has_audio_, has_video_, &devices); break; case content::MEDIA_ENUMERATE_DEVICES: // Do nothing. NOTREACHED(); break; } callback_.Run(devices, scoped_ptr<content::MediaStreamUI>()); } void MediaStreamDevicesController::Deny(bool update_content_setting) { callback_.Run(content::MediaStreamDevices(), scoped_ptr<content::MediaStreamUI>()); } bool MediaStreamDevicesController::IsAudioDeviceBlockedByPolicy() const { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); return false; } bool MediaStreamDevicesController::IsVideoDeviceBlockedByPolicy() const { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); return false; } bool MediaStreamDevicesController::IsRequestAllowedByDefault() const { return true; } bool MediaStreamDevicesController::IsRequestBlockedByDefault() const { return false; } bool MediaStreamDevicesController::IsDefaultMediaAccessBlocked() const { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); return false; } void MediaStreamDevicesController::HandleTapMediaRequest() { content::MediaStreamDevices devices; if (request_.audio_type == content::MEDIA_TAB_AUDIO_CAPTURE) { devices.push_back(content::MediaStreamDevice( content::MEDIA_TAB_VIDEO_CAPTURE, "", "")); } if (request_.video_type == content::MEDIA_TAB_VIDEO_CAPTURE) { devices.push_back(content::MediaStreamDevice( content::MEDIA_TAB_AUDIO_CAPTURE, "", "")); } if (request_.video_type == content::MEDIA_DESKTOP_VIDEO_CAPTURE) { devices.push_back(content::MediaStreamDevice( content::MEDIA_DESKTOP_VIDEO_CAPTURE, std::string(), "Screen")); } callback_.Run(devices, scoped_ptr<content::MediaStreamUI>()); } bool MediaStreamDevicesController::IsSchemeSecure() const { return (request_.security_origin.SchemeIsSecure()); } bool MediaStreamDevicesController::ShouldAlwaysAllowOrigin() const { return true; }
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/nw/src/media/media_stream_devices_controller.h" #include "base/values.h" #include "content/nw/src/media/media_capture_devices_dispatcher.h" #include "content/nw/src/media/media_internals.h" #include "content/public/browser/browser_thread.h" #include "content/public/common/desktop_media_id.h" #include "content/public/common/media_stream_request.h" using content::BrowserThread; namespace { bool HasAnyAvailableDevice() { MediaCaptureDevicesDispatcher* dispatcher = MediaInternals::GetInstance()->GetMediaCaptureDevicesDispatcher(); const content::MediaStreamDevices& audio_devices = dispatcher->GetAudioCaptureDevices(); const content::MediaStreamDevices& video_devices = dispatcher->GetVideoCaptureDevices(); return !audio_devices.empty() || !video_devices.empty(); }; const char kAudioKey[] = "audio"; const char kVideoKey[] = "video"; } // namespace MediaStreamDevicesController::MediaStreamDevicesController( const content::MediaStreamRequest& request, const content::MediaResponseCallback& callback) : request_(request), callback_(callback), has_audio_(content::IsAudioMediaType(request.audio_type) && !IsAudioDeviceBlockedByPolicy()), has_video_(content::IsVideoMediaType(request.video_type) && !IsVideoDeviceBlockedByPolicy()) { } MediaStreamDevicesController::~MediaStreamDevicesController() {} #if 0 // static void MediaStreamDevicesController::RegisterUserPrefs( PrefServiceSyncable* prefs) { prefs->RegisterBooleanPref(prefs::kVideoCaptureAllowed, true, PrefServiceSyncable::UNSYNCABLE_PREF); prefs->RegisterBooleanPref(prefs::kAudioCaptureAllowed, true, PrefServiceSyncable::UNSYNCABLE_PREF); } #endif bool MediaStreamDevicesController::DismissInfoBarAndTakeActionOnSettings() { // If this is a no UI check for policies only go straight to accept - policy // check will be done automatically on the way. if (request_.request_type == content::MEDIA_OPEN_DEVICE) { Accept(false); return true; } if (request_.audio_type == content::MEDIA_TAB_AUDIO_CAPTURE || request_.video_type == content::MEDIA_TAB_VIDEO_CAPTURE || request_.video_type == content::MEDIA_DESKTOP_VIDEO_CAPTURE) { HandleTapMediaRequest(); return true; } #if 0 // Deny the request if the security origin is empty, this happens with // file access without |--allow-file-access-from-files| flag. if (request_.security_origin.is_empty()) { Deny(false); return true; } #endif // Deny the request if there is no device attached to the OS. if (!HasAnyAvailableDevice()) { Deny(false); return true; } // Check if any allow exception has been made for this request. if (IsRequestAllowedByDefault()) { Accept(false); return true; } #if 0 // Check if any block exception has been made for this request. if (IsRequestBlockedByDefault()) { Deny(false); return true; } // Check if the media default setting is set to block. if (IsDefaultMediaAccessBlocked()) { Deny(false); return true; } #endif // Don't show the infobar. return true; } const std::string& MediaStreamDevicesController::GetSecurityOriginSpec() const { return request_.security_origin.spec(); } void MediaStreamDevicesController::Accept(bool update_content_setting) { // Get the default devices for the request. content::MediaStreamDevices devices; MediaCaptureDevicesDispatcher* dispatcher = MediaInternals::GetInstance()->GetMediaCaptureDevicesDispatcher(); switch (request_.request_type) { case content::MEDIA_OPEN_DEVICE: { const content::MediaStreamDevice* device = NULL; // For open device request pick the desired device or fall back to the // first available of the given type. if (request_.audio_type == content::MEDIA_DEVICE_AUDIO_CAPTURE) { device = dispatcher-> GetRequestedAudioDevice(request_.requested_audio_device_id); // TODO(wjia): Confirm this is the intended behavior. if (!device) { device = dispatcher->GetFirstAvailableAudioDevice(); } } else if (request_.video_type == content::MEDIA_DEVICE_VIDEO_CAPTURE) { // Pepper API opens only one device at a time. device = dispatcher->GetRequestedVideoDevice(request_.requested_video_device_id); // TODO(wjia): Confirm this is the intended behavior. if (!device) { device = dispatcher->GetFirstAvailableVideoDevice(); } } if (device) devices.push_back(*device); break; } case content::MEDIA_GENERATE_STREAM: { bool needs_audio_device = has_audio_; bool needs_video_device = has_video_; // Get the exact audio or video device if an id is specified. if (!request_.requested_audio_device_id.empty()) { const content::MediaStreamDevice* audio_device = dispatcher->GetRequestedAudioDevice(request_.requested_audio_device_id); if (audio_device) { devices.push_back(*audio_device); needs_audio_device = false; } } if (!request_.requested_video_device_id.empty()) { const content::MediaStreamDevice* video_device = dispatcher->GetRequestedVideoDevice(request_.requested_video_device_id); if (video_device) { devices.push_back(*video_device); needs_video_device = false; } } // If either or both audio and video devices were requested but not // specified by id, get the default devices. if (needs_audio_device || needs_video_device) { media::GetDefaultDevicesForProfile( needs_audio_device, needs_video_device, &devices); } break; } case content::MEDIA_DEVICE_ACCESS: // Get the default devices for the request. media::GetDefaultDevicesForProfile( has_audio_, has_video_, &devices); break; case content::MEDIA_ENUMERATE_DEVICES: // Do nothing. NOTREACHED(); break; } callback_.Run(devices, scoped_ptr<content::MediaStreamUI>()); } void MediaStreamDevicesController::Deny(bool update_content_setting) { callback_.Run(content::MediaStreamDevices(), scoped_ptr<content::MediaStreamUI>()); } bool MediaStreamDevicesController::IsAudioDeviceBlockedByPolicy() const { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); return false; } bool MediaStreamDevicesController::IsVideoDeviceBlockedByPolicy() const { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); return false; } bool MediaStreamDevicesController::IsRequestAllowedByDefault() const { return true; } bool MediaStreamDevicesController::IsRequestBlockedByDefault() const { return false; } bool MediaStreamDevicesController::IsDefaultMediaAccessBlocked() const { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); return false; } void MediaStreamDevicesController::HandleTapMediaRequest() { content::MediaStreamDevices devices; if (request_.audio_type == content::MEDIA_TAB_AUDIO_CAPTURE) { devices.push_back(content::MediaStreamDevice( content::MEDIA_TAB_VIDEO_CAPTURE, "", "")); } if (request_.video_type == content::MEDIA_TAB_VIDEO_CAPTURE) { devices.push_back(content::MediaStreamDevice( content::MEDIA_TAB_AUDIO_CAPTURE, "", "")); } if (request_.video_type == content::MEDIA_DESKTOP_VIDEO_CAPTURE) { content::DesktopMediaID media_id = content::DesktopMediaID::Parse(request_.requested_video_device_id); devices.push_back(content::MediaStreamDevice( content::MEDIA_DESKTOP_VIDEO_CAPTURE, media_id.ToString(), "Screen")); } callback_.Run(devices, scoped_ptr<content::MediaStreamUI>()); } bool MediaStreamDevicesController::IsSchemeSecure() const { return (request_.security_origin.SchemeIsSecure()); } bool MediaStreamDevicesController::ShouldAlwaysAllowOrigin() const { return true; }
use media_id when doing screen capture
use media_id when doing screen capture Fix #1309
C++
mit
parksangkil/nw.js,Sunggil/nw.js,askdaddy/nw.js,markYoungH/nw.js,nwjs/nw.js,Arteris/nw.js,chinakids/nw.js,youprofit/nw.js,mvinan/nw.js,pztrick/nw.js,zhangtianye/node-webkit,Ivshti/node-webkit,fancycode/node-webkit,M4sse/nw.js,liu78778/node-webkit,ondra-novak/nw.js,PUSEN/nw.js,markYoungH/nw.js,xzmagic/nw.js,Jonekee/nw.js,liu78778/node-webkit,wpsmith/nw.js,weave-lab/nw.js,parlaylabs/nw.js,dushu1203/nw.js,Ivshti/node-webkit,iesus17/nw.js,mylikes/nw.js,RobertoMalatesta/nw.js,mauricionr/nw.js,zhangtianye/node-webkit,jaruba/nw.js,tshinnic/nw.js,iesus17/nw.js,yshyee/nw.js,markYoungH/nw.js,PUSEN/nw.js,nwjs/nw.js,sumyfly/nw.js,wakermahmud/nw.js,XenonDevelops/nw.js,weave-lab/nw.js,nwjs/nw.js,ezshine/nw.js,mcanthony/nw.js,lifeinoppo/nw.js,kurainooni/nw.js,youprofit/nw.js,artBrown/nw.js,RobertoMalatesta/nw.js,techlabs28/nw.js,XenonDevelops/nw.js,glizer/nw.js,amoylel/nw.js,KaminoDice/nw.js,Arteris/nw.js,trojanspike/nw.js,jaruba/nw.js,angeliaz/nw.js,p5150j/nw.js,trojanspike/nw.js,angeliaz/nw.js,pdx1989/nw.js,initialjk/node-webkit,techlabs28/nw.js,GabrielNicolasAvellaneda/nw.js,xzmagic/nw.js,haroldoramirez/nw.js,zhangweiabc/nw.js,glizer/nw.js,imshibaji/nw.js,mcdongWang/nwjs_Chinese,pdx1989/nw.js,bright-sparks/nw.js,InnerAc/nw.js,zcczcw/nw.js,chengky/nw.js,AustinKwang/nw.js,erickuofucker/nw.js,dougmolineux/nw.js,zcczcw/nw.js,angeliaz/nw.js,VolosSoftware/nw.js,ezshine/nw.js,sumyfly/nw.js,ezshine/nw.js,mylikes/nw.js,parlaylabs/nw.js,trojanspike/nw.js,iesus17/nw.js,eprincev-egor/nw.js,parksangkil/nw.js,weave-lab/nw.js,InnerAc/nw.js,mcanthony/nw.js,Sunggil/nw.js,VolosSoftware/nw.js,kurainooni/nw.js,wakermahmud/nw.js,mcanthony/nw.js,jomolinare/nw.js,zhangweiabc/nw.js,techlabs28/nw.js,xzmagic/nw.js,jomolinare/nw.js,mylikes/nw.js,haroldoramirez/nw.js,xebitstudios/nw.js,jomaf1010/nw.js,Arteris/nw.js,redgecombe/nw.js,ezshine/nw.js,parksangkil/nw.js,chengky/nw.js,kurainooni/nw.js,mcdongWang/nwjs_Chinese,composite/nw.js,parlaylabs/nw.js,mvinan/nw.js,parlaylabs/nw.js,lifeinoppo/nw.js,AustinKwang/nw.js,InnerAc/nw.js,Wombatpm/node-webkit,RobertoMalatesta/nw.js,youprofit/nw.js,GabrielNicolasAvellaneda/nw.js,dougmolineux/nw.js,chinakids/nw.js,luiseduardohdbackup/nw.js,markYoungH/nw.js,zhangweiabc/nw.js,amoylel/nw.js,youprofit/nw.js,trevorlinton/tint,Wombatpm/node-webkit,occupytheweb/nw.js,pztrick/nw.js,KaminoDice/nw.js,luisbrito/nw.js,zcczcw/nw.js,parksangkil/nw.js,pztrick/nw.js,lidxgz/nw.js,alex-zhang/nw.js,Ivshti/node-webkit,baiwyc119/nw.js,youprofit/nw.js,belmer/nw.js,tshinnic/nw.js,baiwyc119/nw.js,ondra-novak/nw.js,bright-sparks/nw.js,InnerAc/nw.js,lifeinoppo/nw.js,happy-barrage/nw.js,eprincev-egor/nw.js,280455936/nw.js,mylikes/nw.js,Ivshti/node-webkit,amoylel/nw.js,happy-barrage/nw.js,liu78778/node-webkit,nwjs/nw.js,redgecombe/nw.js,kurainooni/nw.js,glizer/nw.js,parksangkil/nw.js,fancycode/node-webkit,parlaylabs/nw.js,RobertoMalatesta/nw.js,alex-zhang/nw.js,redgecombe/nw.js,InnerAc/nw.js,tanzhihang/nw.js,XenonDevelops/nw.js,tanzhihang/nw.js,advisory/nw.js,GabrielNicolasAvellaneda/nw.js,jqk6/nw.js,luisbrito/nw.js,sumyfly/nw.js,eprincev-egor/nw.js,nwjs/nw.js,jomolinare/nw.js,Ivshti/node-webkit,techlabs28/nw.js,jqk6/nw.js,Arteris/nw.js,alex-zhang/nw.js,xebitstudios/nw.js,luisbrito/nw.js,artBrown/nw.js,dougmolineux/nw.js,VolosSoftware/nw.js,wpsmith/nw.js,lifeinoppo/nw.js,jaruba/nw.js,chinakids/nw.js,trojanspike/nw.js,composite/nw.js,GabrielNicolasAvellaneda/nw.js,p5150j/nw.js,GabrielNicolasAvellaneda/nw.js,haroldoramirez/nw.js,zhangtianye/node-webkit,mvinan/nw.js,imshibaji/nw.js,wpsmith/nw.js,weave-lab/nw.js,Jonekee/nw.js,occupytheweb/nw.js,haroldoramirez/nw.js,zhangweiabc/nw.js,composite/nw.js,luiseduardohdbackup/nw.js,wakermahmud/nw.js,weave-lab/nw.js,dushu1203/nw.js,parksangkil/nw.js,belmer/nw.js,RobertoMalatesta/nw.js,fancycode/node-webkit,bright-sparks/nw.js,jomolinare/nw.js,angeliaz/nw.js,VolosSoftware/nw.js,advisory/nw.js,p5150j/nw.js,mcdongWang/nwjs_Chinese,initialjk/node-webkit,nwjs/nw.js,dougmolineux/nw.js,askdaddy/nw.js,M4sse/nw.js,Jonekee/nw.js,luiseduardohdbackup/nw.js,yshyee/nw.js,zhaosichao/nw.js,tshinnic/nw.js,ondra-novak/nw.js,initialjk/node-webkit,VolosSoftware/nw.js,askdaddy/nw.js,parlaylabs/nw.js,Arteris/nw.js,askdaddy/nw.js,VolosSoftware/nw.js,advisory/nw.js,sumyfly/nw.js,trevorlinton/tint,eprincev-egor/nw.js,280455936/nw.js,InnerAc/nw.js,Wombatpm/node-webkit,chinakids/nw.js,eprincev-egor/nw.js,yshyee/nw.js,bright-sparks/nw.js,280455936/nw.js,jaruba/nw.js,composite/nw.js,mvinan/nw.js,jqk6/nw.js,wakermahmud/nw.js,mauricionr/nw.js,erickuofucker/nw.js,redgecombe/nw.js,wpsmith/nw.js,jaruba/nw.js,techlabs28/nw.js,lifeinoppo/nw.js,ysjian/nw.js,Sunggil/nw.js,mcdongWang/nwjs_Chinese,280455936/nw.js,Wombatpm/node-webkit,xebitstudios/nw.js,XenonDevelops/nw.js,zcczcw/nw.js,dushu1203/nw.js,Sunggil/nw.js,occupytheweb/nw.js,ysjian/nw.js,pdx1989/nw.js,amoylel/nw.js,Wombatpm/node-webkit,Arteris/nw.js,mylikes/nw.js,280455936/nw.js,glizer/nw.js,alex-zhang/nw.js,lidxgz/nw.js,weave-lab/nw.js,occupytheweb/nw.js,trueinteractions/tint,jaruba/nw.js,erickuofucker/nw.js,Sunggil/nw.js,composite/nw.js,zcczcw/nw.js,jomaf1010/nw.js,wakermahmud/nw.js,redgecombe/nw.js,zhaosichao/nw.js,initialjk/node-webkit,jqk6/nw.js,luisbrito/nw.js,belmer/nw.js,initialjk/node-webkit,tanzhihang/nw.js,ezshine/nw.js,happy-barrage/nw.js,imshibaji/nw.js,baiwyc119/nw.js,artBrown/nw.js,artBrown/nw.js,glizer/nw.js,pdx1989/nw.js,ysjian/nw.js,280455936/nw.js,askdaddy/nw.js,imshibaji/nw.js,iesus17/nw.js,baiwyc119/nw.js,trojanspike/nw.js,AustinKwang/nw.js,Jonekee/nw.js,xzmagic/nw.js,alex-zhang/nw.js,redgecombe/nw.js,trojanspike/nw.js,fancycode/node-webkit,pztrick/nw.js,haroldoramirez/nw.js,redgecombe/nw.js,lidxgz/nw.js,erickuofucker/nw.js,trojanspike/nw.js,markYoungH/nw.js,initialjk/node-webkit,pztrick/nw.js,pdx1989/nw.js,pztrick/nw.js,KaminoDice/nw.js,AustinKwang/nw.js,tanzhihang/nw.js,PUSEN/nw.js,p5150j/nw.js,xzmagic/nw.js,Arteris/nw.js,GabrielNicolasAvellaneda/nw.js,Wombatpm/node-webkit,pdx1989/nw.js,chengky/nw.js,AustinKwang/nw.js,angeliaz/nw.js,tshinnic/nw.js,mcanthony/nw.js,occupytheweb/nw.js,erickuofucker/nw.js,RobertoMalatesta/nw.js,ezshine/nw.js,Sunggil/nw.js,liu78778/node-webkit,askdaddy/nw.js,parlaylabs/nw.js,composite/nw.js,fancycode/node-webkit,weave-lab/nw.js,Jonekee/nw.js,iesus17/nw.js,techlabs28/nw.js,trevorlinton/tint,jomolinare/nw.js,zhangweiabc/nw.js,wpsmith/nw.js,artBrown/nw.js,youprofit/nw.js,mylikes/nw.js,kurainooni/nw.js,belmer/nw.js,M4sse/nw.js,jqk6/nw.js,xebitstudios/nw.js,techlabs28/nw.js,p5150j/nw.js,dushu1203/nw.js,ezshine/nw.js,erickuofucker/nw.js,Sunggil/nw.js,mcanthony/nw.js,KaminoDice/nw.js,lifeinoppo/nw.js,amoylel/nw.js,jomolinare/nw.js,erickuofucker/nw.js,trueinteractions/tint,PUSEN/nw.js,chinakids/nw.js,AustinKwang/nw.js,haroldoramirez/nw.js,advisory/nw.js,baiwyc119/nw.js,tanzhihang/nw.js,Jonekee/nw.js,amoylel/nw.js,happy-barrage/nw.js,belmer/nw.js,xebitstudios/nw.js,mcdongWang/nwjs_Chinese,chengky/nw.js,jqk6/nw.js,kurainooni/nw.js,dushu1203/nw.js,luisbrito/nw.js,sumyfly/nw.js,baiwyc119/nw.js,luiseduardohdbackup/nw.js,mauricionr/nw.js,dushu1203/nw.js,KaminoDice/nw.js,luiseduardohdbackup/nw.js,luisbrito/nw.js,ysjian/nw.js,dougmolineux/nw.js,zhangweiabc/nw.js,p5150j/nw.js,chinakids/nw.js,sumyfly/nw.js,happy-barrage/nw.js,initialjk/node-webkit,imshibaji/nw.js,dougmolineux/nw.js,advisory/nw.js,trueinteractions/tint,280455936/nw.js,chengky/nw.js,zhangtianye/node-webkit,zcczcw/nw.js,jomaf1010/nw.js,lidxgz/nw.js,trevorlinton/tint,alex-zhang/nw.js,kurainooni/nw.js,mcdongWang/nwjs_Chinese,liu78778/node-webkit,Wombatpm/node-webkit,tshinnic/nw.js,belmer/nw.js,alex-zhang/nw.js,liu78778/node-webkit,mcanthony/nw.js,KaminoDice/nw.js,artBrown/nw.js,zhangweiabc/nw.js,ysjian/nw.js,Jonekee/nw.js,trueinteractions/tint,jaruba/nw.js,mauricionr/nw.js,pztrick/nw.js,M4sse/nw.js,RobertoMalatesta/nw.js,belmer/nw.js,GabrielNicolasAvellaneda/nw.js,angeliaz/nw.js,XenonDevelops/nw.js,lidxgz/nw.js,yshyee/nw.js,bright-sparks/nw.js,ondra-novak/nw.js,zhaosichao/nw.js,chinakids/nw.js,mvinan/nw.js,markYoungH/nw.js,xzmagic/nw.js,happy-barrage/nw.js,mvinan/nw.js,advisory/nw.js,XenonDevelops/nw.js,trueinteractions/tint,tshinnic/nw.js,baiwyc119/nw.js,zhaosichao/nw.js,bright-sparks/nw.js,zcczcw/nw.js,AustinKwang/nw.js,mylikes/nw.js,advisory/nw.js,zhaosichao/nw.js,sumyfly/nw.js,M4sse/nw.js,lifeinoppo/nw.js,xebitstudios/nw.js,xebitstudios/nw.js,ondra-novak/nw.js,luiseduardohdbackup/nw.js,zhaosichao/nw.js,jomaf1010/nw.js,jomolinare/nw.js,KaminoDice/nw.js,eprincev-egor/nw.js,occupytheweb/nw.js,dougmolineux/nw.js,XenonDevelops/nw.js,zhangtianye/node-webkit,yshyee/nw.js,wakermahmud/nw.js,happy-barrage/nw.js,jomaf1010/nw.js,trueinteractions/tint,dushu1203/nw.js,composite/nw.js,wakermahmud/nw.js,iesus17/nw.js,bright-sparks/nw.js,PUSEN/nw.js,angeliaz/nw.js,trevorlinton/tint,luiseduardohdbackup/nw.js,mauricionr/nw.js,Ivshti/node-webkit,trevorlinton/tint,yshyee/nw.js,amoylel/nw.js,VolosSoftware/nw.js,wpsmith/nw.js,askdaddy/nw.js,wpsmith/nw.js,youprofit/nw.js,mcanthony/nw.js,InnerAc/nw.js,p5150j/nw.js,iesus17/nw.js,eprincev-egor/nw.js,PUSEN/nw.js,M4sse/nw.js,PUSEN/nw.js,yshyee/nw.js,haroldoramirez/nw.js,M4sse/nw.js,imshibaji/nw.js,pdx1989/nw.js,ysjian/nw.js,zhangtianye/node-webkit,tanzhihang/nw.js,lidxgz/nw.js,chengky/nw.js,xzmagic/nw.js,fancycode/node-webkit,chengky/nw.js,jqk6/nw.js,parksangkil/nw.js,ysjian/nw.js,mvinan/nw.js,zhaosichao/nw.js,glizer/nw.js,luisbrito/nw.js,artBrown/nw.js,lidxgz/nw.js,ondra-novak/nw.js,imshibaji/nw.js,mauricionr/nw.js,tshinnic/nw.js,trueinteractions/tint,jomaf1010/nw.js,tanzhihang/nw.js,markYoungH/nw.js,occupytheweb/nw.js,jomaf1010/nw.js,ondra-novak/nw.js,glizer/nw.js
7b48aa4a9f2e79aaf9ff5253128f9a54482546db
Applications/Rasterization/otbRasterization.cxx
Applications/Rasterization/otbRasterization.cxx
/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "otbWrapperApplication.h" #include "otbWrapperApplicationFactory.h" #include "otbGeoInformationConversion.h" #include "otbOGRDataSourceWrapper.h" #include "otbOGRDataSourceToLabelImageFilter.h" #include "otbGenericRSTransform.h" namespace otb { namespace Wrapper { class Rasterization : public Application { public: /** Standard class typedefs. */ typedef Rasterization Self; typedef Application Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; /** Standard macro */ itkNewMacro(Self); itkTypeMacro(Rasterization, otb::Application); /** Filters typedef */ // the application produces a binary mask : no need to use a FloatVectorImageType typedef UInt8ImageType::PointType PointType; typedef UInt8ImageType::SizeType SizeType; typedef UInt8ImageType::SpacingType SpacingType; typedef UInt8ImageType::IndexType IndexType; // Misc typedef otb::GenericRSTransform<> RSTransformType; typedef otb::PipelineMemoryPrintCalculator MemoryCalculatorType; // Exact rasterization mode typedef otb::OGRDataSourceToLabelImageFilter<FloatImageType> OGRDataSourceToMapFilterType; private: void DoInit() { SetName("Rasterization"); SetDescription("Rasterize a vector dataset."); SetDocName("Rasterization"); SetDocLongDescription("This application allows to reproject and rasterize a vector dataset. The grid of the rasterized output can be set by using a reference image, or by setting all parmeters (origin, size, spacing) by hand. In the latter case, at least the spacing (ground sampling distance) is needed (other parameters are computed automatically). The rasterized output can also be in a different projection reference system than the input dataset.\n There are two rasterize mode available in the application. The first is the binary mode: it allows to render all pixels belonging to a geometry of the input dataset in the foreground color, while rendering the other in background color. The second one allows to render pixels belonging to a geometry woth respect to an attribute of this geometry. The field of the attribute to render can be set by the user. In the second mode, the background value is still used for unassociated pixels."); SetDocLimitations("None"); SetDocAuthors("OTB-Team"); SetDocSeeAlso("For now, support of input dataset with multiple layers having different projection reference system is limited."); AddDocTag(Tags::Vector); AddParameter(ParameterType_InputFilename, "in", "Input vector dataset"); SetParameterDescription( "in", "The input vector dataset to be rasterized" ); AddParameter(ParameterType_OutputImage, "out", "Ouptut image"); SetParameterDescription( "out", "An output image containing the rasterized vector dataset" ); AddParameter(ParameterType_InputImage, "im", "Input reference image"); SetParameterDescription( "im", "A reference image from which to import output grid and projection reference system information." ); MandatoryOff("im"); AddParameter(ParameterType_Int, "szx", "Output size x"); SetParameterDescription( "szx", "Output size along x axis (useless if support image is given)" ); MandatoryOff("szx"); SetMinimumParameterIntValue("szx",1); AddParameter(ParameterType_Int, "szy", "Output size y"); SetParameterDescription( "szy", "Output size along y axis (useless if support image is given)" ); MandatoryOff("szy"); SetMinimumParameterIntValue("szy",1); AddParameter(ParameterType_Int, "epsg", "Output EPSG code"); SetParameterDescription( "epsg", "EPSG code for the output projection reference system (EPSG 4326 for WGS84, 32631 for UTM31N...,useless if support image is given)" ); MandatoryOff("epsg"); AddParameter(ParameterType_Float, "orx", "Output Upper-left x"); SetParameterDescription( "orx", "Output upper-left x coordinate (useless if support image is given)" ); MandatoryOff("orx"); AddParameter(ParameterType_Float, "ory", "Output Upper-left y"); SetParameterDescription( "ory", "Output upper-left y coordinate (useless if support image is given)" ); MandatoryOff("ory"); AddParameter(ParameterType_Float, "spx", "Spacing (GSD) x"); SetParameterDescription( "spx", "Spacing (ground sampling distance) along x axis (useless if support image is given)" ); MandatoryOff("spx"); AddParameter(ParameterType_Float, "spy", "Spacing (GSD) y"); SetParameterDescription( "spy", "Spacing (ground sampling distance) along y axis (useless if support image is given)" ); MandatoryOff("spy"); AddParameter(ParameterType_Float,"background", "Background value"); SetParameterDescription("background","Default value for pixels not belonging to any geometry"); SetDefaultParameterFloat("background",0.); AddParameter(ParameterType_Choice,"mode","Rasterization mode"); SetParameterDescription("mode","Choice of rasterization modes"); AddChoice("mode.binary","Binary mode"); SetParameterDescription("mode.binary","In this mode, pixels within a geometry will hold the user-defined foreground value"); AddParameter(ParameterType_Float,"mode.binary.foreground","Foreground value"); SetParameterDescription("mode.binary.foreground","Value for pixels inside a geometry"); SetDefaultParameterFloat("mode.binary.foreground",255); AddChoice("mode.attribute","Attribute burning mode"); SetParameterDescription("mode.attribute","In this mode, pixels within a geometry will hold the value of a user-defined field extracted from this geometry."); AddParameter(ParameterType_String,"mode.attribute.field","The attribute field to burn"); SetParameterDescription("mode.attribute.field","Name of the attribute field to burn"); SetParameterString("mode.attribute.field","DN"); AddRAMParameter(); SetDocExampleParameterValue("in","qb_RoadExtract_classification.shp"); SetDocExampleParameterValue("out", "rasterImage.tif"); SetDocExampleParameterValue("spx","1."); SetDocExampleParameterValue("spy","1."); } void DoUpdateParameters() { // Nothing to do } void DoExecute() { otb::ogr::DataSource::Pointer ogrDS; UInt8ImageType::Pointer referenceImage; ogrDS = otb::ogr::DataSource::New(GetParameterString("in"), otb::ogr::DataSource::Modes::read); bool validInputProjRef = false; std::string inputProjectionRef = ""; otb::ogr::DataSource::const_iterator lit = ogrDS->begin(); // Retrieve extent double ulx, uly, lrx, lry; bool extentAvailable = true; try { inputProjectionRef = ogrDS->GetGlobalExtent(ulx,uly,lrx,lry); } catch(itk::ExceptionObject & err) { extentAvailable = false; } if(!extentAvailable && (!(HasValue("spx") && HasValue("spy")) || (!(HasValue("orx") && HasValue("ory"))))) { otbAppLogWARNING(<<"Failed to retrieve the spatial extent of the dataset. The application will retry in force mode, which means it might have to walk the entire dataset to determine extent. This might be a long process for large datasets. Consider setting the orx, ory, spx and spy parameters."); try { inputProjectionRef = ogrDS->GetGlobalExtent(ulx,uly,lrx,lry,true); extentAvailable = true; } catch(itk::ExceptionObject & err) { extentAvailable = false; otbAppLogFATAL(<<"Failed to retrieve the spatial extent of the dataset in force mode. The spatial extent is mandatory when orx, ory, spx and spy parameters are not set, consider setting them. Error from library: "<<err.GetDescription()); } } if(extentAvailable) { otbAppLogINFO("Input dataset extent is ("<<ulx<<", "<<uly<<") ("<<lrx<<", "<<lry<<")"); } if(inputProjectionRef == "") { otbAppLogWARNING("Failed to find a valid projection ref in dataset. The application will assume that the given reference image or origin, spacing and size are consistent with the dataset geometry. Output EPSG code will be ignored."); validInputProjRef = false; } else { validInputProjRef = true; otbAppLogINFO("Input dataset projection reference system is: "<<inputProjectionRef); } // region information SizeType size; PointType origin; SpacingType spacing; // reading projection information // two choice : std::string outputProjectionRef; // a reference image is given as input if (HasValue("im")) { if (HasValue("szx") || HasValue("szy") || HasValue("orx") || HasValue("ory") || HasValue("spx") || HasValue("spy") || HasValue("epsg")) { otbAppLogWARNING("A reference image has been given, other parameters " "regarding the output image will be ignored"); } referenceImage = GetParameterUInt8Image("im"); outputProjectionRef = referenceImage->GetProjectionRef(); size = referenceImage->GetLargestPossibleRegion().GetSize(); origin = referenceImage->GetOrigin(); spacing = referenceImage->GetSpacing(); } else if (HasValue("spx") && HasValue("spy")) { if (HasValue("epsg")) { unsigned int RSID = GetParameterInt("epsg"); outputProjectionRef = otb::GeoInformationConversion::ToWKT(RSID); } else { outputProjectionRef = inputProjectionRef; } spacing[0] = GetParameterFloat("spx"); spacing[1] = GetParameterFloat("spy"); if ( HasValue("orx") && HasValue("ory")) { origin[0] = GetParameterFloat("orx"); origin[1] = GetParameterFloat("ory"); } else if(extentAvailable) { origin[0] = (spacing[0] > 0 ? ulx : lrx); origin[1] = (spacing[1] > 0 ? uly : lry); // Transform to output EPSG if(validInputProjRef) { RSTransformType::Pointer rsTransform = RSTransformType::New(); rsTransform->SetInputProjectionRef(inputProjectionRef); rsTransform->SetOutputProjectionRef(outputProjectionRef); rsTransform->InstanciateTransform(); origin = rsTransform->TransformPoint(origin); } } else { otbAppLogFATAL(<<"The orx and ory parameters are not set and the dataset extent could not be retrieved. The application can not determine the origin of the output raster"); } if (HasValue("szx") && HasValue("szy")) { size[0] = GetParameterInt("szx"); size[1] = GetParameterInt("szy"); } else if(extentAvailable) { // Transform to output EPSG PointType lrout; lrout[0] = (spacing[0] > 0 ? lrx : ulx); lrout[1] = (spacing[1] > 0 ? lry : uly); if(validInputProjRef) { RSTransformType::Pointer rsTransform = RSTransformType::New(); rsTransform->SetInputProjectionRef(inputProjectionRef); rsTransform->SetOutputProjectionRef(outputProjectionRef); rsTransform->InstanciateTransform(); lrout = rsTransform->TransformPoint(lrout); } size[0]=static_cast<unsigned int>((lrout[0] - origin[0])/spacing[0]); size[1]=static_cast<unsigned int>((lrout[1] - origin[1])/spacing[1]); } else { otbAppLogFATAL(<<"The szx and szy parameters are not set and the dataset extent could not be retrieved. The application can not deterimine the size of the output raster"); } } else { otbAppLogFATAL("No reference image was given, at least spx and spy parameters must be set."); } m_OGRDataSourceRendering = OGRDataSourceToMapFilterType::New(); m_OGRDataSourceRendering->AddOGRDataSource(ogrDS); m_OGRDataSourceRendering->SetOutputSize(size); m_OGRDataSourceRendering->SetOutputOrigin(origin); m_OGRDataSourceRendering->SetOutputSpacing(spacing); m_OGRDataSourceRendering->SetBackgroundValue(GetParameterFloat("background")); if(GetParameterString("mode") == "binary") { m_OGRDataSourceRendering->SetBurnAttributeMode(false); m_OGRDataSourceRendering->SetForegroundValue(GetParameterFloat("mode.binary.foreground")); } else if(GetParameterString("mode") == "attribute") { m_OGRDataSourceRendering->SetBurnAttributeMode(true); m_OGRDataSourceRendering->SetBurnAttribute(GetParameterString("mode.attribute.field")); } if(validInputProjRef) { m_OGRDataSourceRendering->SetOutputProjectionRef(outputProjectionRef); } otbAppLogINFO("Output projection reference system is: "<<outputProjectionRef); otbAppLogINFO("Output origin: "<<origin); otbAppLogINFO("Output size: "<<size); otbAppLogINFO("Output spacing: "<<spacing); SetParameterOutputImage<FloatImageType>("out", m_OGRDataSourceRendering->GetOutput()); } OGRDataSourceToMapFilterType::Pointer m_OGRDataSourceRendering; }; } } OTB_APPLICATION_EXPORT(otb::Wrapper::Rasterization)
/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "otbWrapperApplication.h" #include "otbWrapperApplicationFactory.h" #include "otbGeoInformationConversion.h" #include "otbOGRDataSourceWrapper.h" #include "otbOGRDataSourceToLabelImageFilter.h" #include "otbGenericRSTransform.h" namespace otb { namespace Wrapper { class Rasterization : public Application { public: /** Standard class typedefs. */ typedef Rasterization Self; typedef Application Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; /** Standard macro */ itkNewMacro(Self); itkTypeMacro(Rasterization, otb::Application); /** Filters typedef */ // the application produces a binary mask : no need to use a FloatVectorImageType typedef UInt8ImageType::PointType PointType; typedef UInt8ImageType::SizeType SizeType; typedef UInt8ImageType::SpacingType SpacingType; typedef UInt8ImageType::IndexType IndexType; // Misc typedef otb::GenericRSTransform<> RSTransformType; typedef otb::PipelineMemoryPrintCalculator MemoryCalculatorType; // Exact rasterization mode typedef otb::OGRDataSourceToLabelImageFilter<FloatImageType> OGRDataSourceToMapFilterType; private: void DoInit() { SetName("Rasterization"); SetDescription("Rasterize a vector dataset."); SetDocName("Rasterization"); SetDocLongDescription("This application allows to reproject and rasterize a vector dataset. The grid of the rasterized output can be set by using a reference image, or by setting all parmeters (origin, size, spacing) by hand. In the latter case, at least the spacing (ground sampling distance) is needed (other parameters are computed automatically). The rasterized output can also be in a different projection reference system than the input dataset.\n There are two rasterize mode available in the application. The first is the binary mode: it allows to render all pixels belonging to a geometry of the input dataset in the foreground color, while rendering the other in background color. The second one allows to render pixels belonging to a geometry woth respect to an attribute of this geometry. The field of the attribute to render can be set by the user. In the second mode, the background value is still used for unassociated pixels."); SetDocLimitations("None"); SetDocAuthors("OTB-Team"); SetDocSeeAlso("For now, support of input dataset with multiple layers having different projection reference system is limited."); AddDocTag(Tags::Vector); AddParameter(ParameterType_InputFilename, "in", "Input vector dataset"); SetParameterDescription( "in", "The input vector dataset to be rasterized" ); AddParameter(ParameterType_OutputImage, "out", "Ouptut image"); SetParameterDescription( "out", "An output image containing the rasterized vector dataset" ); AddParameter(ParameterType_InputImage, "im", "Input reference image"); SetParameterDescription( "im", "A reference image from which to import output grid and projection reference system information." ); MandatoryOff("im"); AddParameter(ParameterType_Int, "szx", "Output size x"); SetParameterDescription( "szx", "Output size along x axis (useless if support image is given)" ); MandatoryOff("szx"); SetMinimumParameterIntValue("szx",1); AddParameter(ParameterType_Int, "szy", "Output size y"); SetParameterDescription( "szy", "Output size along y axis (useless if support image is given)" ); MandatoryOff("szy"); SetMinimumParameterIntValue("szy",1); AddParameter(ParameterType_Int, "epsg", "Output EPSG code"); SetParameterDescription( "epsg", "EPSG code for the output projection reference system (EPSG 4326 for WGS84, 32631 for UTM31N...,useless if support image is given)" ); MandatoryOff("epsg"); AddParameter(ParameterType_Float, "orx", "Output Upper-left x"); SetParameterDescription( "orx", "Output upper-left x coordinate (useless if support image is given)" ); MandatoryOff("orx"); AddParameter(ParameterType_Float, "ory", "Output Upper-left y"); SetParameterDescription( "ory", "Output upper-left y coordinate (useless if support image is given)" ); MandatoryOff("ory"); AddParameter(ParameterType_Float, "spx", "Spacing (GSD) x"); SetParameterDescription( "spx", "Spacing (ground sampling distance) along x axis (useless if support image is given)" ); MandatoryOff("spx"); AddParameter(ParameterType_Float, "spy", "Spacing (GSD) y"); SetParameterDescription( "spy", "Spacing (ground sampling distance) along y axis (useless if support image is given)" ); MandatoryOff("spy"); AddParameter(ParameterType_Float,"background", "Background value"); SetParameterDescription("background","Default value for pixels not belonging to any geometry"); SetDefaultParameterFloat("background",0.); AddParameter(ParameterType_Choice,"mode","Rasterization mode"); SetParameterDescription("mode","Choice of rasterization modes"); AddChoice("mode.binary","Binary mode"); SetParameterDescription("mode.binary","In this mode, pixels within a geometry will hold the user-defined foreground value"); AddParameter(ParameterType_Float,"mode.binary.foreground","Foreground value"); SetParameterDescription("mode.binary.foreground","Value for pixels inside a geometry"); SetDefaultParameterFloat("mode.binary.foreground",255); AddChoice("mode.attribute","Attribute burning mode"); SetParameterDescription("mode.attribute","In this mode, pixels within a geometry will hold the value of a user-defined field extracted from this geometry."); AddParameter(ParameterType_String,"mode.attribute.field","The attribute field to burn"); SetParameterDescription("mode.attribute.field","Name of the attribute field to burn"); SetParameterString("mode.attribute.field","DN"); AddRAMParameter(); SetDocExampleParameterValue("in","qb_RoadExtract_classification.shp"); SetDocExampleParameterValue("out", "rasterImage.tif"); SetDocExampleParameterValue("spx","1."); SetDocExampleParameterValue("spy","1."); } void DoUpdateParameters() { // Nothing to do } void DoExecute() { otb::ogr::DataSource::Pointer ogrDS; UInt8ImageType::Pointer referenceImage; ogrDS = otb::ogr::DataSource::New(GetParameterString("in"), otb::ogr::DataSource::Modes::read); bool validInputProjRef = false; std::string inputProjectionRef = ""; otb::ogr::DataSource::const_iterator lit = ogrDS->begin(); // Retrieve extent double ulx, uly, lrx, lry; bool extentAvailable = true; try { inputProjectionRef = ogrDS->GetGlobalExtent(ulx,uly,lrx,lry); } catch(const itk::ExceptionObject&) { extentAvailable = false; } if(!extentAvailable && (!(HasValue("spx") && HasValue("spy")) || (!(HasValue("orx") && HasValue("ory"))))) { otbAppLogWARNING(<<"Failed to retrieve the spatial extent of the dataset. The application will retry in force mode, which means it might have to walk the entire dataset to determine extent. This might be a long process for large datasets. Consider setting the orx, ory, spx and spy parameters."); try { inputProjectionRef = ogrDS->GetGlobalExtent(ulx,uly,lrx,lry,true); extentAvailable = true; } catch(itk::ExceptionObject & err) { extentAvailable = false; otbAppLogFATAL(<<"Failed to retrieve the spatial extent of the dataset in force mode. The spatial extent is mandatory when orx, ory, spx and spy parameters are not set, consider setting them. Error from library: "<<err.GetDescription()); } } if(extentAvailable) { otbAppLogINFO("Input dataset extent is ("<<ulx<<", "<<uly<<") ("<<lrx<<", "<<lry<<")"); } if(inputProjectionRef == "") { otbAppLogWARNING("Failed to find a valid projection ref in dataset. The application will assume that the given reference image or origin, spacing and size are consistent with the dataset geometry. Output EPSG code will be ignored."); validInputProjRef = false; } else { validInputProjRef = true; otbAppLogINFO("Input dataset projection reference system is: "<<inputProjectionRef); } // region information SizeType size; PointType origin; SpacingType spacing; // reading projection information // two choice : std::string outputProjectionRef; // a reference image is given as input if (HasValue("im")) { if (HasValue("szx") || HasValue("szy") || HasValue("orx") || HasValue("ory") || HasValue("spx") || HasValue("spy") || HasValue("epsg")) { otbAppLogWARNING("A reference image has been given, other parameters " "regarding the output image will be ignored"); } referenceImage = GetParameterUInt8Image("im"); outputProjectionRef = referenceImage->GetProjectionRef(); size = referenceImage->GetLargestPossibleRegion().GetSize(); origin = referenceImage->GetOrigin(); spacing = referenceImage->GetSpacing(); } else if (HasValue("spx") && HasValue("spy")) { if (HasValue("epsg")) { unsigned int RSID = GetParameterInt("epsg"); outputProjectionRef = otb::GeoInformationConversion::ToWKT(RSID); } else { outputProjectionRef = inputProjectionRef; } spacing[0] = GetParameterFloat("spx"); spacing[1] = GetParameterFloat("spy"); if ( HasValue("orx") && HasValue("ory")) { origin[0] = GetParameterFloat("orx"); origin[1] = GetParameterFloat("ory"); } else if(extentAvailable) { origin[0] = (spacing[0] > 0 ? ulx : lrx); origin[1] = (spacing[1] > 0 ? uly : lry); // Transform to output EPSG if(validInputProjRef) { RSTransformType::Pointer rsTransform = RSTransformType::New(); rsTransform->SetInputProjectionRef(inputProjectionRef); rsTransform->SetOutputProjectionRef(outputProjectionRef); rsTransform->InstanciateTransform(); origin = rsTransform->TransformPoint(origin); } } else { otbAppLogFATAL(<<"The orx and ory parameters are not set and the dataset extent could not be retrieved. The application can not determine the origin of the output raster"); } if (HasValue("szx") && HasValue("szy")) { size[0] = GetParameterInt("szx"); size[1] = GetParameterInt("szy"); } else if(extentAvailable) { // Transform to output EPSG PointType lrout; lrout[0] = (spacing[0] > 0 ? lrx : ulx); lrout[1] = (spacing[1] > 0 ? lry : uly); if(validInputProjRef) { RSTransformType::Pointer rsTransform = RSTransformType::New(); rsTransform->SetInputProjectionRef(inputProjectionRef); rsTransform->SetOutputProjectionRef(outputProjectionRef); rsTransform->InstanciateTransform(); lrout = rsTransform->TransformPoint(lrout); } size[0]=static_cast<unsigned int>((lrout[0] - origin[0])/spacing[0]); size[1]=static_cast<unsigned int>((lrout[1] - origin[1])/spacing[1]); } else { otbAppLogFATAL(<<"The szx and szy parameters are not set and the dataset extent could not be retrieved. The application can not deterimine the size of the output raster"); } } else { otbAppLogFATAL("No reference image was given, at least spx and spy parameters must be set."); } m_OGRDataSourceRendering = OGRDataSourceToMapFilterType::New(); m_OGRDataSourceRendering->AddOGRDataSource(ogrDS); m_OGRDataSourceRendering->SetOutputSize(size); m_OGRDataSourceRendering->SetOutputOrigin(origin); m_OGRDataSourceRendering->SetOutputSpacing(spacing); m_OGRDataSourceRendering->SetBackgroundValue(GetParameterFloat("background")); if(GetParameterString("mode") == "binary") { m_OGRDataSourceRendering->SetBurnAttributeMode(false); m_OGRDataSourceRendering->SetForegroundValue(GetParameterFloat("mode.binary.foreground")); } else if(GetParameterString("mode") == "attribute") { m_OGRDataSourceRendering->SetBurnAttributeMode(true); m_OGRDataSourceRendering->SetBurnAttribute(GetParameterString("mode.attribute.field")); } if(validInputProjRef) { m_OGRDataSourceRendering->SetOutputProjectionRef(outputProjectionRef); } otbAppLogINFO("Output projection reference system is: "<<outputProjectionRef); otbAppLogINFO("Output origin: "<<origin); otbAppLogINFO("Output size: "<<size); otbAppLogINFO("Output spacing: "<<spacing); SetParameterOutputImage<FloatImageType>("out", m_OGRDataSourceRendering->GetOutput()); } OGRDataSourceToMapFilterType::Pointer m_OGRDataSourceRendering; }; } } OTB_APPLICATION_EXPORT(otb::Wrapper::Rasterization)
remove unused variable, and catch by const-ref
WRG: remove unused variable, and catch by const-ref
C++
apache-2.0
orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB
acccf2da13203428211ddae120c39f4863cd80fb
src/sub.cpp
src/sub.cpp
/* * Copyright 2013-2016 Christian Lockley * * 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. */ /* * This file contains functions that are used be more than one module. */ #include "watchdogd.hpp" #include "sub.hpp" #include "testdir.hpp" #include "pidfile.hpp" int CloseWraper(const int *pfd) { if (pfd == NULL) { return -1; } return close(*pfd); } int IsDaemon(struct cfgoptions *const s) { if (s->options & DAEMONIZE) return true; return false; } int LockFile(int fd, pid_t pid) { struct flock fl; fl.l_type = F_WRLCK; fl.l_whence = SEEK_SET; fl.l_start = 0; fl.l_len = 0; fl.l_pid = pid; return fcntl(fd, F_SETLKW, &fl); } int UnlockFile(int fd, pid_t pid) { struct flock fl; fl.l_type = F_UNLCK; fl.l_whence = SEEK_SET; fl.l_start = 0; fl.l_len = 0; fl.l_pid = pid; return fcntl(fd, F_SETLKW, &fl); } int Wasprintf(char **ret, const char *format, ...) { //http://stackoverflow.com/questions/4899221/substitute-or-workaround-for-asprintf-on-aix va_list ap; *ret = NULL; va_start(ap, format); int count = portable_vsnprintf(NULL, 0, format, ap); va_end(ap); if (count >= 0) { char *buffer = (char *)malloc((size_t) count + 1); if (buffer == NULL) return -1; va_start(ap, format); count = portable_vsnprintf(buffer, (size_t) count + 1, format, ap); va_end(ap); if (count < 0) { free(buffer); *ret = NULL; return count; } *ret = buffer; } return count; } int Wasnprintf(size_t *len, char **ret, const char *format, ...) { va_list ap; if (*len == 0) { *ret = NULL; } va_start(ap, format); int count = portable_vsnprintf(NULL, 0, format, ap); va_end(ap); if (count+1 < *len) { va_start(ap, format); count = portable_vsnprintf(*ret, (size_t) count + 1, format, ap); va_end(ap); return count; } else { free(*ret); } if (count >= 0) { char *buffer = (char *)malloc((size_t) count + 1); if (buffer == NULL) return -1; va_start(ap, format); count = portable_vsnprintf(buffer, (size_t) count + 1, format, ap); va_end(ap); if (count < 0) { free(buffer); *ret = NULL; *len = 0; return count; } *ret = buffer; *len = count; } return count; } int EndDaemon(struct cfgoptions *s, int keepalive) { if (s == NULL) return -1; extern volatile sig_atomic_t stop; stop = 1; if (s->options & ENABLEPING) { for (pingobj_iter_t * iter = ping_iterator_get(s->pingObj); iter != NULL; iter = ping_iterator_next(iter)) { free(ping_iterator_get_context(iter)); ping_iterator_set_context(iter, NULL); } for (int cnt = 0; cnt < config_setting_length(s->ipAddresses); cnt++) { const char *ipAddress = config_setting_get_string_elem(s->ipAddresses, cnt); if (ping_host_remove(s->pingObj, ipAddress) != 0) { fprintf(stderr, "watchdogd: %s\n", ping_get_error(s->pingObj)); ping_destroy(s->pingObj); return -1; } } ping_destroy(s->pingObj); } if (keepalive == 0) { FreeExeList(&processes); config_destroy(&s->cfg); Logmsg(LOG_INFO, "stopping watchdog daemon"); closelog(); munlockall(); FreeLocale(); return 0; } FreeExeList(&processes); Logmsg(LOG_INFO, "restarting system"); closelog(); SetLogTarget(STANDARD_ERROR); munlockall(); FreeLocale(); return 0; } void ResetSignalHandlers(size_t maxsigno) { if (maxsigno < 1) return; struct sigaction sa; sa.sa_handler = SIG_DFL; sa.sa_flags = 0; sigfillset(&sa.sa_mask); for (size_t i = 1; i < maxsigno; sigaction(i, &sa, NULL), i++) ; } void NormalizeTimespec(struct timespec *const tp) { assert(tp != NULL); while (tp->tv_nsec < 0) { if (tp->tv_sec == 0) { tp->tv_nsec = 0; return; } tp->tv_sec -= 1; tp->tv_nsec += 1000000000; } while (tp->tv_nsec >= 1000000000) { tp->tv_nsec -= 1000000000; tp->tv_sec++; } } long ConvertStringToInt(const char *const str) { if (str == NULL) { return -1; } char *endptr = NULL; long ret = strtol((str), &endptr, 10); if (*endptr != '\0') { if (errno == 0) { errno = ERANGE; } return -1; } return ret; } int IsExe(const char *pathname, bool returnfildes) { struct stat buffer; if (pathname == NULL) return -1; int fildes = open(pathname, O_RDONLY | O_CLOEXEC); if (fildes == -1) return -1; if (fstat(fildes, &buffer) != 0) { close(fildes); return -1; } if (S_ISREG(buffer.st_mode) == 0) { close(fildes); return -1; } if (!(buffer.st_mode & S_IXUSR)) { close(fildes); return -1; } if (!(buffer.st_mode & S_IRUSR)) { close(fildes); return -1; } if (returnfildes == true) //For use with fexecve return fildes; close(fildes); return 0; } int CreateDetachedThread(void *(*startFunction) (void *), void *const arg) { pthread_t thread; pthread_attr_t attr; if (arg == NULL) return -1; if (*startFunction == NULL) return -1; if (pthread_attr_init(&attr) != 0) return -1; size_t stackSize = 0; if (pthread_attr_getstacksize(&attr, &stackSize) == 0) { const size_t targetStackSize = 131072; if ((targetStackSize >= PTHREAD_STACK_MIN) && (stackSize > targetStackSize)) { if (pthread_attr_setstacksize(&attr, 1048576) != 0) { Logmsg(LOG_CRIT, "pthread_attr_setstacksize: %s\n", MyStrerror(errno)); } } } else { Logmsg(LOG_CRIT, "pthread_attr_getstacksize: %s\n", MyStrerror(errno)); } pthread_attr_setguardsize(&attr, 0); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); errno = 0; if (pthread_create(&thread, &attr, startFunction, arg) != 0) { int ret = -errno; pthread_attr_destroy(&attr); return ret; } pthread_attr_destroy(&attr); return 0; } void FatalError(struct cfgoptions *s) { assert(s != NULL); Logmsg(LOG_CRIT, "fatal error"); config_destroy(&s->cfg); abort(); }
/* * Copyright 2013-2016 Christian Lockley * * 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. */ /* * This file contains functions that are used be more than one module. */ #include "watchdogd.hpp" #include "sub.hpp" #include "testdir.hpp" #include "pidfile.hpp" int CloseWraper(const int *pfd) { if (pfd == NULL) { return -1; } return close(*pfd); } int IsDaemon(struct cfgoptions *const s) { if (s->options & DAEMONIZE) return true; return false; } int LockFile(int fd, pid_t pid) { struct flock fl; fl.l_type = F_WRLCK; fl.l_whence = SEEK_SET; fl.l_start = 0; fl.l_len = 0; fl.l_pid = pid; return fcntl(fd, F_SETLKW, &fl); } int UnlockFile(int fd, pid_t pid) { struct flock fl; fl.l_type = F_UNLCK; fl.l_whence = SEEK_SET; fl.l_start = 0; fl.l_len = 0; fl.l_pid = pid; return fcntl(fd, F_SETLKW, &fl); } int Wasprintf(char **ret, const char *format, ...) { //http://stackoverflow.com/questions/4899221/substitute-or-workaround-for-asprintf-on-aix va_list ap; *ret = NULL; va_start(ap, format); int count = portable_vsnprintf(NULL, 0, format, ap); va_end(ap); if (count >= 0) { char *buffer = (char *)malloc((size_t) count + 1); if (buffer == NULL) return -1; va_start(ap, format); count = portable_vsnprintf(buffer, (size_t) count + 1, format, ap); va_end(ap); if (count < 0) { free(buffer); *ret = NULL; return count; } *ret = buffer; } return count; } int Wasnprintf(size_t *len, char **ret, const char *format, ...) { va_list ap; if (*len == 0) { *ret = NULL; } va_start(ap, format); int count = portable_vsnprintf(NULL, 0, format, ap); va_end(ap); if (count+1 < *len) { va_start(ap, format); count = portable_vsnprintf(*ret, (size_t) count + 1, format, ap); va_end(ap); return count; } else { free(*ret); } if (count >= 0) { char *buffer = (char *)malloc((size_t) count + 1); if (buffer == NULL) return -1; va_start(ap, format); count = portable_vsnprintf(buffer, (size_t) count + 1, format, ap); va_end(ap); if (count < 0) { free(buffer); *ret = NULL; *len = 0; return count; } *ret = buffer; *len = count; } return count; } int EndDaemon(struct cfgoptions *s, int keepalive) { if (s == NULL) return -1; extern volatile sig_atomic_t stop; stop = 1; if (s->options & ENABLEPING) { for (pingobj_iter_t * iter = ping_iterator_get(s->pingObj); iter != NULL; iter = ping_iterator_next(iter)) { free(ping_iterator_get_context(iter)); ping_iterator_set_context(iter, NULL); } for (int cnt = 0; cnt < config_setting_length(s->ipAddresses); cnt++) { const char *ipAddress = config_setting_get_string_elem(s->ipAddresses, cnt); if (ping_host_remove(s->pingObj, ipAddress) != 0) { fprintf(stderr, "watchdogd: %s\n", ping_get_error(s->pingObj)); ping_destroy(s->pingObj); return -1; } } ping_destroy(s->pingObj); } if (keepalive == 0) { FreeExeList(&processes); config_destroy(&s->cfg); Logmsg(LOG_INFO, "stopping watchdog daemon"); closelog(); munlockall(); FreeLocale(); return 0; } FreeExeList(&processes); Logmsg(LOG_INFO, "restarting system"); closelog(); SetLogTarget(STANDARD_ERROR); munlockall(); FreeLocale(); return 0; } void ResetSignalHandlers(size_t maxsigno) { if (maxsigno < 1) return; struct sigaction sa; sa.sa_handler = SIG_DFL; sa.sa_flags = 0; sigfillset(&sa.sa_mask); for (size_t i = 1; i < maxsigno; sigaction(i, &sa, NULL), i++) ; } void NormalizeTimespec(struct timespec *const tp) { assert(tp != NULL); while (tp->tv_nsec < 0) { if (tp->tv_sec == 0) { tp->tv_nsec = 0; return; } tp->tv_sec -= 1; tp->tv_nsec += 1000000000; } while (tp->tv_nsec >= 1000000000) { tp->tv_nsec -= 1000000000; tp->tv_sec++; } } long ConvertStringToInt(const char *const str) { if (str == NULL) { return -1; } char *endptr = NULL; long ret = strtol((str), &endptr, 10); if (*endptr != '\0') { if (errno == 0) { errno = ERANGE; } return -1; } return ret; } int IsExe(const char *pathname, bool returnfildes) { struct stat buffer; if (pathname == NULL) return -1; int fildes = open(pathname, O_RDONLY | O_CLOEXEC); if (fildes == -1) return -1; if (fstat(fildes, &buffer) != 0) { close(fildes); return -1; } if (S_ISREG(buffer.st_mode) == 0) { close(fildes); return -1; } if (!(buffer.st_mode & S_IXUSR)) { close(fildes); return -1; } if (!(buffer.st_mode & S_IRUSR)) { close(fildes); return -1; } if (returnfildes == true) //For use with fexecve return fildes; close(fildes); return 0; } int CreateDetachedThread(void *(*startFunction) (void *), void *const arg) { pthread_t thread; pthread_attr_t attr = {0}; if (arg == NULL) return -1; if (*startFunction == NULL) return -1; if (pthread_attr_init(&attr) != 0) return -1; size_t stackSize = 0; if (pthread_attr_getstacksize(&attr, &stackSize) == 0) { const size_t targetStackSize = 131072; if ((targetStackSize >= PTHREAD_STACK_MIN) && (stackSize > targetStackSize)) { if (pthread_attr_setstacksize(&attr, 1048576) != 0) { Logmsg(LOG_CRIT, "pthread_attr_setstacksize: %s\n", MyStrerror(errno)); } } } else { Logmsg(LOG_CRIT, "pthread_attr_getstacksize: %s\n", MyStrerror(errno)); } pthread_attr_setguardsize(&attr, 0); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); errno = 0; if (pthread_create(&thread, &attr, startFunction, arg) != 0) { int ret = -errno; pthread_attr_destroy(&attr); return ret; } pthread_attr_destroy(&attr); return 0; } void FatalError(struct cfgoptions *s) { assert(s != NULL); Logmsg(LOG_CRIT, "fatal error"); config_destroy(&s->cfg); abort(); }
initialize struct
initialize struct
C++
apache-2.0
clockley/watchdogd,clockley/watchdogd
a099f813869811e1599fdc289b74bc43b63735ed
src/api/unified/signal.cpp
src/api/unified/signal.cpp
/******************************************************* * Copyright (c) 2015, ArrayFire * All rights reserved. * * This file is distributed under 3-clause BSD license. * The complete license agreement can be obtained at: * http://arrayfire.com/licenses/BSD-3-Clause ********************************************************/ #include <af/array.h> #include <af/signal.h> #include "symbol_manager.hpp" af_err af_approx1(af_array *yo, const af_array yi, const af_array xo, const af_interp_type method, const float offGrid) { CHECK_ARRAYS(yi, xo); return CALL(yo, yi, xo, method, offGrid); } af_err af_approx2(af_array *zo, const af_array zi, const af_array xo, const af_array yo, const af_interp_type method, const float offGrid) { CHECK_ARRAYS(zi, xo, yo); return CALL(zo, zi, xo, yo, method, offGrid); } af_err af_approx1_uniform(af_array *yo, const af_array yi, const af_array xo, const int xdim, const double xi_beg, const double xi_step, const af_interp_type method, const float offGrid) { CHECK_ARRAYS(yi, xo); return CALL(yo, yi, xo, xdim, xi_beg, xi_step, method, offGrid); } af_err af_approx2_uniform(af_array *zo, const af_array zi, const af_array xo, const int xdim, const double xi_beg, const double xi_step, const af_array yo, const int ydim, const double yi_beg, const double yi_step, const af_interp_type method, const float offGrid) { CHECK_ARRAYS(zi, xo, yo); return CALL(zo, zi, xo, xdim, xi_beg, xi_step, yo, ydim, yi_beg, yi_step, method, offGrid); } af_err af_set_fft_plan_cache_size(size_t cache_size) { return CALL(cache_size); } #define FFT_HAPI_DEF(af_func) \ af_err af_func(af_array in, const double norm_factor) { \ CHECK_ARRAYS(in); \ return CALL(in, norm_factor); \ } FFT_HAPI_DEF(af_fft_inplace) FFT_HAPI_DEF(af_fft2_inplace) FFT_HAPI_DEF(af_fft3_inplace) FFT_HAPI_DEF(af_ifft_inplace) FFT_HAPI_DEF(af_ifft2_inplace) FFT_HAPI_DEF(af_ifft3_inplace) af_err af_fft(af_array *out, const af_array in, const double norm_factor, const dim_t odim0) { CHECK_ARRAYS(in); return CALL(out, in, norm_factor, odim0); } af_err af_fft2(af_array *out, const af_array in, const double norm_factor, const dim_t odim0, const dim_t odim1) { CHECK_ARRAYS(in); return CALL(out, in, norm_factor, odim0, odim1); } af_err af_fft3(af_array *out, const af_array in, const double norm_factor, const dim_t odim0, const dim_t odim1, const dim_t odim2) { CHECK_ARRAYS(in); return CALL(out, in, norm_factor, odim0, odim1, odim2); } af_err af_ifft(af_array *out, const af_array in, const double norm_factor, const dim_t odim0) { CHECK_ARRAYS(in); return CALL(out, in, norm_factor, odim0); } af_err af_ifft2(af_array *out, const af_array in, const double norm_factor, const dim_t odim0, const dim_t odim1) { CHECK_ARRAYS(in); return CALL(out, in, norm_factor, odim0, odim1); } af_err af_ifft3(af_array *out, const af_array in, const double norm_factor, const dim_t odim0, const dim_t odim1, const dim_t odim2) { CHECK_ARRAYS(in); return CALL(out, in, norm_factor, odim0, odim1, odim2); } af_err af_fft_r2c(af_array *out, const af_array in, const double norm_factor, const dim_t pad0) { CHECK_ARRAYS(in); return CALL(out, in, norm_factor, pad0); } af_err af_fft2_r2c(af_array *out, const af_array in, const double norm_factor, const dim_t pad0, const dim_t pad1) { CHECK_ARRAYS(in); return CALL(out, in, norm_factor, pad0, pad1); } af_err af_fft3_r2c(af_array *out, const af_array in, const double norm_factor, const dim_t pad0, const dim_t pad1, const dim_t pad2) { CHECK_ARRAYS(in); return CALL(out, in, norm_factor, pad0, pad1, pad2); } #define FFTC2R_HAPI_DEF(af_func) \ af_err af_func(af_array *out, const af_array in, const double norm_factor, \ const bool is_odd) { \ CHECK_ARRAYS(in); \ return CALL(out, in, norm_factor, is_odd); \ } FFTC2R_HAPI_DEF(af_fft_c2r) FFTC2R_HAPI_DEF(af_fft2_c2r) FFTC2R_HAPI_DEF(af_fft3_c2r) #define CONV_HAPI_DEF(af_func) \ af_err af_func(af_array *out, const af_array signal, \ const af_array filter, const af_conv_mode mode, \ af_conv_domain domain) { \ CHECK_ARRAYS(signal, filter); \ return CALL(out, signal, filter, mode, domain); \ } CONV_HAPI_DEF(af_convolve1) CONV_HAPI_DEF(af_convolve2) CONV_HAPI_DEF(af_convolve3) #define FFT_CONV_HAPI_DEF(af_func) \ af_err af_func(af_array *out, const af_array signal, \ const af_array filter, const af_conv_mode mode) { \ CHECK_ARRAYS(signal, filter); \ return CALL(out, signal, filter, mode); \ } FFT_CONV_HAPI_DEF(af_fft_convolve1) FFT_CONV_HAPI_DEF(af_fft_convolve2) FFT_CONV_HAPI_DEF(af_fft_convolve3) af_err af_convolve2_sep(af_array *out, const af_array col_filter, const af_array row_filter, const af_array signal, const af_conv_mode mode) { CHECK_ARRAYS(col_filter, row_filter, signal); return CALL(out, col_filter, row_filter, signal, mode); } af_err af_fir(af_array *y, const af_array b, const af_array x) { CHECK_ARRAYS(b, x); return CALL(y, b, x); } af_err af_iir(af_array *y, const af_array b, const af_array a, const af_array x) { CHECK_ARRAYS(b, a, x); return CALL(y, b, a, x); } af_err af_medfilt(af_array *out, const af_array in, const dim_t wind_length, const dim_t wind_width, const af_border_type edge_pad) { CHECK_ARRAYS(in); return CALL(out, in, wind_length, wind_width, edge_pad); } af_err af_medfilt1(af_array *out, const af_array in, const dim_t wind_width, const af_border_type edge_pad) { CHECK_ARRAYS(in); return CALL(out, in, wind_width, edge_pad); } af_err af_medfilt2(af_array *out, const af_array in, const dim_t wind_length, const dim_t wind_width, const af_border_type edge_pad) { CHECK_ARRAYS(in); return CALL(out, in, wind_length, wind_width, edge_pad); }
/******************************************************* * Copyright (c) 2015, ArrayFire * All rights reserved. * * This file is distributed under 3-clause BSD license. * The complete license agreement can be obtained at: * http://arrayfire.com/licenses/BSD-3-Clause ********************************************************/ #include <af/array.h> #include <af/signal.h> #include "symbol_manager.hpp" af_err af_approx1(af_array *yo, const af_array yi, const af_array xo, const af_interp_type method, const float offGrid) { CHECK_ARRAYS(yi, xo); return CALL(yo, yi, xo, method, offGrid); } af_err af_approx1_v2(af_array *yo, const af_array yi, const af_array xo, const af_interp_type method, const float offGrid) { CHECK_ARRAYS(yi, xo); return CALL(yo, yi, xo, method, offGrid); } af_err af_approx2(af_array *zo, const af_array zi, const af_array xo, const af_array yo, const af_interp_type method, const float offGrid) { CHECK_ARRAYS(zi, xo, yo); return CALL(zo, zi, xo, yo, method, offGrid); } af_err af_approx1_uniform(af_array *yo, const af_array yi, const af_array xo, const int xdim, const double xi_beg, const double xi_step, const af_interp_type method, const float offGrid) { CHECK_ARRAYS(yi, xo); return CALL(yo, yi, xo, xdim, xi_beg, xi_step, method, offGrid); } af_err af_approx1_uniform_v2(af_array *yo, const af_array yi, const af_array xo, const int xdim, const double xi_beg, const double xi_step, const af_interp_type method, const float offGrid) { CHECK_ARRAYS(yi, xo); return CALL(yo, yi, xo, xdim, xi_beg, xi_step, method, offGrid); } af_err af_approx2_uniform(af_array *zo, const af_array zi, const af_array xo, const int xdim, const double xi_beg, const double xi_step, const af_array yo, const int ydim, const double yi_beg, const double yi_step, const af_interp_type method, const float offGrid) { CHECK_ARRAYS(zi, xo, yo); return CALL(zo, zi, xo, xdim, xi_beg, xi_step, yo, ydim, yi_beg, yi_step, method, offGrid); } af_err af_set_fft_plan_cache_size(size_t cache_size) { return CALL(cache_size); } #define FFT_HAPI_DEF(af_func) \ af_err af_func(af_array in, const double norm_factor) { \ CHECK_ARRAYS(in); \ return CALL(in, norm_factor); \ } FFT_HAPI_DEF(af_fft_inplace) FFT_HAPI_DEF(af_fft2_inplace) FFT_HAPI_DEF(af_fft3_inplace) FFT_HAPI_DEF(af_ifft_inplace) FFT_HAPI_DEF(af_ifft2_inplace) FFT_HAPI_DEF(af_ifft3_inplace) af_err af_fft(af_array *out, const af_array in, const double norm_factor, const dim_t odim0) { CHECK_ARRAYS(in); return CALL(out, in, norm_factor, odim0); } af_err af_fft2(af_array *out, const af_array in, const double norm_factor, const dim_t odim0, const dim_t odim1) { CHECK_ARRAYS(in); return CALL(out, in, norm_factor, odim0, odim1); } af_err af_fft3(af_array *out, const af_array in, const double norm_factor, const dim_t odim0, const dim_t odim1, const dim_t odim2) { CHECK_ARRAYS(in); return CALL(out, in, norm_factor, odim0, odim1, odim2); } af_err af_ifft(af_array *out, const af_array in, const double norm_factor, const dim_t odim0) { CHECK_ARRAYS(in); return CALL(out, in, norm_factor, odim0); } af_err af_ifft2(af_array *out, const af_array in, const double norm_factor, const dim_t odim0, const dim_t odim1) { CHECK_ARRAYS(in); return CALL(out, in, norm_factor, odim0, odim1); } af_err af_ifft3(af_array *out, const af_array in, const double norm_factor, const dim_t odim0, const dim_t odim1, const dim_t odim2) { CHECK_ARRAYS(in); return CALL(out, in, norm_factor, odim0, odim1, odim2); } af_err af_fft_r2c(af_array *out, const af_array in, const double norm_factor, const dim_t pad0) { CHECK_ARRAYS(in); return CALL(out, in, norm_factor, pad0); } af_err af_fft2_r2c(af_array *out, const af_array in, const double norm_factor, const dim_t pad0, const dim_t pad1) { CHECK_ARRAYS(in); return CALL(out, in, norm_factor, pad0, pad1); } af_err af_fft3_r2c(af_array *out, const af_array in, const double norm_factor, const dim_t pad0, const dim_t pad1, const dim_t pad2) { CHECK_ARRAYS(in); return CALL(out, in, norm_factor, pad0, pad1, pad2); } #define FFTC2R_HAPI_DEF(af_func) \ af_err af_func(af_array *out, const af_array in, const double norm_factor, \ const bool is_odd) { \ CHECK_ARRAYS(in); \ return CALL(out, in, norm_factor, is_odd); \ } FFTC2R_HAPI_DEF(af_fft_c2r) FFTC2R_HAPI_DEF(af_fft2_c2r) FFTC2R_HAPI_DEF(af_fft3_c2r) #define CONV_HAPI_DEF(af_func) \ af_err af_func(af_array *out, const af_array signal, \ const af_array filter, const af_conv_mode mode, \ af_conv_domain domain) { \ CHECK_ARRAYS(signal, filter); \ return CALL(out, signal, filter, mode, domain); \ } CONV_HAPI_DEF(af_convolve1) CONV_HAPI_DEF(af_convolve2) CONV_HAPI_DEF(af_convolve3) #define FFT_CONV_HAPI_DEF(af_func) \ af_err af_func(af_array *out, const af_array signal, \ const af_array filter, const af_conv_mode mode) { \ CHECK_ARRAYS(signal, filter); \ return CALL(out, signal, filter, mode); \ } FFT_CONV_HAPI_DEF(af_fft_convolve1) FFT_CONV_HAPI_DEF(af_fft_convolve2) FFT_CONV_HAPI_DEF(af_fft_convolve3) af_err af_convolve2_sep(af_array *out, const af_array col_filter, const af_array row_filter, const af_array signal, const af_conv_mode mode) { CHECK_ARRAYS(col_filter, row_filter, signal); return CALL(out, col_filter, row_filter, signal, mode); } af_err af_fir(af_array *y, const af_array b, const af_array x) { CHECK_ARRAYS(b, x); return CALL(y, b, x); } af_err af_iir(af_array *y, const af_array b, const af_array a, const af_array x) { CHECK_ARRAYS(b, a, x); return CALL(y, b, a, x); } af_err af_medfilt(af_array *out, const af_array in, const dim_t wind_length, const dim_t wind_width, const af_border_type edge_pad) { CHECK_ARRAYS(in); return CALL(out, in, wind_length, wind_width, edge_pad); } af_err af_medfilt1(af_array *out, const af_array in, const dim_t wind_width, const af_border_type edge_pad) { CHECK_ARRAYS(in); return CALL(out, in, wind_width, edge_pad); } af_err af_medfilt2(af_array *out, const af_array in, const dim_t wind_length, const dim_t wind_width, const af_border_type edge_pad) { CHECK_ARRAYS(in); return CALL(out, in, wind_length, wind_width, edge_pad); }
Add approx1_*_v2 functions to the unified backend
Add approx1_*_v2 functions to the unified backend
C++
bsd-3-clause
9prady9/arrayfire,arrayfire/arrayfire,arrayfire/arrayfire,umar456/arrayfire,9prady9/arrayfire,umar456/arrayfire,arrayfire/arrayfire,arrayfire/arrayfire,9prady9/arrayfire,9prady9/arrayfire,umar456/arrayfire,umar456/arrayfire
1af7465107ae4e90be48d53b60e07e9a62cc0994
src/utf8.hh
src/utf8.hh
#ifndef utf8_hh_INCLUDED #define utf8_hh_INCLUDED namespace Kakoune { namespace utf8 { using Codepoint = uint32_t; // returns an iterator to next character first byte template<typename Iterator> Iterator next(Iterator it) { if (*it++ & 0x80) while ((*(it) & 0xC0) == 0x80) ++it; return it; } // returns it's parameter if it points to a character first byte, // or else returns next character first byte template<typename Iterator> Iterator finish(Iterator it) { while ((*(it) & 0xC0) == 0x80) ++it; return it; } // returns an iterator to the previous character first byte template<typename Iterator> Iterator previous(Iterator it) { while ((*(--it) & 0xC0) == 0x80) ; return it; } // returns an iterator pointing to the first byte of the // dth character after (or before if d < 0) the character // pointed by it template<typename Iterator, typename Distance> Iterator advance(Iterator it, Distance d) { if (d < 0) { while (d++) it = previous(it); } else { while (d--) it = next(it); } return it; } // returns the character count between begin and end template<typename Iterator> size_t distance(Iterator begin, Iterator end) { size_t dist = 0; while (begin != end) { if ((*begin++ & 0xC0) != 0x80) ++dist; } } // return true if it points to the first byte of a (either single or // multibyte) character template<typename Iterator> bool is_character_start(Iterator it) { return (*it & 0xC0) != 0x80; } struct invalid_utf8_sequence{}; // returns the codepoint of the character whose first byte // is pointed by it template<typename Iterator> Codepoint codepoint(Iterator it) { // According to rfc3629, UTF-8 allows only up to 4 bytes. // (21 bits codepoint) Codepoint cp; char byte = *it++; if (not (byte & 0x80)) // 0xxxxxxx cp = byte; else if ((byte & 0xE0) == 0xC0) // 110xxxxx { cp = ((byte & 0x1F) << 6) | (*it & 0x3F); } else if ((byte & 0xF0) == 0xE0) // 1110xxxx { cp = ((byte & 0x0F) << 12) | ((*it++ & 0x3F) << 6); cp |= (*it & 0x3F); } else if ((byte & 0xF8) == 0xF0) // 11110xxx { cp = ((byte & 0x0F) << 18) | ((*it++ & 0x3F) << 12); cp |= (*it++ & 0x3F) << 6; cp |= (*it & 0x3F); } else throw invalid_utf8_sequence{}; } } } #endif // utf8_hh_INCLUDED
#ifndef utf8_hh_INCLUDED #define utf8_hh_INCLUDED #include <cstdint> #include <cstddef> namespace Kakoune { namespace utf8 { using Codepoint = uint32_t; // returns an iterator to next character first byte template<typename Iterator> Iterator next(Iterator it) { if (*it++ & 0x80) while ((*(it) & 0xC0) == 0x80) ++it; return it; } // returns it's parameter if it points to a character first byte, // or else returns next character first byte template<typename Iterator> Iterator finish(Iterator it) { while ((*(it) & 0xC0) == 0x80) ++it; return it; } // returns an iterator to the previous character first byte template<typename Iterator> Iterator previous(Iterator it) { while ((*(--it) & 0xC0) == 0x80) ; return it; } // returns an iterator pointing to the first byte of the // dth character after (or before if d < 0) the character // pointed by it template<typename Iterator, typename Distance> Iterator advance(Iterator it, Distance d) { if (d < 0) { while (d++) it = previous(it); } else { while (d--) it = next(it); } return it; } // returns the character count between begin and end template<typename Iterator> size_t distance(Iterator begin, Iterator end) { size_t dist = 0; while (begin != end) { if ((*begin++ & 0xC0) != 0x80) ++dist; } } // return true if it points to the first byte of a (either single or // multibyte) character template<typename Iterator> bool is_character_start(Iterator it) { return (*it & 0xC0) != 0x80; } struct invalid_utf8_sequence{}; // returns the codepoint of the character whose first byte // is pointed by it template<typename Iterator> Codepoint codepoint(Iterator it) { // According to rfc3629, UTF-8 allows only up to 4 bytes. // (21 bits codepoint) Codepoint cp; char byte = *it++; if (not (byte & 0x80)) // 0xxxxxxx cp = byte; else if ((byte & 0xE0) == 0xC0) // 110xxxxx { cp = ((byte & 0x1F) << 6) | (*it & 0x3F); } else if ((byte & 0xF0) == 0xE0) // 1110xxxx { cp = ((byte & 0x0F) << 12) | ((*it++ & 0x3F) << 6); cp |= (*it & 0x3F); } else if ((byte & 0xF8) == 0xF0) // 11110xxx { cp = ((byte & 0x0F) << 18) | ((*it++ & 0x3F) << 12); cp |= (*it++ & 0x3F) << 6; cp |= (*it & 0x3F); } else throw invalid_utf8_sequence{}; } struct invalid_codepoint{}; template<typename OutputIterator> void dump(OutputIterator& it, Codepoint cp) { if (cp <= 0x7F) *it++ = cp; else if (cp <= 0x7FF) { *it++ = 0xC0 | (cp >> 6); *it++ = 0x80 | (cp & 0x3F); } else if (cp <= 0xFFFF) { *it++ = 0xE0 | (cp >> 12); *it++ = 0x80 | ((cp >> 6) & 0x3F); *it++ = 0x80 | (cp & 0x3F); } else if (cp <= 0x10FFFF) { *it++ = 0xF0 | (cp >> 18); *it++ = 0x80 | ((cp >> 12) & 0x3F); *it++ = 0x80 | ((cp >> 6) & 0x3F); *it++ = 0x80 | (cp & 0x3F); } else throw invalid_codepoint{}; } } } #endif // utf8_hh_INCLUDED
add dump(OutputIterator& it, Codepoint cp)
utf8: add dump(OutputIterator& it, Codepoint cp)
C++
unlicense
alpha123/kakoune,xificurC/kakoune,jkonecny12/kakoune,rstacruz/kakoune,occivink/kakoune,alpha123/kakoune,zakgreant/kakoune,elegios/kakoune,elegios/kakoune,lenormf/kakoune,Somasis/kakoune,casimir/kakoune,casimir/kakoune,danr/kakoune,lenormf/kakoune,Asenar/kakoune,zakgreant/kakoune,xificurC/kakoune,rstacruz/kakoune,alpha123/kakoune,mawww/kakoune,zakgreant/kakoune,Asenar/kakoune,alexherbo2/kakoune,casimir/kakoune,Somasis/kakoune,elegios/kakoune,danr/kakoune,occivink/kakoune,flavius/kakoune,casimir/kakoune,ekie/kakoune,jjthrash/kakoune,ekie/kakoune,jjthrash/kakoune,danielma/kakoune,flavius/kakoune,mawww/kakoune,alexherbo2/kakoune,jkonecny12/kakoune,occivink/kakoune,danr/kakoune,jkonecny12/kakoune,alexherbo2/kakoune,Asenar/kakoune,lenormf/kakoune,jkonecny12/kakoune,xificurC/kakoune,alexherbo2/kakoune,rstacruz/kakoune,flavius/kakoune,jjthrash/kakoune,mawww/kakoune,occivink/kakoune,danielma/kakoune,xificurC/kakoune,lenormf/kakoune,alpha123/kakoune,danielma/kakoune,danielma/kakoune,danr/kakoune,ekie/kakoune,Asenar/kakoune,jjthrash/kakoune,rstacruz/kakoune,mawww/kakoune,ekie/kakoune,Somasis/kakoune,Somasis/kakoune,zakgreant/kakoune,elegios/kakoune,flavius/kakoune
07c4acd51410ff075ebfca4a202e721f50065333
src/pal/src/arch/arm/signalhandlerhelper.cpp
src/pal/src/arch/arm/signalhandlerhelper.cpp
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #include "pal/dbgmsg.h" SET_DEFAULT_DEBUG_CHANNEL(EXCEPT); // some headers have code with asserts, so do this first #include "pal/palinternal.h" #include "pal/context.h" #include "pal/signal.hpp" #include "pal/utils.h" #include <sys/ucontext.h> /*++ Function : signal_handler_worker Handles signal on the original stack where the signal occured. Invoked via setcontext. Parameters : POSIX signal handler parameter list ("man sigaction" for details) returnPoint - context to which the function returns if the common_signal_handler returns (no return value) --*/ void ExecuteHandlerOnOriginalStack(int code, siginfo_t *siginfo, void *context, SignalHandlerWorkerReturnPoint* returnPoint) { ucontext_t *ucontext = (ucontext_t *)context; size_t faultSp = (size_t)MCREG_Sp(ucontext->uc_mcontext); _ASSERTE(IS_ALIGNED(faultSp, 4)); size_t fakeFrameReturnAddress; if (IS_ALIGNED(faultSp, 8)) { fakeFrameReturnAddress = (size_t)SignalHandlerWorkerReturnOffset0 + (size_t)CallSignalHandlerWrapper0; } else { fakeFrameReturnAddress = (size_t)SignalHandlerWorkerReturnOffset4 + (size_t)CallSignalHandlerWrapper4; } // preserve 8 bytes long red zone and align stack pointer size_t* sp = (size_t*)ALIGN_DOWN(faultSp - 8, 8); #ifndef __linux__ size_t cpsr = (size_t)MCREG_Cpsr(ucontext->uc_mcontext); // Build fake stack frame to enable the stack unwinder to unwind from signal_handler_worker to the faulting instruction // align --sp; // pushed LR with correct mode bit *--sp = (size_t)MCREG_Pc(ucontext->uc_mcontext) | ((cpsr & (1 << 5)) >> 5); // pushed frame pointer *--sp = (size_t)MCREG_R11(ucontext->uc_mcontext); *--sp = (size_t)MCREG_R7(ucontext->uc_mcontext); #else size_t size = ALIGN_UP(sizeof(ucontext->uc_mcontext), 8); sp -= size / sizeof(size_t); *(sigcontext *)sp = ucontext->uc_mcontext; #endif // Switch the current context to the signal_handler_worker and the original stack CONTEXT context2; RtlCaptureContext(&context2); // We don't care about the other registers state since the stack unwinding restores // them for the target frame directly from the signal context. context2.Sp = (size_t)sp; context2.R7 = (size_t)sp; // Fp and Sp are the same context2.Lr = fakeFrameReturnAddress; context2.Pc = (size_t)signal_handler_worker; context2.R0 = code; context2.R1 = (size_t)siginfo; context2.R2 = (size_t)context; context2.R3 = (size_t)returnPoint; RtlRestoreContext(&context2, NULL); }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #include "pal/dbgmsg.h" SET_DEFAULT_DEBUG_CHANNEL(EXCEPT); // some headers have code with asserts, so do this first #include "pal/palinternal.h" #include "pal/context.h" #include "pal/signal.hpp" #include "pal/utils.h" #include <sys/ucontext.h> /*++ Function : signal_handler_worker Handles signal on the original stack where the signal occured. Invoked via setcontext. Parameters : POSIX signal handler parameter list ("man sigaction" for details) returnPoint - context to which the function returns if the common_signal_handler returns (no return value) --*/ void ExecuteHandlerOnOriginalStack(int code, siginfo_t *siginfo, void *context, SignalHandlerWorkerReturnPoint* returnPoint) { ucontext_t *ucontext = (ucontext_t *)context; size_t faultSp = (size_t)MCREG_Sp(ucontext->uc_mcontext); _ASSERTE(IS_ALIGNED(faultSp, 4)); size_t fakeFrameReturnAddress; if (IS_ALIGNED(faultSp, 8)) { fakeFrameReturnAddress = (size_t)SignalHandlerWorkerReturnOffset0 + (size_t)CallSignalHandlerWrapper0; } else { fakeFrameReturnAddress = (size_t)SignalHandlerWorkerReturnOffset4 + (size_t)CallSignalHandlerWrapper4; } // preserve 8 bytes long red zone and align stack pointer size_t* sp = (size_t*)ALIGN_DOWN(faultSp - 8, 8); #ifndef __linux__ size_t cpsr = (size_t)MCREG_Cpsr(ucontext->uc_mcontext); // Build fake stack frame to enable the stack unwinder to unwind from signal_handler_worker to the faulting instruction // align --sp; // pushed LR with correct mode bit *--sp = (size_t)MCREG_Pc(ucontext->uc_mcontext) | ((cpsr & (1 << 5)) >> 5); // pushed frame pointer *--sp = (size_t)MCREG_R11(ucontext->uc_mcontext); *--sp = (size_t)MCREG_R7(ucontext->uc_mcontext); #else size_t size = ALIGN_UP(sizeof(ucontext->uc_mcontext), 8); sp -= size / sizeof(size_t); *(mcontext_t *)sp = ucontext->uc_mcontext; #endif // Switch the current context to the signal_handler_worker and the original stack CONTEXT context2; RtlCaptureContext(&context2); // We don't care about the other registers state since the stack unwinding restores // them for the target frame directly from the signal context. context2.Sp = (size_t)sp; context2.R7 = (size_t)sp; // Fp and Sp are the same context2.Lr = fakeFrameReturnAddress; context2.Pc = (size_t)signal_handler_worker; context2.R0 = code; context2.R1 = (size_t)siginfo; context2.R2 = (size_t)context; context2.R3 = (size_t)returnPoint; RtlRestoreContext(&context2, NULL); }
Use mcontext_t instead of sigcontext (#18983)
Use mcontext_t instead of sigcontext (#18983) The type of uc_mcontext has always been `mcontext_t`, but earlier versions of Glibc just typedef'ed this to `sigcontext`. Newer versions of Glibc (since 2.27) [introduced an explicit struct type](https://sourceware.org/git/?p=glibc.git;a=blobdiff;f=sysdeps/unix/sysv/linux/arm/sys/ucontext.h;h=192d1bdeac3e62e13110f68614f7af624047c3a9;hp=2abceef2a4ca9bbb6e42208eaee548228b041e5b;hb=4fa9b3bfe6759c82beb4b043a54a3598ca467289;hpb=5898f4548efdcd7c0fd437a74eeb80facc51a117) and now compilation fails.
C++
mit
mmitche/coreclr,wtgodbe/coreclr,poizan42/coreclr,wtgodbe/coreclr,cshung/coreclr,krk/coreclr,cshung/coreclr,wtgodbe/coreclr,krk/coreclr,mmitche/coreclr,mmitche/coreclr,cshung/coreclr,cshung/coreclr,poizan42/coreclr,mmitche/coreclr,cshung/coreclr,krk/coreclr,poizan42/coreclr,poizan42/coreclr,wtgodbe/coreclr,krk/coreclr,mmitche/coreclr,poizan42/coreclr,poizan42/coreclr,krk/coreclr,cshung/coreclr,wtgodbe/coreclr,mmitche/coreclr,wtgodbe/coreclr,krk/coreclr
cbea82eac5a5973482152cfec224b95c194afa8c
C++/099_Recover_Binary_Search_Tree.cpp
C++/099_Recover_Binary_Search_Tree.cpp
//99. Recover Binary Search Tree /* *Two elements of a binary search tree (BST) are swapped by mistake. * *Recover the tree without changing its structure. * *Tag: Tree, Depth-first Search * *Author: Linsen Wu */ #include "stdafx.h" #include <vector> #include <algorithm> using namespace std; // Definition for a binary tree node. struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; class Solution { public: //O(n) space solution void recoverTree(TreeNode* root) { vector<TreeNode*> list; vector<int > vals; InOrderTravel(root, list, vals); sort(vals.begin(), vals.end()); for(int i =0; i< list.size(); i++) { list[i]->val = vals[i]; } } void InOrderTravel(TreeNode* node, vector<TreeNode*>& list, vector<int>& vals) { if(node == NULL) return; InOrderTravel(node->left, list, vals); list.push_back(node); vals.push_back(node->val); InOrderTravel(node->right, list, vals); } //O(1) space solution void recoverTree_O1(TreeNode *root) { TreeNode *f1=NULL, *f2=NULL; TreeNode *current,*pre, *parent=NULL; if(root == NULL) return; bool found = false; current = root; while(current != NULL) { if(current->left == NULL) { if(parent && parent->val > current->val) { if(!found) { f1 = parent; found = true; } f2 = current; } parent = current; current = current->right; } else { /* Find the inorder predecessor of current */ pre = current->left; while(pre->right != NULL && pre->right != current) pre = pre->right; /* Make current as right child of its inorder predecessor */ if(pre->right == NULL) { pre->right = current; current = current->left; } /* Revert the changes made in if part to restore the original tree i.e., fix the right child of predecssor */ else { pre->right = NULL; if(parent->val > current->val) { if(!found) { f1 = parent; found = true; } f2 = current; } parent = current; current = current->right; } /* End of if condition pre->right == NULL */ } /* End of if condition current->left == NULL*/ } /* End of while */ if(f1 && f2) swap(f1->val, f2->val); } // Function to traverse binary tree without recursion and without stack /* vector<int> inorderTraversal(TreeNode *root) { vector<int> result; TreeNode *current,*pre; if(root == NULL) return result; current = root; while(current != NULL) { if(current->left == NULL) { result.push_back(current->val); current = current->right; } else { // Find the inorder predecessor of current pre = current->left; while(pre->right != NULL && pre->right != current) pre = pre->right; // Make current as right child of its inorder predecessor if(pre->right == NULL) { pre->right = current; current = current->left; } // Revert the changes made in if part to restore the original tree i.e., fix the right child of predecssor else { pre->right = NULL; result.push_back(current->val); current = current->right; } // End of if condition pre->right == NULL } // End of if condition current->left == NULL } // End of while return result; } */ } }; int _tmain(int argc, _TCHAR* argv[]) { return 0; }
//99. Recover Binary Search Tree /* *Two elements of a binary search tree (BST) are swapped by mistake. * *Recover the tree without changing its structure. * *Tag: Tree, Depth-first Search * *Author: Linsen Wu */ #include "stdafx.h" #include <vector> #include <algorithm> using namespace std; // Definition for a binary tree node. struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; class Solution { public: //O(n) space solution void recoverTree(TreeNode* root) { vector<TreeNode*> list; vector<int > vals; InOrderTravel(root, list, vals); sort(vals.begin(), vals.end()); for(int i =0; i< list.size(); i++) { list[i]->val = vals[i]; } } void InOrderTravel(TreeNode* node, vector<TreeNode*>& list, vector<int>& vals) { if(node == NULL) return; InOrderTravel(node->left, list, vals); list.push_back(node); vals.push_back(node->val); InOrderTravel(node->right, list, vals); } //O(1) space solution void recoverTree_O1(TreeNode *root) { TreeNode *f1=NULL, *f2=NULL; TreeNode *current,*pre, *parent=NULL; if(root == NULL) return; bool found = false; current = root; while(current != NULL) { if(current->left == NULL) { if(parent && parent->val > current->val) { if(!found) { f1 = parent; found = true; } f2 = current; } parent = current; current = current->right; } else { /* Find the inorder predecessor of current */ pre = current->left; while(pre->right != NULL && pre->right != current) pre = pre->right; /* Make current as right child of its inorder predecessor */ if(pre->right == NULL) { pre->right = current; current = current->left; } /* Revert the changes made in if part to restore the original tree i.e., fix the right child of predecssor */ else { pre->right = NULL; if(parent->val > current->val) { if(!found) { f1 = parent; found = true; } f2 = current; } parent = current; current = current->right; } /* End of if condition pre->right == NULL */ } /* End of if condition current->left == NULL*/ } /* End of while */ if(f1 && f2) swap(f1->val, f2->val); } // Function to traverse binary tree without recursion and without stack /* vector<int> inorderTraversal(TreeNode *root) { vector<int> result; TreeNode *current,*pre; if(root == NULL) return result; current = root; while(current != NULL) { if(current->left == NULL) { result.push_back(current->val); current = current->right; } else { // Find the inorder predecessor of current pre = current->left; while(pre->right != NULL && pre->right != current) pre = pre->right; // Make current as right child of its inorder predecessor if(pre->right == NULL) { pre->right = current; current = current->left; } // Revert the changes made in if part to restore the original tree i.e., fix the right child of predecssor else { pre->right = NULL; result.push_back(current->val); current = current->right; } // End of if condition pre->right == NULL } // End of if condition current->left == NULL } // End of while return result; } */ } }; int _tmain(int argc, _TCHAR* argv[]) { return 0; }
improve the format
improve the format
C++
mit
bssrdf/LeetCode-Sol-Res,bssrdf/LeetCode-Sol-Res,FreeTymeKiyan/LeetCode-Sol-Res,FreeTymeKiyan/LeetCode-Sol-Res
5d8f43cfffe99c13afd03f7cccb3d6c33379941e
chrome/browser/extensions/extensions_service_unittest.cc
chrome/browser/extensions/extensions_service_unittest.cc
// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <vector> #include "base/file_path.h" #include "base/file_util.h" #include "base/message_loop.h" #include "base/path_service.h" #include "base/string_util.h" #include "chrome/browser/extensions/extensions_service.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/json_value_serializer.h" #include "testing/gtest/include/gtest/gtest.h" #include "testing/platform_test.h" // A mock implementation of ExtensionsServiceFrontendInterface for testing the // backend. class ExtensionsServiceTestFrontend : public ExtensionsServiceFrontendInterface { public: ~ExtensionsServiceTestFrontend() { for (ExtensionList::iterator iter = extensions_.begin(); iter != extensions_.end(); ++iter) { delete *iter; } } std::vector<std::string>* errors() { return &errors_; } ExtensionList* extensions() { return &extensions_; } // ExtensionsServiceFrontendInterface virtual MessageLoop* GetMessageLoop() { return &message_loop_; } virtual void OnExtensionLoadError(const std::string& message) { errors_.push_back(message); } virtual void OnExtensionsLoadedFromDirectory(ExtensionList* new_extensions) { extensions_.insert(extensions_.end(), new_extensions->begin(), new_extensions->end()); delete new_extensions; } private: MessageLoop message_loop_; ExtensionList extensions_; std::vector<std::string> errors_; }; // make the test a PlatformTest to setup autorelease pools properly on mac typedef PlatformTest ExtensionsServiceTest; // Test loading extensions from the profile directory. TEST_F(ExtensionsServiceTest, LoadAllExtensionsFromDirectory) { std::wstring extensions_dir; ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &extensions_dir)); FilePath manifest_path = FilePath::FromWStringHack(extensions_dir).Append( FILE_PATH_LITERAL("extensions")); scoped_refptr<ExtensionsServiceBackend> backend(new ExtensionsServiceBackend); scoped_refptr<ExtensionsServiceTestFrontend> frontend( new ExtensionsServiceTestFrontend); std::vector<Extension*> extensions; EXPECT_TRUE(backend->LoadExtensionsFromDirectory(manifest_path, scoped_refptr<ExtensionsServiceFrontendInterface>(frontend.get()))); frontend->GetMessageLoop()->RunAllPending(); // Note: There can be more errors if there are extra directories, like .svn // directories. EXPECT_TRUE(frontend->errors()->size() >= 2u); EXPECT_EQ(2u, frontend->extensions()->size()); EXPECT_EQ(std::wstring(L"com.google.myextension1"), frontend->extensions()->at(0)->id()); EXPECT_EQ(std::wstring(L"My extension 1"), frontend->extensions()->at(0)->name()); EXPECT_EQ(std::wstring(L"The first extension that I made."), frontend->extensions()->at(0)->description()); EXPECT_EQ(2u, frontend->extensions()->at(0)->content_scripts().size()); EXPECT_EQ(std::wstring(L"script1.user.js"), frontend->extensions()->at(0)->content_scripts().at(0)); EXPECT_EQ(std::wstring(L"script2.user.js"), frontend->extensions()->at(0)->content_scripts().at(1)); EXPECT_EQ(std::wstring(L"com.google.myextension2"), frontend->extensions()->at(1)->id()); EXPECT_EQ(std::wstring(L"My extension 2"), frontend->extensions()->at(1)->name()); EXPECT_EQ(std::wstring(L""), frontend->extensions()->at(1)->description()); EXPECT_EQ(0u, frontend->extensions()->at(1)->content_scripts().size()); };
// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <algorithm> #include <vector> #include "base/file_path.h" #include "base/file_util.h" #include "base/message_loop.h" #include "base/path_service.h" #include "base/string_util.h" #include "chrome/browser/extensions/extension.h" #include "chrome/browser/extensions/extensions_service.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/json_value_serializer.h" #include "testing/gtest/include/gtest/gtest.h" #include "testing/platform_test.h" namespace { struct ExtensionsOrder { bool operator()(const Extension* a, const Extension* b) { return a->name() < b->name(); } }; } // namespace // A mock implementation of ExtensionsServiceFrontendInterface for testing the // backend. class ExtensionsServiceTestFrontend : public ExtensionsServiceFrontendInterface { public: ~ExtensionsServiceTestFrontend() { for (ExtensionList::iterator iter = extensions_.begin(); iter != extensions_.end(); ++iter) { delete *iter; } } std::vector<std::string>* errors() { return &errors_; } ExtensionList* extensions() { return &extensions_; } // ExtensionsServiceFrontendInterface virtual MessageLoop* GetMessageLoop() { return &message_loop_; } virtual void OnExtensionLoadError(const std::string& message) { errors_.push_back(message); } virtual void OnExtensionsLoadedFromDirectory(ExtensionList* new_extensions) { extensions_.insert(extensions_.end(), new_extensions->begin(), new_extensions->end()); delete new_extensions; // In the tests we rely on extensions being in particular order, // which is not always the case (and is not guaranteed by used APIs). std::stable_sort(extensions_.begin(), extensions_.end(), ExtensionsOrder()); } private: MessageLoop message_loop_; ExtensionList extensions_; std::vector<std::string> errors_; }; // make the test a PlatformTest to setup autorelease pools properly on mac typedef PlatformTest ExtensionsServiceTest; // Test loading extensions from the profile directory. TEST_F(ExtensionsServiceTest, LoadAllExtensionsFromDirectory) { std::wstring extensions_dir; ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &extensions_dir)); FilePath manifest_path = FilePath::FromWStringHack(extensions_dir).Append( FILE_PATH_LITERAL("extensions")); scoped_refptr<ExtensionsServiceBackend> backend(new ExtensionsServiceBackend); scoped_refptr<ExtensionsServiceTestFrontend> frontend( new ExtensionsServiceTestFrontend); std::vector<Extension*> extensions; EXPECT_TRUE(backend->LoadExtensionsFromDirectory(manifest_path, scoped_refptr<ExtensionsServiceFrontendInterface>(frontend.get()))); frontend->GetMessageLoop()->RunAllPending(); // Note: There can be more errors if there are extra directories, like .svn // directories. EXPECT_TRUE(frontend->errors()->size() >= 2u); ASSERT_EQ(2u, frontend->extensions()->size()); EXPECT_EQ(std::wstring(L"com.google.myextension1"), frontend->extensions()->at(0)->id()); EXPECT_EQ(std::wstring(L"My extension 1"), frontend->extensions()->at(0)->name()); EXPECT_EQ(std::wstring(L"The first extension that I made."), frontend->extensions()->at(0)->description()); ASSERT_EQ(2u, frontend->extensions()->at(0)->content_scripts().size()); EXPECT_EQ(std::wstring(L"script1.user.js"), frontend->extensions()->at(0)->content_scripts().at(0)); EXPECT_EQ(std::wstring(L"script2.user.js"), frontend->extensions()->at(0)->content_scripts().at(1)); EXPECT_EQ(std::wstring(L"com.google.myextension2"), frontend->extensions()->at(1)->id()); EXPECT_EQ(std::wstring(L"My extension 2"), frontend->extensions()->at(1)->name()); EXPECT_EQ(std::wstring(L""), frontend->extensions()->at(1)->description()); ASSERT_EQ(0u, frontend->extensions()->at(1)->content_scripts().size()); };
Fix extensions_service_unittest on Linux.
Fix extensions_service_unittest on Linux. I was getting failures which are not present on buildbot, I don't know why. But with these changes it should be more solid. This also prevents a segfault which I got (out of bounds array access). Review URL: http://codereview.chromium.org/13258 git-svn-id: dd90618784b6a4b323ea0c23a071cb1c9e6f2ac7@6787 4ff67af0-8c30-449e-8e8b-ad334ec8d88c
C++
bsd-3-clause
wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser
b92d7a418a2e56976db2d1153a68cc9e65f3b7f3
src/platform/3ds/tappy-plane/source/main.cpp
src/platform/3ds/tappy-plane/source/main.cpp
// // main.cpp // tappyplane // // Created by Stephen Gowen on 8/20/15. // Copyright (c) 2015 Gowen Game Dev. All rights reserved. // #include <string.h> #include <3ds.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include "DSGameScreen.h" #include "Vector2D.h" #include "TouchEvent.h" #include "Vector2D.h" #include "Rectangle.h" #include "Assets.h" #include "OverlapTester.h" #include "Renderer.h" #include "LineBatcher.h" #include "RectangleBatcher.h" #include "Triangle.h" #include "Font.h" #include "SpriteBatcher.h" #include "LineBatcher.h" #include "CircleBatcher.h" #include "Rectangle.h" #include "Circle.h" #include "GameButton.h" #include "SpikePhysicalEntity.h" #include "ResourceConstants.h" extern "C" { #include "sfx.h" #include "filesystem.h" } #define TICKS_PER_SEC (268123480) int main(int argc, char** argv) { DSGameScreen gameScreen = DSGameScreen(400, 240, 320, 240); u64 lastTick = svcGetSystemTick(); touchPosition lastTouchPosition = {0, 0}; // Main loop while (aptMainLoop()) { u64 newTick = svcGetSystemTick(); float deltaTime = ((float) (newTick - lastTick)) / TICKS_PER_SEC; lastTick = newTick; hidScanInput(); u32 kDown = hidKeysDown(); if (kDown & KEY_START) { break; // break in order to return to hbmenu } touchPosition touch; //Read the touch screen coordinates hidTouchRead(&touch); if (lastTouchPosition.px == 0 && lastTouchPosition.py == 0) { if (touch.px != 0 && touch.py != 0) { gameScreen.onTouch(Touch_Type::DOWN, touch.px, touch.py); } } else { if (touch.px == 0 && touch.py == 0) { gameScreen.onTouch(Touch_Type::UP, lastTouchPosition.px, lastTouchPosition.py); } else { gameScreen.onTouch(Touch_Type::DRAGGED, touch.px, touch.py); } } lastTouchPosition.px = touch.px; lastTouchPosition.py = touch.py; gameScreen.update(deltaTime); gameScreen.render(); // Handle Sound for this frame short soundId; while ((soundId = gameScreen.getCurrentSoundId()) > 0) { switch (soundId) { case ASCEND_SOUND: // TODO, play sound break; case SCORE_SOUND: // TODO, play sound break; case HIT_SOUND: // TODO, play sound break; case LAND_SOUND: // TODO, play sound break; default: break; } } } gameScreen.exit(); return 0; }
// // main.cpp // tappyplane // // Created by Stephen Gowen on 8/20/15. // Copyright (c) 2015 Gowen Game Dev. All rights reserved. // #include <string.h> #include <3ds.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include "DSGameScreen.h" #include "Vector2D.h" #include "TouchEvent.h" #include "Vector2D.h" #include "Rectangle.h" #include "Assets.h" #include "OverlapTester.h" #include "Renderer.h" #include "LineBatcher.h" #include "RectangleBatcher.h" #include "Triangle.h" #include "Font.h" #include "SpriteBatcher.h" #include "LineBatcher.h" #include "CircleBatcher.h" #include "Rectangle.h" #include "Circle.h" #include "GameButton.h" #include "SpikePhysicalEntity.h" #include "ResourceConstants.h" extern "C" { #include "sfx.h" #include "filesystem.h" } #define TICKS_PER_SEC (268123480) //SFX_s* ascendSFX; //SFX_s* hitSFX; //SFX_s* landSFX; //SFX_s* scoreSFX; int main(int argc, char** argv) { //init fs // filesystemInit(argc, argv); // // initSound(); // // char str1[] = "ascend.raw"; // char* ascendSFXFn = &str1[0]; // // char str2[] = "hit.raw"; // char* hitSFXFn = &str2[0]; // // char str3[] = "land.raw"; // char* landSFXFn = &str3[0]; // // char str4[] = "score.raw"; // char* scoreSFXFn = &str4[0]; // // ascendSFX = createSFX(ascendSFXFn, SOUND_FORMAT_16BIT); // hitSFX = createSFX(hitSFXFn, SOUND_FORMAT_16BIT); // landSFX = createSFX(landSFXFn, SOUND_FORMAT_16BIT); // scoreSFX = createSFX(scoreSFXFn, SOUND_FORMAT_16BIT); DSGameScreen gameScreen = DSGameScreen(400, 240, 320, 240); u64 lastTick = svcGetSystemTick(); touchPosition lastTouchPosition = {0, 0}; // Main loop while (aptMainLoop()) { u64 newTick = svcGetSystemTick(); float deltaTime = ((float) (newTick - lastTick)) / TICKS_PER_SEC; lastTick = newTick; hidScanInput(); gameScreen.update(deltaTime); gameScreen.render(); u32 kDown = hidKeysDown(); if (kDown & KEY_START) { break; // break in order to return to hbmenu } touchPosition touch; //Read the touch screen coordinates hidTouchRead(&touch); if (lastTouchPosition.px == 0 && lastTouchPosition.py == 0) { if (touch.px != 0 && touch.py != 0) { gameScreen.onTouch(Touch_Type::DOWN, touch.px, touch.py); } } else { if (touch.px == 0 && touch.py == 0) { gameScreen.onTouch(Touch_Type::UP, lastTouchPosition.px, lastTouchPosition.py); } else { gameScreen.onTouch(Touch_Type::DRAGGED, touch.px, touch.py); } } lastTouchPosition.px = touch.px; lastTouchPosition.py = touch.py; // short soundId; // while ((soundId = gameScreen.getCurrentSoundId()) > 0) // { // switch (soundId) // { // case ASCEND_SOUND: // playSFX(ascendSFX); // break; // case SCORE_SOUND: // playSFX(scoreSFX); // break; // case HIT_SOUND: // playSFX(hitSFX); // break; // case LAND_SOUND: // playSFX(landSFX); // break; // default: // break; // } // } } // exitSound(); gameScreen.exit(); return 0; }
Revert "Removing commented lines"
Revert "Removing commented lines" This reverts commit 284a2550da13f41a9fa7a2c59d4ca91ba0b6e67c.
C++
mit
GowenGameDevOpenSource/tappy-plane,GowenGameDevOpenSource/tappy-plane,GowenGameDevOpenSource/tappy-plane,GowenGameDevOpenSource/tappy-plane
6be3ceb4010e287d9067bc40143dff8b4d3f863d
src/programs/libpfasst_swe_sphere/chooks.cpp
src/programs/libpfasst_swe_sphere/chooks.cpp
#include <mpi.h> #include "SphereDataVars.hpp" #include "SphereDataCtx.hpp" #include "ceval.hpp" extern "C" { void cecho_error(SphereData_Spectral* sd, int step) { // not implemented } void cecho_residual(SphereDataCtx *i_ctx, double i_norm, int i_current_proc) { // get the residual vector std::vector<std::vector<double> >& residuals = i_ctx->get_residuals(); // save the residual residuals[i_current_proc].push_back(i_norm); } void cecho_output_invariants( SphereDataCtx *i_ctx, SphereDataVars *i_Y, int i_current_proc, int i_current_step, int i_current_iter, int i_nnodes, int i_niters ) { const SphereData_Spectral& phi_Y = i_Y->get_phi(); const SphereData_Spectral& vort_Y = i_Y->get_vort(); const SphereData_Spectral& div_Y = i_Y->get_div(); // get the current space-time level const int level = i_Y->get_level(); // get the simulation variables SimulationVariables* simVars = i_ctx->get_simulation_variables(); // get the SphereDiagnostics object from context SphereHelpers_Diagnostics* sphereDiagnostics = i_ctx->get_sphere_diagnostics(); // get the SphereOperators object from context SphereOperators_SphereData* sphereOperators = i_ctx->get_sphere_operators(level); // compute the invariants sphereDiagnostics->update_phi_vrt_div_2_mass_energy_enstrophy( *sphereOperators, phi_Y, vort_Y, div_Y, *simVars ); std::cout << std::setprecision(20) << "mass = " << simVars->diag.total_mass << " energy = " << simVars->diag.total_energy << " potential_enstrophy = " << simVars->diag.total_potential_enstrophy << std::endl; // save the invariants for plotting at the end i_ctx->save_physical_invariants(i_current_step); } void cecho_output_jump( SphereDataCtx *i_ctx, SphereDataVars *i_Y, int i_current_proc, int i_current_step, int i_current_iter, int i_nnodes, int i_niters ) { const SphereData_Spectral& phi_Y = i_Y->get_phi(); const SphereData_Spectral& vort_Y = i_Y->get_vort(); const SphereData_Spectral& div_Y = i_Y->get_div(); // get the pointer to the Simulation Variables object SimulationVariables* simVars = i_ctx->get_simulation_variables(); simVars->timecontrol.current_timestep_nr = i_current_step + 1; auto current_dt = simVars->timecontrol.current_timestep_size; simVars->timecontrol.current_simulation_time = (i_current_step + 1) * current_dt; // write the data to file std::string filename = "prog_jump_phi_current_proc_"+std::to_string(i_current_proc) +"_current_iter_"+std::to_string(i_current_iter) +"_nnodes_" +std::to_string(i_nnodes) +"_niters_" +std::to_string(i_niters); write_file(*i_ctx, phi_Y, filename.c_str()); filename = "prog_jump_vort_current_proc_"+std::to_string(i_current_proc) +"_current_iter_"+std::to_string(i_current_iter) +"_nnodes_" +std::to_string(i_nnodes) +"_niters_" +std::to_string(i_niters); write_file(*i_ctx, vort_Y, filename.c_str()); filename = "prog_jump_div_current_proc_"+std::to_string(i_current_proc) +"_current_iter_"+std::to_string(i_current_iter) +"_nnodes_" +std::to_string(i_nnodes) +"_niters_" +std::to_string(i_niters); write_file(*i_ctx, div_Y, filename.c_str()); } void cecho_output_solution( SphereDataCtx *i_ctx, SphereDataVars *i_Y, int i_current_proc, int i_current_step, int i_current_iter, int i_nnodes, int i_niters ) { const SphereData_Spectral& phi_Y = i_Y->get_phi(); const SphereData_Spectral& vort_Y = i_Y->get_vort(); const SphereData_Spectral& div_Y = i_Y->get_div(); // get the pointer to the Simulation Variables object SimulationVariables* simVars = i_ctx->get_simulation_variables(); simVars->timecontrol.current_timestep_nr = i_current_step + 1; auto current_dt = simVars->timecontrol.current_timestep_size; simVars->timecontrol.current_simulation_time = (i_current_step + 1) * current_dt; // write the data to file std::string filename = "prog_phi_current_proc_"+std::to_string(i_current_proc) +"_current_iter_"+std::to_string(i_current_iter) +"_nnodes_" +std::to_string(i_nnodes) +"_niters_" +std::to_string(i_niters); write_file(*i_ctx, phi_Y, filename.c_str()); filename = "prog_vort_current_proc_"+std::to_string(i_current_proc) +"_current_iter_"+std::to_string(i_current_iter) +"_nnodes_" +std::to_string(i_nnodes) +"_niters_" +std::to_string(i_niters); write_file(*i_ctx, vort_Y, filename.c_str()); filename = "prog_div_current_proc_"+std::to_string(i_current_proc) +"_current_iter_"+std::to_string(i_current_iter) +"_nnodes_" +std::to_string(i_nnodes) +"_niters_" +std::to_string(i_niters); write_file(*i_ctx, div_Y, filename.c_str()); } }
#include <mpi.h> #include "SphereDataVars.hpp" #include "SphereDataCtx.hpp" #include "ceval.hpp" extern "C" { void cecho_error(SphereData_Spectral* sd, int step) { // not implemented } void cecho_residual(SphereDataCtx *i_ctx, double i_norm, int i_current_proc) { // get the residual vector std::vector<std::vector<double> >& residuals = i_ctx->get_residuals(); // save the residual residuals[i_current_proc].push_back(i_norm); } void cecho_output_invariants(SphereDataCtx *i_ctx, SphereDataVars *i_Y, int i_current_proc, int i_current_step, int i_current_iter, int i_nnodes, int i_niters ) { const SphereData_Spectral& phi_Y = i_Y->get_phi(); const SphereData_Spectral& vort_Y = i_Y->get_vort(); const SphereData_Spectral& div_Y = i_Y->get_div(); // get the current space-time level const int level = i_Y->get_level(); // get the simulation variables SimulationVariables* simVars = i_ctx->get_simulation_variables(); // get the SphereDiagnostics object from context SphereHelpers_Diagnostics* sphereDiagnostics = i_ctx->get_sphere_diagnostics(); // get the SphereOperators object from context SphereOperators_SphereData* sphereOperators = i_ctx->get_sphere_operators(level); // compute the invariants sphereDiagnostics->update_phi_vrt_div_2_mass_energy_enstrophy( *sphereOperators, phi_Y, vort_Y, div_Y, *simVars ); std::cout << std::setprecision(20) << "mass = " << simVars->diag.total_mass << " energy = " << simVars->diag.total_energy << " potential_enstrophy = " << simVars->diag.total_potential_enstrophy << std::endl; // save the invariants for plotting at the end i_ctx->save_physical_invariants(i_current_step); } void cecho_output_jump(SphereDataCtx *i_ctx, SphereDataVars *i_Y, int i_current_proc, int i_current_step, int i_current_iter, int i_nnodes, int i_niters ) { const SphereData_Spectral& phi_Y = i_Y->get_phi(); const SphereData_Spectral& vort_Y = i_Y->get_vort(); const SphereData_Spectral& div_Y = i_Y->get_div(); // get the pointer to the Simulation Variables object SimulationVariables* simVars = i_ctx->get_simulation_variables(); simVars->timecontrol.current_timestep_nr = i_current_step + 1; auto current_dt = simVars->timecontrol.current_timestep_size; simVars->timecontrol.current_simulation_time = (i_current_step + 1) * current_dt; // write the data to file std::string filename = "prog_jump_phi_current_proc_"+std::to_string(i_current_proc) +"_current_iter_"+std::to_string(i_current_iter) +"_nnodes_" +std::to_string(i_nnodes) +"_niters_" +std::to_string(i_niters); write_file(*i_ctx, phi_Y, filename.c_str()); filename = "prog_jump_vort_current_proc_"+std::to_string(i_current_proc) +"_current_iter_"+std::to_string(i_current_iter) +"_nnodes_" +std::to_string(i_nnodes) +"_niters_" +std::to_string(i_niters); write_file(*i_ctx, vort_Y, filename.c_str()); filename = "prog_jump_div_current_proc_"+std::to_string(i_current_proc) +"_current_iter_"+std::to_string(i_current_iter) +"_nnodes_" +std::to_string(i_nnodes) +"_niters_" +std::to_string(i_niters); write_file(*i_ctx, div_Y, filename.c_str()); } void cecho_output_solution(SphereDataCtx *i_ctx, SphereDataVars *i_Y, int i_current_proc, int i_current_step, int i_current_iter, int i_nnodes, int i_niters ) { // get the pointer to the Simulation Variables object SimulationVariables* simVars = i_ctx->get_simulation_variables(); // update timecontrol information simVars->timecontrol.current_timestep_nr = i_current_step + 1; auto current_dt = simVars->timecontrol.current_timestep_size; simVars->timecontrol.current_simulation_time = (i_current_step + 1) * current_dt; // check if output is necessary const auto output_dt = simVars->iodata.output_each_sim_seconds; if (output_dt < 0) { // no output required return; } if (output_dt != 0) { // == 0 means output at every step if (std::fmod(simVars->timecontrol.current_simulation_time, output_dt) != 0) { // we haven't reached the next output time yet -> no output required return; } } const SphereData_Spectral& phi_Y = i_Y->get_phi(); const SphereData_Spectral& vort_Y = i_Y->get_vort(); const SphereData_Spectral& div_Y = i_Y->get_div(); // write the data to file std::string filename = "prog_phi_current_proc_"+std::to_string(i_current_proc) +"_current_iter_"+std::to_string(i_current_iter) +"_nnodes_" +std::to_string(i_nnodes) +"_niters_" +std::to_string(i_niters); write_file(*i_ctx, phi_Y, filename.c_str()); filename = "prog_vort_current_proc_"+std::to_string(i_current_proc) +"_current_iter_"+std::to_string(i_current_iter) +"_nnodes_" +std::to_string(i_nnodes) +"_niters_" +std::to_string(i_niters); write_file(*i_ctx, vort_Y, filename.c_str()); filename = "prog_div_current_proc_"+std::to_string(i_current_proc) +"_current_iter_"+std::to_string(i_current_iter) +"_nnodes_" +std::to_string(i_nnodes) +"_niters_" +std::to_string(i_niters); write_file(*i_ctx, div_Y, filename.c_str()); } }
Add Support for Output Frequency Flag -o
Add Support for Output Frequency Flag -o -o output_freq now affects the output frequency of libpfasst_swe_sphere: output_freq < 0 --> no output in between, only at final time step output_freq = 0 --> output at every time step output_freq > 0 --> output if (current_time mod output_freq) == 0 Also did some reformatting to keep indentation consistent with rest of SWEET
C++
mit
schreiberx/sweet,schreiberx/sweet,schreiberx/sweet,schreiberx/sweet
c664c1c1a5d8196dd5a8c9397e60afeef4c06229
gi/pyp-topics/src/train-contexts.cc
gi/pyp-topics/src/train-contexts.cc
// STL #include <iostream> #include <fstream> #include <algorithm> #include <iterator> // Boost #include <boost/program_options/parsers.hpp> #include <boost/program_options/variables_map.hpp> #include <boost/scoped_ptr.hpp> // Local #include "pyp-topics.hh" #include "corpus.hh" #include "contexts_corpus.hh" #include "gzstream.hh" static const char *REVISION = "$Rev$"; // Namespaces using namespace boost; using namespace boost::program_options; using namespace std; int main(int argc, char **argv) { cout << "Pitman Yor topic models: Copyright 2010 Phil Blunsom\n"; cout << REVISION << '\n' <<endl; //////////////////////////////////////////////////////////////////////////////////////////// // Command line processing variables_map vm; // Command line processing { options_description cmdline_specific("Command line specific options"); cmdline_specific.add_options() ("help,h", "print help message") ("config,c", value<string>(), "config file specifying additional command line options") ; options_description config_options("Allowed options"); config_options.add_options() ("help,h", "print help message") ("data,d", value<string>(), "file containing the documents and context terms") ("topics,t", value<int>()->default_value(50), "number of topics") ("document-topics-out,o", value<string>(), "file to write the document topics to") ("default-topics-out", value<string>(), "file to write default term topic assignments.") ("topic-words-out,w", value<string>(), "file to write the topic word distribution to") ("samples,s", value<int>()->default_value(10), "number of sampling passes through the data") ("backoff-type", value<string>(), "backoff type: none|simple") // ("filter-singleton-contexts", "filter singleton contexts") ("hierarchical-topics", "Use a backoff hierarchical PYP as the P0 for the document topics distribution.") ("freq-cutoff-start", value<int>()->default_value(0), "initial frequency cutoff.") ("freq-cutoff-end", value<int>()->default_value(0), "final frequency cutoff.") ("freq-cutoff-interval", value<int>()->default_value(0), "number of iterations between frequency decrement.") ("max-threads", value<int>()->default_value(1), "maximum number of simultaneous threads allowed") ("max-contexts-per-document", value<int>()->default_value(0), "Only sample the n most frequent contexts for a document.") ("num-jobs", value<int>()->default_value(1), "allows finer control over parallelization") ; cmdline_specific.add(config_options); store(parse_command_line(argc, argv, cmdline_specific), vm); notify(vm); if (vm.count("config") > 0) { ifstream config(vm["config"].as<string>().c_str()); store(parse_config_file(config, config_options), vm); } if (vm.count("help")) { cout << cmdline_specific << "\n"; return 1; } } //////////////////////////////////////////////////////////////////////////////////////////// if (!vm.count("data")) { cerr << "Please specify a file containing the data." << endl; return 1; } assert(vm["max-threads"].as<int>() > 0); assert(vm["num-jobs"].as<int>() > -1); // seed the random number generator: 0 = automatic, specify value otherwise unsigned long seed = 0; PYPTopics model(vm["topics"].as<int>(), vm.count("hierarchical-topics"), seed, vm["max-threads"].as<int>(), vm["num-jobs"].as<int>()); // read the data BackoffGenerator* backoff_gen=0; if (vm.count("backoff-type")) { if (vm["backoff-type"].as<std::string>() == "none") { backoff_gen = 0; } else if (vm["backoff-type"].as<std::string>() == "simple") { backoff_gen = new SimpleBackoffGenerator(); } else { cerr << "Backoff type (--backoff-type) must be one of none|simple." <<endl; return(1); } } ContextsCorpus contexts_corpus; contexts_corpus.read_contexts(vm["data"].as<string>(), backoff_gen, /*vm.count("filter-singleton-contexts")*/ false); model.set_backoff(contexts_corpus.backoff_index()); if (backoff_gen) delete backoff_gen; // train the sampler model.sample_corpus(contexts_corpus, vm["samples"].as<int>(), vm["freq-cutoff-start"].as<int>(), vm["freq-cutoff-end"].as<int>(), vm["freq-cutoff-interval"].as<int>(), vm["max-contexts-per-document"].as<int>()); if (vm.count("document-topics-out")) { ogzstream documents_out(vm["document-topics-out"].as<string>().c_str()); int document_id=0; map<int,int> all_terms; for (Corpus::const_iterator corpusIt=contexts_corpus.begin(); corpusIt != contexts_corpus.end(); ++corpusIt, ++document_id) { vector<int> unique_terms; for (Document::const_iterator docIt=corpusIt->begin(); docIt != corpusIt->end(); ++docIt) { if (unique_terms.empty() || *docIt != unique_terms.back()) unique_terms.push_back(*docIt); // increment this terms frequency pair<map<int,int>::iterator,bool> insert_result = all_terms.insert(make_pair(*docIt,1)); if (!insert_result.second) all_terms[*docIt] = all_terms[*docIt] + 1; //insert_result.first++; } documents_out << contexts_corpus.key(document_id) << '\t'; documents_out << model.max(document_id).first << " " << corpusIt->size() << " ||| "; for (std::vector<int>::const_iterator termIt=unique_terms.begin(); termIt != unique_terms.end(); ++termIt) { if (termIt != unique_terms.begin()) documents_out << " ||| "; vector<std::string> strings = contexts_corpus.context2string(*termIt); copy(strings.begin(), strings.end(),ostream_iterator<std::string>(documents_out, " ")); std::pair<int,PYPTopics::F> maxinfo = model.max(document_id, *termIt); documents_out << "||| C=" << maxinfo.first << " P=" << maxinfo.second; } documents_out <<endl; } documents_out.close(); if (vm.count("default-topics-out")) { ofstream default_topics(vm["default-topics-out"].as<string>().c_str()); default_topics << model.max_topic() <<endl; for (std::map<int,int>::const_iterator termIt=all_terms.begin(); termIt != all_terms.end(); ++termIt) { vector<std::string> strings = contexts_corpus.context2string(termIt->first); default_topics << model.max(-1, termIt->first).first << " ||| " << termIt->second << " ||| "; copy(strings.begin(), strings.end(),ostream_iterator<std::string>(default_topics, " ")); default_topics <<endl; } } } if (vm.count("topic-words-out")) { ogzstream topics_out(vm["topic-words-out"].as<string>().c_str()); model.print_topic_terms(topics_out); topics_out.close(); } cout <<endl; return 0; }
// STL #include <iostream> #include <fstream> #include <algorithm> #include <iterator> // Boost #include <boost/program_options/parsers.hpp> #include <boost/program_options/variables_map.hpp> #include <boost/scoped_ptr.hpp> // Local #include "pyp-topics.hh" #include "corpus.hh" #include "contexts_corpus.hh" #include "gzstream.hh" static const char *REVISION = "$Rev$"; // Namespaces using namespace boost; using namespace boost::program_options; using namespace std; int main(int argc, char **argv) { cout << "Pitman Yor topic models: Copyright 2010 Phil Blunsom\n"; cout << REVISION << '\n' <<endl; //////////////////////////////////////////////////////////////////////////////////////////// // Command line processing variables_map vm; // Command line processing { options_description cmdline_specific("Command line specific options"); cmdline_specific.add_options() ("help,h", "print help message") ("config,c", value<string>(), "config file specifying additional command line options") ; options_description config_options("Allowed options"); config_options.add_options() ("data,d", value<string>(), "file containing the documents and context terms") ("topics,t", value<int>()->default_value(50), "number of topics") ("document-topics-out,o", value<string>(), "file to write the document topics to") ("default-topics-out", value<string>(), "file to write default term topic assignments.") ("topic-words-out,w", value<string>(), "file to write the topic word distribution to") ("samples,s", value<int>()->default_value(10), "number of sampling passes through the data") ("backoff-type", value<string>(), "backoff type: none|simple") // ("filter-singleton-contexts", "filter singleton contexts") ("hierarchical-topics", "Use a backoff hierarchical PYP as the P0 for the document topics distribution.") ("freq-cutoff-start", value<int>()->default_value(0), "initial frequency cutoff.") ("freq-cutoff-end", value<int>()->default_value(0), "final frequency cutoff.") ("freq-cutoff-interval", value<int>()->default_value(0), "number of iterations between frequency decrement.") ("max-threads", value<int>()->default_value(1), "maximum number of simultaneous threads allowed") ("max-contexts-per-document", value<int>()->default_value(0), "Only sample the n most frequent contexts for a document.") ("num-jobs", value<int>()->default_value(1), "allows finer control over parallelization") ; cmdline_specific.add(config_options); store(parse_command_line(argc, argv, cmdline_specific), vm); notify(vm); if (vm.count("config") > 0) { ifstream config(vm["config"].as<string>().c_str()); store(parse_config_file(config, config_options), vm); } if (vm.count("help")) { cout << cmdline_specific << "\n"; return 1; } } //////////////////////////////////////////////////////////////////////////////////////////// if (!vm.count("data")) { cerr << "Please specify a file containing the data." << endl; return 1; } assert(vm["max-threads"].as<int>() > 0); assert(vm["num-jobs"].as<int>() > -1); // seed the random number generator: 0 = automatic, specify value otherwise unsigned long seed = 0; PYPTopics model(vm["topics"].as<int>(), vm.count("hierarchical-topics"), seed, vm["max-threads"].as<int>(), vm["num-jobs"].as<int>()); // read the data BackoffGenerator* backoff_gen=0; if (vm.count("backoff-type")) { if (vm["backoff-type"].as<std::string>() == "none") { backoff_gen = 0; } else if (vm["backoff-type"].as<std::string>() == "simple") { backoff_gen = new SimpleBackoffGenerator(); } else { cerr << "Backoff type (--backoff-type) must be one of none|simple." <<endl; return(1); } } ContextsCorpus contexts_corpus; contexts_corpus.read_contexts(vm["data"].as<string>(), backoff_gen, /*vm.count("filter-singleton-contexts")*/ false); model.set_backoff(contexts_corpus.backoff_index()); if (backoff_gen) delete backoff_gen; // train the sampler model.sample_corpus(contexts_corpus, vm["samples"].as<int>(), vm["freq-cutoff-start"].as<int>(), vm["freq-cutoff-end"].as<int>(), vm["freq-cutoff-interval"].as<int>(), vm["max-contexts-per-document"].as<int>()); if (vm.count("document-topics-out")) { ogzstream documents_out(vm["document-topics-out"].as<string>().c_str()); int document_id=0; map<int,int> all_terms; for (Corpus::const_iterator corpusIt=contexts_corpus.begin(); corpusIt != contexts_corpus.end(); ++corpusIt, ++document_id) { vector<int> unique_terms; for (Document::const_iterator docIt=corpusIt->begin(); docIt != corpusIt->end(); ++docIt) { if (unique_terms.empty() || *docIt != unique_terms.back()) unique_terms.push_back(*docIt); // increment this terms frequency pair<map<int,int>::iterator,bool> insert_result = all_terms.insert(make_pair(*docIt,1)); if (!insert_result.second) all_terms[*docIt] = all_terms[*docIt] + 1; //insert_result.first++; } documents_out << contexts_corpus.key(document_id) << '\t'; documents_out << model.max(document_id).first << " " << corpusIt->size() << " ||| "; for (std::vector<int>::const_iterator termIt=unique_terms.begin(); termIt != unique_terms.end(); ++termIt) { if (termIt != unique_terms.begin()) documents_out << " ||| "; vector<std::string> strings = contexts_corpus.context2string(*termIt); copy(strings.begin(), strings.end(),ostream_iterator<std::string>(documents_out, " ")); std::pair<int,PYPTopics::F> maxinfo = model.max(document_id, *termIt); documents_out << "||| C=" << maxinfo.first << " P=" << maxinfo.second; } documents_out <<endl; } documents_out.close(); if (vm.count("default-topics-out")) { ofstream default_topics(vm["default-topics-out"].as<string>().c_str()); default_topics << model.max_topic() <<endl; for (std::map<int,int>::const_iterator termIt=all_terms.begin(); termIt != all_terms.end(); ++termIt) { vector<std::string> strings = contexts_corpus.context2string(termIt->first); default_topics << model.max(-1, termIt->first).first << " ||| " << termIt->second << " ||| "; copy(strings.begin(), strings.end(),ostream_iterator<std::string>(default_topics, " ")); default_topics <<endl; } } } if (vm.count("topic-words-out")) { ogzstream topics_out(vm["topic-words-out"].as<string>().c_str()); model.print_topic_terms(topics_out); topics_out.close(); } cout <<endl; return 0; }
fix duplicate help argument
fix duplicate help argument git-svn-id: 357248c53bdac2d7b36f7ee045286eb205fcf757@605 ec762483-ff6d-05da-a07a-a48fb63a330f
C++
apache-2.0
kho/mr-cdec,agesmundo/FasterCubePruning,agesmundo/FasterCubePruning,agesmundo/FasterCubePruning,agesmundo/FasterCubePruning,kho/mr-cdec,pks/cdec-dtrain-legacy,pks/cdec-dtrain-legacy,kho/mr-cdec,pks/cdec-dtrain-legacy,kho/mr-cdec,pks/cdec-dtrain-legacy,pks/cdec-dtrain-legacy,agesmundo/FasterCubePruning,agesmundo/FasterCubePruning,pks/cdec-dtrain-legacy,kho/mr-cdec,kho/mr-cdec
ea36e7a74c339e993177239484801d39979d6103
chrome/common/extensions/extension_manifests_unittest.cc
chrome/common/extensions/extension_manifests_unittest.cc
// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/file_path.h" #include "base/file_util.h" #include "base/path_service.h" #include "base/scoped_ptr.h" #include "base/string_util.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/extensions/extension.h" #include "chrome/common/extensions/extension_constants.h" #include "chrome/common/extensions/extension_error_utils.h" #include "chrome/common/json_value_serializer.h" #include "testing/gtest/include/gtest/gtest.h" namespace errors = extension_manifest_errors; class ManifestTest : public testing::Test { public: ManifestTest() : enable_apps_(true) {} protected: Extension* LoadExtension(const std::string& name, std::string* error) { return LoadExtensionWithLocation(name, Extension::INTERNAL, error); } Extension* LoadExtensionWithLocation(const std::string& name, Extension::Location location, std::string* error) { FilePath path; PathService::Get(chrome::DIR_TEST_DATA, &path); path = path.AppendASCII("extensions") .AppendASCII("manifest_tests") .AppendASCII(name.c_str()); EXPECT_TRUE(file_util::PathExists(path)); JSONFileValueSerializer serializer(path); scoped_ptr<DictionaryValue> value( static_cast<DictionaryValue*>(serializer.Deserialize(NULL, error))); if (!value.get()) return NULL; scoped_ptr<Extension> extension(new Extension(path.DirName())); extension->set_location(location); extension->set_apps_enabled(enable_apps_); if (!extension->InitFromValue(*value, false, error)) return NULL; return extension.release(); } Extension* LoadAndExpectSuccess(const std::string& name) { std::string error; Extension* extension = LoadExtension(name, &error); EXPECT_TRUE(extension); EXPECT_EQ("", error); return extension; } void LoadAndExpectError(const std::string& name, const std::string& expected_error) { std::string error; scoped_ptr<Extension> extension(LoadExtension(name, &error)); EXPECT_FALSE(extension.get()) << "Expected failure loading extension '" << name << "', but didn't get one."; EXPECT_TRUE(MatchPatternASCII(error, expected_error)) << name << " expected '" << expected_error << "' but got '" << error << "'"; } bool enable_apps_; }; TEST_F(ManifestTest, AppsDisabledByDefault) { #if defined(OS_CHROMEOS) // On ChromeOS, apps are enabled by default. if (Extension::AppsAreEnabled()) return; #endif enable_apps_ = false; LoadAndExpectError("launch_local_path.json", errors::kAppsNotEnabled); } TEST_F(ManifestTest, ValidApp) { scoped_ptr<Extension> extension(LoadAndExpectSuccess("valid_app.json")); EXPECT_EQ(GURL("http://www.google.com/"), extension->web_extent().origin()); EXPECT_EQ(2u, extension->web_extent().paths().size()); EXPECT_EQ("mail/", extension->web_extent().paths()[0]); EXPECT_EQ("foobar/", extension->web_extent().paths()[1]); EXPECT_EQ(Extension::LAUNCH_WINDOW, extension->launch_container()); EXPECT_EQ(false, extension->launch_fullscreen()); EXPECT_EQ("mail/", extension->launch_web_url()); } TEST_F(ManifestTest, AppWebOrigin) { LoadAndExpectError("web_origin_wrong_type.json", errors::kInvalidWebOrigin); LoadAndExpectError("web_origin_invalid_1.json", errors::kInvalidWebOrigin); LoadAndExpectError("web_origin_invalid_2.json", errors::kInvalidWebOrigin); LoadAndExpectError("web_origin_invalid_3.json", errors::kInvalidWebOrigin); } TEST_F(ManifestTest, AppWebPaths) { LoadAndExpectError("web_paths_wrong_type.json", errors::kInvalidWebPaths); LoadAndExpectError("web_paths_invalid_path_1.json", ExtensionErrorUtils::FormatErrorMessage( errors::kInvalidWebPath, "0")); LoadAndExpectError("web_paths_invalid_path_2.json", ExtensionErrorUtils::FormatErrorMessage( errors::kInvalidWebPath, "0")); } // This test crashes. http://crbug.com/47230 TEST_F(ManifestTest, DISABLED_AppLaunchContainer) { scoped_ptr<Extension> extension; extension.reset(LoadAndExpectSuccess("launch_tab.json")); EXPECT_EQ(Extension::LAUNCH_TAB, extension->launch_container()); extension.reset(LoadAndExpectSuccess("launch_window.json")); EXPECT_EQ(Extension::LAUNCH_WINDOW, extension->launch_container()); extension.reset(LoadAndExpectSuccess("launch_panel.json")); EXPECT_EQ(Extension::LAUNCH_PANEL, extension->launch_container()); extension.reset(LoadAndExpectSuccess("launch_default.json")); EXPECT_EQ(Extension::LAUNCH_TAB, extension->launch_container()); extension.reset(LoadAndExpectSuccess("launch_fullscreen.json")); EXPECT_EQ(true, extension->launch_fullscreen()); extension.reset(LoadAndExpectSuccess("launch_width.json")); EXPECT_EQ(640, extension->launch_width()); extension.reset(LoadAndExpectSuccess("launch_height.json")); EXPECT_EQ(480, extension->launch_height()); LoadAndExpectError("launch_container_invalid_type.json", errors::kInvalidLaunchContainer); LoadAndExpectError("launch_container_invalid_value.json", errors::kInvalidLaunchContainer); LoadAndExpectError("launch_container_without_launch_url.json", errors::kLaunchURLRequired); LoadAndExpectError("launch_fullscreen_invalid.json", errors::kInvalidLaunchFullscreen); LoadAndExpectError("launch_width_invalid.json", errors::kInvalidLaunchWidthContainer); LoadAndExpectError("launch_width_negative.json", errors::kInvalidLaunchWidth); LoadAndExpectError("launch_height_invalid.json", errors::kInvalidLaunchHeightContainer); LoadAndExpectError("launch_height_negative.json", errors::kInvalidLaunchHeight); } TEST_F(ManifestTest, AppLaunchURL) { LoadAndExpectError("launch_path_and_url.json", errors::kLaunchPathAndURLAreExclusive); LoadAndExpectError("launch_path_invalid_type.json", errors::kInvalidLaunchLocalPath); LoadAndExpectError("launch_path_invalid_value.json", errors::kInvalidLaunchLocalPath); LoadAndExpectError("launch_url_invalid_type.json", errors::kInvalidLaunchWebURL); scoped_ptr<Extension> extension; extension.reset(LoadAndExpectSuccess("launch_local_path.json")); EXPECT_EQ(extension->url().spec() + "launch.html", extension->GetFullLaunchURL().spec()); extension.reset(LoadAndExpectSuccess("launch_web_url_relative.json")); EXPECT_EQ(GURL("http://www.google.com/launch.html"), extension->GetFullLaunchURL()); extension.reset(LoadAndExpectSuccess("launch_web_url_absolute.json")); EXPECT_EQ(GURL("http://www.google.com/launch.html"), extension->GetFullLaunchURL()); } TEST_F(ManifestTest, Override) { LoadAndExpectError("override_newtab_and_history.json", errors::kMultipleOverrides); LoadAndExpectError("override_invalid_page.json", errors::kInvalidChromeURLOverrides); scoped_ptr<Extension> extension; extension.reset(LoadAndExpectSuccess("override_new_tab.json")); EXPECT_EQ(extension->url().spec() + "newtab.html", extension->GetChromeURLOverrides().find("newtab")->second.spec()); extension.reset(LoadAndExpectSuccess("override_history.json")); EXPECT_EQ(extension->url().spec() + "history.html", extension->GetChromeURLOverrides().find("history")->second.spec()); } TEST_F(ManifestTest, ChromeURLPermissionInvalid) { LoadAndExpectError("permission_chrome_url_invalid.json", errors::kInvalidPermissionScheme); } TEST_F(ManifestTest, ChromeResourcesPermissionValidOnlyForComponents) { LoadAndExpectError("permission_chrome_resources_url.json", errors::kInvalidPermissionScheme); std::string error; scoped_ptr<Extension> extension; extension.reset(LoadExtensionWithLocation( "permission_chrome_resources_url.json", Extension::COMPONENT, &error)); EXPECT_EQ("", error); } TEST_F(ManifestTest, ChromeURLContentScriptInvalid) { LoadAndExpectError("content_script_chrome_url_invalid.json", errors::kInvalidMatch); }
// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/file_path.h" #include "base/file_util.h" #include "base/path_service.h" #include "base/scoped_ptr.h" #include "base/string_util.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/extensions/extension.h" #include "chrome/common/extensions/extension_constants.h" #include "chrome/common/extensions/extension_error_utils.h" #include "chrome/common/json_value_serializer.h" #include "testing/gtest/include/gtest/gtest.h" namespace errors = extension_manifest_errors; class ManifestTest : public testing::Test { public: ManifestTest() : enable_apps_(true) {} protected: Extension* LoadExtension(const std::string& name, std::string* error) { return LoadExtensionWithLocation(name, Extension::INTERNAL, error); } Extension* LoadExtensionWithLocation(const std::string& name, Extension::Location location, std::string* error) { FilePath path; PathService::Get(chrome::DIR_TEST_DATA, &path); path = path.AppendASCII("extensions") .AppendASCII("manifest_tests") .AppendASCII(name.c_str()); EXPECT_TRUE(file_util::PathExists(path)); JSONFileValueSerializer serializer(path); scoped_ptr<DictionaryValue> value( static_cast<DictionaryValue*>(serializer.Deserialize(NULL, error))); if (!value.get()) return NULL; scoped_ptr<Extension> extension(new Extension(path.DirName())); extension->set_location(location); extension->set_apps_enabled(enable_apps_); if (!extension->InitFromValue(*value, false, error)) return NULL; return extension.release(); } Extension* LoadAndExpectSuccess(const std::string& name) { std::string error; Extension* extension = LoadExtension(name, &error); EXPECT_TRUE(extension); EXPECT_EQ("", error); return extension; } void LoadAndExpectError(const std::string& name, const std::string& expected_error) { std::string error; scoped_ptr<Extension> extension(LoadExtension(name, &error)); EXPECT_FALSE(extension.get()) << "Expected failure loading extension '" << name << "', but didn't get one."; EXPECT_TRUE(MatchPatternASCII(error, expected_error)) << name << " expected '" << expected_error << "' but got '" << error << "'"; } bool enable_apps_; }; TEST_F(ManifestTest, AppsDisabledByDefault) { #if defined(OS_CHROMEOS) // On ChromeOS, apps are enabled by default. if (Extension::AppsAreEnabled()) return; #endif enable_apps_ = false; LoadAndExpectError("launch_local_path.json", errors::kAppsNotEnabled); } TEST_F(ManifestTest, ValidApp) { scoped_ptr<Extension> extension(LoadAndExpectSuccess("valid_app.json")); EXPECT_EQ(GURL("http://www.google.com/"), extension->web_extent().origin()); EXPECT_EQ(2u, extension->web_extent().paths().size()); EXPECT_EQ("mail/", extension->web_extent().paths()[0]); EXPECT_EQ("foobar/", extension->web_extent().paths()[1]); EXPECT_EQ(Extension::LAUNCH_WINDOW, extension->launch_container()); EXPECT_EQ(false, extension->launch_fullscreen()); EXPECT_EQ("mail/", extension->launch_web_url()); } TEST_F(ManifestTest, AppWebOrigin) { LoadAndExpectError("web_origin_wrong_type.json", errors::kInvalidWebOrigin); LoadAndExpectError("web_origin_invalid_1.json", errors::kInvalidWebOrigin); LoadAndExpectError("web_origin_invalid_2.json", errors::kInvalidWebOrigin); LoadAndExpectError("web_origin_invalid_3.json", errors::kInvalidWebOrigin); } TEST_F(ManifestTest, AppWebPaths) { LoadAndExpectError("web_paths_wrong_type.json", errors::kInvalidWebPaths); LoadAndExpectError("web_paths_invalid_path_1.json", ExtensionErrorUtils::FormatErrorMessage( errors::kInvalidWebPath, "0")); LoadAndExpectError("web_paths_invalid_path_2.json", ExtensionErrorUtils::FormatErrorMessage( errors::kInvalidWebPath, "0")); } TEST_F(ManifestTest, AppLaunchContainer) { scoped_ptr<Extension> extension; extension.reset(LoadAndExpectSuccess("launch_tab.json")); EXPECT_EQ(Extension::LAUNCH_TAB, extension->launch_container()); extension.reset(LoadAndExpectSuccess("launch_window.json")); EXPECT_EQ(Extension::LAUNCH_WINDOW, extension->launch_container()); extension.reset(LoadAndExpectSuccess("launch_panel.json")); EXPECT_EQ(Extension::LAUNCH_PANEL, extension->launch_container()); extension.reset(LoadAndExpectSuccess("launch_default.json")); EXPECT_EQ(Extension::LAUNCH_TAB, extension->launch_container()); extension.reset(LoadAndExpectSuccess("launch_fullscreen.json")); EXPECT_EQ(true, extension->launch_fullscreen()); extension.reset(LoadAndExpectSuccess("launch_width.json")); EXPECT_EQ(640, extension->launch_width()); extension.reset(LoadAndExpectSuccess("launch_height.json")); EXPECT_EQ(480, extension->launch_height()); LoadAndExpectError("launch_container_invalid_type.json", errors::kInvalidLaunchContainer); LoadAndExpectError("launch_container_invalid_value.json", errors::kInvalidLaunchContainer); LoadAndExpectError("launch_container_without_launch_url.json", errors::kLaunchURLRequired); LoadAndExpectError("launch_fullscreen_invalid.json", errors::kInvalidLaunchFullscreen); LoadAndExpectError("launch_width_invalid.json", errors::kInvalidLaunchWidthContainer); LoadAndExpectError("launch_width_negative.json", errors::kInvalidLaunchWidth); LoadAndExpectError("launch_height_invalid.json", errors::kInvalidLaunchHeightContainer); LoadAndExpectError("launch_height_negative.json", errors::kInvalidLaunchHeight); } TEST_F(ManifestTest, AppLaunchURL) { LoadAndExpectError("launch_path_and_url.json", errors::kLaunchPathAndURLAreExclusive); LoadAndExpectError("launch_path_invalid_type.json", errors::kInvalidLaunchLocalPath); LoadAndExpectError("launch_path_invalid_value.json", errors::kInvalidLaunchLocalPath); LoadAndExpectError("launch_url_invalid_type.json", errors::kInvalidLaunchWebURL); scoped_ptr<Extension> extension; extension.reset(LoadAndExpectSuccess("launch_local_path.json")); EXPECT_EQ(extension->url().spec() + "launch.html", extension->GetFullLaunchURL().spec()); extension.reset(LoadAndExpectSuccess("launch_web_url_relative.json")); EXPECT_EQ(GURL("http://www.google.com/launch.html"), extension->GetFullLaunchURL()); extension.reset(LoadAndExpectSuccess("launch_web_url_absolute.json")); EXPECT_EQ(GURL("http://www.google.com/launch.html"), extension->GetFullLaunchURL()); } TEST_F(ManifestTest, Override) { LoadAndExpectError("override_newtab_and_history.json", errors::kMultipleOverrides); LoadAndExpectError("override_invalid_page.json", errors::kInvalidChromeURLOverrides); scoped_ptr<Extension> extension; extension.reset(LoadAndExpectSuccess("override_new_tab.json")); EXPECT_EQ(extension->url().spec() + "newtab.html", extension->GetChromeURLOverrides().find("newtab")->second.spec()); extension.reset(LoadAndExpectSuccess("override_history.json")); EXPECT_EQ(extension->url().spec() + "history.html", extension->GetChromeURLOverrides().find("history")->second.spec()); } TEST_F(ManifestTest, ChromeURLPermissionInvalid) { LoadAndExpectError("permission_chrome_url_invalid.json", errors::kInvalidPermissionScheme); } TEST_F(ManifestTest, ChromeResourcesPermissionValidOnlyForComponents) { LoadAndExpectError("permission_chrome_resources_url.json", errors::kInvalidPermissionScheme); std::string error; scoped_ptr<Extension> extension; extension.reset(LoadExtensionWithLocation( "permission_chrome_resources_url.json", Extension::COMPONENT, &error)); EXPECT_EQ("", error); } TEST_F(ManifestTest, ChromeURLContentScriptInvalid) { LoadAndExpectError("content_script_chrome_url_invalid.json", errors::kInvalidMatch); }
Enable ManifestTest.AppLaunchContainer as it should be passing now.
Enable ManifestTest.AppLaunchContainer as it should be passing now. BUG=47230 TEST=test passes TBR=robertshield Review URL: http://codereview.chromium.org/2844016 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@50553 0039d316-1c4b-4281-b951-d872f2087c98
C++
bsd-3-clause
yitian134/chromium,adobe/chromium,yitian134/chromium,adobe/chromium,yitian134/chromium,Crystalnix/house-of-life-chromium,Crystalnix/house-of-life-chromium,yitian134/chromium,adobe/chromium,Crystalnix/house-of-life-chromium,yitian134/chromium,gavinp/chromium,adobe/chromium,ropik/chromium,gavinp/chromium,ropik/chromium,gavinp/chromium,adobe/chromium,yitian134/chromium,gavinp/chromium,yitian134/chromium,gavinp/chromium,Crystalnix/house-of-life-chromium,ropik/chromium,ropik/chromium,adobe/chromium,adobe/chromium,Crystalnix/house-of-life-chromium,Crystalnix/house-of-life-chromium,Crystalnix/house-of-life-chromium,gavinp/chromium,adobe/chromium,gavinp/chromium,yitian134/chromium,gavinp/chromium,adobe/chromium,gavinp/chromium,adobe/chromium,Crystalnix/house-of-life-chromium,yitian134/chromium,Crystalnix/house-of-life-chromium,ropik/chromium,Crystalnix/house-of-life-chromium,ropik/chromium,ropik/chromium,adobe/chromium,Crystalnix/house-of-life-chromium,ropik/chromium,gavinp/chromium,yitian134/chromium,ropik/chromium
66431fef6cc4c721cebc295b810f0e26b2b451e2
functor.cpp
functor.cpp
/** * Copyright © 2017 IBM Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "config.h" #include "functor.hpp" #include "manager.hpp" #include <sdbusplus/bus.hpp> namespace phosphor { namespace inventory { namespace manager { namespace functor { bool PropertyConditionBase::operator()(sdbusplus::bus::bus& bus, sdbusplus::message::message&, Manager& mgr) const { std::string path(_path); return (*this)(path, bus, mgr); } bool PropertyConditionBase::operator()(const std::string& path, sdbusplus::bus::bus& bus, Manager& mgr) const { std::string host; if (_service) { host.assign(_service); } else { auto mapperCall = bus.new_method_call( "xyz.openbmc_project.ObjectMapper", "/xyz/openbmc_project/object_mapper", "xyz.openbmc_project.ObjectMapper", "GetObject"); mapperCall.append(path); mapperCall.append(std::vector<std::string>({_iface})); auto mapperResponseMsg = bus.call(mapperCall); if (mapperResponseMsg.is_method_error()) { return false; } std::map<std::string, std::vector<std::string>> mapperResponse; mapperResponseMsg.read(mapperResponse); if (mapperResponse.empty()) { return false; } host = mapperResponse.begin()->first; } // When the host service name is inventory manager, eval using // a given `getProperty` function to retrieve a property value from // an interface hosted by inventory manager. if (host == BUSNAME) { try { return eval(mgr); } catch (const std::exception& e) { // Unable to find property on inventory manager, // default condition to false. return false; } } auto hostCall = bus.new_method_call( host.c_str(), path.c_str(), "org.freedesktop.DBus.Properties", "Get"); hostCall.append(_iface); hostCall.append(_property); auto hostResponseMsg = bus.call(hostCall); if (hostResponseMsg.is_method_error()) { return false; } return eval(hostResponseMsg); } } // namespace functor } // namespace manager } // namespace inventory } // namespace phosphor // vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
/** * Copyright © 2017 IBM Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "config.h" #include "functor.hpp" #include "manager.hpp" #include <phosphor-logging/lg2.hpp> #include <sdbusplus/bus.hpp> namespace phosphor { namespace inventory { namespace manager { namespace functor { bool PropertyConditionBase::operator()(sdbusplus::bus::bus& bus, sdbusplus::message::message&, Manager& mgr) const { std::string path(_path); return (*this)(path, bus, mgr); } bool PropertyConditionBase::operator()(const std::string& path, sdbusplus::bus::bus& bus, Manager& mgr) const { std::string host; if (_service) { host.assign(_service); } else { auto mapperCall = bus.new_method_call( "xyz.openbmc_project.ObjectMapper", "/xyz/openbmc_project/object_mapper", "xyz.openbmc_project.ObjectMapper", "GetObject"); mapperCall.append(path); mapperCall.append(std::vector<std::string>({_iface})); std::map<std::string, std::vector<std::string>> mapperResponse; try { auto mapperResponseMsg = bus.call(mapperCall); mapperResponseMsg.read(mapperResponse); } catch (const std::exception& e) { lg2::error("Failed to execute GetObject method: {ERROR}", "ERROR", e); return false; } if (mapperResponse.empty()) { return false; } host = mapperResponse.begin()->first; } // When the host service name is inventory manager, eval using // a given `getProperty` function to retrieve a property value from // an interface hosted by inventory manager. if (host == BUSNAME) { try { return eval(mgr); } catch (const std::exception& e) { // Unable to find property on inventory manager, // default condition to false. return false; } } auto hostCall = bus.new_method_call( host.c_str(), path.c_str(), "org.freedesktop.DBus.Properties", "Get"); hostCall.append(_iface); hostCall.append(_property); try { auto hostResponseMsg = bus.call(hostCall); return eval(hostResponseMsg); } catch (const std::exception& e) { lg2::error("Failed to execute Get method: {ERROR}", "ERROR", e); return false; } } } // namespace functor } // namespace manager } // namespace inventory } // namespace phosphor // vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
Handle D-Bus exceptions
Handle D-Bus exceptions The is_method_error method is deprecated, remove and add try-catch to handler D-Bus exceptions around mapper call. Signed-off-by: George Liu <[email protected]> Change-Id: I1a40b6550b51059e13a71676f5daeb3f637f9182
C++
apache-2.0
openbmc/phosphor-inventory-manager,openbmc/phosphor-inventory-manager
fde4e11fb06e18c07a2578cf64eadaeb9f2fd2f1
groups/csa/csabase/csabase_tool.cpp
groups/csa/csabase/csabase_tool.cpp
// csabase_tool.cpp -*-C++-*- #include <csabase_tool.h> #include <csabase_debug.h> #include <csabase_diagnostic_builder.h> #include <llvm/Option/ArgList.h> #include <llvm/Support/Allocator.h> #include <llvm/Support/Host.h> #include <llvm/Support/ManagedStatic.h> #include <llvm/Support/Path.h> #include <llvm/Support/Process.h> #include <llvm/Support/Program.h> #include <llvm/Support/Signals.h> #include <llvm/Support/StringSaver.h> #include <llvm/Support/TargetSelect.h> #include <llvm/Support/Timer.h> #include <clang/Driver/Compilation.h> #include <clang/Driver/Driver.h> #include <clang/Driver/Options.h> #include <clang/Frontend/ChainedDiagnosticConsumer.h> #include <clang/Frontend/CompilerInstance.h> #include <clang/Frontend/FrontendDiagnostic.h> #include <clang/Frontend/SerializedDiagnosticPrinter.h> #include <clang/Frontend/TextDiagnosticBuffer.h> #include <clang/Frontend/TextDiagnosticPrinter.h> #include <clang/FrontendTool/Utils.h> #include <clang/Tooling/CompilationDatabase.h> #include <clang/Tooling/Tooling.h> #include <memory> #include <set> #include <string> #include <system_error> using namespace clang; using namespace clang::driver; using namespace clang::tooling; using namespace llvm; using namespace llvm::opt; // Most of this code is cribbed from clang's driver.cpp. namespace { void LLVMErrorHandler(void *UserData, const std::string& Message, bool GenCrashDiag) { DiagnosticsEngine &Diags = *static_cast<DiagnosticsEngine*>(UserData); Diags.Report(diag::err_fe_error_backend) << Message; sys::RunInterruptHandlers(); exit(GenCrashDiag ? 70 : 1); } } std::string GetExecutablePath(const char *Argv0, bool CanonicalPrefixes) { if (!CanonicalPrefixes) return Argv0; void *P = (void *)(intptr_t)GetExecutablePath; return sys::fs::getMainExecutable(Argv0, P); } int cc1_main(ArrayRef<const char *> Argv, const char *Argv0, void *MainAddr) { std::unique_ptr<CompilerInstance> Clang(new CompilerInstance()); IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs()); // Initialize targets first, so that --version shows registered targets. InitializeNativeTarget(); InitializeNativeTargetAsmPrinter(); InitializeNativeTargetAsmParser(); IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions(); TextDiagnosticBuffer *DiagsBuffer = new TextDiagnosticBuffer; DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagsBuffer); bool Success = CompilerInvocation::CreateFromArgs( Clang->getInvocation(), Argv.begin(), Argv.end(), Diags); if (Clang->getHeaderSearchOpts().UseBuiltinIncludes && Clang->getHeaderSearchOpts().ResourceDir.empty()) Clang->getHeaderSearchOpts().ResourceDir = CompilerInvocation::GetResourcesPath(Argv0, MainAddr); Clang->createDiagnostics(); if (!Clang->hasDiagnostics()) return 1; install_fatal_error_handler( LLVMErrorHandler, static_cast<void *>(&Clang->getDiagnostics())); DiagsBuffer->FlushDiagnostics(Clang->getDiagnostics()); if (!Success) return 1; Success = ExecuteCompilerInvocation(Clang.get()); TimerGroup::printAll(errs()); remove_fatal_error_handler(); if (Clang->getFrontendOpts().DisableFree) { BuryPointer(std::move(Clang)); return !Success; } llvm_shutdown(); return !Success; } static void SetInstallDir(SmallVectorImpl<const char *>& argv, Driver& TheDriver, bool CanonicalPrefixes) { SmallString<128> InstalledPath(argv[0]); if (sys::path::filename(InstalledPath) == InstalledPath) if (ErrorOr<std::string> Tmp = sys::findProgramByName( sys::path::filename(InstalledPath.str()))) InstalledPath = *Tmp; // FIXME: We don't actually canonicalize this, we just make it absolute. if (CanonicalPrefixes) sys::fs::make_absolute(InstalledPath); InstalledPath = sys::path::parent_path(InstalledPath); if (sys::fs::exists(InstalledPath.c_str())) TheDriver.setInstalledDir(InstalledPath); } static int ExecuteCC1Tool(ArrayRef<const char *> argv, StringRef Tool) { void *GetExecutablePathVP = (void *)(intptr_t)GetExecutablePath; return cc1_main(argv.slice(2), argv[0], GetExecutablePathVP); } int csabase::run(int argc_, const char **argv_) { sys::PrintStackTraceOnErrorSignal(argv_[0], true); PrettyStackTraceProgram X(argc_, argv_); if (sys::Process::FixupStandardFileDescriptors()) return 1; SmallVector<const char *, 2560> argv(argv_, argv_ + argc_); std::vector<std::string> scratch; std::unique_ptr<CompilationDatabase> Compilations; std::string ErrorMessage; bool after_dashes = false; std::set<std::string> defined, included; auto ins = [&](StringRef s, size_t i) { scratch.emplace_back(s); argv.insert(argv.begin() + i, scratch.back().data()); return i + 1; }; // Compilation Database Handling // // If there is a '--p=directory' option specified, look for a compilation // database in that directory. If there isn't one, assume that this is a // deliberate choice and do not attempt to look for one elsewhere. // // If there is no such option, look for a compilation database with respect // to each source file until one is found, and use that one (even if other // compilation databases would be found with respect to further sources). // // For each source file to be processed, look it up in the compilation // database and use the first entry (if found). Entries past the first are // ignored. From that entry, insert all '-D' and '-I' options ahead of the // source file in the command line, taking include path options relative to // the directory specified in the compilation database command. Macros and // include paths are only inserted once (even if macro definitions change) // and they're cumulative. for (size_t i = 0; i < argv.size(); ++i) { StringRef arg(argv[i]); if (arg == "-cc1") { break; } else if (arg.startswith("--p=")) { arg = arg.drop_front(4); Compilations = CompilationDatabase::autoDetectFromDirectory( arg, ErrorMessage); argv.erase(argv.begin() + i--); if (!Compilations) { // Allow opt out of compilation database, e.g., by '--p=-'. break; } } else if (arg == "-D") { StringRef def = argv[i + 1]; defined.insert(def.split('=').first); ++i; } else if (arg.startswith("-D")) { defined.insert(arg.drop_front(2).split('=').first); } else if (arg == "-U") { StringRef def = argv[i + 1]; defined.insert(def); ++i; } else if (arg.startswith("-U")) { defined.insert(arg.drop_front(2)); } else if (arg == "-I") { StringRef dir = argv[i + 1]; included.insert(dir); ++i; } else if (arg.startswith("-I")) { included.insert(arg.drop_front(2)); } else if (after_dashes) { if (!Compilations) { Compilations = CompilationDatabase::autoDetectFromSource( arg, ErrorMessage); } if (Compilations) { StringRef argstem = sys::path::stem(arg); for (auto cc : Compilations->getAllCompileCommands()) { if (sys::path::stem(cc.Filename) == argstem) { for (size_t j = 0; j < cc.CommandLine.size(); ++j) { StringRef ca = cc.CommandLine[j]; if (ca.startswith("-D")) { StringRef def = ca.drop_front(2); if (def.size() == 0) { def = cc.CommandLine[j++]; } if (defined.insert(def).second) { i = ins("-D", i); i = ins(def, i); } } else if (ca.startswith("-I")) { StringRef dir = ca.drop_front(2); if (dir.size() == 0) { dir = cc.CommandLine[j++]; } if (included.insert(dir).second) { i = ins("-I", i); if (sys::path::is_absolute(dir)) { i = ins(dir, i); } else { SmallVector<char, 1024> path( cc.Directory.begin(), cc.Directory.end()); sys::path::append(path, dir); sys::path::remove_dots(path, true); i = ins(StringRef(path.begin(), path.size()), i); } } } } break; // Use the first command line found only. } } } } else if (arg == "--") { after_dashes = true; argv.erase(argv.begin() + i--); if (Compilations && i == argv.size() - 1) { for (const auto &s : Compilations->getAllFiles()) { ins(s, i); } } } } InitializeNativeTarget(); BumpPtrAllocator Alloc; StringSaver Saver(Alloc); bool MarkEOLs = argv.size() <= 1 || !StringRef(argv[1]).startswith("-cc1"); cl::ExpandResponseFiles(Saver, cl::TokenizeGNUCommandLine, argv, MarkEOLs); auto FirstArg = std::find_if(argv.begin() + 1, argv.end(), [](const char *A) { return A != nullptr; }); if (FirstArg != argv.end() && StringRef(*FirstArg).startswith("-cc1")) { // If -cc1 came from a response file, remove the EOL sentinels. if (MarkEOLs) { auto newEnd = std::remove(argv.begin(), argv.end(), nullptr); argv.resize(newEnd - argv.begin()); } return ExecuteCC1Tool(argv, argv[1] + 4); } bool CanonicalPrefixes = true; raw_ostream *ForVersion = 0; for (int i = 1, size = argv.size(); i < size; ++i) { // Skip end-of-line response file markers if (argv[i] == nullptr) continue; if (StringRef(argv[i]) == "-no-canonical-prefixes") { CanonicalPrefixes = false; } else if (StringRef(argv[i]) == "--version") { ForVersion = &outs(); } else if (!ForVersion && StringRef(argv[i]) == "-v") { ForVersion = &errs(); } } std::string Path = GetExecutablePath(argv[0], CanonicalPrefixes); StringRef ExFile = StringRef(sys::path::filename(Path)); if (ForVersion) { StringRef Name = ExFile.drop_back(ExFile.endswith("_bin") ? 4 : 0); *ForVersion << Name << " version " BDE_VERIFY_VERSION " based on\n"; } IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions; std::unique_ptr<OptTable> Opts(createDriverOptTable()); unsigned MissingIndex, MissingCount; InputArgList Args = Opts->ParseArgs(argv, MissingIndex, MissingCount); (void)ParseDiagnosticArgs(*DiagOpts, Args); TextDiagnosticPrinter *DiagClient = new TextDiagnosticPrinter(errs(), &*DiagOpts); DiagClient->setPrefix(ExFile); IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs()); DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagClient); if (!DiagOpts->DiagnosticSerializationFile.empty()) { auto SerializedConsumer = clang::serialized_diags::create( DiagOpts->DiagnosticSerializationFile, &*DiagOpts, true); Diags.setClient(new ChainedDiagnosticConsumer( Diags.takeClient(), std::move(SerializedConsumer))); } ProcessWarningOptions(Diags, *DiagOpts, false); Driver TheDriver(Path, sys::getDefaultTargetTriple(), Diags); #undef CCF #define CCF(D, X, O) \ if ((D.X = !!::getenv(#O))) D.X##Filename = ::getenv(#O "_FILE") CCF(TheDriver, CCPrintOptions, CC_PRINT_OPTIONS); CCF(TheDriver, CCPrintHeaders, CC_PRINT_HEADERS); CCF(TheDriver, CCLogDiagnostics, CC_LOG_DIAGNOSTICS); #undef CCF SetInstallDir(argv, TheDriver, CanonicalPrefixes); std::unique_ptr<Compilation> C(TheDriver.BuildCompilation(argv)); int Res = 0; SmallVector<std::pair<int, const Command *>, 4> FailingCommands; if (C.get()) Res = TheDriver.ExecuteCompilation(*C, FailingCommands); for (const auto& P : FailingCommands) { int CommandRes = P.first; const Command *FailingCommand = P.second; if (!Res) Res = CommandRes; bool DiagnoseCrash = CommandRes < 0 || CommandRes == 70; #ifdef LLVM_ON_WIN32 DiagnoseCrash |= CommandRes == 3; #endif if (DiagnoseCrash) { TheDriver.generateCompilationDiagnostics(*C, *FailingCommand); break; } } Diags.getClient()->finish(); TimerGroup::printAll(errs()); llvm_shutdown(); #ifdef LLVM_ON_WIN32 if (Res < 0) Res = 1; #endif return Res; } // ---------------------------------------------------------------------------- // Copyright (C) 2014 Bloomberg Finance L.P. // // 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. // ----------------------------- END-OF-FILE ----------------------------------
// csabase_tool.cpp -*-C++-*- #include <csabase_tool.h> #include <csabase_debug.h> #include <csabase_diagnostic_builder.h> #include <llvm/Option/ArgList.h> #include <llvm/Support/Allocator.h> #include <llvm/Support/Host.h> #include <llvm/Support/ManagedStatic.h> #include <llvm/Support/Path.h> #include <llvm/Support/Process.h> #include <llvm/Support/Program.h> #include <llvm/Support/Signals.h> #include <llvm/Support/StringSaver.h> #include <llvm/Support/TargetSelect.h> #include <llvm/Support/Timer.h> #include <clang/Driver/Compilation.h> #include <clang/Driver/Driver.h> #include <clang/Driver/Options.h> #include <clang/Frontend/ChainedDiagnosticConsumer.h> #include <clang/Frontend/CompilerInstance.h> #include <clang/Frontend/FrontendDiagnostic.h> #include <clang/Frontend/SerializedDiagnosticPrinter.h> #include <clang/Frontend/TextDiagnosticBuffer.h> #include <clang/Frontend/TextDiagnosticPrinter.h> #include <clang/FrontendTool/Utils.h> #include <clang/Tooling/CompilationDatabase.h> #include <clang/Tooling/Tooling.h> #include <memory> #include <set> #include <string> #include <system_error> using namespace clang; using namespace clang::driver; using namespace clang::tooling; using namespace llvm; using namespace llvm::opt; // Most of this code is cribbed from clang's driver.cpp. namespace { void LLVMErrorHandler(void *UserData, const std::string& Message, bool GenCrashDiag) { DiagnosticsEngine &Diags = *static_cast<DiagnosticsEngine*>(UserData); Diags.Report(diag::err_fe_error_backend) << Message; sys::RunInterruptHandlers(); exit(GenCrashDiag ? 70 : 1); } } std::string GetExecutablePath(const char *Argv0, bool CanonicalPrefixes) { if (!CanonicalPrefixes) return Argv0; void *P = (void *)(intptr_t)GetExecutablePath; return sys::fs::getMainExecutable(Argv0, P); } int cc1_main(ArrayRef<const char *> Argv, const char *Argv0, void *MainAddr) { std::unique_ptr<CompilerInstance> Clang(new CompilerInstance()); IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs()); // Initialize targets first, so that --version shows registered targets. InitializeNativeTarget(); InitializeNativeTargetAsmPrinter(); InitializeNativeTargetAsmParser(); IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions(); TextDiagnosticBuffer *DiagsBuffer = new TextDiagnosticBuffer; DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagsBuffer); bool Success = CompilerInvocation::CreateFromArgs( Clang->getInvocation(), Argv.begin(), Argv.end(), Diags); if (Clang->getHeaderSearchOpts().UseBuiltinIncludes && Clang->getHeaderSearchOpts().ResourceDir.empty()) Clang->getHeaderSearchOpts().ResourceDir = CompilerInvocation::GetResourcesPath(Argv0, MainAddr); Clang->createDiagnostics(); if (!Clang->hasDiagnostics()) return 1; install_fatal_error_handler( LLVMErrorHandler, static_cast<void *>(&Clang->getDiagnostics())); DiagsBuffer->FlushDiagnostics(Clang->getDiagnostics()); if (!Success) return 1; Success = ExecuteCompilerInvocation(Clang.get()); TimerGroup::printAll(errs()); remove_fatal_error_handler(); if (Clang->getFrontendOpts().DisableFree) { BuryPointer(std::move(Clang)); return !Success; } llvm_shutdown(); return !Success; } static void SetInstallDir(SmallVectorImpl<const char *>& argv, Driver& TheDriver, bool CanonicalPrefixes) { SmallString<128> InstalledPath(argv[0]); if (sys::path::filename(InstalledPath) == InstalledPath) if (ErrorOr<std::string> Tmp = sys::findProgramByName( sys::path::filename(InstalledPath.str()))) InstalledPath = *Tmp; // FIXME: We don't actually canonicalize this, we just make it absolute. if (CanonicalPrefixes) sys::fs::make_absolute(InstalledPath); InstalledPath = sys::path::parent_path(InstalledPath); if (sys::fs::exists(InstalledPath.c_str())) TheDriver.setInstalledDir(InstalledPath); } static int ExecuteCC1Tool(ArrayRef<const char *> argv, StringRef Tool) { void *GetExecutablePathVP = (void *)(intptr_t)GetExecutablePath; return cc1_main(argv.slice(2), argv[0], GetExecutablePathVP); } int csabase::run(int argc_, const char **argv_) { sys::PrintStackTraceOnErrorSignal(argv_[0], true); PrettyStackTraceProgram X(argc_, argv_); if (sys::Process::FixupStandardFileDescriptors()) return 1; SmallVector<const char *, 2560> argv(argv_, argv_ + argc_); std::vector<std::string> scratch; std::unique_ptr<CompilationDatabase> Compilations; std::string ErrorMessage; bool after_dashes = false; std::set<std::string> defined, included; auto ins = [&](StringRef s, size_t i) { scratch.emplace_back(s); argv.insert(argv.begin() + i, scratch.back().data()); return i + 1; }; // Compilation Database Handling // // If there is a '--p=directory' option specified, look for a compilation // database in that directory. If there isn't one, assume that this is a // deliberate choice and do not attempt to look for one elsewhere. // // If there is no such option, look for a compilation database with respect // to each source file until one is found, and use that one (even if other // compilation databases would be found with respect to further sources). // // For each source file to be processed, look it up in the compilation // database and use the first entry (if found). Entries past the first are // ignored. From that entry, insert all '-D' and '-I' options ahead of the // source file in the command line, taking include path options relative to // the directory specified in the compilation database command. Macros and // include paths are only inserted once (even if macro definitions change) // and they're cumulative. for (size_t i = 0; i < argv.size(); ++i) { StringRef arg(argv[i]); if (arg == "-cc1") { break; } else if (arg.startswith("--p=")) { arg = arg.drop_front(4); Compilations = CompilationDatabase::autoDetectFromDirectory( arg, ErrorMessage); argv.erase(argv.begin() + i--); if (!Compilations) { // Allow opt out of compilation database, e.g., by '--p=-'. break; } } else if (arg == "-D") { StringRef def = argv[i + 1]; defined.insert(def.split('=').first); ++i; } else if (arg.startswith("-D")) { defined.insert(arg.drop_front(2).split('=').first); } else if (arg == "-U") { StringRef def = argv[i + 1]; defined.insert(def); ++i; } else if (arg.startswith("-U")) { defined.insert(arg.drop_front(2)); } else if (arg == "-I") { StringRef dir = argv[i + 1]; included.insert(dir); ++i; } else if (arg.startswith("-I")) { included.insert(arg.drop_front(2)); } else if (after_dashes) { if (!Compilations) { Compilations = CompilationDatabase::autoDetectFromSource( arg, ErrorMessage); } if (Compilations) { StringRef argstem = sys::path::stem(arg); for (auto cc : Compilations->getAllCompileCommands()) { if (sys::path::stem(cc.Filename) == argstem) { size_t n = cc.CommandLine.size(); for (size_t j = 0; j < n; ++j) { StringRef ca = cc.CommandLine[j]; if (ca.consume_front("-D")) { StringRef def = ca; if (def.size() == 0 && j + 1 < n) { def = cc.CommandLine[++j]; } if (def.size() > 0 && defined.insert(def).second) { i = ins("-D", i); i = ins(def, i); } } else if (ca.consume_front("-I") || ca.consume_front("-isystem")) { StringRef dir = ca; if (dir.size() == 0 && j + 1 < n) { dir = cc.CommandLine[++j]; } if (dir.size() > 0 && included.insert(dir).second) { i = ins("-I", i); if (sys::path::is_absolute(dir)) { i = ins(dir, i); } else { SmallVector<char, 1024> path( cc.Directory.begin(), cc.Directory.end()); sys::path::append(path, dir); sys::path::remove_dots(path, true); i = ins(StringRef(path.begin(), path.size()), i); } } } } break; // Use the first command line found only. } } } } else if (arg == "--") { after_dashes = true; argv.erase(argv.begin() + i--); if (Compilations && i == argv.size() - 1) { for (const auto &s : Compilations->getAllFiles()) { ins(s, i); } } } } InitializeNativeTarget(); BumpPtrAllocator Alloc; StringSaver Saver(Alloc); bool MarkEOLs = argv.size() <= 1 || !StringRef(argv[1]).startswith("-cc1"); cl::ExpandResponseFiles(Saver, cl::TokenizeGNUCommandLine, argv, MarkEOLs); auto FirstArg = std::find_if(argv.begin() + 1, argv.end(), [](const char *A) { return A != nullptr; }); if (FirstArg != argv.end() && StringRef(*FirstArg).startswith("-cc1")) { // If -cc1 came from a response file, remove the EOL sentinels. if (MarkEOLs) { auto newEnd = std::remove(argv.begin(), argv.end(), nullptr); argv.resize(newEnd - argv.begin()); } return ExecuteCC1Tool(argv, argv[1] + 4); } bool CanonicalPrefixes = true; raw_ostream *ForVersion = 0; for (int i = 1, size = argv.size(); i < size; ++i) { // Skip end-of-line response file markers if (argv[i] == nullptr) continue; if (StringRef(argv[i]) == "-no-canonical-prefixes") { CanonicalPrefixes = false; } else if (StringRef(argv[i]) == "--version") { ForVersion = &outs(); } else if (!ForVersion && StringRef(argv[i]) == "-v") { ForVersion = &errs(); } } std::string Path = GetExecutablePath(argv[0], CanonicalPrefixes); StringRef ExFile = StringRef(sys::path::filename(Path)); if (ForVersion) { StringRef Name = ExFile.drop_back(ExFile.endswith("_bin") ? 4 : 0); *ForVersion << Name << " version " BDE_VERIFY_VERSION " based on\n"; } IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions; std::unique_ptr<OptTable> Opts(createDriverOptTable()); unsigned MissingIndex, MissingCount; InputArgList Args = Opts->ParseArgs(argv, MissingIndex, MissingCount); (void)ParseDiagnosticArgs(*DiagOpts, Args); TextDiagnosticPrinter *DiagClient = new TextDiagnosticPrinter(errs(), &*DiagOpts); DiagClient->setPrefix(ExFile); IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs()); DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagClient); if (!DiagOpts->DiagnosticSerializationFile.empty()) { auto SerializedConsumer = clang::serialized_diags::create( DiagOpts->DiagnosticSerializationFile, &*DiagOpts, true); Diags.setClient(new ChainedDiagnosticConsumer( Diags.takeClient(), std::move(SerializedConsumer))); } ProcessWarningOptions(Diags, *DiagOpts, false); Driver TheDriver(Path, sys::getDefaultTargetTriple(), Diags); #undef CCF #define CCF(D, X, O) \ if ((D.X = !!::getenv(#O))) D.X##Filename = ::getenv(#O "_FILE") CCF(TheDriver, CCPrintOptions, CC_PRINT_OPTIONS); CCF(TheDriver, CCPrintHeaders, CC_PRINT_HEADERS); CCF(TheDriver, CCLogDiagnostics, CC_LOG_DIAGNOSTICS); #undef CCF SetInstallDir(argv, TheDriver, CanonicalPrefixes); std::unique_ptr<Compilation> C(TheDriver.BuildCompilation(argv)); int Res = 0; SmallVector<std::pair<int, const Command *>, 4> FailingCommands; if (C.get()) Res = TheDriver.ExecuteCompilation(*C, FailingCommands); for (const auto& P : FailingCommands) { int CommandRes = P.first; const Command *FailingCommand = P.second; if (!Res) Res = CommandRes; bool DiagnoseCrash = CommandRes < 0 || CommandRes == 70; #ifdef LLVM_ON_WIN32 DiagnoseCrash |= CommandRes == 3; #endif if (DiagnoseCrash) { TheDriver.generateCompilationDiagnostics(*C, *FailingCommand); break; } } Diags.getClient()->finish(); TimerGroup::printAll(errs()); llvm_shutdown(); #ifdef LLVM_ON_WIN32 if (Res < 0) Res = 1; #endif return Res; } // ---------------------------------------------------------------------------- // Copyright (C) 2014 Bloomberg Finance L.P. // // 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. // ----------------------------- END-OF-FILE ----------------------------------
Handle -isystem like -I in compilation database
Handle -isystem like -I in compilation database
C++
apache-2.0
bloomberg/bde_verify,bloomberg/bde_verify,bloomberg/bde_verify,bloomberg/bde_verify,bloomberg/bde_verify
2508661759672d71b3a12eccdd2836c192139627
src/import/chips/p9/procedures/hwp/memory/lib/workarounds/mcbist_workarounds.C
src/import/chips/p9/procedures/hwp/memory/lib/workarounds/mcbist_workarounds.C
/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/memory/lib/workarounds/mcbist_workarounds.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file mcbist_workarounds.C /// @brief Workarounds for the MCBISt engine /// Workarounds are very deivce specific, so there is no attempt to generalize /// this code in any way. /// // *HWP HWP Owner: Brian Silver <[email protected]> // *HWP HWP Backup: Steven Glancy <[email protected]> // *HWP Team: Memory // *HWP Level: 2 // *HWP Consumed by: FSP:HB #include <fapi2.H> #include <p9_mc_scom_addresses.H> #include <p9_mc_scom_addresses_fld.H> #include <lib/mss_attribute_accessors.H> #include <lib/utils/scom.H> #include <lib/utils/pos.H> #include <lib/dimm/kind.H> #include <lib/workarounds/mcbist_workarounds.H> #include <lib/mcbist/mcbist.H> #include <lib/fir/fir.H> using fapi2::TARGET_TYPE_MCBIST; using fapi2::TARGET_TYPE_DIMM; using fapi2::FAPI2_RC_SUCCESS; namespace mss { namespace workarounds { namespace mcbist { /// /// @brief Replace reads with displays in the passed in MCBIST program /// @param[in,out] the MCBIST program to check for read/display replacement /// @note Useful for testing /// void replace_read_helper(mss::mcbist::program<TARGET_TYPE_MCBIST>& io_program) { using TT = mss::mcbistTraits<TARGET_TYPE_MCBIST>; io_program.change_maint_broadcast_mode(mss::OFF); io_program.change_end_boundary(mss::mcbist::end_boundary::STOP_AFTER_ADDRESS); for (auto& st : io_program.iv_subtests) { uint64_t l_op = 0; st.iv_mcbmr.extractToRight<TT::OP_TYPE, TT::OP_TYPE_LEN>(l_op); if (l_op == mss::mcbist::op_type::READ) { l_op = mss::mcbist::op_type::DISPLAY; } st.iv_mcbmr.insertFromRight<TT::OP_TYPE, TT::OP_TYPE_LEN>(l_op); } } /// /// @brief End of rank work around /// For Nimbus DD1 the MCBIST engine doesn't detect the end of rank properly /// for a 1R DIMM during a super-fast read. To work around this, we check the /// MCBIST to see if any port has a 1R DIMM on it and if so we change our stop /// conditions to immediate. However, because that doesn't work (by design) with /// read, we also must change all reads to displays (slow read.) /// @param[in] i_target the fapi2 target of the mcbist /// @param[in,out] io_program the mcbist program to check /// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok /// fapi2::ReturnCode end_of_rank( const fapi2::Target<TARGET_TYPE_MCBIST>& i_target, mss::mcbist::program<TARGET_TYPE_MCBIST>& io_program ) { using TT = mss::mcbistTraits<TARGET_TYPE_MCBIST>; // If we don't need the mcbist work-around, we're done. if (! mss::chip_ec_feature_mcbist_end_of_rank(i_target) ) { return FAPI2_RC_SUCCESS; } // First things first - lets find out if we have an 1R DIMM on our side of the chip. const auto l_dimm_kinds = dimm::kind::vector( mss::find_targets<TARGET_TYPE_DIMM>(i_target) ); const auto l_kind = std::find_if(l_dimm_kinds.begin(), l_dimm_kinds.end(), [](const dimm::kind & k) -> bool { // If total ranks are 1, we have a 1R DIMM, SDP. This is the fellow of concern return k.iv_total_ranks == 1; }); // If we don't find the fellow of concern, we can get outta here if (l_kind == l_dimm_kinds.end()) { FAPI_INF("no 1R SDP DIMM on this MCBIST (%s), we're ok", mss::c_str(i_target)); return FAPI2_RC_SUCCESS; } if( ! io_program.iv_config.getBit<TT::MCBIST_CFG_PAUSE_AFTER_RANK>() ) { FAPI_INF("not checking rank boundaries on this MCBIST (%s), we're ok", mss::c_str(i_target)); return FAPI2_RC_SUCCESS; } // If we're here, we need to fix up our program. We need to set our stop to stop immediate, which implies // we don't do broadcasts and we can't do read, we have to do display. replace_read_helper(io_program); return fapi2::FAPI2_RC_SUCCESS; } /// /// @brief WAT debug attention /// For Nimbus DD1 the MCBIST engine uses the WAT debug bit as a workaround /// @param[in] i_target the fapi2 target of the mcbist /// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok /// fapi2::ReturnCode wat_debug_attention( const fapi2::Target<fapi2::TARGET_TYPE_MCBIST>& i_target ) { // MCBIST attentions are already special attention if (mss::chip_ec_feature_mss_wat_debug_attn(i_target)) { fapi2::ReturnCode l_rc; fir::reg<MCBIST_MCBISTFIRQ> mcbist_fir_register(i_target, l_rc); FAPI_TRY(l_rc, "unable to create fir::reg for %d", MCBIST_MCBISTFIRQ); FAPI_TRY(mcbist_fir_register.attention<MCBIST_MCBISTFIRQ_WAT_DEBUG_ATTN>().write()); } return fapi2::FAPI2_RC_SUCCESS; fapi_try_exit: return fapi2::current_err; } } // close namespace mcbist } // close namespace workarounds } // close namespace mss
/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/memory/lib/workarounds/mcbist_workarounds.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2017 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file mcbist_workarounds.C /// @brief Workarounds for the MCBISt engine /// Workarounds are very deivce specific, so there is no attempt to generalize /// this code in any way. /// // *HWP HWP Owner: Brian Silver <[email protected]> // *HWP HWP Backup: Steven Glancy <[email protected]> // *HWP Team: Memory // *HWP Level: 2 // *HWP Consumed by: FSP:HB #include <fapi2.H> #include <p9_mc_scom_addresses.H> #include <p9_mc_scom_addresses_fld.H> #include <lib/mss_attribute_accessors.H> #include <lib/utils/scom.H> #include <lib/utils/pos.H> #include <lib/dimm/kind.H> #include <lib/workarounds/mcbist_workarounds.H> #include <lib/mcbist/mcbist.H> #include <lib/fir/fir.H> using fapi2::TARGET_TYPE_MCBIST; using fapi2::TARGET_TYPE_DIMM; using fapi2::FAPI2_RC_SUCCESS; namespace mss { namespace workarounds { namespace mcbist { /// /// @brief Replace reads with displays in the passed in MCBIST program /// @param[in,out] the MCBIST program to check for read/display replacement /// @note Useful for testing /// void replace_read_helper(mss::mcbist::program<TARGET_TYPE_MCBIST>& io_program) { using TT = mss::mcbistTraits<TARGET_TYPE_MCBIST>; io_program.change_maint_broadcast_mode(mss::OFF); io_program.change_end_boundary(mss::mcbist::end_boundary::STOP_AFTER_ADDRESS); for (auto& st : io_program.iv_subtests) { uint64_t l_op = 0; st.iv_mcbmr.extractToRight<TT::OP_TYPE, TT::OP_TYPE_LEN>(l_op); if (l_op == mss::mcbist::op_type::READ) { l_op = mss::mcbist::op_type::DISPLAY; } st.iv_mcbmr.insertFromRight<TT::OP_TYPE, TT::OP_TYPE_LEN>(l_op); } } /// /// @brief End of rank work around /// For Nimbus DD1 the MCBIST engine doesn't detect the end of rank properly /// for a 1R DIMM during a super-fast read. To work around this, we check the /// MCBIST to see if any port has a 1R DIMM on it and if so we change our stop /// conditions to immediate. However, because that doesn't work (by design) with /// read, we also must change all reads to displays (slow read.) /// @param[in] i_target the fapi2 target of the mcbist /// @param[in,out] io_program the mcbist program to check /// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok /// fapi2::ReturnCode end_of_rank( const fapi2::Target<TARGET_TYPE_MCBIST>& i_target, mss::mcbist::program<TARGET_TYPE_MCBIST>& io_program ) { using TT = mss::mcbistTraits<TARGET_TYPE_MCBIST>; // If we don't need the mcbist work-around, we're done. if (! mss::chip_ec_feature_mcbist_end_of_rank(i_target) ) { return FAPI2_RC_SUCCESS; } // First things first - lets find out if we have an 1R DIMM on our side of the chip. const auto l_dimm_kinds = dimm::kind::vector( mss::find_targets<TARGET_TYPE_DIMM>(i_target) ); const auto l_kind = std::find_if(l_dimm_kinds.begin(), l_dimm_kinds.end(), [](const dimm::kind & k) -> bool { // If total ranks are 1, we have a 1R DIMM, SDP. This is the fellow of concern return k.iv_total_ranks == 1; }); // If we don't find the fellow of concern, we can get outta here if (l_kind == l_dimm_kinds.end()) { FAPI_INF("no 1R SDP DIMM on this MCBIST (%s), we're ok", mss::c_str(i_target)); return FAPI2_RC_SUCCESS; } // Keep in mind that pause-on-error-mode is two bits and it doesn't encode master/slave. The // end_boundary enums are constructed such that STOP_AFTER_MASTER_RANK is really stop on // either master or slave for the purposes of this field. So, checking stop-after-master-rank // will catch both master and slave pauses which is correct for this work-around. uint64_t l_pause_mode = 0; io_program.iv_config.extractToRight<TT::CFG_PAUSE_ON_ERROR_MODE, TT::CFG_PAUSE_ON_ERROR_MODE_LEN>(l_pause_mode); if( l_pause_mode != mss::mcbist::end_boundary::STOP_AFTER_MASTER_RANK ) { FAPI_INF("not checking rank boundaries on this MCBIST (%s), we're ok", mss::c_str(i_target)); return FAPI2_RC_SUCCESS; } // If we're here, we need to fix up our program. We need to set our stop to stop immediate, which implies // we don't do broadcasts and we can't do read, we have to do display. replace_read_helper(io_program); return fapi2::FAPI2_RC_SUCCESS; } /// /// @brief WAT debug attention /// For Nimbus DD1 the MCBIST engine uses the WAT debug bit as a workaround /// @param[in] i_target the fapi2 target of the mcbist /// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok /// fapi2::ReturnCode wat_debug_attention( const fapi2::Target<fapi2::TARGET_TYPE_MCBIST>& i_target ) { // MCBIST attentions are already special attention if (mss::chip_ec_feature_mss_wat_debug_attn(i_target)) { fapi2::ReturnCode l_rc; fir::reg<MCBIST_MCBISTFIRQ> mcbist_fir_register(i_target, l_rc); FAPI_TRY(l_rc, "unable to create fir::reg for %d", MCBIST_MCBISTFIRQ); FAPI_TRY(mcbist_fir_register.attention<MCBIST_MCBISTFIRQ_WAT_DEBUG_ATTN>().write()); } return fapi2::FAPI2_RC_SUCCESS; fapi_try_exit: return fapi2::current_err; } } // close namespace mcbist } // close namespace workarounds } // close namespace mss
Change MCBIST 1R work around to actually check the pause bits
Change MCBIST 1R work around to actually check the pause bits Change-Id: If74067133ab901ab08860a26f7dc234a2c351c79 Reviewed-on: http://ralgit01.raleigh.ibm.com/gerrit1/34986 Tested-by: Jenkins Server <[email protected]> Tested-by: Hostboot CI <[email protected]> Dev-Ready: Brian R. Silver <[email protected]> Reviewed-by: STEPHEN GLANCY <[email protected]> Reviewed-by: JACOB L. HARVEY <[email protected]> Reviewed-by: Louis Stermole <[email protected]> Reviewed-by: Jennifer A. Stofer <[email protected]> Reviewed-on: http://ralgit01.raleigh.ibm.com/gerrit1/34995 Reviewed-by: Hostboot Team <[email protected]> Tested-by: FSP CI Jenkins <fsp-CI-jenkins+6963c9c00f6fe376c46a8e103faee5c9a2f9eaf2@us.ibm.com> Tested-by: Jenkins OP Build CI <[email protected]> Reviewed-by: Daniel M. Crowell <[email protected]>
C++
apache-2.0
Over-enthusiastic/hostboot,Over-enthusiastic/hostboot,Over-enthusiastic/hostboot,Over-enthusiastic/hostboot,Over-enthusiastic/hostboot
8f36fa40109984baf6175835804d77daa0f093c2
steampy.cpp
steampy.cpp
//SteamPy #include <steam/steam_api.h> #include <steam/isteamfriends.h> #include <steam/isteamugc.h> #include <steam/isteamutils.h> #if defined _WIN32 extern "C" { //Steam __declspec(dllexport) bool SteamInit(void); //SteamFriends __declspec(dllexport) const char* GetPersonaName(void); __declspec(dllexport) int GetFriendCount(void); __declspec(dllexport) const char* GetFriendNameByIndex(int index, int flag); __declspec(dllexport) int GetFriendStateByIndex(int index, int flag); __declspec(dllexport) int GetPersonaState(void); __declspec(dllexport) uint32 GetFriendGame(int index, int flag); __declspec(dllexport) bool IsFriendInGame(int index, int flag); __declspec(dllexport) void SetPersonaName(const char* newname); //SteamUtils __declspec(dllexport) uint32 GetSecondsSinceAppActive(void); __declspec(dllexport) uint32 GetSecondsSinceComputerActive(void); __declspec(dllexport) bool IsOverlayEnabled(void); __declspec(dllexport) uint8 GetCurrentBatteryPower(void); __declspec(dllexport) uint32 GetServerRealTime(void); __declspec(dllexport) const char* GetIPCountry(); __declspec(dllexport) bool IsSteamRunningInVR(); } #else extern "C" { //Steam __attribute__((__visibility__("default"))) bool SteamInit(void); //SteamFriends __attribute__((__visibility__("default"))) const char* GetPersonaName(void); __attribute__((__visibility__("default"))) int GetFriendCount(void); __attribute__((__visibility__("default"))) const char* GetFriendNameByIndex(int index, int flag); __attribute__((__visibility__("default"))) int GetFriendStateByIndex(int index, int flag); __attribute__((__visibility__("default"))) int GetPersonaState(void); __attribute__((__visibility__("default"))) uint32 GetFriendGame(int index, int flag); __attribute__((__visibility__("default"))) bool IsFriendInGame(int index, int flag); __attribute__((__visibility__("default"))) void SetPersonaName(const char* newname); //SteamUtils __attribute__((__visibility__("default"))) bool IsOverlayEnabled(void); __attribute__((__visibility__("default"))) uint8 GetCurrentBatteryPower(void); __attribute__((__visibility__("default"))) uint32 GetSecondsSinceAppActive(void); __attribute__((__visibility__("default"))) uint32 GetSecondsSinceComputerActive(void); __attribute__((__visibility__("default"))) uint32 GetServerRealTime(void); __attribute__((__visibility__("default"))) const char* GetIPCountry(); __attribute__((__visibility__("default"))) bool IsSteamRunningInVR(); } #endif bool SteamInit() { return SteamAPI_Init(); } const char* GetPersonaName() { return SteamFriends()->GetPersonaName(); } int GetFriendCount(int flag) { return SteamFriends()->GetFriendCount(flag); } const char* GetFriendNameByIndex(int index, int flag) { const char* name = SteamFriends()->GetFriendPersonaName(SteamFriends()->GetFriendByIndex(index, flag)); return name; } int GetFriendStateByIndex(int index, int flag) { return SteamFriends()->GetFriendPersonaState(SteamFriends()->GetFriendByIndex(index, flag)); } int GetPersonaState() { return SteamFriends()->GetPersonaState(); } uint32 GetFriendGame(int index, int flag) { FriendGameInfo_t* friendgame = new FriendGameInfo_t(); SteamFriends()->GetFriendGamePlayed(SteamFriends()->GetFriendByIndex(index, flag), friendgame); return friendgame->m_gameID.AppID(); } bool IsFriendInGame(int index, int flag) { return SteamFriends()->GetFriendGamePlayed(SteamFriends()->GetFriendByIndex(index, flag), new FriendGameInfo_t()); } void SetPersonaName(const char* newname) { SteamFriends()->SetPersonaName(newname); } bool IsOverlayEnabled() { return SteamUtils()->IsOverlayEnabled(); } uint8 GetCurrentBatteryPower() { return SteamUtils()->GetCurrentBatteryPower(); } const char* GetIPCountry() { return SteamUtils()->GetIPCountry(); }
//SteamPy #include <steam/steam_api.h> #include <steam/isteamfriends.h> #include <steam/isteamugc.h> #include <steam/isteamutils.h> #if defined _WIN32 extern "C" { //Steam __declspec(dllexport) bool SteamInit(void); //SteamFriends __declspec(dllexport) const char* GetPersonaName(void); __declspec(dllexport) int GetFriendCount(void); __declspec(dllexport) const char* GetFriendNameByIndex(int index, int flag); __declspec(dllexport) int GetFriendStateByIndex(int index, int flag); __declspec(dllexport) int GetPersonaState(void); __declspec(dllexport) uint32 GetFriendGame(int index, int flag); __declspec(dllexport) bool IsFriendInGame(int index, int flag); __declspec(dllexport) void SetPersonaName(const char* newname); //SteamUtils __declspec(dllexport) uint32 GetSecondsSinceAppActive(void); __declspec(dllexport) uint32 GetSecondsSinceComputerActive(void); __declspec(dllexport) bool IsOverlayEnabled(void); __declspec(dllexport) uint8 GetCurrentBatteryPower(void); __declspec(dllexport) uint32 GetServerRealTime(void); __declspec(dllexport) const char* GetIPCountry(); __declspec(dllexport) bool IsSteamRunningInVR(); } #else extern "C" { //Steam __attribute__((__visibility__("default"))) bool SteamInit(void); //SteamFriends __attribute__((__visibility__("default"))) const char* GetPersonaName(void); __attribute__((__visibility__("default"))) int GetFriendCount(void); __attribute__((__visibility__("default"))) const char* GetFriendNameByIndex(int index, int flag); __attribute__((__visibility__("default"))) int GetFriendStateByIndex(int index, int flag); __attribute__((__visibility__("default"))) int GetPersonaState(void); __attribute__((__visibility__("default"))) uint32 GetFriendGame(int index, int flag); __attribute__((__visibility__("default"))) bool IsFriendInGame(int index, int flag); __attribute__((__visibility__("default"))) void SetPersonaName(const char* newname); //SteamUtils __attribute__((__visibility__("default"))) bool IsOverlayEnabled(void); __attribute__((__visibility__("default"))) uint8 GetCurrentBatteryPower(void); __attribute__((__visibility__("default"))) uint32 GetSecondsSinceAppActive(void); __attribute__((__visibility__("default"))) uint32 GetSecondsSinceComputerActive(void); __attribute__((__visibility__("default"))) uint32 GetServerRealTime(void); __attribute__((__visibility__("default"))) const char* GetIPCountry(); __attribute__((__visibility__("default"))) bool IsSteamRunningInVR(); } #endif bool SteamInit() { return SteamAPI_Init(); } const char* GetPersonaName() { return SteamFriends()->GetPersonaName(); } int GetFriendCount(int flag) { return SteamFriends()->GetFriendCount(flag); } const char* GetFriendNameByIndex(int index, int flag) { const char* name = SteamFriends()->GetFriendPersonaName(SteamFriends()->GetFriendByIndex(index, flag)); return name; } int GetFriendStateByIndex(int index, int flag) { return SteamFriends()->GetFriendPersonaState(SteamFriends()->GetFriendByIndex(index, flag)); } int GetPersonaState() { return SteamFriends()->GetPersonaState(); } uint32 GetFriendGame(int index, int flag) { FriendGameInfo_t* friendgame = new FriendGameInfo_t(); SteamFriends()->GetFriendGamePlayed(SteamFriends()->GetFriendByIndex(index, flag), friendgame); return friendgame->m_gameID.AppID(); } bool IsFriendInGame(int index, int flag) { return SteamFriends()->GetFriendGamePlayed(SteamFriends()->GetFriendByIndex(index, flag), new FriendGameInfo_t()); } void SetPersonaName(const char* newname) { SteamFriends()->SetPersonaName(newname); } bool IsOverlayEnabled() { return SteamUtils()->IsOverlayEnabled(); } uint8 GetCurrentBatteryPower() { return SteamUtils()->GetCurrentBatteryPower(); } const char* GetIPCountry() { return SteamUtils()->GetIPCountry(); } uint32 GetSecondsSinceAppActive() { return SteamUtils()->GetSecondsSinceAppActive(); } uint32 GetSecondsSinceComputerActive() { return SteamUtils()->GetSecondsSinceComputerActive(); } uint32 GetServerRealTime() { return SteamUtils()->GetServerRealTime(); } bool IsSteamRunningInVR() { return SteamUtils()->IsSteamRunningInVR(); }
complete steampy.cpp
complete steampy.cpp
C++
mit
Gramps/SteamworksForPython,Gramps/SteamworksForPython
684e10732087955b65549452a68d2ec41a2bdcf3
src/examples/standard_extractor_la-cupula.cpp
src/examples/standard_extractor_la-cupula.cpp
/* * Copyright (C) 2006-2016 Music Technology Group - Universitat Pompeu Fabra * * This file is part of Essentia * * Essentia is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation (FSF), either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the Affero GNU General Public License * version 3 along with this program. If not, see http://www.gnu.org/licenses/ */ #include <essentia/algorithmfactory.h> #include <essentia/essentiamath.h> #include <essentia/scheduler/network.h> #include <essentia/streaming/algorithms/poolstorage.h> #include "credit_libav.h" using namespace std; using namespace essentia; using namespace essentia::standard; int essentia_main(string audioFilename, string outputFilename) { // Returns: 1 on essentia error try { essentia::init(); cout.precision(10); // TODO ???? // instanciate factory and create algorithms: AlgorithmFactory& factory = AlgorithmFactory::instance(); Real sr = 44100.f; int framesize = 512; int hopsize = 256; Pool pool; // Algorithm instantiations Algorithm* audioStereo = factory.create("AudioLoader", "filename", audioFilename); Algorithm* monoMixer = factory.create("MonoMixer"); Algorithm* frameCutter = factory.create("FrameCutter", "frameSize", framesize, "hopSize", hopsize, "startFromZero", true); Algorithm* discontinuityDetector = factory.create("DiscontinuityDetector", "detectionThreshold", 15, "frameSize", framesize, "hopSize", hopsize, "silenceThreshold", -25); Algorithm* gapsDetector = factory.create("GapsDetector", "frameSize", framesize, "hopSize", hopsize, "silenceThreshold", -70); // in the first itteration of the assessment it was found // that low level noise was sometimes considered noise Algorithm* startStopCut = factory.create("StartStopCut", "maximumStartTime", 1, // Found song with only this margin (to double-check) "maximumStopTime", 1); Algorithm* saturationDetector = factory.create("SaturationDetector", "frameSize", framesize, "hopSize", hopsize, "differentialThreshold", 0.0001, "minimumDuration", 2.0f); // An experiment on rock songs showed that distortion is evident when // the median duration of the saturated regions is around 2ms Algorithm* truePeakDetector = factory.create("TruePeakDetector", "threshold", 0.0f); // The algorithm should skip beginings. Algorithm* clickDetector = factory.create("ClickDetector", "frameSize", framesize, "hopSize", hopsize, "silenceThreshold", -25, // This is to high. Just a work around to the problem on initial and final non-silent parts "detectionThreshold", 38); // Experiments showed that a higher threshold is not eenough to detect audible clicks. Algorithm* loudnessEBUR128 = factory.create("LoudnessEBUR128"); Algorithm* humDetector = factory.create("HumDetector", "sampleRate", sr, "frameSize", framesize, "hopSize", hopsize); Algorithm* snr = factory.create("SNR", "frameSize", framesize, "sampleRate", sr); Algorithm* startStopSilence = factory.create("StartStopSilence"); Algorithm* windowing = factory.create("Windowing", "size", framesize, "zeroPadding", 0, "type", "hann", "normalized", false); cout << "-------- connecting algos ---------" << endl; Real fs; int ch, br; std::string md5, cod; vector<StereoSample> audioBuffer; audioStereo->output("audio").set(audioBuffer); audioStereo->output("sampleRate").set(fs); audioStereo->output("numberChannels").set(ch); audioStereo->output("md5").set(md5); audioStereo->output("bit_rate").set(br); audioStereo->output("codec").set(cod); vector<Real> momentaryLoudness, shortTermLoudness; Real integratedLoudness, loudnessRange; loudnessEBUR128->input("signal").set(audioBuffer); loudnessEBUR128->output("momentaryLoudness").set(momentaryLoudness); loudnessEBUR128->output("shortTermLoudness").set(shortTermLoudness); loudnessEBUR128->output("integratedLoudness").set(integratedLoudness); loudnessEBUR128->output("loudnessRange").set(loudnessRange); vector<Real> audio; monoMixer->input("audio").set(audioBuffer); monoMixer->input("numberChannels").set(2); monoMixer->output("audio").set(audio); int startStopCutStart, startStopCutEnd; startStopCut->input("audio").set(audio); startStopCut->output("startCut").set(startStopCutStart); startStopCut->output("stopCut").set(startStopCutEnd); TNT::Array2D<Real> r; vector<Real> frequencies, saliences, starts, ends; humDetector->input("signal").set(audio); humDetector->output("r").set(r); humDetector->output("frequencies").set(frequencies); humDetector->output("saliences").set(saliences); humDetector->output("starts").set(starts); humDetector->output("ends").set(ends); std::vector<Real> peakLocations, truePeakDetectorOutput; truePeakDetector->input("signal").set(audio); truePeakDetector->output("peakLocations").set(peakLocations); truePeakDetector->output("output") .set(truePeakDetectorOutput); std::vector<Real> frame; frameCutter->input("signal").set(audio); frameCutter->output("frame").set(frame); // Time domain algorithms do not require Windowing. std::vector<Real> discontinuityLocations, discontinuityAmplitudes; discontinuityDetector->input("frame").set(frame); discontinuityDetector->output("discontinuityLocations").set(discontinuityLocations); discontinuityDetector->output("discontinuityAmplitudes").set(discontinuityAmplitudes); std::vector<Real> gapsDetectorStarts, gapsDetectorEnds; gapsDetector->input("frame").set(frame); gapsDetector->output("starts").set(gapsDetectorStarts); gapsDetector->output("ends").set(gapsDetectorEnds); std::vector<Real> saturationDetectorStarts, saturationDetectorEnds; saturationDetector->input("frame").set(frame); saturationDetector->output("starts").set(saturationDetectorStarts); saturationDetector->output("ends").set(saturationDetectorEnds); std::vector<Real> clickDetectorStarts, clickDetectorEnds; clickDetector->input("frame").set(frame); clickDetector->output("starts").set(clickDetectorStarts); clickDetector->output("ends").set(clickDetectorEnds); int startFrame, stopFrame; startStopSilence->input("frame").set(frame); startStopSilence->output("startFrame").set(startFrame); startStopSilence->output("stopFrame").set(stopFrame); std::vector<Real> windowedFrame; windowing->input("frame").set(frame); windowing->output("frame").set(windowedFrame); Real averagedSNR, instantSNR; std::vector<Real> spectralSNR; snr->input("frame").set(windowedFrame); snr->output("instantSNR").set(instantSNR); snr->output("averagedSNR").set(averagedSNR); snr->output("spectralSNR").set(spectralSNR); cout << "-------- running algos ---------" << endl; audioStereo->compute(); loudnessEBUR128->compute(); pool.add("EBUR128.integratedLoudness", integratedLoudness); pool.add("EBUR128.range", loudnessRange); monoMixer->compute(); pool.add("duration", audio.size() / sr); startStopCut->compute(); pool.add("startStopCut.start", startStopCutStart); pool.add("startStopCut.end", startStopCutEnd); humDetector->compute(); if (frequencies.size() > 0) { pool.add("humDetector.frequencies", frequencies); pool.add("humDetector.saliences", saliences); pool.add("humDetector.starts", ends); pool.add("humDetector.ends", ends); } truePeakDetector->compute(); for (uint i = 0; i < peakLocations.size(); i++) peakLocations[i] /= sr; if (peakLocations.size() > 0) pool.add("truePeakDetector.locations", peakLocations); while (true) { // compute a frame frameCutter->compute(); // if it was the last one (ie: it was empty), then we're done. if (!frame.size()) { break; } // if the frame is silent, just drop it and go on processing // if (isSilent(frame)) continue; discontinuityDetector->compute(); gapsDetector->compute(); saturationDetector->compute(); clickDetector->compute(); windowing->compute(); snr->compute(); startStopSilence->compute(); } pool.add("filename", audioFilename); if (discontinuityLocations.size() > 0) { for (uint i = 0; i < discontinuityLocations.size(); i++) discontinuityLocations[i] /= sr; pool.add("discontinuities.locations", discontinuityLocations); pool.add("discontinuities.amplitudes", discontinuityAmplitudes); } if (gapsDetectorStarts.size() > 0) { pool.add("gaps.averagedSNR", averagedSNR); pool.add("gaps.spectralSNR", spectralSNR); } if (saturationDetectorStarts.size() > 0) { pool.add("saturationDetector.starts", saturationDetectorStarts); pool.add("saturationDetector.ends", saturationDetectorEnds); } if (clickDetectorStarts.size() > 0) { pool.add("clickDetector.starts", clickDetectorStarts); pool.add("clickDetector.ends", clickDetectorEnds); } pool.add("snr.spectralSNR", spectralSNR); pool.add("snr.averagedSNR", averagedSNR); pool.add("startStopSilince.start", startFrame * hopsize / fs); pool.add("startStopSilince.end", stopFrame * hopsize / fs); cout << "-------- writting Yalm ---------" << endl; // Write to yaml file. Algorithm* output = standard::AlgorithmFactory::create("YamlOutput", "filename", outputFilename); output->input("pool").set(pool); output->compute(); delete output; delete frameCutter; delete discontinuityDetector; delete gapsDetector; delete startStopCut; delete saturationDetector; delete truePeakDetector; delete clickDetector; delete windowing; delete humDetector; delete snr; delete loudnessEBUR128; delete startStopSilence; essentia::shutdown(); cout << "-------- Done! ---------" << endl; } catch (EssentiaException& e) { cerr << e.what() << endl; return 1; } return 0; } int main(int argc, char* argv[]) { string audioFilename, outputFilename; switch (argc) { case 3: audioFilename = argv[1]; outputFilename = argv[2]; break; default: return -1; } return essentia_main(audioFilename, outputFilename); }
/* * Copyright (C) 2006-2016 Music Technology Group - Universitat Pompeu Fabra * * This file is part of Essentia * * Essentia is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation (FSF), either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the Affero GNU General Public License * version 3 along with this program. If not, see http://www.gnu.org/licenses/ */ #include <essentia/algorithmfactory.h> #include <essentia/essentiamath.h> #include <essentia/scheduler/network.h> #include <essentia/streaming/algorithms/poolstorage.h> #include "credit_libav.h" using namespace std; using namespace essentia; using namespace essentia::standard; int essentia_main(string audioFilename, string outputFilename) { // Returns: 1 on essentia error try { essentia::init(); cout.precision(10); // TODO ???? // instanciate factory and create algorithms: AlgorithmFactory& factory = AlgorithmFactory::instance(); Real sr = 44100.f; int framesize = 512; int hopsize = 256; Pool pool; // Algorithm instantiations Algorithm* audioStereo = factory.create("AudioLoader", "filename", audioFilename); Algorithm* monoMixer = factory.create("MonoMixer"); Algorithm* frameCutter = factory.create("FrameCutter", "frameSize", framesize, "hopSize", hopsize, "startFromZero", true); Algorithm* discontinuityDetector = factory.create("DiscontinuityDetector", "detectionThreshold", 15, "frameSize", framesize, "hopSize", hopsize, "silenceThreshold", -25); Algorithm* gapsDetector = factory.create("GapsDetector", "frameSize", framesize, "hopSize", hopsize, "silenceThreshold", -70); // in the first itteration of the assessment it was found // that low level noise was sometimes considered noise Algorithm* startStopCut = factory.create("StartStopCut", "maximumStartTime", 1, // Found song with only this margin (to double-check) "maximumStopTime", 1); Algorithm* saturationDetector = factory.create("SaturationDetector", "frameSize", framesize, "hopSize", hopsize, "differentialThreshold", 0.0001, "minimumDuration", 2.0f); // An experiment on rock songs showed that distortion is evident when // the median duration of the saturated regions is around 2ms Algorithm* truePeakDetector = factory.create("TruePeakDetector", "threshold", 0.0f); // The algorithm should skip beginings. Algorithm* clickDetector = factory.create("ClickDetector", "frameSize", framesize, "hopSize", hopsize, "silenceThreshold", -25, // This is to high. Just a work around to the problem on initial and final non-silent parts "detectionThreshold", 38); // Experiments showed that a higher threshold is not eenough to detect audible clicks. Algorithm* loudnessEBUR128 = factory.create("LoudnessEBUR128"); Algorithm* humDetector = factory.create("HumDetector", "sampleRate", sr, "frameSize", framesize, "hopSize", hopsize); Algorithm* snr = factory.create("SNR", "frameSize", framesize, "sampleRate", sr); Algorithm* startStopSilence = factory.create("StartStopSilence"); Algorithm* windowing = factory.create("Windowing", "size", framesize, "zeroPadding", 0, "type", "hann", "normalized", false); cout << "-------- connecting algos ---------" << endl; Real fs; int ch, br; std::string md5, cod; vector<StereoSample> audioBuffer; audioStereo->output("audio").set(audioBuffer); audioStereo->output("sampleRate").set(fs); audioStereo->output("numberChannels").set(ch); audioStereo->output("md5").set(md5); audioStereo->output("bit_rate").set(br); audioStereo->output("codec").set(cod); vector<Real> momentaryLoudness, shortTermLoudness; Real integratedLoudness, loudnessRange; loudnessEBUR128->input("signal").set(audioBuffer); loudnessEBUR128->output("momentaryLoudness").set(momentaryLoudness); loudnessEBUR128->output("shortTermLoudness").set(shortTermLoudness); loudnessEBUR128->output("integratedLoudness").set(integratedLoudness); loudnessEBUR128->output("loudnessRange").set(loudnessRange); vector<Real> audio; monoMixer->input("audio").set(audioBuffer); monoMixer->input("numberChannels").set(2); monoMixer->output("audio").set(audio); int startStopCutStart, startStopCutEnd; startStopCut->input("audio").set(audio); startStopCut->output("startCut").set(startStopCutStart); startStopCut->output("stopCut").set(startStopCutEnd); TNT::Array2D<Real> r; vector<Real> frequencies, saliences, starts, ends; humDetector->input("signal").set(audio); humDetector->output("r").set(r); humDetector->output("frequencies").set(frequencies); humDetector->output("saliences").set(saliences); humDetector->output("starts").set(starts); humDetector->output("ends").set(ends); std::vector<Real> peakLocations, truePeakDetectorOutput; truePeakDetector->input("signal").set(audio); truePeakDetector->output("peakLocations").set(peakLocations); truePeakDetector->output("output") .set(truePeakDetectorOutput); std::vector<Real> frame; frameCutter->input("signal").set(audio); frameCutter->output("frame").set(frame); // Time domain algorithms do not require Windowing. std::vector<Real> discontinuityLocations, discontinuityAmplitudes; discontinuityDetector->input("frame").set(frame); discontinuityDetector->output("discontinuityLocations").set(discontinuityLocations); discontinuityDetector->output("discontinuityAmplitudes").set(discontinuityAmplitudes); std::vector<Real> gapsDetectorStarts, gapsDetectorEnds; gapsDetector->input("frame").set(frame); gapsDetector->output("starts").set(gapsDetectorStarts); gapsDetector->output("ends").set(gapsDetectorEnds); std::vector<Real> saturationDetectorStarts, saturationDetectorEnds; saturationDetector->input("frame").set(frame); saturationDetector->output("starts").set(saturationDetectorStarts); saturationDetector->output("ends").set(saturationDetectorEnds); std::vector<Real> clickDetectorStarts, clickDetectorEnds; clickDetector->input("frame").set(frame); clickDetector->output("starts").set(clickDetectorStarts); clickDetector->output("ends").set(clickDetectorEnds); int startFrame, stopFrame; startStopSilence->input("frame").set(frame); startStopSilence->output("startFrame").set(startFrame); startStopSilence->output("stopFrame").set(stopFrame); std::vector<Real> windowedFrame; windowing->input("frame").set(frame); windowing->output("frame").set(windowedFrame); Real averagedSNR, instantSNR; std::vector<Real> spectralSNR; snr->input("frame").set(windowedFrame); snr->output("instantSNR").set(instantSNR); snr->output("averagedSNR").set(averagedSNR); snr->output("spectralSNR").set(spectralSNR); cout << "-------- running algos ---------" << endl; audioStereo->compute(); loudnessEBUR128->compute(); pool.add("EBUR128.integratedLoudness", integratedLoudness); pool.add("EBUR128.range", loudnessRange); monoMixer->compute(); pool.add("duration", audio.size() / sr); startStopCut->compute(); pool.add("startStopCut.start", startStopCutStart); pool.add("startStopCut.end", startStopCutEnd); humDetector->compute(); if (frequencies.size() > 0) { pool.add("humDetector.frequencies", frequencies); pool.add("humDetector.saliences", saliences); pool.add("humDetector.starts", ends); pool.add("humDetector.ends", ends); } truePeakDetector->compute(); for (uint i = 0; i < peakLocations.size(); i++) peakLocations[i] /= sr; if (peakLocations.size() > 0) pool.add("truePeakDetector.locations", peakLocations); while (true) { // compute a frame frameCutter->compute(); // if it was the last one (ie: it was empty), then we're done. if (!frame.size()) { break; } // if the frame is silent, just drop it and go on processing // if (isSilent(frame)) continue; discontinuityDetector->compute(); gapsDetector->compute(); saturationDetector->compute(); clickDetector->compute(); windowing->compute(); snr->compute(); startStopSilence->compute(); } pool.add("filename", audioFilename); if (discontinuityLocations.size() > 0) { for (uint i = 0; i < discontinuityLocations.size(); i++) discontinuityLocations[i] /= sr; pool.add("discontinuities.locations", discontinuityLocations); pool.add("discontinuities.amplitudes", discontinuityAmplitudes); } if (gapsDetectorStarts.size() > 0) { pool.add("gaps.averagedSNR", averagedSNR); pool.add("gaps.spectralSNR", spectralSNR); } if (saturationDetectorStarts.size() > 0) { pool.add("saturationDetector.starts", saturationDetectorStarts); pool.add("saturationDetector.ends", saturationDetectorEnds); } if (clickDetectorStarts.size() > 0) { pool.add("clickDetector.starts", clickDetectorStarts); pool.add("clickDetector.ends", clickDetectorEnds); } pool.add("snr.spectralSNR", spectralSNR); pool.add("snr.averagedSNR", averagedSNR); pool.add("startStopSilence.start", startFrame * hopsize / fs); pool.add("startStopSilence.end", stopFrame * hopsize / fs); cout << "-------- writting Yalm ---------" << endl; // Write to yaml file. Algorithm* output = standard::AlgorithmFactory::create("YamlOutput", "filename", outputFilename); output->input("pool").set(pool); output->compute(); delete output; delete frameCutter; delete discontinuityDetector; delete gapsDetector; delete startStopCut; delete saturationDetector; delete truePeakDetector; delete clickDetector; delete windowing; delete humDetector; delete snr; delete loudnessEBUR128; delete startStopSilence; essentia::shutdown(); cout << "-------- Done! ---------" << endl; } catch (EssentiaException& e) { cerr << e.what() << endl; return 1; } return 0; } int main(int argc, char* argv[]) { string audioFilename, outputFilename; switch (argc) { case 3: audioFilename = argv[1]; outputFilename = argv[2]; break; default: return -1; } return essentia_main(audioFilename, outputFilename); }
fix typo `startStopSilince` in la-cupula extractor
fix typo `startStopSilince` in la-cupula extractor Closes #3
C++
agpl-3.0
carthach/essentia,MTG/essentia,carthach/essentia,carthach/essentia,carthach/essentia,MTG/essentia,MTG/essentia,MTG/essentia,carthach/essentia,MTG/essentia
0164e2d3b433c2c9625ec0ec9777d30de53ba1b9
src/stan/lang/ast/type/double_block_type.hpp
src/stan/lang/ast/type/double_block_type.hpp
#ifndef STAN_LANG_AST_DOUBLE_BLOCK_TYPE_HPP #define STAN_LANG_AST_DOUBLE_BLOCK_TYPE_HPP #include <stan/lang/ast/node/offset_multiplier.hpp> #include <stan/lang/ast/node/range.hpp> namespace stan { namespace lang { /** * Double block var type. */ struct double_block_type { /** * Bounds constraints */ range bounds_; /** * Offset and multiplier */ offset_multiplier ls_; /** * Construct a block var type with default values. */ double_block_type(); /** * Construct a block var type with specified values. * * @param bounds variable upper and/or lower bounds * @param ls variable offset and multiplier */ explicit double_block_type(const range &bounds, const offset_multiplier &ls); /** * Construct a block var type with specified values. * * @param bounds variable upper and/or lower bounds */ explicit double_block_type(const range &bounds); /** * Construct a block var type with specified values. * * @param ls variable offset and multiplier */ explicit double_block_type(const offset_multiplier &ls); /** * Get bounds constraints. */ range bounds() const; /** * Get offset and multiplier. */ offset_multiplier ls() const; }; } // namespace lang } // namespace stan #endif
#ifndef STAN_LANG_AST_DOUBLE_BLOCK_TYPE_HPP #define STAN_LANG_AST_DOUBLE_BLOCK_TYPE_HPP #include <stan/lang/ast/node/offset_multiplier.hpp> #include <stan/lang/ast/node/range.hpp> namespace stan { namespace lang { /** * Double block var type. */ struct double_block_type { /** * Bounds constraints */ range bounds_; /** * Offset and multiplier */ offset_multiplier ls_; /** * Construct a block var type with default values. */ double_block_type(); /** * Construct a block var type with specified values. * * @param bounds variable upper and/or lower bounds * @param ls variable offset and multiplier */ explicit double_block_type(const range &bounds, const offset_multiplier &ls); /** * Construct a block var type with specified values. * * @param bounds variable upper and/or lower bounds */ explicit double_block_type(const range &bounds); /** * Construct a block var type with specified values. * * @param ls variable offset and multiplier */ explicit double_block_type(const offset_multiplier &ls); /** * Get bounds constraints. */ range bounds() const; /** * Get offset and multiplier. */ offset_multiplier ls() const; }; } // namespace lang } // namespace stan #endif
Update double_block_type.hpp
Update double_block_type.hpp
C++
bsd-3-clause
stan-dev/stan,stan-dev/stan,stan-dev/stan,stan-dev/stan,stan-dev/stan
db24b78c33b00694a7cd98c787317fd687b76bf9
examples/libvroom.cpp
examples/libvroom.cpp
#include <iostream> #include <boost/log/core.hpp> #include <boost/log/expressions.hpp> #include <boost/log/trivial.hpp> #include <boost/log/utility/setup/common_attributes.hpp> #include <boost/log/utility/setup/console.hpp> #include "../src/routing/routed_wrapper.h" #include "../src/structures/vroom/input/input.h" #include "../src/structures/vroom/job.h" #include "../src/structures/vroom/vehicle.h" #include "../src/utils/exceptions.h" void log_solution(const solution& sol) { std::cout << "Total cost: " << sol.summary.cost << std::endl; std::cout << "Unassigned: " << sol.summary.unassigned << std::endl; // Log unassigned jobs if any. std::cout << "Unassigned job ids: ["; for (const auto& j : sol.unassigned) { std::cout << j.id << ", "; } std::cout << "]" << std::endl; // Describe routes in solution. for (const auto& route : sol.routes) { std::cout << "Steps for vehicle " << route.vehicle << " (cost: " << route.cost << ")" << std::endl; // Describe all route steps. for (const auto& step : route.steps) { std::string step_type; switch (step.type) { case TYPE::START: step_type = "Start"; break; case TYPE::END: step_type = "End"; break; case TYPE::JOB: step_type = "Job"; break; } std::cout << step_type; // Add job ids. if (step.type == TYPE::JOB) { std::cout << " " << step.job; } // Add location if known. if (step.location.has_coordinates()) { std::cout << " - " << step.location.lon() << ";" << step.location.lat(); } std::cout << std::endl; } } } std::unique_ptr<routed_wrapper> routing_wrapper() { // Create a wrapper for OSRM queries. return std::make_unique<routed_wrapper>("localhost", // OSRM server "5000", // OSRM port "car" // Profile ); } void run_example_with_osrm() { input problem_instance(std::move(routing_wrapper()), false); // Query for route geometry after solving. // Create one-dimension capacity restrictions to model the situation // where one vehicle can handle 4 jobs. amount_t vehicle_capacity(1); amount_t job_amount(1); vehicle_capacity[0] = 4; job_amount[0] = 1; // Define vehicles (use boost::none for no start or no end). location_t depot({2.35044, 48.71764}); vehicle_t v1(1, // id depot, // start depot, // end vehicle_capacity, // capacity {1, 14}); // skills problem_instance.add_vehicle(v1); vehicle_t v2(2, // id depot, // start depot, // end vehicle_capacity, // capacity {2, 14}); // skills problem_instance.add_vehicle(v2); // Set jobs id, amount, required skills and location. std::vector<job_t> jobs; jobs.push_back(job_t(1, job_amount, {1}, coords_t({1.98935, 48.701}))); jobs.push_back(job_t(2, job_amount, {1}, coords_t({2.03655, 48.61128}))); jobs.push_back(job_t(3, job_amount, {2}, coords_t({2.39719, 49.07611}))); jobs.push_back(job_t(4, job_amount, {2}, coords_t({2.41808, 49.22619}))); jobs.push_back(job_t(5, job_amount, {14}, coords_t({2.28325, 48.5958}))); jobs.push_back(job_t(6, job_amount, {14}, coords_t({2.89357, 48.90736}))); for (const auto& j : jobs) { problem_instance.add_job(j); } // Skills definitions set the following constraints: // - jobs 1 and 2 can only be served by vehicle 1 // - jobs 3 and 4 can only be served by vehicle 2 // - jobs 5 and 6 can be served by either one of the vehicles // Solve! try { auto sol = problem_instance.solve(2); // Use 2 threads. log_solution(sol); } catch (const custom_exception& e) { std::cerr << "[Error] " << e.get_message() << std::endl; } } void run_example_with_custom_matrix() { input problem_instance(std::move(routing_wrapper()), false); // Query for route geometry after solving. // Define custom matrix and bypass OSRM call. matrix<cost_t> matrix_input({{0, 2713, 2218, 4317, 5698, 2191, 3528}, {2876, 0, 1109, 5198, 6361, 2963, 5385}, {2359, 1082, 0, 5797, 7178, 1883, 5008}, {4097, 5228, 5584, 0, 2236, 5511, 3669}, {5472, 6432, 6959, 2232, 0, 6886, 4581}, {2083, 2954, 1887, 5736, 7117, 0, 4593}, {3679, 5526, 5166, 3506, 4471, 4631, 0}}); problem_instance.set_matrix(std::move(matrix_input)); // Create one-dimension capacity restrictions to model the situation // where one vehicle can handle 4 jobs. amount_t vehicle_capacity(1); amount_t job_amount(1); vehicle_capacity[0] = 4; job_amount[0] = 1; // Define vehicles (use boost::none for no start or no end). location_t depot(0); // index in the provided matrix. vehicle_t v1(1, // id depot, // start depot, // end vehicle_capacity, // capacity {1, 14}); // skills problem_instance.add_vehicle(v1); vehicle_t v2(2, // id depot, // start depot, // end vehicle_capacity, // capacity {2, 14}); // skills problem_instance.add_vehicle(v2); // Set jobs id, amount, required skills and index of location in the // matrix (coordinates are optional). std::vector<job_t> jobs; jobs.push_back(job_t(1, job_amount, {1}, 1)); jobs.push_back(job_t(2, job_amount, {1}, 2)); jobs.push_back(job_t(3, job_amount, {2}, 3)); jobs.push_back(job_t(4, job_amount, {2}, 4)); jobs.push_back(job_t(5, job_amount, {14}, 5)); jobs.push_back(job_t(6, job_amount, {14}, 6)); for (const auto& j : jobs) { problem_instance.add_job(j); } // Skills definitions set the following constraints: // - jobs 1 and 2 can only be served by vehicle 1 // - jobs 3 and 4 can only be served by vehicle 2 // - jobs 5 and 6 can be served by either one of the vehicles // Solve! try { auto sol = problem_instance.solve(2); // Use 2 threads. log_solution(sol); } catch (const custom_exception& e) { std::cerr << "[Error] " << e.get_message() << std::endl; } } int main() { // Log level. boost::log::core::get()->set_filter(boost::log::trivial::severity >= boost::log::trivial::error); run_example_with_osrm(); // run_example_with_custom_matrix(); return 0; }
#include <iostream> #include <boost/log/core.hpp> #include <boost/log/expressions.hpp> #include <boost/log/trivial.hpp> #include <boost/log/utility/setup/common_attributes.hpp> #include <boost/log/utility/setup/console.hpp> #include "../src/routing/routed_wrapper.h" #include "../src/structures/vroom/input/input.h" #include "../src/structures/vroom/job.h" #include "../src/structures/vroom/vehicle.h" #include "../src/utils/exceptions.h" void log_solution(const solution& sol) { std::cout << "Total cost: " << sol.summary.cost << std::endl; std::cout << "Unassigned: " << sol.summary.unassigned << std::endl; // Log unassigned jobs if any. std::cout << "Unassigned job ids: ["; for (const auto& j : sol.unassigned) { std::cout << j.id << ", "; } std::cout << "]" << std::endl; // Describe routes in solution. for (const auto& route : sol.routes) { std::cout << "Steps for vehicle " << route.vehicle << " (cost: " << route.cost << ")" << std::endl; // Describe all route steps. for (const auto& step : route.steps) { std::string step_type; switch (step.type) { case TYPE::START: step_type = "Start"; break; case TYPE::END: step_type = "End"; break; case TYPE::JOB: step_type = "Job"; break; } std::cout << step_type; // Add job ids. if (step.type == TYPE::JOB) { std::cout << " " << step.job; } // Add location if known. if (step.location.has_coordinates()) { std::cout << " - " << step.location.lon() << ";" << step.location.lat(); } std::cout << std::endl; } } } std::unique_ptr<routed_wrapper> routing_wrapper() { // Create a wrapper for OSRM queries. return std::make_unique<routed_wrapper>("localhost", // OSRM server "5000", // OSRM port "car" // Profile ); } void run_example_with_osrm() { input problem_instance(std::move(routing_wrapper()), false); // Query for route geometry after solving. // Create one-dimension capacity restrictions to model the situation // where one vehicle can handle 4 jobs. amount_t vehicle_capacity(1); amount_t job_amount(1); vehicle_capacity[0] = 4; job_amount[0] = 1; // Define vehicles (use boost::none for no start or no end). location_t depot({2.35044, 48.71764}); vehicle_t v1(1, // id depot, // start depot, // end vehicle_capacity, // capacity {1, 14}); // skills problem_instance.add_vehicle(v1); vehicle_t v2(2, // id depot, // start depot, // end vehicle_capacity, // capacity {2, 14}); // skills problem_instance.add_vehicle(v2); // Set jobs id, location, amount and required skills. Last two can // be omitted if no constraints are required. std::vector<job_t> jobs; jobs.push_back(job_t(1, coords_t({1.98935, 48.701}), job_amount, {1})); jobs.push_back(job_t(2, coords_t({2.03655, 48.61128}), job_amount, {1})); jobs.push_back(job_t(3, coords_t({2.39719, 49.07611}), job_amount, {2})); jobs.push_back(job_t(4, coords_t({2.41808, 49.22619}), job_amount, {2})); jobs.push_back(job_t(5, coords_t({2.28325, 48.5958}), job_amount, {14})); jobs.push_back(job_t(6, coords_t({2.89357, 48.90736}), job_amount, {14})); for (const auto& j : jobs) { problem_instance.add_job(j); } // Skills definitions set the following constraints: // - jobs 1 and 2 can only be served by vehicle 1 // - jobs 3 and 4 can only be served by vehicle 2 // - jobs 5 and 6 can be served by either one of the vehicles // Solve! try { auto sol = problem_instance.solve(2); // Use 2 threads. log_solution(sol); } catch (const custom_exception& e) { std::cerr << "[Error] " << e.get_message() << std::endl; } } void run_example_with_custom_matrix() { input problem_instance(std::move(routing_wrapper()), false); // Query for route geometry after solving. // Define custom matrix and bypass OSRM call. matrix<cost_t> matrix_input({{0, 2713, 2218, 4317, 5698, 2191, 3528}, {2876, 0, 1109, 5198, 6361, 2963, 5385}, {2359, 1082, 0, 5797, 7178, 1883, 5008}, {4097, 5228, 5584, 0, 2236, 5511, 3669}, {5472, 6432, 6959, 2232, 0, 6886, 4581}, {2083, 2954, 1887, 5736, 7117, 0, 4593}, {3679, 5526, 5166, 3506, 4471, 4631, 0}}); problem_instance.set_matrix(std::move(matrix_input)); // Create one-dimension capacity restrictions to model the situation // where one vehicle can handle 4 jobs. amount_t vehicle_capacity(1); amount_t job_amount(1); vehicle_capacity[0] = 4; job_amount[0] = 1; // Define vehicles (use boost::none for no start or no end). location_t depot(0); // index in the provided matrix. vehicle_t v1(1, // id depot, // start depot, // end vehicle_capacity, // capacity {1, 14}); // skills problem_instance.add_vehicle(v1); vehicle_t v2(2, // id depot, // start depot, // end vehicle_capacity, // capacity {2, 14}); // skills problem_instance.add_vehicle(v2); // Set jobs id, index of location in the matrix (coordinates are // optional), amount and required skills. Last two can be omitted if // no constraints are required. std::vector<job_t> jobs; jobs.push_back(job_t(1, 1, job_amount, {1})); jobs.push_back(job_t(2, 2, job_amount, {1})); jobs.push_back(job_t(3, 3, job_amount, {2})); jobs.push_back(job_t(4, 4, job_amount, {2})); jobs.push_back(job_t(5, 5, job_amount, {14})); jobs.push_back(job_t(6, 6, job_amount, {14})); for (const auto& j : jobs) { problem_instance.add_job(j); } // Skills definitions set the following constraints: // - jobs 1 and 2 can only be served by vehicle 1 // - jobs 3 and 4 can only be served by vehicle 2 // - jobs 5 and 6 can be served by either one of the vehicles // Solve! try { auto sol = problem_instance.solve(2); // Use 2 threads. log_solution(sol); } catch (const custom_exception& e) { std::cerr << "[Error] " << e.get_message() << std::endl; } } int main() { // Log level. boost::log::core::get()->set_filter(boost::log::trivial::severity >= boost::log::trivial::error); run_example_with_osrm(); // run_example_with_custom_matrix(); return 0; }
Adjust libvroom example.
Adjust libvroom example.
C++
bsd-2-clause
jcoupey/vroom,jcoupey/vroom,VROOM-Project/vroom,VROOM-Project/vroom,VROOM-Project/vroom