hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
77k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
653k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
1
c217d399851f509ee29ab5c0ddb0a334b18ea89f
3,645
hpp
C++
libs/xpressive/boost/xpressive/proto/v1_/proto_typeof.hpp
xoxox4dev/madedit
8e0dd08818e040b099251c1eb8833b836cb36c6e
[ "Ruby" ]
22
2015-06-28T17:48:54.000Z
2021-04-16T08:47:26.000Z
libs/xpressive/boost/xpressive/proto/v1_/proto_typeof.hpp
mcanthony/madedit
8e0dd08818e040b099251c1eb8833b836cb36c6e
[ "Ruby" ]
null
null
null
libs/xpressive/boost/xpressive/proto/v1_/proto_typeof.hpp
mcanthony/madedit
8e0dd08818e040b099251c1eb8833b836cb36c6e
[ "Ruby" ]
12
2015-04-25T00:40:35.000Z
2021-11-11T06:39:48.000Z
/////////////////////////////////////////////////////////////////////////////// /// \file proto_typeof.hpp /// Type registrations so that proto1 expression templates can be used together /// with the Boost.Typeof library. // // Copyright 2007 Eric Niebler. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_XPRESSIVE_PROTO_PROTO_TYPEOF_H #define BOOST_XPRESSIVE_PROTO_PROTO_TYPEOF_H // MS compatible compilers support #pragma once #if defined(_MSC_VER) && (_MSC_VER >= 1020) # pragma once #endif #include <boost/config.hpp> #include <boost/typeof/typeof.hpp> #include <boost/xpressive/proto/v1_/proto_fwd.hpp> #include BOOST_TYPEOF_INCREMENT_REGISTRATION_GROUP() BOOST_TYPEOF_REGISTER_TYPE(boost::proto1::unary_tag) BOOST_TYPEOF_REGISTER_TYPE(boost::proto1::binary_tag) BOOST_TYPEOF_REGISTER_TYPE(boost::proto1::nary_tag) BOOST_TYPEOF_REGISTER_TYPE(boost::proto1::noop_tag) BOOST_TYPEOF_REGISTER_TYPE(boost::proto1::unary_plus_tag) BOOST_TYPEOF_REGISTER_TYPE(boost::proto1::unary_minus_tag) BOOST_TYPEOF_REGISTER_TYPE(boost::proto1::unary_star_tag) BOOST_TYPEOF_REGISTER_TYPE(boost::proto1::complement_tag) BOOST_TYPEOF_REGISTER_TYPE(boost::proto1::address_of_tag) BOOST_TYPEOF_REGISTER_TYPE(boost::proto1::logical_not_tag) BOOST_TYPEOF_REGISTER_TYPE(boost::proto1::pre_inc_tag) BOOST_TYPEOF_REGISTER_TYPE(boost::proto1::pre_dec_tag) BOOST_TYPEOF_REGISTER_TYPE(boost::proto1::post_inc_tag) BOOST_TYPEOF_REGISTER_TYPE(boost::proto1::post_dec_tag) BOOST_TYPEOF_REGISTER_TYPE(boost::proto1::left_shift_tag) BOOST_TYPEOF_REGISTER_TYPE(boost::proto1::right_shift_tag) BOOST_TYPEOF_REGISTER_TYPE(boost::proto1::multiply_tag) BOOST_TYPEOF_REGISTER_TYPE(boost::proto1::divide_tag) BOOST_TYPEOF_REGISTER_TYPE(boost::proto1::modulus_tag) BOOST_TYPEOF_REGISTER_TYPE(boost::proto1::add_tag) BOOST_TYPEOF_REGISTER_TYPE(boost::proto1::subtract_tag) BOOST_TYPEOF_REGISTER_TYPE(boost::proto1::less_tag) BOOST_TYPEOF_REGISTER_TYPE(boost::proto1::greater_tag) BOOST_TYPEOF_REGISTER_TYPE(boost::proto1::less_equal_tag) BOOST_TYPEOF_REGISTER_TYPE(boost::proto1::greater_equal_tag) BOOST_TYPEOF_REGISTER_TYPE(boost::proto1::equal_tag) BOOST_TYPEOF_REGISTER_TYPE(boost::proto1::not_equal_tag) BOOST_TYPEOF_REGISTER_TYPE(boost::proto1::logical_or_tag) BOOST_TYPEOF_REGISTER_TYPE(boost::proto1::logical_and_tag) BOOST_TYPEOF_REGISTER_TYPE(boost::proto1::bitand_tag) BOOST_TYPEOF_REGISTER_TYPE(boost::proto1::bitor_tag) BOOST_TYPEOF_REGISTER_TYPE(boost::proto1::bitxor_tag) BOOST_TYPEOF_REGISTER_TYPE(boost::proto1::comma_tag) BOOST_TYPEOF_REGISTER_TYPE(boost::proto1::mem_ptr_tag) BOOST_TYPEOF_REGISTER_TYPE(boost::proto1::assign_tag) BOOST_TYPEOF_REGISTER_TYPE(boost::proto1::left_shift_assign_tag) BOOST_TYPEOF_REGISTER_TYPE(boost::proto1::right_shift_assign_tag) BOOST_TYPEOF_REGISTER_TYPE(boost::proto1::multiply_assign_tag) BOOST_TYPEOF_REGISTER_TYPE(boost::proto1::divide_assign_tag) BOOST_TYPEOF_REGISTER_TYPE(boost::proto1::modulus_assign_tag) BOOST_TYPEOF_REGISTER_TYPE(boost::proto1::add_assign_tag) BOOST_TYPEOF_REGISTER_TYPE(boost::proto1::subtract_assign_tag) BOOST_TYPEOF_REGISTER_TYPE(boost::proto1::bitand_assign_tag) BOOST_TYPEOF_REGISTER_TYPE(boost::proto1::bitor_assign_tag) BOOST_TYPEOF_REGISTER_TYPE(boost::proto1::bitxor_assign_tag) BOOST_TYPEOF_REGISTER_TYPE(boost::proto1::subscript_tag) BOOST_TYPEOF_REGISTER_TYPE(boost::proto1::function_tag) BOOST_TYPEOF_REGISTER_TEMPLATE(boost::proto1::unary_op, (typename)(typename)) BOOST_TYPEOF_REGISTER_TEMPLATE(boost::proto1::binary_op, (typename)(typename)(typename)) #endif
47.960526
88
0.836763
c21e828b819fbdc15790471d7b9b16ed3aff16b2
8,475
hpp
C++
src/CellGraph.hpp
iosonofabio/ExpressionMatrix2
a6fc6938fe857fe1bd6a9200071957691295ba3c
[ "MIT" ]
null
null
null
src/CellGraph.hpp
iosonofabio/ExpressionMatrix2
a6fc6938fe857fe1bd6a9200071957691295ba3c
[ "MIT" ]
null
null
null
src/CellGraph.hpp
iosonofabio/ExpressionMatrix2
a6fc6938fe857fe1bd6a9200071957691295ba3c
[ "MIT" ]
null
null
null
// The cell graph is a graph in which each vertex // corresponds to a cell. // An undirected edge is created between two vertices // if the there is good similarity between the // expression vectors of the corresponding cells. #ifndef CZI_EXPRESSION_MATRIX2_CELL_GRAPH_HPP #define CZI_EXPRESSION_MATRIX2_CELL_GRAPH_HPP #include "CZI_ASSERT.hpp" #include "Ids.hpp" #include "orderPairs.hpp" #include <boost/graph/adjacency_list.hpp> #include "array.hpp" #include "iosfwd.hpp" #include "map.hpp" #include "string.hpp" #include "utility.hpp" #include "vector.hpp" namespace ChanZuckerberg { namespace ExpressionMatrix2 { class CellGraph; class CellGraphVertex; class CellGraphVertexInfo; class CellGraphEdge; class ClusterTable; // The base class for class CellGraph. typedef boost::adjacency_list< boost::listS, boost::listS, boost::undirectedS, CellGraphVertex, CellGraphEdge> CellGraphBaseClass; namespace MemoryMapped { template<class T> class Vector; } } } // A class used by label propagation algorithm to keep track // of the total weight of each cluster for each vertex. class ChanZuckerberg::ExpressionMatrix2::ClusterTable { public: void addWeight(uint32_t clusterId, float weight); void addWeightQuick(uint32_t clusterId, float weight); // Does not check if already there. Does not update the best cluster. uint32_t bestCluster(); void findBestCluster(); void clear(); bool isEmpty() const; private: vector< pair<uint32_t, float> > data; uint32_t bestClusterId = std::numeric_limits<uint32_t>::max(); float bestWeight = -1.; }; inline void ChanZuckerberg::ExpressionMatrix2::ClusterTable::addWeightQuick(uint32_t clusterId, float weight) { data.push_back(make_pair(clusterId, weight)); } inline void ChanZuckerberg::ExpressionMatrix2::ClusterTable::addWeight(uint32_t clusterId, float weight) { for(pair<uint32_t, float>& p: data) { if(p.first == clusterId) { p.second += weight; if(clusterId == bestClusterId) { if(weight < 0.) { findBestCluster(); } else { bestWeight = p.second; } } else { if(p.second > bestWeight) { bestClusterId = clusterId; bestWeight = p.second; } } return; } } data.push_back(make_pair(clusterId, weight)); if(weight > bestWeight) { bestClusterId = clusterId; bestWeight = weight; } } inline uint32_t ChanZuckerberg::ExpressionMatrix2::ClusterTable::bestCluster() { return bestClusterId; } inline void ChanZuckerberg::ExpressionMatrix2::ClusterTable::findBestCluster() { bestClusterId = std::numeric_limits<uint32_t>::max(); bestWeight = -1.; for(const pair<uint32_t, float>& p: data) { if(p.second > bestWeight) { bestWeight = p.second; bestClusterId = p.first; } } } inline void ChanZuckerberg::ExpressionMatrix2::ClusterTable::clear() { data.clear(); } inline bool ChanZuckerberg::ExpressionMatrix2::ClusterTable::isEmpty() const { return data.empty(); } // A vertex of the cell graph. // The base class CellGraphVertexInfo is used to communicate with Python. class ChanZuckerberg::ExpressionMatrix2::CellGraphVertexInfo { public: CellId cellId = invalidCellId; array<double, 2> position; ClusterTable clusterTable; double x() const { return position[0]; } double y() const { return position[1]; } CellGraphVertexInfo() { } CellGraphVertexInfo(const CellGraphVertexInfo& that) : cellId(that.cellId), position(that.position) { } CellGraphVertexInfo(CellId cellId) : cellId(cellId) { } bool operator==(const CellGraphVertexInfo& that) { return cellId==that.cellId && position==that.position; } }; class ChanZuckerberg::ExpressionMatrix2::CellGraphVertex : public CellGraphVertexInfo { public: // Use the base class constructors. using CellGraphVertexInfo::CellGraphVertexInfo; // Additional fields not needed in Python. uint32_t group = 0; uint32_t clusterId = 0; string color; double value = 0.; }; // An edge of the cell graph. class ChanZuckerberg::ExpressionMatrix2::CellGraphEdge { public: float similarity = -1.; CellGraphEdge() { } CellGraphEdge(float similarity) : similarity(similarity) { } string color; }; class ChanZuckerberg::ExpressionMatrix2::CellGraph : public CellGraphBaseClass { public: // Use the constructors of the base class. using CellGraphBaseClass::CellGraphBaseClass; typedef CellGraph Graph; Graph& graph() { return *this; } const Graph& graph() const { return *this; } CellGraph( const MemoryMapped::Vector<CellId>& cellSet, // The cell set to be used. const string& similarPairsName, // The name of the SimilarPairs object to be used to create the graph. double similarityThreshold, // The minimum similarity to create an edge. size_t maxConnectivity // The maximum number of neighbors (k of the k-NN graph). ); // Only keep an edge if it is one of the best k edges for either // of the two vertices. This turns the graph into a k-nearest-neighbor graph. void keepBestEdgesOnly(std::size_t k); // Write in Graphviz format. void write(ostream&) const; void write(const string& fileName) const; // Simple graph statistics. ostream& writeStatistics(ostream&) const; // Remove isolated vertices and returns\ the number of vertices that were removed size_t removeIsolatedVertices(); // Use Graphviz to compute the graph layout and store it in the vertex positions. void computeLayout(); bool layoutWasComputed = false; // Clustering using the label propagation algorithm. // The cluster each vertex is assigned to is stored in the clusterId data member of the vertex. void labelPropagationClustering( ostream&, size_t seed, // Seed for random number generator. size_t stableIterationCountThreshold, // Stop after this many iterations without changes. size_t maxIterationCount // Stop after this many iterations no matter what. ); // Vertex table, keyed by cell id. map<CellId, vertex_descriptor> vertexTable; // Compute minimum and maximum coordinates of all the vertices. void computeCoordinateRange( double& xMin, double& xMax, double& yMin, double& yMax) const; // Assign integer colors to groups. // The same color can be used for multiple groups, but if two // groups are joined by one or more edges they must have distinct colors. // On return, colorTable[group] contains the integer color assigned to each group. // This processes the groups in increasing order beginning at group 0, // so it is best if the group numbers are all contiguous, starting at zero, // and in decreasing size of group. void assignColorsToGroups(vector<uint32_t>& colorTable); // Write the graph in svg format. // This does not use Graphviz. It uses the graph layout stored in the vertices, // and previously computed using Graphviz. // The last argument specifies the color assigned to each vertex group. // If empty, vertex groups are not used, and each vertex is drawn // with its own color. void writeSvg( ostream& s, bool hideEdges, double svgSizePixels, double xViewBoxCenter, double yViewBoxCenter, double viewBoxHalfSize, double vertexRadius, double edgeThickness, const map<int, string>& groupColors, const string& geneSetName // Used for the cell URL ) const; class Writer { public: Writer(const Graph&); void operator()(ostream&) const; void operator()(ostream&, vertex_descriptor) const; void operator()(ostream&, edge_descriptor) const; const Graph& graph; double minEdgeSimilarity; }; }; #endif
29.023973
128
0.653923
c2204f53bccd49ff55d67f901341be870061d5c3
955
hpp
C++
lib/Array/concat.hpp
LiquidFun/WiredLedCube
dc2aac8bccf02d325b31081d6dc52f8ca79bd62a
[ "MIT" ]
1
2021-04-06T09:48:39.000Z
2021-04-06T09:48:39.000Z
lib/Array/concat.hpp
LiquidFun/WiredLedCube
dc2aac8bccf02d325b31081d6dc52f8ca79bd62a
[ "MIT" ]
null
null
null
lib/Array/concat.hpp
LiquidFun/WiredLedCube
dc2aac8bccf02d325b31081d6dc52f8ca79bd62a
[ "MIT" ]
null
null
null
#pragma once #include <stddef.h> #include "Array.hpp" #include "IntegerSequence.hpp" #include "make_array.hpp" #include "MakeIntegerSequence.hpp" namespace T27 { namespace intern { template <class T, int... inds1, int... inds2> constexpr Array<T, sizeof...(inds1) + sizeof...(inds2)> concat_( const Array<T, sizeof...(inds1)> &arr1, IntSequence<inds1...>, const Array<T, sizeof...(inds2)> &arr2, IntSequence<inds2...>) { return make_array<T>(arr1[inds1]..., arr2[inds2]...); } } // namespace intern template <class T, size_t size1, size_t size2> constexpr Array<T, size1 + size2> concat( const Array<T, size1> &arr1, const Array<T, size2> &arr2) { return intern::concat_( arr1, MakeIntSequence<size1>{}, arr2, MakeIntSequence<size2>{}); } } // namespace T27
25.131579
72
0.559162
c222d086ec30d6d6ac0c7e70eca167724294b61b
31,512
cpp
C++
sdl2_framework/DrawingSurface.cpp
chrisjpurdy/ksp_2d
54f6f31aea7b6228a62168f7963058fa3a9243a2
[ "MIT" ]
2
2022-01-07T11:35:35.000Z
2022-01-09T22:37:06.000Z
sdl2_framework/DrawingSurface.cpp
chrisjpurdy/ksp_2d
54f6f31aea7b6228a62168f7963058fa3a9243a2
[ "MIT" ]
null
null
null
sdl2_framework/DrawingSurface.cpp
chrisjpurdy/ksp_2d
54f6f31aea7b6228a62168f7963058fa3a9243a2
[ "MIT" ]
null
null
null
#include "header.h" #if defined(_MSC_VER) #include <SDL_syswm.h> #endif #include <math.h> #include "BaseEngine.h" #include "DisplayableObject.h" #include "DrawingSurface.h" #include "DrawingFilters.h" #include "FontManager.h" #include "templates.h" /* Template function to swap two values over, storing one in a temporary variable of the correct type and using assignment operator Note: this existed before std::swap() existed, and is only used for ints and floats in the coursework framework. You could instead "#include <utility>" and use "std::swap()" */ template <typename T> inline void swapPoints(T& v1, T& v2) { T t = v1; v1 = v2; v2 = t; } // Constant for PI - used in GetAngle below. const double DrawingSurface::MY_PI = 3.14159265358979323846; DrawingSurface::DrawingSurface(BaseEngine* m_pCreatorEngine) : m_pSDLSurface(nullptr), m_pCreatorEngine(m_pCreatorEngine), mySDLSurfaceLockedCount(0), m_pFilter(nullptr), checkBoundsForDrawings(false), m_iBoundsTop(0), m_iBoundsBottom(0), m_iBoundsLeft(0), m_iBoundsRight(0), m_bTempUnlocked(false) { // Default to checking that points are on the screen unless anyone says otherwise (e.g. unless someone clears it) this->setDrawPointsFilter(m_pCreatorEngine); } /* Determine the angle (in radians) of point 2 from point 1. Note that it also checks the quadrant, so you get a result from 0 to 2PI. Implemented as a template so you can use with ints, doubles, etc */ double DrawingSurface::getAngle(double tX1, double tY1, double tX2, double tY2) { double dAngle = MY_PI / 2; // Default when X1==X2 if (tX1 != tX2) dAngle = atan((double)(tY2 - tY1) / (double)(tX2 - tX1)); else if (tY2 < tY1) dAngle += MY_PI; if (tX2 < tX1) dAngle += MY_PI; return dAngle; } /* Draw a string in the specified font to the specified surface (foreground or background). */ void DrawingSurface::drawFastString(int iX, int iY, const char* pText, unsigned int uiColour, Font* pFont) { if (pFont == NULL) pFont = m_pCreatorEngine->getDefaultFont(); SDL_Color color = { (Uint8)((uiColour & 0xff0000) >> 16), (Uint8)((uiColour & 0xff00) >> 8), (Uint8)((uiColour & 0xff)), 0 }; if ((pFont != NULL) && (pFont->getTTFFont() != NULL)) { SDL_Surface *sText = TTF_RenderText_Solid(pFont->getTTFFont(), pText, color); SDL_Rect rcDest = { iX,iY,0,0 }; mySDLTempUnlockSurface(); SDL_BlitSurface(sText, NULL, m_pSDLSurface, &rcDest); mySDLTempRelockSurface(); SDL_FreeSurface(sText); } } /* Draw a scalable string in the specified font to the specified surface (foreground or background). */ void DrawingSurface::drawScalableString(int iX, int iY, const char* pText, unsigned int uiColour, Font* pFont) { if (pFont == NULL) pFont = m_pCreatorEngine->getDefaultFont(); SDL_Color color = { (Uint8)((uiColour & 0xff0000) >> 16), (Uint8)((uiColour & 0xff00) >> 8), (Uint8)((uiColour & 0xff)), 0 }; unsigned int testColor = 0; if ((pFont != NULL) && (pFont->getTTFFont() != NULL)) { SDL_Surface *sText = TTF_RenderText_Solid(pFont->getTTFFont(), pText, color); SDL_Rect rcDest = { iX,iY,0,0 }; for (int x = 0; x < sText->w; x++) { for (int y = 0; y < sText->h; y++) { // Get colour from the surface drawing to... switch (sText->format->BitsPerPixel) { case 8: testColor = *((Uint8*)sText->pixels + y * sText->pitch + x); break; case 16: testColor = *((Uint16*)sText->pixels + y * sText->pitch / 2 + x); break; case 32: testColor = *((Uint32*)sText->pixels + y * sText->pitch / 4 + x); break; default: // Should never happen testColor = 0; break; } //testColor = ((unsigned int*)(sText->pixels))[y*sText->w + x]; //printf("%08x ", testColor); if ( testColor ) setPixel(x + iX, y + iY, uiColour); } //printf("\n"); } SDL_FreeSurface(sText); } } /* Copy all of the background (e.g. tiles) to the foreground display. e.g. removing any object drawn on top. */ void DrawingSurface::copyEntireSurface( DrawingSurface* pFrom ) { memcpy(m_pSDLSurface->pixels, pFrom->m_pSDLSurface->pixels, sizeof(unsigned int) * getIntsPerWindowRow() * getSurfaceHeight()); // ::SDL_UpperBlitScaled } /* Copy some of the background onto the foreground, e.g. removing an object which was drawn on top. Note that x, y, width and height are trimmed to fit inside THIS surface (that is being copied FROM) and that these are REAL not VIRTUAL positions. (Ignore this if you aren't using filters.) */ void DrawingSurface::copyRectangleFrom(DrawingSurface* pFrom, int iRealX, int iRealY, int iWidth, int iHeight, int iSourceOffsetX, int iSourceOffsetY) { if (iRealX + iWidth < 0) return; // Nothing to do if (iRealY + iHeight < 0) return; // Nothing to do if (iRealX >= pFrom->getSurfaceWidth() ) return; // Nothing to do if (iRealY >= pFrom->getSurfaceHeight() ) return; // Nothing to do // Ensure position is within the bounds if (iRealX < 0) { iWidth += iRealX; iRealX = 0; /*Note that iRealX was negative*/ } if (iRealY < 0) { iHeight += iRealY; iRealY = 0; /*Note that iRealY was negative*/ } // In case source offsets are -ve... if (iRealX + iSourceOffsetX < 0) { iWidth += (iRealX + iSourceOffsetX); iRealX = -iSourceOffsetX; /*Note that offset was negative*/ } if (iRealY + iSourceOffsetY < 0) { iHeight += (iRealY + iSourceOffsetY); iRealY = -iSourceOffsetY; /*Note that offset was negative*/ } // Ensure width is within bounds if ((iRealX + iWidth) >= pFrom->getSurfaceWidth()) iWidth = pFrom->getSurfaceWidth() - iRealX; // Ensure height is within bounds if ((iRealY + iHeight) >= pFrom->getSurfaceHeight()) iHeight = pFrom->getSurfaceHeight() - iRealY; // In case source offsets were +ve... if (iRealX + iSourceOffsetX + iWidth >= pFrom->getSurfaceWidth() ) iWidth = pFrom->getSurfaceWidth() - iRealX - iSourceOffsetX; if (iRealY + iSourceOffsetY + iHeight >= pFrom->getSurfaceHeight() ) iHeight = pFrom->getSurfaceHeight() - iRealY - iSourceOffsetY; int iStartDest = iRealY * getIntsPerWindowRow() + iRealX; int iStartSrc = (iRealY + iSourceOffsetY) * getIntsPerWindowRow() + iRealX + iSourceOffsetX; int iIncrement = getIntsPerWindowRow() - iWidth; //std::cout << "Copy to " << iRealX << "," << iRealY << " from " << (iRealX + iSourceOffsetX) << "," << (iRealY + iSourceOffsetY) << " size " << iWidth << "," << iHeight << std::endl; // Use drawing code or use blit? #if AVOID_BLIT unsigned int * puiSource = ((unsigned int *)pFrom->m_pSDLSurface->pixels) + iStartSrc; unsigned int * puiDest = ((unsigned int *)m_pSDLSurface->pixels) + iStartDest; for (int i = 0; i < iHeight; i++) { // Copy a line for (int j = 0; j < iWidth; j++) *puiDest++ = *puiSource++; // Align on the next line puiSource += iIncrement; puiDest += iIncrement; } #else SDL_Rect rectDest = { iRealX, iRealY, iWidth, iHeight }; SDL_Rect rectSrc = { iRealX + iSourceOffsetX, iRealY + iSourceOffsetY, iWidth, iHeight }; mySDLTempUnlockSurface(); CHECK_BLIT_SURFACE(this); ::SDL_BlitSurface(pFrom->m_pSDLSurface, &rectSrc, m_pSDLSurface, &rectDest); mySDLTempRelockSurface(); #endif } /* Draw a vertical sided region. If two points are the same then it is a triangle. To do an arbitrary triangle, just draw two next to each other, one for left and one for right. Basically to ensure that the triangle is filled (no pixels are missed) it is better to draw lines down each column than to try to draw at arbitrary angles. This means that we have a shape where the starting and ending points are horizontally fixed (same x coordinate), and we are drawing a load of vertical lines from points on the top to points on the bottom of the region. */ void DrawingSurface::drawVerticalSidedRegion( double fX1, double fX2,// X positions double fY1a, double fY2a, // Start y positions for x1 and x2 double fY1b, double fY2b, // End y positions for x1 and x2 unsigned int uiColour) { if ( checkBoundsForDrawings ) { if (fX1 < m_iBoundsLeft && fX2 < m_iBoundsLeft) return; // No need to draw cos this is off the left of the display if (fX1 > m_iBoundsRight && fX2 > m_iBoundsRight) return; // No need to draw cos this is off the right of the display if (fY1a < m_iBoundsTop && fY1b < m_iBoundsTop && fY2a < m_iBoundsTop && fY2b < m_iBoundsTop) return; // No need to draw cos this is off the top of the display if (fY1a > m_iBoundsBottom && fY1b > m_iBoundsBottom && fY2a > m_iBoundsBottom && fY2b > m_iBoundsBottom) return; // No need to draw cos this is off the bottom of the display } // Ensure X1< X2, otherwise steps will go wrong! // Switch the points if x and y are wrong way round if (fX2< fX1) { swapPoints(fX1, fX2); swapPoints(fY1a, fY2a); swapPoints(fY1b, fY2b); } int iXStart = (int)(fX1 + 0.5); int iXEnd = (int)(fX2 + 0.5); // If integer x positions are the same then avoid floating point inaccuracy problems by a special case if (iXStart == iXEnd) { int iYStart = (int)(fY1a + 0.5); int iYEnd = (int)(fY2a + 0.5); for (int iY = iYStart; iY <= iYEnd; iY++) setPixel(iXStart, iY, uiColour); } else { // Draw left hand side int iYStart = (int)(fY1a + 0.5); int iYEnd = (int)(fY1b + 0.5); if (iYStart > iYEnd) swapPoints(iYStart, iYEnd); //printf( "Firstline %d to %d (%f to %f)\n", iYStart, iYEnd, fY1a, fY1b ); for (int iY = iYStart; iY <= iYEnd; iY++) setPixel(iXStart, iY, uiColour); // Draw the middle for (int iX = iXStart + 1; iX< iXEnd; iX++) { double fYStart = fY1a + ((((double)iX) - fX1)*(fY2a - fY1a)) / (fX2 - fX1); double fYEnd = fY1b + ((((double)iX) - fX1)*(fY2b - fY1b)) / (fX2 - fX1); if (fYEnd< fYStart) swapPoints(fYStart, fYEnd); int iYStart2 = (int)(fYStart + 0.5); int iYEnd2 = (int)(fYEnd + 0.5); //printf( "Line from %d to %d (%f to %f)\n", iYStart, iYEnd, fYStart, fYEnd ); for (int iY = iYStart2; iY <= iYEnd2; iY++) setPixel(iX, iY, uiColour); } // Draw right hand side iYStart = (int)(fY2a + 0.5); iYEnd = (int)(fY2b + 0.5); if (iYStart> iYEnd) swapPoints(iYStart, iYEnd); //printf( "Last line %d to %d (%f to %f)\n", iYStart, iYEnd, fY2a, fY2b ); for (int iY = iYStart; iY <= iYEnd; iY++) setPixel(iXEnd, iY, uiColour); } } /* Draw a triangle, as two vertical sided regions. Try this on paper to see how it works. Basically to ensure that the triangle is filled (no pixels are missed) it is better to draw lines down each column than to try to draw at arbitrary angles. */ void DrawingSurface::drawTriangle( double fX1, double fY1, double fX2, double fY2, double fX3, double fY3, unsigned int uiColour) { if (checkBoundsForDrawings) { if (fX1 < m_iBoundsLeft && fX2 < m_iBoundsLeft && fX3 < m_iBoundsLeft) return; // No need to draw cos this is off the left of the display if (fX1 >= m_iBoundsRight && fX2 >= m_iBoundsRight && fX3 >= m_iBoundsRight) return; // No need to draw cos this is off the right of the display if (fY1 < m_iBoundsTop && fY2 < m_iBoundsTop && fY3 < m_iBoundsTop) return; // No need to draw cos this is off the top of the display if (fY1 >= m_iBoundsBottom && fY2 >= m_iBoundsBottom && fY3 >= m_iBoundsBottom ) return; // No need to draw cos this is off the bottom of the display } // Ensure order is 1 2 3 from left to right if (fX1 > fX2) { swapPoints(fX1, fX2); swapPoints(fY1, fY2); } // Bigger of 1 and 2 is in position 2 if (fX2 > fX3) { swapPoints(fX2, fX3); swapPoints(fY2, fY3); } // Bigger of new 2 and 3 is in position 3 if (fX1 > fX2) { swapPoints(fX1, fX2); swapPoints(fY1, fY2); } // Bigger of 1 and new 2 is in position 2 if (fX1 == fX2) drawVerticalSidedRegion(fX1, fX3, fY1, fY3, fY2, fY3, uiColour); else if (fX2 == fX3) drawVerticalSidedRegion(fX1, fX3, fY1, fY2, fY1, fY3, uiColour); else { // Split into two triangles. Find position on line 1-3 to split at double dSplitPointY = (double)fY1 + (((double)((fX2 - fX1)*(fY3 - fY1))) / (double)(fX3 - fX1)); drawVerticalSidedRegion(fX1, fX2, fY1, fY2, fY1, dSplitPointY, uiColour); drawVerticalSidedRegion(fX2, fX3, fY2, fY3, dSplitPointY, fY3, uiColour); } } /* Draw a rectangle on the specified surface This is probably the easiest function to do, hence is a special case. */ void DrawingSurface::drawRectangle(int iX1, int iY1, int iX2, int iY2, unsigned int uiColour) { if (checkBoundsForDrawings) { if (iX1 < m_iBoundsLeft && iX2 < m_iBoundsLeft) return; // No need to draw cos this is off the left of the display if (iX1 >= m_iBoundsRight && iX2 >= m_iBoundsRight) return; // No need to draw cos this is off the right of the display if (iY1 < m_iBoundsTop && iY2 < m_iBoundsTop) return; // No need to draw cos this is off the top of the display if (iY1 >= m_iBoundsBottom && iY2 >= m_iBoundsBottom) return; // No need to draw cos this is off the bottom of the display } if (iX2 < iX1) { int t = iX1; iX1 = iX2; iX2 = t; } if (iY2 < iY1) { int t = iY1; iY1 = iY2; iY2 = t; } for (int iX = iX1; iX <= iX2; iX++) for (int iY = iY1; iY <= iY2; iY++) setPixel(iX, iY, uiColour); } /* Draw an oval on the specified surface. This is drawn by checking each pixel inside a bounding rectangle to see whether it should be filled or not. There are probably faster ways to do this! */ void DrawingSurface::drawOval(int iX1, int iY1, int iX2, int iY2, unsigned int uiColour) { if (checkBoundsForDrawings) { if (iX1 < m_iBoundsLeft && iX2 < m_iBoundsLeft ) return; // No need to draw cos this is off the left of the display if (iX1 >= m_iBoundsRight && iX2 >= m_iBoundsRight ) return; // No need to draw cos this is off the right of the display if (iY1 < m_iBoundsTop && iY2 < m_iBoundsTop ) return; // No need to draw cos this is off the top of the display if (iY1 >= m_iBoundsBottom && iY2 >= m_iBoundsBottom ) return; // No need to draw cos this is off the bottom of the display } if (iX2 < iX1) { int t = iX1; iX1 = iX2; iX2 = t; } if (iY2 < iY1) { int t = iY1; iY1 = iY2; iY2 = t; } double fCentreX = ((double)(iX2 + iX1)) / 2.0; double fCentreY = ((double)(iY2 + iY1)) / 2.0; double fXFactor = (double)((iX2 - iX1) * (iX2 - iX1)) / 4.0; double fYFactor = (double)((iY2 - iY1) * (iY2 - iY1)) / 4.0; double fDist; for (int iX = iX1; iX <= iX2; iX++) for (int iY = iY1; iY <= iY2; iY++) { fDist = ((double)iX - fCentreX) * ((double)iX - fCentreX) / fXFactor + ((double)iY - fCentreY) * ((double)iY - fCentreY) / fYFactor; if (fDist <= 1.0) setPixel(iX, iY, uiColour); } } /* Draw an oval on the specified surface. This is a REALLY slow version of the above function, which just draws a perimeter pixel. Probably there is a much better way to do this. */ void DrawingSurface::drawHollowOval(int iX1, int iY1, int iX2, int iY2, int iX3, int iY3, int iX4, int iY4, unsigned int uiColour) { if (checkBoundsForDrawings) { if (iX1 < m_iBoundsLeft && iX2 < m_iBoundsLeft && iX3 < m_iBoundsLeft && iX4 < m_iBoundsLeft) return; // No need to draw cos this is off the left of the display if (iX1 >= m_iBoundsRight && iX2 >= m_iBoundsRight && iX3 >= m_iBoundsRight && iX4 >= m_iBoundsRight) return; // No need to draw cos this is off the right of the display if (iY1 < m_iBoundsTop && iY2 < m_iBoundsTop && iY3 < m_iBoundsTop && iY4 < m_iBoundsTop) return; // No need to draw cos this is off the top of the display if (iY1 >= m_iBoundsBottom && iY2 >= m_iBoundsBottom && iY3 >= m_iBoundsBottom && iY4 >= m_iBoundsBottom) return; // No need to draw cos this is off the bottom of the display } if (iX2 < iX1) swapPoints(iX1, iX2); if (iY2 < iY1) swapPoints(iY1, iY2); if (iX4 < iX3) swapPoints(iX3, iX4); if (iY4 < iY3) swapPoints(iY3, iY4); double fCentreX1 = ((double)(iX2 + iX1)) / 2.0; double fCentreY1 = ((double)(iY2 + iY1)) / 2.0; double fXFactor1 = (double)((iX2 - iX1) * (iX2 - iX1)) / 4.0; double fYFactor1 = (double)((iY2 - iY1) * (iY2 - iY1)) / 4.0; double fCentreX2 = ((double)(iX4 + iX3)) / 2.0; double fCentreY2 = ((double)(iY4 + iY3)) / 2.0; double fXFactor2 = (double)((iX4 - iX3) * (iX4 - iX3)) / 4.0; double fYFactor2 = (double)((iY4 - iY3) * (iY4 - iY3)) / 4.0; double fDist1, fDist2; for (int iX = iX1; iX <= iX2; iX++) for (int iY = iY1; iY <= iY2; iY++) { fDist1 = ((double)iX - fCentreX1) * ((double)iX - fCentreX1) / fXFactor1 + ((double)iY - fCentreY1) * ((double)iY - fCentreY1) / fYFactor1; fDist2 = ((double)iX - fCentreX2) * ((double)iX - fCentreX2) / fXFactor2 + ((double)iY - fCentreY2) * ((double)iY - fCentreY2) / fYFactor2; if ((fDist1 <= 1.0) && (fDist2 >= 1.0)) setPixel(iX, iY, uiColour); } } /* Draw a line on the specified surface. For each horizontal pixel position, work out which vertical position at which to colour in the pixel. */ void DrawingSurface::drawLine(double fX1, double fY1, double fX2, double fY2, unsigned int uiColour) { if (checkBoundsForDrawings) { if (fX1 < m_iBoundsLeft && fX2 < m_iBoundsLeft ) return; // No need to draw cos this is off the left of the display if (fX1 >= m_iBoundsRight && fX2 >= m_iBoundsRight ) return; // No need to draw cos this is off the right of the display if (fY1 < m_iBoundsTop && fY2 < m_iBoundsTop ) return; // No need to draw cos this is off the top of the display if (fY1 >= m_iBoundsBottom && fY2 >= m_iBoundsBottom ) return; // No need to draw cos this is off the bottom of the display } int iX1 = (int)(fX1 + 0.5); int iX2 = (int)(fX2 + 0.5); int iY1 = (int)(fY1 + 0.5); int iY2 = (int)(fY2 + 0.5); int iSteps = (iX2 - iX1); if (iSteps < 0) iSteps = -iSteps; if (iY2 > iY1) iSteps += (iY2 - iY1); else iSteps += (iY1 - iY2); iSteps += 2; double fXStep = ((double)(fX2 - fX1)) / iSteps; double fYStep = ((double)(fY2 - fY1)) / iSteps; for (int i = 0; i <= iSteps; i++) { setPixel((int)(0.5 + fX1 + fXStep * i), (int)(0.5 + fY1 + fYStep * i), uiColour); } } /* Draw a thick line on the specified surface. This is like the DrawLine() function, but has a width to the line. */ void DrawingSurface::drawThickLine(double fX1, double fY1, double fX2, double fY2, unsigned int uiColour, int iThickness) { if (checkBoundsForDrawings) { if (fX1 < m_iBoundsLeft && fX2 < m_iBoundsLeft ) return; // No need to draw cos this is off the left of the display if (fX1 >= m_iBoundsRight && fX2 >= m_iBoundsRight ) return; // No need to draw cos this is off the right of the display if (fY1 < m_iBoundsTop && fY2 < m_iBoundsTop ) return; // No need to draw cos this is off the top of the display if (fY1 >= m_iBoundsBottom && fY2 >= m_iBoundsBottom ) return; // No need to draw cos this is off the bottom of the display } if (iThickness < 2) { // Go to the quicker draw function drawLine(fX1, fY1, fX2, fY2, uiColour); return; } double fAngle1 = getAngle(fX1, fY1, fX2, fY2); double fAngle1a = fAngle1 - ((5 * M_PI) / 4.0); double fAngle1b = fAngle1 + ((5 * M_PI) / 4.0); double fRectX1 = fX1 + iThickness * cos(fAngle1a) * 0.5; double fRectY1 = fY1 + iThickness * sin(fAngle1a) * 0.5; double fRectX2 = fX1 + iThickness * cos(fAngle1b) * 0.5; double fRectY2 = fY1 + iThickness * sin(fAngle1b) * 0.5; double fAngle2 = fAngle1 + M_PI; double fAngle2a = fAngle2 - ((5 * M_PI) / 4.0); double fAngle2b = fAngle2 + ((5 * M_PI) / 4.0); double fRectX3 = fX2 + iThickness * cos(fAngle2a) * 0.5; double fRectY3 = fY2 + iThickness * sin(fAngle2a) * 0.5; double fRectX4 = fX2 + iThickness * cos(fAngle2b) * 0.5; double fRectY4 = fY2 + iThickness * sin(fAngle2b) * 0.5; drawTriangle(fRectX1, fRectY1, fRectX2, fRectY2, fRectX3, fRectY3, uiColour); drawTriangle(fRectX3, fRectY3, fRectX4, fRectY4, fRectX1, fRectY1, uiColour); } /* Draw a filled polygon on the specified surface. The trick here is to not fill in any bits that shouldn't be filled, but to not miss anything. This was a pain to write to be honest, and there is a chance it may have an error I have not found so far. */ void DrawingSurface::drawPolygon( int iPoints, double* pXArray, double* pYArray, unsigned int uiColour) { if (iPoints == 1) { setPixel( (int)(pXArray[0]+0.5), (int)(pYArray[0] + 0.5), uiColour); return; } if (iPoints == 2) { drawLine(pXArray[0], pYArray[0], pXArray[1], pYArray[1], uiColour); return; } /* if ( iPoints == 3 ) { printf( "Draw triangle for points 0, 1, 2 of %d available\n", iPoints ); DrawTriangle( pXArray[0], pYArray[0], pXArray[1], pYArray[1], pXArray[2], pYArray[2], uiColour, pTarget ); return; } */ // Otherwise attempt to eliminate a point by filling the polygon, then call this again double fXCentre, fYCentre; //fX1, fX2, fX3, fY1, fY2, fY3; int i2, i3; double fAngle1, fAngle2, fAngle3; for (int i1 = 0; i1 < iPoints; i1++) { i2 = i1 + 1; if (i2 >= iPoints) i2 -= iPoints; i3 = i1 + 2; if (i3 >= iPoints) i3 -= iPoints; fXCentre = (pXArray[i1] + pXArray[i2] + pXArray[i3]) / 3.0; fYCentre = (pYArray[i1] + pYArray[i2] + pYArray[i3]) / 3.0; fAngle1 = getAngle(fXCentre, fYCentre, pXArray[i1], pYArray[i1]); fAngle2 = getAngle(fXCentre, fYCentre, pXArray[i2], pYArray[i2]); fAngle3 = getAngle(fXCentre, fYCentre, pXArray[i3], pYArray[i3]); // Now work out the relative angle positions and make sure all are positive fAngle2 -= fAngle1; if (fAngle2 < 0) fAngle2 += 2 * M_PI; fAngle3 -= fAngle1; if (fAngle3 < 0) fAngle3 += 2 * M_PI; if (fAngle2 < fAngle3) { // Then points are in clockwise order so central one can be eliminated as long as we don't // fill an area that we shouldn't bool bPointIsWithinTriangle = false; if (iPoints > 3) { // Need to check that there isn't a point within the area - for convex shapes double fLineAngle12 = getAngle(pXArray[i1], pYArray[i1], pXArray[i2], pYArray[i2]); if (fLineAngle12 < 0) fLineAngle12 += M_PI * 2.0; double fLineAngle23 = getAngle(pXArray[i2], pYArray[i2], pXArray[i3], pYArray[i3]); if (fLineAngle23 < 0) fLineAngle23 += M_PI * 2.0; double fLineAngle31 = getAngle(pXArray[i3], pYArray[i3], pXArray[i1], pYArray[i1]); if (fLineAngle31 < 0) fLineAngle31 += M_PI * 2.0; for (int i = i3 + 1; i != i1; i++) { if (i >= iPoints) { i = 0; if (i1 == 0) break; // From the for loop - finished } // Otherwise we need to work out whether point i is to right of line i3 to i1 double fPointAngle1 = getAngle(pXArray[i1], pYArray[i1], pXArray[i], pYArray[i]); if (fPointAngle1 < 0) fPointAngle1 += M_PI * 2.0; fPointAngle1 -= fLineAngle12; if (fPointAngle1 < 0) fPointAngle1 += M_PI * 2.0; double fPointAngle2 = getAngle(pXArray[i2], pYArray[i2], pXArray[i], pYArray[i]); if (fPointAngle2 < 0) fPointAngle2 += M_PI * 2.0; fPointAngle2 -= fLineAngle23; if (fPointAngle2 < 0) fPointAngle2 += M_PI * 2.0; double fPointAngle3 = getAngle(pXArray[i3], pYArray[i3], pXArray[i], pYArray[i]); if (fPointAngle3 < 0) fPointAngle3 += M_PI * 2.0; fPointAngle3 -= fLineAngle31; if (fPointAngle3 < 0) fPointAngle3 += M_PI * 2.0; if ((fPointAngle1 < M_PI) && (fPointAngle2 < M_PI) && (fPointAngle3 < M_PI)) bPointIsWithinTriangle = true; } } if (!bPointIsWithinTriangle) {// If not then try the next position //printf("Draw for points %d, %d, %d of %d available\n", i1, i2, i3, iPoints); drawTriangle(pXArray[i1], pYArray[i1], pXArray[i2], pYArray[i2], pXArray[i3], pYArray[i3], /*GetColour(iPoints)*/uiColour); // Remove the point i2 and then recurse for (int i = i2; i < (iPoints - 1); i++) { //printf("\tCopy point %d to %d\n", i + 1, i); pXArray[i] = pXArray[i + 1]; pYArray[i] = pYArray[i + 1]; } if (iPoints > 3) drawPolygon(iPoints - 1, pXArray, pYArray, uiColour); return; // Done } } } } /* Added in 2014 since it was used in the GroundMovement playback program so may be useful elsewhere too, but students can ignore this */ void DrawingSurface::drawShortenedArrow(int iX1, int iY1, int iX2, int iY2, int iShortenedStart, int iShortenedEnd, unsigned int uiColour, int iThickness, int iHeadSize) { if (checkBoundsForDrawings) { if (iX1 < m_iBoundsLeft && iX2 < m_iBoundsLeft) return; // No need to draw cos this is off the left of the display if (iX1 >= m_iBoundsRight && iX2 >= m_iBoundsRight) return; // No need to draw cos this is off the right of the display if (iY1 < m_iBoundsTop && iY2 < m_iBoundsTop) return; // No need to draw cos this is off the top of the display if (iY1 >= m_iBoundsBottom && iY2 >= m_iBoundsBottom) return; // No need to draw cos this is off the bottom of the display } double dAngle1 = getAngle(iX1, iY1, iX2, iY2); double dAngle2 = dAngle1 + M_PI; double dX1 = iX1 + iShortenedStart * cos(dAngle1); double dY1 = iY1 + iShortenedStart * sin(dAngle1); double dX2 = iX2 + iShortenedEnd * cos(dAngle2); double dY2 = iY2 + iShortenedEnd * sin(dAngle2); // First draw the line if (iThickness < 2) { // Go to the quicker draw function drawLine(dX1, dY1, dX2, dY2, uiColour); } else { double dX1l = iX1 + iShortenedStart * cos(dAngle1); double dY1l = iY1 + iShortenedStart * sin(dAngle1); double dX2l = iX2 + (iShortenedEnd + iThickness * 1.5) * cos(dAngle2); double dY2l = iY2 + (iShortenedEnd + iThickness * 1.5) * sin(dAngle2); drawThickLine(dX1l, dY1l, dX2l, dY2l, uiColour, iThickness); } // Now draw the arrow head. // Need three points - one is end of line and others are at 60 degrees from it. drawTriangle( dX2, dY2, dX2 + iHeadSize * cos(dAngle2 + M_PI / 6.0), dY2 + iHeadSize * sin(dAngle2 + M_PI / 6.0), dX2 + iHeadSize * cos(dAngle2 - M_PI / 6.0), dY2 + iHeadSize * sin(dAngle2 - M_PI / 6.0), uiColour); } /* Added in 2014 since it was used in the GroundMovement playback program so may be useful elsewhere too, but students can ignore this */ void DrawingSurface::drawShortenedLine(int iX1, int iY1, int iX2, int iY2, int iShortenedStart, int iShortenedEnd, unsigned int uiColour, int iThickness) { if (checkBoundsForDrawings) { if (iX1 < m_iBoundsLeft && iX2 < m_iBoundsLeft ) return; // No need to draw cos this is off the left of the display if (iX1 >= m_iBoundsRight && iX2 >= m_iBoundsRight ) return; // No need to draw cos this is off the right of the display if (iY1 < m_iBoundsTop && iY2 < m_iBoundsTop ) return; // No need to draw cos this is off the top of the display if (iY1 >= m_iBoundsBottom && iY2 >= m_iBoundsBottom ) return; // No need to draw cos this is off the bottom of the display } double dAngle1 = getAngle(iX1, iY1, iX2, iY2); double dAngle2 = dAngle1 + M_PI; // First draw the line if (iThickness < 2) { // Go to the quicker draw function double dX1 = iX1 + iShortenedStart * cos(dAngle1); double dY1 = iY1 + iShortenedStart * sin(dAngle1); double dX2 = iX2 + iShortenedEnd * cos(dAngle2); double dY2 = iY2 + iShortenedEnd * sin(dAngle2); drawLine(dX1, dY1, dX2, dY2, uiColour); } else { double dX1l = iX1 + iShortenedStart * cos(dAngle1); double dY1l = iY1 + iShortenedStart * sin(dAngle1); double dX2l = iX2 + iShortenedEnd * cos(dAngle2); double dY2l = iY2 + iShortenedEnd * sin(dAngle2); //if (iX1 == iX2) // printf("Draw shortened line %d,%d to %d,%d shortened by %d,%d is %f,%f %f,%f\n", iX1, iY1, iX2, iY2, iShortenedStart, iShortenedEnd, dX1l, dY1l, dX2l, dY2l); drawThickLine(dX1l, dY1l, dX2l, dY2l, uiColour, iThickness); } } // Get the minimum x coordinate which would be within the redraw region int DrawingSurface::getVirtualRedrawMinX() { int iMin = convertRealToVirtualXPosition(0); if (this->m_pCreatorEngine->getRedrawAllScreen()) return iMin; int iRedrawMin = this->m_pCreatorEngine->getRedrawRectVirtualLeft(); if (iRedrawMin > iMin) iMin = iRedrawMin; return iMin; } int DrawingSurface::getVirtualRedrawMinY() { int iMin = convertRealToVirtualYPosition(0); if (this->m_pCreatorEngine->getRedrawAllScreen()) return iMin; int iRedrawMin = this->m_pCreatorEngine->getRedrawRectVirtualTop(); if (iRedrawMin > iMin) iMin = iRedrawMin; return iMin; } int DrawingSurface::getVirtualRedrawMaxX() { int iMax = convertRealToVirtualXPosition(getSurfaceWidth()); if (this->m_pCreatorEngine->getRedrawAllScreen()) return iMax; int iRedrawMax = this->m_pCreatorEngine->getRedrawRectVirtualRight(); if (iMax > iRedrawMax ) iMax = iRedrawMax; return iMax; } int DrawingSurface::getVirtualRedrawMaxY() { int iMax = convertRealToVirtualYPosition(getSurfaceHeight()); if (this->m_pCreatorEngine->getRedrawAllScreen()) return iMax; int iRedrawMax = this->m_pCreatorEngine->getRedrawRectVirtualBottom(); if (iMax > iRedrawMax ) iMax = iRedrawMax; return iMax; } // Get the minimum x coordinate which would be within the redraw region int DrawingSurface::getRealRedrawMinX() { if (m_pCreatorEngine->getRedrawAllScreen()) return 0; int iMin = 0; int iRedrawMin = this->m_pCreatorEngine->getRedrawRectRealLeft(); if (iRedrawMin > iMin) iMin = iRedrawMin; return iMin; } int DrawingSurface::getRealRedrawMinY() { if (m_pCreatorEngine->getRedrawAllScreen()) return 0; int iMin = 0; int iRedrawMin = this->m_pCreatorEngine->getRedrawRectRealTop(); if (iRedrawMin > iMin) iMin = iRedrawMin; return iMin; } int DrawingSurface::getRealRedrawMaxX() { if (m_pCreatorEngine->getRedrawAllScreen()) return getSurfaceWidth(); int iMax = getSurfaceWidth(); int iRedrawMax = this->m_pCreatorEngine->getRedrawRectRealRight(); if (iMax > iRedrawMax ) iMax = iRedrawMax; return iMax; } int DrawingSurface::getRealRedrawMaxY() { if (m_pCreatorEngine->getRedrawAllScreen()) return getSurfaceHeight(); int iMax = getSurfaceHeight(); int iRedrawMax = this->m_pCreatorEngine->getRedrawRectRealBottom(); if (iMax > iRedrawMax ) iMax = iRedrawMax; return iMax; } /* Draw an oval on the specified surface - without any scaling or checking etc - BE CAREFUL WITH THIS!. */ void DrawingSurface::rawDrawOval(int iX1, int iY1, int iX2, int iY2, unsigned int uiColour) { if (iX2 < iX1) { int t = iX1; iX1 = iX2; iX2 = t; } if (iY2 < iY1) { int t = iY1; iY1 = iY2; iY2 = t; } double fCentreX = ((double)(iX2 + iX1)) / 2.0; double fCentreY = ((double)(iY2 + iY1)) / 2.0; double fXFactor = (double)((iX2 - iX1) * (iX2 - iX1)) / 4.0; double fYFactor = (double)((iY2 - iY1) * (iY2 - iY1)) / 4.0; double fDist; for (int iX = iX1; iX <= iX2; iX++) for (int iY = iY1; iY <= iY2; iY++) { fDist = ((double)iX - fCentreX) * ((double)iX - fCentreX) / fXFactor + ((double)iY - fCentreY) * ((double)iY - fCentreY) / fYFactor; if (fDist <= 1.0) rawSetPixel(iX, iY, uiColour); } }
36.85614
219
0.652862
c2269d3f254b29964f062a782a979882a83d184e
7,457
cpp
C++
examples/ex7_ssl_server/ex7_ssl_server.cpp
saarbastler/beast_http_server
bd19f1651324a0fb05ddc27fb6799fd371627e64
[ "BSD-2-Clause" ]
null
null
null
examples/ex7_ssl_server/ex7_ssl_server.cpp
saarbastler/beast_http_server
bd19f1651324a0fb05ddc27fb6799fd371627e64
[ "BSD-2-Clause" ]
null
null
null
examples/ex7_ssl_server/ex7_ssl_server.cpp
saarbastler/beast_http_server
bd19f1651324a0fb05ddc27fb6799fd371627e64
[ "BSD-2-Clause" ]
null
null
null
#include <iostream> #include <server.hpp> #include <ssl.hpp> using namespace std; template<class Request> auto make_response(const Request & req, const string & user_body){ boost::beast::http::string_body::value_type body(user_body); auto const body_size = body.size(); boost::beast::http::response<boost::beast::http::string_body> res{ std::piecewise_construct, std::make_tuple(std::move(body)), std::make_tuple(boost::beast::http::status::ok, req.version())}; res.set(boost::beast::http::field::server, BOOST_BEAST_VERSION_STRING); res.set(boost::beast::http::field::content_type, "text/html"); res.content_length(body_size); res.keep_alive(req.keep_alive()); return res; } int main() { //g++ -c -std=gnu++14 -I../../include -o ex7_ssl_server.o ./ex7_ssl_server.cpp //g++ -o ex7_ssl_server ex7_ssl_server.o -lboost_system -lboost_thread -lpthread -lboost_regex -licui18n -lssl //root@x0x0:~# curl --insecure https://localhost --request 'GET' --request-target '/1' --cacert /path/to/int.pem --cert-type PEM --tlsv1.2 //root@x0x0:~# curl --insecure https://localhost --request 'GET' --request-target '/2' --cacert /path/to/int.pem --cert-type PEM --tlsv1.2 //root@x0x0:~# openssl s_client -connect localhost:443 -servername localhost -CAfile /root/certs/int.pem std::string const cert = "-----BEGIN CERTIFICATE-----\n" "MIIDwTCCAimgAwIBAgIBATANBgkqhkiG9w0BAQsFADBAMQswCQYDVQQGEwJVUzEL\n" "MAkGA1UECAwCQ0ExDjAMBgNVBAoMBUJlYXN0MRQwEgYDVQQHDAtMb3MgQW5nZWxl\n" "czAeFw0xODA5MDEwOTUzMDJaFw0yMTA5MDEwOTUzMDJaMBQxEjAQBgNVBAMMCWxv\n" "Y2FsaG9zdDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMm2gFNSV49z\n" "mwSn6qJeh8ABnLy61jBs/jmR53cN0cN0+8vBHrhQum4sCAsFgbiMZ4cJzE4d+g0p\n" "Y5qnF8N0jeqxGHg7d0YemTCJjvV9PN0esM02Fqd8sS473SEZpkoT5L4RDWaqggVN\n" "wfFnPeIVNIEE/QshygZyBNBJPqvzwM/buXR17ncQ8kOx0i5VLwrBKowVbG6mBIuF\n" "O96Vst+/mb0c4Lkrsev7hbjM7MFVjpCDm2zOLTYb4GVGHmqB1KPPPxzPiS+upvG1\n" "C5UstgJAbgfynIzRfriGTWPjLDoVhuq5aksJDGCjv14ini2LDJrqQ/AVVw0ZF/uh\n" "VbK/aS+ldD8CAwEAAaNyMHAwCQYDVR0TBAIwADAUBgNVHREEDTALgglsb2NhbGhv\n" "c3QwEwYDVR0lBAwwCgYIKwYBBQUHAwEwOAYIKwYBBQUHAQEELDAqMCgGCCsGAQUF\n" "BzABhhxodHRwOi8vZXhhbXBsZS5sb2NhbGhvc3Q6ODAvMA0GCSqGSIb3DQEBCwUA\n" "A4IBgQAkJbfWAkn7G3JZ3h1x3UzEdKOage9KmimbTW68HrVwyqsE057Ix0L3UVCd\n" "9T1xIeM9SFcsBTpA2mJotWhQak0tGlW9AcJoziRT1c4GvdkDwss0vAPB6XoCSZ9z\n" "bxyFdQaXRNK25kq60wSq1PTvNMZYYQA7Eusj5lpp1Gz+iS57NBfcq/MxiPB79Ysb\n" "6h+YkCPsJNx1S2W3qC2d3pIeOg+5lnXL58cj1XPnBgy84webRgPtxufKlVdfG85Z\n" "cw8a/OeXiCawZQKW5z7DwINsXEtX5cm4hMOlIE9JxaGCUf1yRel/MCT5fKaeSlUt\n" "4IeGaJvyC5zYiockngaJcCW2H2DieWkgRojfgGCagXQ3rs3bdKncNDg5iuu/7jXc\n" "TZ4YMoYmt78Z7D+Rjl624omUV2TYp3dU0xrG5Xutab3gJOrUzIn7/vtU+oJ3Kc7a\n" "Rk544OYp0lFUCgCuWsF9l2nDRcD5QQCDUveww9zQFXgkcGnJ4567Kcq+FlmS7fNo\n" "kNeiKJA=\n" "-----END CERTIFICATE-----\n"; std::string const key = "-----BEGIN PRIVATE KEY-----\n" "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDJtoBTUlePc5sE\n" "p+qiXofAAZy8utYwbP45ked3DdHDdPvLwR64ULpuLAgLBYG4jGeHCcxOHfoNKWOa\n" "pxfDdI3qsRh4O3dGHpkwiY71fTzdHrDNNhanfLEuO90hGaZKE+S+EQ1mqoIFTcHx\n" "Zz3iFTSBBP0LIcoGcgTQST6r88DP27l0de53EPJDsdIuVS8KwSqMFWxupgSLhTve\n" "lbLfv5m9HOC5K7Hr+4W4zOzBVY6Qg5tszi02G+BlRh5qgdSjzz8cz4kvrqbxtQuV\n" "LLYCQG4H8pyM0X64hk1j4yw6FYbquWpLCQxgo79eIp4tiwya6kPwFVcNGRf7oVWy\n" "v2kvpXQ/AgMBAAECggEAFW/s4W4N2jQKFIuX9xuex7wkITamDs12kz27YL66PVCQ\n" "dg4XKrWBqrXJQQqbx7Y8RnC3ItIywfVVHZmGgAJCFuAtXpHLUktsMmlcJSDjOAjL\n" "93M5IyGwXt6D2MG2F4dXtw9u4ita2B90bihvvjhMtS2HiwhTRS4W7t/p5jJomm5q\n" "RdWBGv6wqA6qHAMwyp/FoRY7gO4ZNbfCMn+n02A4PQ4fWZ/wIJgg9Ikl5cjinRon\n" "go6vbFakVr1CEpUJJyNMzSO0oNoOa0SPE90STRxdf+WlrCDjU84NNzjehGxVK2Nm\n" "KCyYtdaY1pSz2YQ0WczcbxFhYvzMLaRbnceMUY228QKBgQDtLLJ3Q44P1/TI9wSH\n" "BBiZPamSbwZmw40zYTNHDBQKcyGP07Anw9UiHWJcvWnMSRE/CtGjn4lw02azjukE\n" "Lx0mKUPdiodOGpr/qzw99lyM7Test8T/9cUR/g/p+lIRc9R1YR+ju6KU90Afv3yL\n" "z+Dy8K3kfeWmKCnumgxPEazDhwKBgQDZuTwsBLq6eiviMaTL1Rd8SZyHztPETq2I\n" "knzDRC0ZZ6qpAgfhUhQHLho8i/W93nIUwekO0y3P2ryBwx0t9GdEH2A7/8RRjQEK\n" "UVztb5Ugki3i3apqX3cPK9KIg6foTEYw4IxZTTjJxBN5BNMTJvQQM2tmfXppr94f\n" "v+SbkK7niQKBgQCgNPoUX7idcSXzfhA714N6N9HMjVyIm/1MQJMvobQD3wNDsR2j\n" "rr/QfILN3FCT4qNYr0kuunxPjy0nixhRcDXDakpiYsnE82nR2+wker7HnxFlhPj4\n" "YR6Oacx8I0++ZDyWUVXa9sr6zw0spN9PXcs4r2T3HCe9FhJFDx/TZUALDwKBgQCU\n" "9jZkC4xSX5o8tSiCSTY7VAXjqS+cRRRXt5ni43dTxWivH3OSxtxrGTDcMgodMN+u\n" "sgkpmnTinE6THZKOSYSJyEnIYzLHdQi8LXS+ArTuRvVcHbsl8lD8MUhnHGS5+82e\n" "TVPZGYt8CEomZ5Weqe0cVIHr6nfhbXE1Gc5oXTI9uQKBgFKbG+08h/UmEhBs78PT\n" "zVz15vXCD6CCZ/gGBxpDO9SJpVWJgo4m4MmmMn2zQyCJU/7vj4lp6oNsRA3ULdRL\n" "RbF5vQoY/3bZcyuKc2PfBAUjvKbLAAFF8VtVj6QUj0IgBKkkqumyvVxwYy/1k56R\n" "mXLnbU9LRnjes0GyZNw2gRBf\n" "-----END PRIVATE KEY-----\n"; std::string const dh = "-----BEGIN DH PARAMETERS-----\n" "MIIBCAKCAQEAw5V8Zv0UXTzjBLBr+Wje5RktwL1K27giAQoZIKfs5MsKqAkaGJOI\n" "jeThplBGu26wZOxUKa0+aSU780JQY75aOYXqw6trLPC8Ay9ogQP9XzbxyJQPj2lJ\n" "LBwHnDVwU9xIYmwVBzo5QbVyssxtQlh+XckOARTQ4dz3x5lob9/W0Q6beRWZG7w6\n" "ruYU2DlZ5HMT2bMJkYV+T1Z6ZBVg8uXjuAvsqjHRJNDvKDPXWeZqHE4I4xFQo5MU\n" "ua0cgFeqJ9lzwiGKgTnwAswKA/c/XIX/xsCAdL1wp+a+U98loQfS/ZvWTg4Wer88\n" "18rx/G5U0pwJzRDqNbX2cwl3+3rj8KlsKwIBAg==\n" "-----END DH PARAMETERS-----\n"; boost::asio::ssl::context ctx{boost::asio::ssl::context::tlsv12}; ctx.set_options(boost::asio::ssl::context::default_workarounds | boost::asio::ssl::context::no_sslv2 | boost::asio::ssl::context::single_dh_use); ctx.use_certificate_chain(boost::asio::buffer(cert.data(), cert.size())); ctx.use_private_key(boost::asio::buffer(key.data(), key.size()), boost::asio::ssl::context::file_format::pem); ctx.use_tmp_dh(boost::asio::buffer(dh.data(), dh.size())); //############################################################################### http::ssl::server my_https_server{ctx}; my_https_server.get("/1", [](auto & req, auto & session){ cout << req << endl; // '/1' session.do_write(make_response(req, "GET 1\n")); }); my_https_server.get("/2", [](auto & req, auto & session){ cout << req << endl; // '/2' session.do_write(make_response(req, "GET 2\n")); }); my_https_server.all(".*", [](auto & req, auto & session){ cout << req << endl; // 'any' session.do_write(make_response(req, "error\n")); }); const auto & address = "127.0.0.1"; uint32_t port = 443; my_https_server.listen(address, port, [](auto & session){ http::base::out(session.getConnection()->stream().lowest_layer().remote_endpoint().address().to_string() + " connected"); session.do_handshake(); }); http::base::processor::get().register_signals_handler([](int signal){ if(signal == SIGINT) http::base::out("Interactive attention signal"); else if(signal == SIGTERM) http::base::out("Termination request"); else http::base::out("Quit"); http::base::processor::get().stop(); }, std::vector<int>{SIGINT,SIGTERM, SIGQUIT}); uint32_t pool_size = boost::thread::hardware_concurrency(); http::base::processor::get().start(pool_size == 0 ? 4 : pool_size << 1); http::base::processor::get().wait(); return 0; }
46.899371
142
0.73488
c22acce4897c7e29eb52e25c5489caea137e48cd
1,102
cpp
C++
OIandACM/OJ/Codeforces/1451C.cpp
ASC8384/-
8d8fb4c1d4c10aca1e10a0faf5ab2b687fd936d2
[ "CC0-1.0" ]
8
2019-08-09T14:28:13.000Z
2021-02-23T03:22:15.000Z
OIandACM/OJ/Codeforces/1451C.cpp
ASC8384/Template
8d8fb4c1d4c10aca1e10a0faf5ab2b687fd936d2
[ "CC0-1.0" ]
null
null
null
OIandACM/OJ/Codeforces/1451C.cpp
ASC8384/Template
8d8fb4c1d4c10aca1e10a0faf5ab2b687fd936d2
[ "CC0-1.0" ]
4
2019-08-16T12:00:41.000Z
2019-11-29T12:01:17.000Z
/* ** Author: ASC_8384 ** Website: www.ASC8384.top ** License: CC0 ** Time: 2020-11-21 22:55:51 */ #include <bits/stdc++.h> typedef long long ll; using namespace std; mt19937 rnd(chrono::steady_clock::now().time_since_epoch().count()); const int size = 2e5 + 9; const ll mod = 1e9 + 7; int a[size]; string s1, s2; //unordered_map<char, int> mp1, mp2; int mp1[33]; int mp2[33]; int main() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); int t = 1; cin >> t; while(t--) { s1.clear(); s2.clear(); memset(mp1, 0, sizeof(mp1)); memset(mp2, 0, sizeof(mp2)); // mp1.clear(); // mp2.clear(); int n, k; cin >> n >> k; cin >> s1 >> s2; for(int i = 0; i < n; i++) mp1[s1[i] - 'a']++, mp2[s2[i] - 'a']++; bool flg = true; for(int i = 0; i <= 30; i++) { if(mp1[i] == mp2[i]) continue; if(mp1[i] < mp2[i]) { flg = false; goto ANS; } if((mp1[i] - mp2[i]) % k == 0) { mp1[i + 1] += k * ((mp1[i] - mp2[i]) / k); } else { flg = false; goto ANS; } } ANS: if(flg) cout << "Yes\n"; else cout << "No\n"; } return 0; }
16.69697
68
0.513612
c2313e39bc1107089d98d69060fe05c8e3cdc0c1
1,906
cpp
C++
Minecraft/Taiga_Biome.cpp
borbrudar/Minecraft_clone
117fbe94390f96e3a6227129de60c08a5cc2ccdc
[ "MIT" ]
null
null
null
Minecraft/Taiga_Biome.cpp
borbrudar/Minecraft_clone
117fbe94390f96e3a6227129de60c08a5cc2ccdc
[ "MIT" ]
null
null
null
Minecraft/Taiga_Biome.cpp
borbrudar/Minecraft_clone
117fbe94390f96e3a6227129de60c08a5cc2ccdc
[ "MIT" ]
null
null
null
#include "Taiga_Biome.h" void Taiga_Biome::drawBiome(Shader shader, Block_Heavy & data, glm::mat4 model) { //draw the trees for (int i = 0; i < trees.size(); i++) { for (int j = 0; j < trees[i].part1.size(); j++) { int x = trees[i].part1[j].x, y = trees[i].part1[j].y, z = trees[i].part1[j].z; model[3][0] = x; model[3][1] = y; model[3][2] = z; shader.setMat4("model", model); trees[i].part1[j].draw(shader, data); if (j == (trees[i].part1.size() - 1)) { trees[i].setStructure(x, y, z); for (int k = 0; k < trees[i].part2.size(); k++) { model[3][0] = trees[i].part2[k].x; model[3][1] = trees[i].part2[k].y; model[3][2] = trees[i].part2[k].z; shader.setMat4("model", model); trees[i].part2[k].draw(shader, data); } } } } } void Taiga_Biome::setBiomeData(int chunkSize, int modelX, int modelZ, int modelY, std::vector<int>& heights, std::vector<Block>& blocks) { //dirt/stone for the surface std::random_device rd; std::default_random_engine engine(rd()); std::uniform_int_distribution<int> dist(0, 1); for (int x = 0; x < chunkSize; x++) { for (int y = 0; y < chunkSize; y++) { for (int z = 0; z < chunkSize; z++) { int temp = dist(engine); if(temp == 0) blocks[x + chunkSize * (y + (z * chunkSize))].type = block_type::type::dirt; if(temp == 1) blocks[x + chunkSize * (y + (z * chunkSize))].type = block_type::type::stone; } } } //load the tree positions std::uniform_int_distribution<int> pos(0, chunkSize - 1); trees.resize(3); for (int i = 0; i < trees.size(); i++) { trees[i].setStructureData(structureType::taiga_tree); int x = pos(engine), z = pos(engine); for (int j = 0; j < trees[i].part1.size(); j++) { trees[i].part1[j].x = x + (modelX * chunkSize); trees[i].part1[j].z = z + (modelZ * chunkSize); trees[i].part1[j].y = heights[x + (z * chunkSize)] + modelY + j; } } }
30.741935
136
0.58447
ea4d3d64447cc74008b0b64b8ede39197bee2f21
1,923
cpp
C++
LiveCam/Core/GLSL/VAO.cpp
KanSmith/LiveCam
8b863f55f08cb3ea5090e417c68ad82ded690743
[ "MIT" ]
null
null
null
LiveCam/Core/GLSL/VAO.cpp
KanSmith/LiveCam
8b863f55f08cb3ea5090e417c68ad82ded690743
[ "MIT" ]
null
null
null
LiveCam/Core/GLSL/VAO.cpp
KanSmith/LiveCam
8b863f55f08cb3ea5090e417c68ad82ded690743
[ "MIT" ]
null
null
null
#include <GLSL/VAO.h> namespace gl { #if 0 VAO::VAO() :id(0) { } VAO::~VAO() { id = 0; } bool VAO::setup() { if(id) { LC_ERROR(ERR_GL_VAO_ALREADY_SETUP); return false; } glGenVertexArrays(1, &id); if(!id) { LC_ERROR(ERR_GL_VAO_CANNOT_CREATE); return false; } return true; } void VAO::enableAttributes(VBO<VertexP>& vbo) { bind(); vbo.bind(); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(VertexP), (GLvoid*)0); unbind(); } void VAO::enableAttributes(VBO<VertexPT>& vbo) { bind(); vbo.bind(); glEnableVertexAttribArray(0); // pos glEnableVertexAttribArray(1); // tex glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(VertexPT), (GLvoid*)0); // pos glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(VertexPT), (GLvoid*)12); // tex vbo.unbind(); unbind(); } void VAO::enableAttributes(VBO<VertexCP>& vbo) { bind(); vbo.bind(); glEnableVertexAttribArray(0); // pos glEnableVertexAttribArray(2); // col glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(VertexCP), (GLvoid*)16); // pos glVertexAttribPointer(2, 4, GL_FLOAT, GL_FALSE, sizeof(VertexCP), (GLvoid*)0); // col vbo.unbind(); unbind(); } void VAO::enableAttributes(VBO<VertexNP>& vbo) { bind(); vbo.bind(); glEnableVertexAttribArray(0); // pos glEnableVertexAttribArray(3); // norm glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(VertexNP), (GLvoid*)12); // pos glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, sizeof(VertexNP), (GLvoid*)0); // norm vbo.unbind(); unbind(); } void VAO::bind() { if(!id) { LC_ERROR(ERR_GL_VAO_NOT_SETUP); return; } glBindVertexArray(id); } void VAO::unbind() { glBindVertexArray(0); } #endif } // gl
19.424242
90
0.609984
ea51aef431a15015a7cc29613f6b088384c01dec
4,489
cpp
C++
core/src/ConfigData.cpp
aschuman/CoBaB
59700463859b267f6e37d5694667e3e4110aa70b
[ "MIT" ]
null
null
null
core/src/ConfigData.cpp
aschuman/CoBaB
59700463859b267f6e37d5694667e3e4110aa70b
[ "MIT" ]
3
2015-11-15T13:24:23.000Z
2016-03-11T12:27:15.000Z
core/src/ConfigData.cpp
aschuman/CoBaB
59700463859b267f6e37d5694667e3e4110aa70b
[ "MIT" ]
3
2015-11-10T07:54:45.000Z
2021-05-11T12:33:12.000Z
#include "ConfigData.h" #include <QTranslator> #include <QApplication> /** * @brief ConfigData::ConfigData Creates the ConfigData object. */ ConfigData::ConfigData() : QSettings("IOSB", "CoBaB"){ Q_INIT_RESOURCE(application); languages.insert("German", QLocale(QLocale::German)); languages.insert("English", QLocale(QLocale::English)); mTranslator = new QTranslator(0); } /** * @brief ConfigData::instance The instance of ConfigData. */ ConfigData* ConfigData::instance = nullptr; /** * @brief ConfigData::getInstance This method ensures that there is only one instance of ConfigData. * @return The only instance of ConfigData. */ ConfigData* ConfigData::getInstance() { if(instance == nullptr) { instance = new ConfigData(); } return instance; } /** * @brief ConfigData::getLanguage Loads the language chosen by the user. * @return The language chosen by the user. */ QString ConfigData::getLanguage() { return QSettings::value("language", "German").toString(); } /** * @brief ConfigData::setLanguage Stores the language and sets the translator. * @param language The language chosen by the user. */ void ConfigData::setLanguage(QString language) { QSettings::setValue("language", language); if(languages.contains(language)) { if(mTranslator->load(languages.value(language), QLatin1String("CoBaB"), QLatin1String("_"), QLatin1String(":/resources/translations"))) { qApp->installTranslator(mTranslator); } } } /** * @brief ConfigData::getSoundOn Loads the sound setting chosen by the user. * @return True if the user wants to hear a notification sound when the search is finished. */ bool ConfigData::getSoundOn() { return QSettings::value("soundOn", false).toBool(); } /** * @brief ConfigData::setSoundOn Stores the sound setting chosen by the user. * @param soundOn True if the user wants to hear a notification sound when the search is finished. */ void ConfigData::setSoundOn(bool soundOn) { QSettings::setValue("soundOn", soundOn); } /** * @brief ConfigData::getHelp Returns the help string in the chosen language. * @return The help string. */ QString ConfigData::getHelp() { return tr("Bibliothek:\nEnthält die zuletzt verwendeten Datensätze und die Datensätze aus dem Standardordner, der per Kommandozeile übergeben werden kann.\n" "Per Doppelklick wird der Datensatz ausgewählt, in dem sich das Bild/Video befindet, das als Grundlage für die inhaltsbasierte Suche dienen soll. \n \n" "Viewer:\nÜber die Buttons 'vorheriges' und 'nächstes' wird das Bild/Video ausgewählt, das als Grundlage für die inhaltsbasierte Suche dienen soll. \n" "Bei einem Rechtsklick auf das Bild werden die verfügbaren Suchalgorithmen aufgelistet. " "Fährt man mit der Maus über einen solchen Algorithmus, erscheint eine Beschreibung zu diesem. " "Durch Klicken auf einen Algorithmus kann mit dem Programm fortgefahren werden. \n" "In den Bildern werden außerdem, falls vorhanden, Annotationen angezeigt. \n" "Nach einem Klick auf den Button 'Bereich auswählen' kann ein eigenes Rechteck auf dem Bild gezogen werden. " "Mit einem Rechtsklick in die Annotation oder das gezogene Rechteck werden die dafür verfügbaren Algorithmen angezeigt. \n\n" "Parameter:\nNach der Auswahl eines Algorithmus kann man Parameter für diesen festlegen. " "Außerdem können weitere Datensätze ausgewählt werden, in denen gesucht werden soll. \n \n" "Bestätigung:\nHier wird die aktuelle Auswahl angezeigt, die dem Algorithmus übergeben wird. \n \n" "Ergebnisse:\nDie Bilder können als positiv (grüner Kasten, ein Klick auf das Bild), negativ (roter Kasten, zweiter Klick) oder wieder neutral (dritter Klick) bewertet werden.\n" "Durch einen Klick auf den Button 'Erneut suchen' wird das Feedback an den Algorithmus übermittelt und eine neue verbesserte Suche gestartet."); } /** * @brief ConfigData::getAbout Returns the about string in the chosen language. * @return The about string. */ QString ConfigData::getAbout() { return tr("CoBaB ermöglicht es, anhand eines ausgewählten Bildes" " oder Videos eine inhaltsbasierte Suche in Bild- oder Videodaten durchzuführen." " Als Ergebnis liefert CoBaB eine Auswahl ähnlicher Bilder oder Videos. Durch die Eingabe von Feedback kann diese Auswahl verfeinert werden.\n\n" "Autoren: Anja Blechinger, Marie Bommersheim, Georgi Georgiev, Tung Nguyen, Vincent Winkler, Violina Zhekova"); }
44.89
182
0.740699
ea54f68fa64e088280e1531c992ec8d53df920c9
1,988
cpp
C++
P4612.cpp
AndrewWayne/OI_Learning
0fe8580066704c8d120a131f6186fd7985924dd4
[ "MIT" ]
null
null
null
P4612.cpp
AndrewWayne/OI_Learning
0fe8580066704c8d120a131f6186fd7985924dd4
[ "MIT" ]
null
null
null
P4612.cpp
AndrewWayne/OI_Learning
0fe8580066704c8d120a131f6186fd7985924dd4
[ "MIT" ]
null
null
null
/* * Author: xiaohei_AWM * Date:5.3 * Mutto: Face to the weakness, expect for the strength. */ #include<cstdio> #include<cstring> #include<algorithm> #include<iostream> #include<cstdlib> #include<ctime> #include<utility> #include<functional> #include<vector> #include<assert.h> using namespace std; #define reg register #define endfile fclose(stdin);fclose(stdout); typedef long long ll; typedef unsigned long long ull; typedef double db; typedef std::pair<int,int> pii; typedef std::pair<ll,ll> pll; namespace IO{ char buf[1<<15],*S,*T; inline char gc(){ if (S==T){ T=(S=buf)+fread(buf,1,1<<15,stdin); if (S==T)return EOF; } return *S++; } inline int read(){ reg int x;reg bool f;reg char c; for(f=0;(c=gc())<'0'||c>'9';f=c=='-'); for(x=c^'0';(c=gc())>='0'&&c<='9';x=(x<<3)+(x<<1)+(c^'0')); return f?-x:x; } inline ll readll(){ reg ll x;reg bool f;reg char c; for(f=0;(c=gc())<'0'||c>'9';f=c=='-'); for(x=c^'0';(c=gc())>='0'&&c<='9';x=(x<<3)+(x<<1)+(c^'0')); return f?-x:x; } } using namespace IO; struct Rectangle{ int x1, x2, y1, y2; Rectangle(){} Rectangle(int x, int y, int p){ x1 = x-p; x2 = x+p; y1 = y-p; y2 = y+p; } }; int n, x, y, p; ll ans = 0; int main(){ n = read(); x = read(), y = read(), p = read(); Rectangle S(x, y, p); for(int i = 1; i < n; i++){ x = read(), y = read(), p = read(); Rectangle A(x, y, p); int D = max(max(A.x1 - S.x2, S.x1 - A.x2), max(A.y1 - S.y2, S.y1 - A.y2)); if(D < 0) D = 0; ans += D; S.x1 -= D; S.x2 += D; S.y1 -= D; S.y2 += D; Rectangle Part; Part.x1 = max(S.x1, A.x1); Part.x2 = min(S.x2, A.x2); Part.y1 = max(S.y1, A.y1); Part.y2 = min(S.y2, A.y2);//慢慢移动 S = Part; } cout << ans; return 0; }
23.666667
82
0.479376
ea5ce77589e9dcc71190384d6405826e9e895524
1,131
cpp
C++
Company-Google/393. UTF-8 Validation/main.cpp
Minecodecraft/LeetCode-Minecode
185fd6efe88d8ffcad94e581915c41502a0361a0
[ "MIT" ]
1
2021-11-19T19:58:33.000Z
2021-11-19T19:58:33.000Z
Company-Google/393. UTF-8 Validation/main.cpp
Minecodecraft/LeetCode-Minecode
185fd6efe88d8ffcad94e581915c41502a0361a0
[ "MIT" ]
null
null
null
Company-Google/393. UTF-8 Validation/main.cpp
Minecodecraft/LeetCode-Minecode
185fd6efe88d8ffcad94e581915c41502a0361a0
[ "MIT" ]
2
2021-11-26T12:47:27.000Z
2022-01-13T16:14:46.000Z
// // main.cpp // 393. UTF-8 Validation // // Created by Jaylen Bian on 7/26/20. // Copyright © 2020 边俊林. All rights reserved. // #include <map> #include <set> #include <queue> #include <string> #include <stack> #include <vector> #include <cstdio> #include <numeric> #include <cstdlib> #include <utility> #include <iostream> #include <algorithm> #include <unordered_map> #include <unordered_set> using namespace std; /// Solution: // class Solution { public: bool validUtf8(vector<int>& data) { int cnt = 0; for (int& n: data) { if (cnt == 0) { if ((n >> 3) == 0b11110) cnt = 3; else if ((n >> 4) == 0b1110) cnt = 2; else if ((n >> 5) == 0b110) cnt = 1; else if ((n >> 7) == 0b1) return false; } else { if ((n >> 6) != 0b10) return false; --cnt; } } return cnt == 0; } }; int main() { Solution sol = Solution(); vector<int> data = {197, 130, 1}; bool res = sol.validUtf8(data); cout << res << endl; return 0; }
20.563636
55
0.50221
ea5ef2d33b7d36eeb530e3e5720301530f805d2e
280
cpp
C++
All_code/57.cpp
jnvshubham7/cpp-programming
7d00f4a3b97b9308e337c5d3547fd3edd47c5e0b
[ "Apache-2.0" ]
1
2021-12-22T12:37:36.000Z
2021-12-22T12:37:36.000Z
All_code/57.cpp
jnvshubham7/CPP_Programming
a17c4a42209556495302ca305b7c3026df064041
[ "Apache-2.0" ]
null
null
null
All_code/57.cpp
jnvshubham7/CPP_Programming
a17c4a42209556495302ca305b7c3026df064041
[ "Apache-2.0" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int main() { freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); int factorial(int n) { int fact = 1; for (int v = 1; v <= n; v++) { fact = fact * v; } return fact; } return 0; }
14
38
0.517857
ea5fc3262d4b79008225d3b325d0a3fe8a01ca37
4,058
cc
C++
mysql-server/sql/rpl_info.cc
silenc3502/MYSQL-Arch-Doc-Summary
fcc6bb65f72a385b9f56debc9b2c00cee5914bae
[ "MIT" ]
null
null
null
mysql-server/sql/rpl_info.cc
silenc3502/MYSQL-Arch-Doc-Summary
fcc6bb65f72a385b9f56debc9b2c00cee5914bae
[ "MIT" ]
null
null
null
mysql-server/sql/rpl_info.cc
silenc3502/MYSQL-Arch-Doc-Summary
fcc6bb65f72a385b9f56debc9b2c00cee5914bae
[ "MIT" ]
null
null
null
/* Copyright (c) 2010, 2019, Oracle and/or its affiliates. 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, version 2.0, as published by the Free Software Foundation. This program is also distributed with certain software (including but not limited to OpenSSL) that is licensed under separate terms, as designated in a particular file or component or in included license documentation. The authors of MySQL hereby grant you an additional permission to link the program and your derivative works with the separately licensed software that they have included with MySQL. 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, version 2.0, 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "sql/rpl_info.h" #include "m_string.h" // strmake #include "mysql/psi/mysql_cond.h" #include "mysql/psi/mysql_mutex.h" #include "thr_mutex.h" Rpl_info::Rpl_info(const char *type, #ifdef HAVE_PSI_INTERFACE PSI_mutex_key *param_key_info_run_lock, PSI_mutex_key *param_key_info_data_lock, PSI_mutex_key *param_key_info_sleep_lock, PSI_mutex_key *param_key_info_thd_lock, PSI_mutex_key *param_key_info_data_cond, PSI_mutex_key *param_key_info_start_cond, PSI_mutex_key *param_key_info_stop_cond, PSI_mutex_key *param_key_info_sleep_cond, #endif uint param_id, const char *param_channel) : Slave_reporting_capability(type), #ifdef HAVE_PSI_INTERFACE key_info_run_lock(param_key_info_run_lock), key_info_data_lock(param_key_info_data_lock), key_info_sleep_lock(param_key_info_sleep_lock), key_info_thd_lock(param_key_info_thd_lock), key_info_data_cond(param_key_info_data_cond), key_info_start_cond(param_key_info_start_cond), key_info_stop_cond(param_key_info_stop_cond), key_info_sleep_cond(param_key_info_sleep_cond), #endif info_thd(nullptr), inited(false), abort_slave(false), slave_running(0), slave_run_id(0), handler(nullptr), internal_id(param_id) { #ifdef HAVE_PSI_INTERFACE mysql_mutex_init(*key_info_run_lock, &run_lock, MY_MUTEX_INIT_FAST); mysql_mutex_init(*key_info_data_lock, &data_lock, MY_MUTEX_INIT_FAST); mysql_mutex_init(*key_info_sleep_lock, &sleep_lock, MY_MUTEX_INIT_FAST); mysql_mutex_init(*key_info_thd_lock, &info_thd_lock, MY_MUTEX_INIT_FAST); mysql_cond_init(*key_info_data_cond, &data_cond); mysql_cond_init(*key_info_start_cond, &start_cond); mysql_cond_init(*key_info_stop_cond, &stop_cond); mysql_cond_init(*key_info_sleep_cond, &sleep_cond); #else mysql_mutex_init(nullptr, &run_lock, MY_MUTEX_INIT_FAST); mysql_mutex_init(nullptr, &data_lock, MY_MUTEX_INIT_FAST); mysql_mutex_init(nullptr, &sleep_lock, MY_MUTEX_INIT_FAST); mysql_mutex_init(nullptr, &info_thd_lock, MY_MUTEX_INIT_FAST); mysql_cond_init(nullptr, &data_cond); mysql_cond_init(nullptr, &start_cond); mysql_cond_init(nullptr, &stop_cond); mysql_cond_init(nullptr, &sleep_cond); #endif if (param_channel) strmake(channel, param_channel, sizeof(channel) - 1); else /*create a default empty channel*/ strmake(channel, "", sizeof(channel) - 1); } Rpl_info::~Rpl_info() { delete handler; mysql_mutex_destroy(&run_lock); mysql_mutex_destroy(&data_lock); mysql_mutex_destroy(&sleep_lock); mysql_mutex_destroy(&info_thd_lock); mysql_cond_destroy(&data_cond); mysql_cond_destroy(&start_cond); mysql_cond_destroy(&stop_cond); mysql_cond_destroy(&sleep_cond); }
40.989899
79
0.750123
ea6304a806f2166c33b63ea65a502beb4a699b6c
1,051
cpp
C++
src/utils/ExpressionManager.cpp
amecky/breakout
b580befabd1226c6c8c26550d5e0e0ca841fe67d
[ "MIT" ]
null
null
null
src/utils/ExpressionManager.cpp
amecky/breakout
b580befabd1226c6c8c26550d5e0e0ca841fe67d
[ "MIT" ]
null
null
null
src/utils/ExpressionManager.cpp
amecky/breakout
b580befabd1226c6c8c26550d5e0e0ca841fe67d
[ "MIT" ]
null
null
null
#include "ExpressionManager.h" #include <diesel.h> ExpressionManager::ExpressionManager() { _vmCtx = vm_create_context(); vm_add_variable(_vmCtx, "TIMER", 0.0f); vm_add_variable(_vmCtx, "PI", ds::PI); vm_add_variable(_vmCtx, "TWO_PI", ds::TWO_PI); } ExpressionManager::~ExpressionManager() { vm_destroy_context(_vmCtx); } void ExpressionManager::setVariable(const char * name, float value) { vm_set_variable(_vmCtx, name, value); } int ExpressionManager::parse(const char * expression) { Expression exp; exp.num = vm_parse(_vmCtx, expression, exp.tokens, 64); _expressions.push_back(exp); return _expressions.size() - 1; } void ExpressionManager::parse(int expressionID, const char * expression) { Expression& exp = _expressions[expressionID]; exp.num = vm_parse(_vmCtx, expression, exp.tokens, 64); } float ExpressionManager::run(int index) { Expression& exp = _expressions[index]; float r = 0.0f; int code = vm_run(_vmCtx, exp.tokens, exp.num, &r); if (code != 0) { DBG_LOG("Error: %s", vm_get_error(code)); } return r; }
26.275
74
0.725975
ea6c81c35e56716575c82f45d8960b1f546f0b36
6,855
cc
C++
src/camera/test/camera_streaming_test/camera_streaming_test.cc
winksaville/Fuchsia
a0ec86f1d51ae8d2538ff3404dad46eb302f9b4f
[ "BSD-3-Clause" ]
3
2020-08-02T04:46:18.000Z
2020-08-07T10:10:53.000Z
src/camera/test/camera_streaming_test/camera_streaming_test.cc
winksaville/Fuchsia
a0ec86f1d51ae8d2538ff3404dad46eb302f9b4f
[ "BSD-3-Clause" ]
null
null
null
src/camera/test/camera_streaming_test/camera_streaming_test.cc
winksaville/Fuchsia
a0ec86f1d51ae8d2538ff3404dad46eb302f9b4f
[ "BSD-3-Clause" ]
1
2020-08-07T10:11:49.000Z
2020-08-07T10:11:49.000Z
// Copyright 2019 The Fuchsia 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 <button_checker.h> #include <fcntl.h> #include <fuchsia/camera/test/cpp/fidl.h> #include <fuchsia/camera2/cpp/fidl.h> #include <lib/devmgr-integration-test/fixture.h> // For RecursiveWaitForFile #include <lib/fdio/fdio.h> #include <lib/zx/vmar.h> #include <unistd.h> #include <zircon/status.h> #include <zircon/types.h> #include <array> #include <atomic> #include <string> #include <fbl/unique_fd.h> #include <openssl/sha.h> #include "garnet/public/lib/gtest/real_loop_fixture.h" // fx run-test camera_full_on_device_test -t camera_streaming_test class CameraStreamingTest : public gtest::RealLoopFixture { protected: CameraStreamingTest() {} ~CameraStreamingTest() override {} virtual void SetUp() override; void BindIspTester(fuchsia::camera::test::IspTesterSyncPtr& ptr); }; // Returns the formatted sha512 string of a buffer. std::string Hash(const void* data, size_t size) { static const char* table = "0123456789abcdef"; uint8_t md[SHA512_DIGEST_LENGTH]{}; SHA512(reinterpret_cast<const uint8_t*>(data), size, md); std::string ret(2 * sizeof(md) + 1, 0); for (uint32_t i = 0; i < SHA512_DIGEST_LENGTH; ++i) { ret[2 * i] = table[(md[i] >> 4) & 0xF]; ret[2 * i + 1] = table[md[i] & 0xF]; } return ret; } void CameraStreamingTest::SetUp() { if (!VerifyDeviceUnmuted()) { GTEST_SKIP(); } } // Connect to the ISP test device. void CameraStreamingTest::BindIspTester(fuchsia::camera::test::IspTesterSyncPtr& ptr) { static const char* kIspTesterDir = "/dev/class/isp-device-test"; int result = open(kIspTesterDir, O_RDONLY); ASSERT_GE(result, 0) << "Error opening " << kIspTesterDir; fbl::unique_fd dir_fd(result); fbl::unique_fd fd; ASSERT_EQ(devmgr_integration_test::RecursiveWaitForFile(dir_fd, "000", &fd), ZX_OK); zx::channel channel; ASSERT_EQ(fdio_get_service_handle(fd.get(), channel.reset_and_get_address()), ZX_OK); ptr.Bind(std::move(channel)); } // Validate the contents of the stream coming from the ISP. TEST_F(CameraStreamingTest, CheckStreamFromIsp) { // Pick something large enough that it's likely larger than any internal ring buffers, but small // enough that the test completes relatively quickly. static const uint32_t kFramesToCheck = 42; // Connect to the tester. fuchsia::camera::test::IspTesterSyncPtr tester; ASSERT_NO_FATAL_FAILURE(BindIspTester(tester)); ASSERT_TRUE(tester.is_bound()); // Request a stream. fuchsia::camera2::StreamPtr stream; fuchsia::sysmem::BufferCollectionInfo_2 buffers; fuchsia::sysmem::ImageFormat_2 format; ASSERT_EQ(tester->CreateStream(stream.NewRequest(), &buffers, &format), ZX_OK); std::atomic_bool stream_alive = true; stream.set_error_handler([&](zx_status_t status) { ADD_FAILURE_AT(__FILE__, __LINE__) << "Stream disconnected: " << zx_status_get_string(status); stream_alive = false; }); // Populate a set of known hashes to constant-value frame data. std::map<std::string, uint8_t> known_hashes; { // Try known transients 0x00 and 0xFF, as well as other likely transients near values k*2^N. static constexpr const std::array<uint8_t, 10> kValuesToCheck{0x00, 0xFF, 0x01, 0xFE, 0x7F, 0x80, 0x3F, 0x40, 0xBF, 0xC0}; std::vector<uint8_t> known_frame(buffers.settings.buffer_settings.size_bytes); for (size_t i = 0; i < kValuesToCheck.size(); ++i) { auto value = kValuesToCheck[i]; std::cout << "\rCalculating hash for fixed value " << static_cast<uint32_t>(value) << " (" << i + 1 << "/" << kValuesToCheck.size() << ")"; std::cout.flush(); memset(known_frame.data(), value, known_frame.size()); known_hashes[Hash(known_frame.data(), known_frame.size())] = value; } std::cout << std::endl; } // Register a frame event handler. std::map<std::string, uint32_t> frame_hashes; std::vector<bool> buffer_owned(buffers.buffer_count, false); std::atomic_uint32_t frames_received{0}; stream.events().OnFrameAvailable = [&](fuchsia::camera2::FrameAvailableInfo event) { if (++frames_received > kFramesToCheck) { // If we've reached the target number of frames, just release the frame and return. stream->ReleaseFrame(event.buffer_id); return; } // Check ownership validity of the buffer. ASSERT_LT(event.buffer_id, buffers.buffer_count); EXPECT_FALSE(buffer_owned[event.buffer_id]) << "Server sent frame " << event.buffer_id << " again without the client releasing it."; buffer_owned[event.buffer_id] = true; // Map and hash the entire contents of the buffer. uintptr_t mapped_addr = 0; ASSERT_EQ(zx::vmar::root_self()->map(0, buffers.buffers[event.buffer_id].vmo, 0, buffers.settings.buffer_settings.size_bytes, ZX_VM_PERM_READ, &mapped_addr), ZX_OK); std::cout << "\rCalculating hash for frame " << frames_received << "/" << kFramesToCheck; std::cout.flush(); auto hash = Hash(reinterpret_cast<void*>(mapped_addr), buffers.settings.buffer_settings.size_bytes); ASSERT_EQ( zx::vmar::root_self()->unmap(mapped_addr, buffers.settings.buffer_settings.size_bytes), ZX_OK); // Verify the hash does not match a prior or known hash. Even with a static scene, thermal // noise should prevent any perfectly identical frames. As a result, this check should only // fail if the frames are not actually coming from the sensor, or are being recycled // incorrectly. auto it = known_hashes.find(hash); if (it != known_hashes.end()) { ADD_FAILURE_AT(__FILE__, __LINE__) << "Frame " << frames_received << " does not contain valid image data - it is just the constant byte value " << it->second; } else { auto it = frame_hashes.find(hash); if (it == frame_hashes.end()) { frame_hashes.emplace(hash, frames_received); } else { ADD_FAILURE_AT(__FILE__, __LINE__) << "Duplicate frame - the contents of frames " << it->second << " and " << frames_received << " both hash to 0x" << hash; } } buffer_owned[event.buffer_id] = false; stream->ReleaseFrame(event.buffer_id); }; // Start the stream. stream->Start(); // Begin the message loop, exiting when a certain number of frames are received, or the stream // connection dies. RunLoopUntil([&]() { return !stream_alive || frames_received >= kFramesToCheck; }); std::cout << std::endl; ASSERT_TRUE(stream_alive); // Stop the stream. stream->Stop(); RunLoopUntilIdle(); }
38.083333
98
0.677316
ea6cef86f165de40ad583269f5207fea3ec23482
1,419
cpp
C++
c++/leetcode/0909-Snakes_and_Ladders-M.cpp
levendlee/leetcode
35e274cb4046f6ec7112cd56babd8fb7d437b844
[ "Apache-2.0" ]
1
2020-03-02T10:56:22.000Z
2020-03-02T10:56:22.000Z
c++/leetcode/0909-Snakes_and_Ladders-M.cpp
levendlee/leetcode
35e274cb4046f6ec7112cd56babd8fb7d437b844
[ "Apache-2.0" ]
null
null
null
c++/leetcode/0909-Snakes_and_Ladders-M.cpp
levendlee/leetcode
35e274cb4046f6ec7112cd56babd8fb7d437b844
[ "Apache-2.0" ]
null
null
null
// 909 Snakes and Ladders // https://leetcode.com/problems/snakes-and-ladders // version: 1; create time: 2020-01-12 11:30:15; class Solution { public: int snakesAndLadders(vector<vector<int>>& board) { const int m = board.size(); if (m == 0) return -1; const int n = board.size(); if (n == 0) return -1; const auto calc_index = [&](const int k) { const int i = m - 1 - (k / n); const int j = ((k / n) % 2) ? (n - 1 - (k % n)) : (k % n); return std::make_pair(i, j); }; vector<bool> visit(m * n, false); queue<int> bfs; bfs.push(0); int steps = 0; while (!bfs.empty()) { const int size = bfs.size(); ++steps; for (int i = 0; i < size; ++i) { const auto k = bfs.front(); bfs.pop(); for (int s = 1; (s <= 6) && (s + k < m * n); ++s) { const auto index = calc_index(k + s); const int i = index.first; const int j = index.second; const int next = board[i][j] != -1 ? board[i][j] - 1 : k + s; if (next == m * n - 1) return steps; if (visit[next]) continue; visit[next] = true; bfs.push(next); } } } return -1; } };
31.533333
81
0.41649
ea6f5953820a8adb5dc11604f040d6b41a602292
2,649
hpp
C++
libvast/vast/access.hpp
ngrodzitski/vast
5d114f53d51db8558f673c7f873bd92ded630bf6
[ "BSD-3-Clause" ]
null
null
null
libvast/vast/access.hpp
ngrodzitski/vast
5d114f53d51db8558f673c7f873bd92ded630bf6
[ "BSD-3-Clause" ]
1
2019-11-29T12:43:41.000Z
2019-11-29T12:43:41.000Z
libvast/vast/access.hpp
ngrodzitski/vast
5d114f53d51db8558f673c7f873bd92ded630bf6
[ "BSD-3-Clause" ]
null
null
null
/****************************************************************************** * _ _____ __________ * * | | / / _ | / __/_ __/ Visibility * * | |/ / __ |_\ \ / / Across * * |___/_/ |_/___/ /_/ Space and Time * * * * This file is part of VAST. It is subject to the license terms in the * * LICENSE file found in the top-level directory of this distribution and at * * http://vast.io/license. No part of VAST, including this file, may be * * copied, modified, propagated, or distributed except according to the terms * * contained in the LICENSE file. * ******************************************************************************/ #pragma once #include <type_traits> namespace vast { /// Wrapper to encapsulate the implementation of concepts requiring access to /// private state. struct access { template <class, class = void> struct state; template <class, class = void> struct parser; template <class, class = void> struct printer; template <class, class = void> struct converter; }; namespace detail { struct has_access_state { template <class T> static auto test(T* x) -> decltype(access::state<T>{}, std::true_type()); template <class> static auto test(...) -> std::false_type; }; struct has_access_parser { template <class T> static auto test(T* x) -> decltype(access::parser<T>{}, std::true_type()); template <class> static auto test(...) -> std::false_type; }; struct has_access_printer { template <class T> static auto test(T* x) -> decltype(access::printer<T>{}, std::true_type()); template <class> static auto test(...) -> std::false_type; }; struct has_access_converter { template <class T> static auto test(T* x) -> decltype(access::converter<T>{}, std::true_type()); template <class> static auto test(...) -> std::false_type; }; } // namespace detail template <class T> constexpr bool has_access_state_v = decltype(detail::has_access_state::test<T>(0))::value; template <class T> constexpr bool has_access_parser_v = decltype(detail::has_access_parser::test<T>(0))::value; template <class T> constexpr bool has_access_printer_v = decltype(detail::has_access_printer::test<T>(0))::value; template <class T> constexpr bool has_access_converter_v = decltype(detail::has_access_converter::test<T>(0))::value; } // namespace vast
29.433333
80
0.563609
ea7525f81d1d57b3a558ed62d3f5d00b2818ae70
2,762
cpp
C++
src/Thread.cpp
TheDSCPL/SSRE_2017-2018_group8
10a74266fbd9fcdb9a2898427096d80f6430b75e
[ "MIT" ]
null
null
null
src/Thread.cpp
TheDSCPL/SSRE_2017-2018_group8
10a74266fbd9fcdb9a2898427096d80f6430b75e
[ "MIT" ]
null
null
null
src/Thread.cpp
TheDSCPL/SSRE_2017-2018_group8
10a74266fbd9fcdb9a2898427096d80f6430b75e
[ "MIT" ]
null
null
null
#include <stdlib.h> #include <chrono> #include <thread> #include <iostream> #include <sys/time.h> #include <string.h> #include "../headers/Thread.hpp" using namespace std; Mutex::Mutex() : mutex(PTHREAD_MUTEX_INITIALIZER) {} void Mutex::lock() { pthread_mutex_lock(&mutex); } void Mutex::unlock() { pthread_mutex_unlock(&mutex); } bool Mutex::isLocked() { static Mutex m; bool ret = false; m.lock(); int r = pthread_mutex_trylock(&mutex); if (r == 0) { //could lock so it's not locked pthread_mutex_unlock(&mutex); } else if (r == EBUSY) ret = true; m.unlock(); return ret; } Mutex::~Mutex() { pthread_mutex_destroy(&mutex); } ThreadCondition::ThreadCondition() : condition(PTHREAD_COND_INITIALIZER) {} void ThreadCondition::wait(Mutex &m) { pthread_cond_wait(&condition, &m.mutex); } void ThreadCondition::timedWait(Mutex &m, long millis) { struct timeval tv; gettimeofday(&tv, NULL); //epoch time timespec t; //epoch target time t.tv_sec = tv.tv_sec + millis / 1000; t.tv_nsec = (tv.tv_usec + millis % 1000) * 1000; pthread_cond_timedwait(&condition, &m.mutex, &t); } void ThreadCondition::signal() { pthread_cond_signal(&condition); } void ThreadCondition::broadcast() { pthread_cond_broadcast(&condition); } ThreadCondition::~ThreadCondition() { pthread_cond_destroy(&condition); } Thread::Thread(std::function<void()> f, std::function<void()> os) : routine(f), onStop(os), running(false), onStopCalledOnLastRun(false) {} //(std::function<void *(void *)>)[&f](void*)->void*{f(); return nullptr;} Thread::~Thread() { //cout << "DELETING THREAD!" << endl; cancel(); } void Thread::start() { onStopCalledOnLastRun = false; pthread_create(&thread, nullptr, trick, (void *) this); // if(pthread_detach(thread)) // cerr << "Couldn't detach thread!" << endl; } void Thread::usleep(long millis) { this_thread::sleep_for(chrono::milliseconds(millis)); } void Thread::_onStop() { if (onStopCalledOnLastRun) return; onStopCalledOnLastRun = true; onStop(); } void *Thread::trick(void *c) {//http://stackoverflow.com/a/1151615 ((Thread *) c)->run(); return nullptr; } void Thread::run() { pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, nullptr); running = true; routine(); running = false; _onStop(); } bool Thread::isRunning() const { return running; } void Thread::join() const { pthread_join(thread, nullptr); } void Thread::cancel() { running = false; _onStop(); //cout << "FINISHED CANCELING!" << endl; pthread_cancel(thread); pthread_join(thread,nullptr); }
22.826446
107
0.636495
ea79d231215bf13d87c39807706844b823687db7
15,937
cpp
C++
server/http.cpp
lzxjack/chat-room
dc00c458045f4343738536ff0bf4e0cc1f70e733
[ "MIT" ]
5
2021-05-25T09:09:03.000Z
2021-11-15T11:43:58.000Z
server/http.cpp
lzxjack/chat-room
dc00c458045f4343738536ff0bf4e0cc1f70e733
[ "MIT" ]
null
null
null
server/http.cpp
lzxjack/chat-room
dc00c458045f4343738536ff0bf4e0cc1f70e733
[ "MIT" ]
2
2021-05-27T07:23:56.000Z
2021-08-23T02:11:49.000Z
#include"http.h" http::http(){ std::cout<<"http is created!"<<std::endl; } http::~http(){ } /* 报文的请求方法解析,成功返回请求方法,失败返回nullptr; */ char* http::http_Request_method(char in_str[],char out_str[]){//数组不能引用 int len=0; for(len=0;len<10;++len){ if(in_str[len]!=' '){ out_str[len]=in_str[len]; }else{ break; } } if(len>=10) return nullptr; return out_str; } /* 报文体解析,成功返回报文体,失败返回nullptr; */ char * http::http_get_Newspaper(char in_str[],char out_str[]){ int len=0,flag=0,addr=0; for(len=0;in_str[len]!='\0';++len){ //printf("%s\n",this->login_status); if(flag==0){ addr++; if(in_str[len]=='/'){ flag=1; } continue; } if(flag==1&&in_str[len]!='?'){ this->login_status[len-addr]=in_str[len]; }else{ this->login_status[len-addr]='\0'; break; } } //printf("this->login_status:%s\n",this->login_status); len=0,flag=0,addr=0; for(len=0;len<1024;++len){ if(flag==0){ addr++; if(in_str[len]=='?'){ flag=1; } continue; } if(flag==1&&in_str[len]!=' '){ out_str[len-addr]=in_str[len]; }else{ out_str[len-addr]='\0'; break; } } if(len>=1024) return nullptr; return out_str; } /* 解析报文体,获取data */ int http::http_get_data(char in_str[]){ //unordered_map是深拷贝吗? this->data_map.clear(); for(int i=0;in_str[i]!='\0';++i){ //char *first=new char [1024]; std::string first; for(int j=0;j<1024;++j){ if(in_str[i]=='\0'){ //400 客户端语法错误 return -1; } if(in_str[i]!='='){ first.push_back(in_str[i]); ++i; }else { first.push_back('\0'); ++i; break; } } //char *second=new char [1024]; std::string second; for(int j=0;j<1024;++j){ if(in_str[i]!='&'&&in_str[i]!='\0'){ second.push_back(in_str[i]); ++i; }else { second.push_back('\0'); break; } } this->data_map.insert(std::make_pair(first.c_str(),second.c_str()));//必须这么存才能在哈希表里找到,不能存对象 } return 0; } /* 把数据改成发送的键值对; */ int http::http_send(char out_str[]){ auto pos=this->data_map.begin(); if(pos==this->data_map.end()){ return -1; } char first[1024]; memset(first,0,sizeof(first)); strcpy(first,"{"); int flag=0; for(;pos!=this->data_map.end();++pos){ if(flag==0){ strcat(first,R"(")"); flag=1; }else{ strcat(first,R"(,")"); } //printf("%s\n",pos->first); //strcat(first,pos->first); //delete [] pos->first; strcat(first,R"(":")"); //printf("%s\n",pos->second); //strcat(first,pos->second); //delete [] pos->second; strcat(first,R"(")"); } strcat(first,"}"); strcpy(out_str,first); //this->data_map.clear(); return 0; } int http::http_get_original_news(char str[]){//获取原始报文 strcpy(this->Request_data,str); std::cout<<"http is created!"<<std::endl; return 0; } int http::http_put(int client_fd){ printf("%s",success); write(client_fd,success,strlen(success)); this->http_get_Newspaper(this->Request_data,this->Newspaper_data); this->http_get_data(this->Newspaper_data); if(strcmp(this->login_status,"logout")==0){ this->data_client.erase(this->data_map["name"].c_str()); char str[]=R"({"delete":0})"; char c_size[1024]; memset(c_size,0,sizeof(c_size)); itoa(strlen(str),c_size,10); printf("%s\r\n\r\n",c_size); write(client_fd,c_size,strlen(c_size)); write(client_fd,"\r\n\r\n",strlen("\r\n\r\n")); write(client_fd,str,strlen(str)); } return 0; } int http::http_post(int client_fd){ printf("%s",success); write(client_fd,success,strlen(success)); this->http_get_Newspaper(this->Request_data,this->Newspaper_data); this->http_get_data(this->Newspaper_data); if(strcmp(this->login_status,"information")==0){ memset(this->Client.name,0,sizeof(this->Client.name)); strcpy(this->Client.name,this->data_map["name"].c_str()); int fd=open("chat_record",O_RDWR|O_APPEND); if(fd==-1){ perror("open error"); return -1; } std::string st; st=st+R"({"name":")"; st=st+this->data_map["name"]; st=st+R"(","msg":")"; st=st+this->data_map["msg"]; st=st+R"(","time":)"; st=st+this->data_map["time"]; st=st+R"(,"id":")"; st=st+this->data_map["id"]; st=st+R"("})"; write(fd,st.c_str(),strlen(st.c_str())); write(fd,"\n",strlen("\n")); auto pos=this->data_client.begin(); for(;pos!=this->data_client.end();++pos){ pos->second.chat_record.push_back(st); } char str[]=R"({"msg":0})"; char c_size[1024]; memset(c_size,0,sizeof(c_size)); itoa(strlen(str),c_size,10); printf("%s\r\n\r\n",c_size); write(client_fd,c_size,strlen(c_size)); write(client_fd,"\r\n\r\n",strlen("\r\n\r\n")); write(client_fd,str,strlen(str)); } return 0; } int http::http_get(int client_fd){ //printf("tthis->Request_data:%s\n",this->Request_data); this->http_get_Newspaper(this->Request_data,this->Newspaper_data); //printf("*******************"); //printf("this->login_status:%s\n",this->login_status); this->http_get_data(this->Newspaper_data); //printf("%s\n",this->Client.name); if(strcmp(this->login_status,"login")==0){ //name=-1不存在//pwd=-1密码错误//login=1成功登录,token=密钥 printf("%s",success); write(client_fd,success,strlen(success)); memset(this->Client.name,0,sizeof(this->Client.name)); strcpy(this->Client.name,this->data_map["name"].c_str()); memset(this->Client.pwd,0,sizeof(this->Client.pwd)); strcpy(this->Client.pwd,this->data_map["pwd"].c_str()); int ret=open(this->Client.name,O_RDONLY); if(ret==-1){ char str[]=R"({"login":-1,"error": 0})"; char c_size[1024]; memset(c_size,0,sizeof(c_size)); itoa(strlen(str),c_size,10); printf("%s\r\n\r\n",c_size); write(client_fd,c_size,strlen(c_size)); write(client_fd,"\r\n\r\n",strlen("\r\n\r\n")); write(client_fd,str,strlen(str)); perror("open error"); return -1; }else{ char str[18]; read(ret,str,sizeof(str)); for(int i=0;i<32;++i){ if(str[i]=='\n'){ str[i]='\0'; break; } } if(strcmp(this->Client.pwd,str)==0){//登陆成功 for(int i=0;i<32;++i){ int x=rand()%26; this->Client._hash[i]='A'+x; } this->Client.client_fd=client_fd; //printf("*****%d\n",this->Client.name); //if(this->data_client.find(this->Client.name)==this->data_client.end()) this->data_client.insert(std::make_pair(this->Client.name,Client)); /*else{ char str[]=R"({"login":-1,"error":2})"; //表示已经登陆 char c_size[1024]; memset(c_size,0,sizeof(c_size)); itoa(strlen(str),c_size,10); printf("%s\r\n\r\n",c_size); write(client_fd,c_size,strlen(c_size)); write(client_fd,"\r\n\r\n",strlen("\r\n\r\n")); write(client_fd,str,strlen(str)); return -1; }*/ char str[256]; memset(str,0,sizeof(str)); strcpy(str,R"({"login":0,"token":")"); strncat(str,this->Client._hash,32); strcat(str,R"("})"); char c_size[1024]; memset(c_size,0,sizeof(c_size)); itoa(strlen(str),c_size,10); printf("%s\r\n\r\n",c_size); write(client_fd,c_size,strlen(c_size)); write(client_fd,"\r\n\r\n",strlen("\r\n\r\n")); write(client_fd,str,strlen(str)); printf("%s\n",str); printf("this->data_client.size()%ld\n\n",this->data_client.size()); return 0; }else{ char str[]=R"({"login":-1,"error":1})"; char c_size[1024]; memset(c_size,0,sizeof(c_size)); itoa(strlen(str),c_size,10); printf("%s\r\n\r\n",c_size); write(client_fd,c_size,strlen(c_size)); write(client_fd,"\r\n\r\n",strlen("\r\n\r\n")); write(client_fd,str,strlen(str)); return -1; } } //close(client_fd); }else if(strcmp(this->login_status,"register")==0){ printf("%s",success); write(client_fd,success,strlen(success)); memset(this->Client.name,0,sizeof(this->Client.name)); strcpy(this->Client.name,this->data_map["name"].c_str()); memset(this->Client.pwd,0,sizeof(this->Client.pwd)); strcpy(this->Client.pwd,this->data_map["pwd"].c_str()); //printf("&&&&&&&&&&&&%s\n",this->Client.name); int ret=open(this->Client.name,O_RDONLY); if(ret!=-1){ char str[]=R"({"register":-1,"error": 0})"; char c_size[1024]; memset(c_size,0,sizeof(c_size)); itoa(strlen(str),c_size,10); printf("%s\r\n\r\n",c_size); write(client_fd,c_size,strlen(c_size)); write(client_fd,"\r\n\r\n",strlen("\r\n\r\n")); write(client_fd,str,strlen(str)); return -1; }else if(strlen(this->Client.name)<3||strlen(this->Client.name)>10){ char str[]=R"({"register":-1,"error": 1})"; char c_size[1024]; memset(c_size,0,sizeof(c_size)); itoa(strlen(str),c_size,10); printf("%s\r\n\r\n",c_size); write(client_fd,c_size,strlen(c_size)); write(client_fd,"\r\n\r\n",strlen("\r\n\r\n")); write(client_fd,str,strlen(str)); return -1; }else if(strlen(this->Client.pwd)<6||strlen(this->Client.pwd)>18){ char str[]=R"({"register":-1,"error": 2})"; char c_size[1024]; memset(c_size,0,sizeof(c_size)); itoa(strlen(str),c_size,10); printf("%s\r\n\r\n",c_size); write(client_fd,c_size,strlen(c_size)); write(client_fd,"\r\n\r\n",strlen("\r\n\r\n")); write(client_fd,str,strlen(str)); return -1; } umask(0000); int fd=open(this->Client.name,O_RDWR|O_CREAT,0777); if(fd==-1){ char str[]=R"({"register":-1,"error": 3})"; char c_size[1024]; memset(c_size,0,sizeof(c_size)); itoa(strlen(str),c_size,10); printf("%s\r\n\r\n",c_size); write(client_fd,c_size,strlen(c_size)); write(client_fd,"\r\n\r\n",strlen("\r\n\r\n")); write(client_fd,str,strlen(str)); perror("open error"); return -1; }else{ char str[]=R"({"register":0})"; char c_size[1024]; memset(c_size,0,sizeof(c_size)); itoa(strlen(str),c_size,10); printf("%s\r\n\r\n",c_size); write(client_fd,c_size,strlen(c_size)); write(client_fd,"\r\n\r\n",strlen("\r\n\r\n")); write(client_fd,str,strlen(str)); write(fd,this->Client.pwd,strlen(this->Client.pwd)); write(fd,"\n\n",strlen("\n\n")); return 0; } return -1; }else if(strcmp(this->login_status,"information")==0){ printf("%s",success); write(client_fd,success,strlen(success)); memset(this->Client.name,0,sizeof(this->Client.name)); strcpy(this->Client.name,this->data_map["name"].c_str()); if(this->data_client.find(this->Client.name)==this->data_client.end()){ char str[]=R"({"information":-1})"; char c_size[1024]; memset(c_size,0,sizeof(c_size)); itoa(strlen(str),c_size,10); printf("%s\r\n\r\n",c_size); write(client_fd,c_size,strlen(c_size)); write(client_fd,"\r\n\r\n",strlen("\r\n\r\n")); write(client_fd,str,strlen(str)); return -1; } char c_size[1024]; memset(c_size,0,sizeof(c_size)); int size=this->data_client[this->Client.name].chat_record.size(); if(size==0){ char str[]=R"({"information":-1,"msg":[],"userCount":)"; char sstr[32]; memset(sstr,0,sizeof(sstr)); itoa(this->data_client.size(),sstr,10); strcat(str,sstr); strcat(str,"}"); char c_size[1024]; memset(c_size,0,sizeof(c_size)); itoa(strlen(str),c_size,10); printf("%s\r\n\r\n",c_size); write(client_fd,c_size,strlen(c_size)); write(client_fd,"\r\n\r\n",strlen("\r\n\r\n")); write(client_fd,str,strlen(str)); return 0; } std::string send_string=R"({"information":0,"msg":[)"; for(int i=0;i<size;++i){ send_string+=this->data_client[this->Client.name].chat_record[i].c_str(); send_string+=","; } send_string[send_string.size()-1]=']'; send_string+=R"(,"userCount":)"; char sstr[32]; memset(sstr,0,sizeof(sstr)); itoa(this->data_client.size(),sstr,10); send_string+=sstr; send_string.push_back('}'); itoa(strlen(send_string.c_str()),c_size,10); printf("%s\r\n\r\n",c_size); write(client_fd,c_size,strlen(c_size)); write(client_fd,"\r\n\r\n",strlen("\r\n\r\n")); write(client_fd,send_string.c_str(),strlen(send_string.c_str())); this->data_client[this->Client.name].chat_record.clear(); /*char str[]=R"({"name":"dw","msg":"qwer"})"; char cc[1024]; memset(cc,0,sizeof(cc)); itoa(strlen(str),cc,10); printf("%s\r\n\r\n",cc); write(client_fd,cc,strlen(cc)); write(client_fd,"\r\n\r\n",strlen("\r\n\r\n")); write(client_fd,str,strlen(str));*/ }else if(strcmp(this->login_status,"logout")==0){ memset(this->Client.name,0,sizeof(this->Client.name)); strcpy(this->Client.name,this->data_map["name"].c_str()); this->data_client.erase(this->Client.name); /*char str[]=R"({"delete":0})"; char c_size[1024]; memset(c_size,0,sizeof(c_size)); itoa(strlen(str),c_size,10); printf("%s\r\n\r\n",c_size); write(client_fd,c_size,strlen(c_size)); write(client_fd,"\r\n\r\n",strlen("\r\n\r\n")); write(client_fd,str,strlen(str));*/ }else { return -1; } return 0; } int http::http_delete(char in_str[]){return 0;}
35.181015
98
0.491749
ea7a37cc9433bda075599a80bb98df3466fa4f70
5,403
cc
C++
xrtl/testing/diffing/diff_provider.cc
google/xrtl
8cf0e7cd67371297149bda8e62d03b8c1e2e2dfe
[ "Apache-2.0" ]
132
2017-03-30T03:26:57.000Z
2021-11-18T09:18:04.000Z
xrtl/testing/diffing/diff_provider.cc
google/xrtl
8cf0e7cd67371297149bda8e62d03b8c1e2e2dfe
[ "Apache-2.0" ]
36
2017-04-02T22:57:53.000Z
2018-06-27T04:20:30.000Z
xrtl/testing/diffing/diff_provider.cc
google/xrtl
8cf0e7cd67371297149bda8e62d03b8c1e2e2dfe
[ "Apache-2.0" ]
24
2017-04-09T12:48:13.000Z
2021-10-20T02:20:07.000Z
// Copyright 2017 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "xrtl/testing/diffing/diff_provider.h" #include "absl/strings/str_join.h" #include "xrtl/base/logging.h" #include "xrtl/testing/file_util.h" namespace xrtl { namespace testing { namespace diffing { DiffProvider::DiffProvider() = default; DiffProvider::~DiffProvider() = default; bool DiffProvider::Initialize(absl::string_view golden_base_path) { golden_base_path_ = std::string(golden_base_path); return true; } bool DiffProvider::CheckIfPublishRequired(DiffPublishMode publish_mode, DiffResult diff_result) { // Determine if we should be publishing the result. bool did_pass = diff_result == DiffResult::kEquivalent; bool needs_publish = false; switch (publish_mode) { case DiffPublishMode::kAlways: VLOG(1) << "Forcing publish because publish mode is kAlways"; needs_publish = true; break; case DiffPublishMode::kNever: VLOG(1) << "Skipping publish because publish mode is kNever"; needs_publish = false; break; case DiffPublishMode::kFailure: needs_publish = !did_pass; break; } return needs_publish; } std::string DiffProvider::MakeGoldenFilePath(absl::string_view test_key, absl::string_view suffix) { std::string relative_path = FileUtil::JoinPathParts( golden_base_path_, absl::StrJoin({test_key, suffix}, "")); return relative_path; } std::string DiffProvider::ResolveGoldenOutputFilePath( absl::string_view test_key, absl::string_view suffix) { std::string relative_path = MakeGoldenFilePath(test_key, suffix); return FileUtil::MakeOutputFilePath(relative_path); } DiffResult DiffProvider::CompareText(absl::string_view test_key, absl::string_view text_value, DiffPublishMode publish_mode, TextDiffer::Options options) { // Load reference file. std::string golden_file_path = MakeGoldenFilePath(test_key, ".txt"); auto golden_text_buffer = FileUtil::LoadTextFile(golden_file_path); if (!golden_text_buffer) { LOG(ERROR) << "Unable to find reference file at " << golden_file_path; return PublishTextResult(publish_mode, test_key, text_value, {}, DiffResult::kMissingReference); } // Diff the text. auto result = TextDiffer::DiffStrings(golden_text_buffer.value(), text_value, options); return PublishTextResult( publish_mode, test_key, text_value, result, result.equivalent ? DiffResult::kEquivalent : DiffResult::kDifferent); } DiffResult DiffProvider::CompareData(absl::string_view test_key, const void* data, size_t data_length, DiffPublishMode publish_mode, DataDiffer::Options options) { // Load reference file. std::string golden_file_path = MakeGoldenFilePath(test_key, ".bin"); auto golden_data_buffer = FileUtil::LoadFile(golden_file_path); if (!golden_data_buffer) { LOG(ERROR) << "Unable to find reference file at " << golden_file_path; return PublishDataResult(publish_mode, test_key, data, data_length, {}, DiffResult::kMissingReference); } // Diff the data. auto result = DataDiffer::DiffBuffers(golden_data_buffer.value().data(), golden_data_buffer.value().size(), data, data_length, options); return PublishDataResult( publish_mode, test_key, data, data_length, result, result.equivalent ? DiffResult::kEquivalent : DiffResult::kDifferent); } DiffResult DiffProvider::CompareImage(absl::string_view test_key, ImageBuffer* image_buffer, DiffPublishMode publish_mode, ImageDiffer::Options options) { // Load reference image. std::string golden_file_path = MakeGoldenFilePath(test_key, ".png"); auto golden_image_buffer = ImageBuffer::Load(golden_file_path, image_buffer->channels()); if (!golden_image_buffer) { LOG(ERROR) << "Unable to find reference file at " << golden_file_path; return PublishImageResult(publish_mode, test_key, image_buffer, {}, DiffResult::kMissingReference); } // Diff the images. auto result = ImageDiffer::DiffImageBuffers(golden_image_buffer.get(), image_buffer, options); return PublishImageResult( publish_mode, test_key, image_buffer, result, result.equivalent ? DiffResult::kEquivalent : DiffResult::kDifferent); } } // namespace diffing } // namespace testing } // namespace xrtl
39.727941
80
0.661484
ea7d8672f124302266848020fc28e0ef2e9c3c59
8,997
cpp
C++
ScriptHookDotNet/SettingsFile.cpp
HazardX/gta4_scripthookdotnet
927b2830952664b63415234541a6c83592e53679
[ "MIT" ]
3
2021-11-14T20:59:58.000Z
2021-12-16T16:41:31.000Z
ScriptHookDotNet/SettingsFile.cpp
HazardX/gta4_scripthookdotnet
927b2830952664b63415234541a6c83592e53679
[ "MIT" ]
2
2021-11-29T14:41:23.000Z
2021-11-30T13:13:51.000Z
ScriptHookDotNet/SettingsFile.cpp
HazardX/gta4_scripthookdotnet
927b2830952664b63415234541a6c83592e53679
[ "MIT" ]
3
2021-11-21T12:41:55.000Z
2021-12-22T16:17:52.000Z
/* * Copyright (c) 2009-2011 Hazard (hazard_x@gmx.net / twitter.com/HazardX) * * 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 "stdafx.h" #include "SettingsFile.h" #include "ContentCache.h" #pragma managed namespace GTA { //namespace value { SettingsFile::SettingsFile(String^ Filename) { pFilename = Filename; categories = gcnew Collections::Generic::Dictionary<String^,SettingCategory^>(); bChanged = false; } SettingsFile^ SettingsFile::Open(String^ Filename) { return ContentCache::GetINI(Filename); } SettingsFile::!SettingsFile() { if (bChanged) Save(); } //String^ SettingsFile::Filename::get() { // return IO::Path::ChangeExtension(script->Filename,"ini"); //} SettingCategory^ SettingsFile::GetCategory(String^ Name) { String^ id = Name->ToLower(); if (categories->ContainsKey(id)) { return categories[id]; } else { SettingCategory^ cat = gcnew SettingCategory(Name); categories[id] = cat; return cat; } } void SettingsFile::Clear() { categories->Clear(); bChanged = true; bAddNextLine = false; } void SettingsFile::Load() { Clear(); array<String^>^ Lines = Helper::StringToLines(Helper::FileToString(Filename, System::Text::Encoding::ASCII)); //if (Lines->Length == 0) NetHook::Log("No settings in file '"+Filename+"'!"); CurrentCategory = String::Empty; for (int i = 0; i < Lines->Length; i++) { if (!bAddNextLine) ParseLine(Lines[i]); else ParseAddLine(Lines[i]); } bChanged = false; } void SettingsFile::ParseLine(String^ DataLine) { try { DataLine = DataLine->Trim(); if (DataLine->StartsWith("/") || DataLine->StartsWith("'") || DataLine->StartsWith("#")) return; if (DataLine->StartsWith("[")) { int sPos = DataLine->IndexOf("]"); if (sPos<=1) return; CurrentCategory = DataLine->Substring(1,sPos-1); return; } int eq = DataLine->IndexOf("="); if (eq <= 0) return; String^ name = DataLine->Substring(0, eq)->Trim(); String^ val; if (eq < DataLine->Length-1) { val = DataLine->Substring(eq+1)->Trim(); if (val->EndsWith("\\n\\")) { pLastValueName = name; bAddNextLine = true; if (val->Length > 3) val = val->Substring(0,val->Length-3); else val = String::Empty; } val = val->Replace("\\n",Environment::NewLine); val = val->Replace("#\\#n#","\\n"); } else { val = String::Empty; } //values->Add(name->ToLower(), val); GetCategory(CurrentCategory)->SetValue(name, val); //NetHook::Log("Found setting '"+name+"' with value '"+val+"'!"); } catchErrors("Error in setting file '"+Filename+"'",)//catch(...) {} } void SettingsFile::ParseAddLine(String^ DataLine) { bAddNextLine = false; try { DataLine = DataLine->Trim(); if (DataLine->Length > 0) { if (DataLine->EndsWith("\\n\\")) { //pLastValueName = name; bAddNextLine = true; if (DataLine->Length > 3) DataLine = DataLine->Substring(0,DataLine->Length-3); else DataLine = String::Empty; } DataLine = DataLine->Replace("\\n",Environment::NewLine); DataLine = DataLine->Replace("#\\#n#","\\n"); } else { DataLine = String::Empty; } SetValue(CurrentCategory, pLastValueName, GetValueString(pLastValueName, CurrentCategory, String::Empty) + Environment::NewLine + DataLine); } catchErrors("Error in setting file '"+Filename+"'",)//catch(...) {} } bool SettingsFile::Save() { if (!bChanged) return true; if (SaveCopyTo(Filename)) { bChanged = false; return true; } else { return false; } } bool SettingsFile::SaveCopyTo(String^ Filename) { System::Text::StringBuilder^ sb = gcnew System::Text::StringBuilder(); array<String^>^ cats = GetCategoryNames(); for (int i = 0; i < cats->Length; i++) { SaveCategory(sb, cats[i]); } return Helper::StringToFile(Filename, sb->ToString(), System::Text::Encoding::ASCII); } void SettingsFile::SaveCategory(System::Text::StringBuilder^ sb, String^ CategoryName) { array<String^>^ vals = GetValueNames(CategoryName); if (vals->Length == 0) return; String^ val; sb->AppendLine(); if (CategoryName->Length > 0) sb->AppendLine("[" + CategoryName + "]"); for (int i = 0; i < vals->Length; i++) { val = GetValueString(vals[i], CategoryName, String::Empty); val = val->Replace("\\n","#\\#n#"); val = val->Replace("\r",String::Empty); val = val->Replace("\n","\\n"); sb->AppendLine(vals[i] + "=" + val); } } array<String^>^ SettingsFile::GetCategoryNames() { List<String^>^ list = gcnew List<String^>(); //list->Add(String::Empty); for each (KeyValuePair<String^,SettingCategory^> kvp in categories) { if (kvp.Key->Length > 0) list->Add(kvp.Value->Name); } list->Sort(); list->Insert(0, String::Empty); return list->ToArray(); } array<String^>^ SettingsFile::GetValueNames(String^ Category) { return GetCategory(Category)->GetValueNames(); } String^ SettingsFile::GetValueString(String^ OptionName, String^ Category, String^ DefaultValue) { return GetCategory(Category)->GetValue(OptionName,DefaultValue); } String^ SettingsFile::GetValueString(String^ OptionName, String^ Category) { return GetValueString(OptionName, Category, String::Empty); //OptionName = OptionName->ToLower(); //if (!values->ContainsKey(OptionName)) return DefaultValue; //return values[OptionName]; } String^ SettingsFile::GetValueString(String^ OptionName) { return GetValueString(OptionName, String::Empty, String::Empty); } int SettingsFile::GetValueInteger(String^ OptionName, String^ Category, int DefaultValue) { String^ val = GetValueString(OptionName, Category, String::Empty); return Helper::StringToInteger(val, DefaultValue); } float SettingsFile::GetValueFloat(String^ OptionName, String^ Category, float DefaultValue) { String^ val = GetValueString(OptionName, Category, String::Empty); return Helper::StringToFloat(val, DefaultValue); } bool SettingsFile::GetValueBool(String^ OptionName, String^ Category, bool DefaultValue) { String^ val = GetValueString(OptionName, Category, String::Empty); return Helper::StringToBoolean(val, DefaultValue); } Vector3 SettingsFile::GetValueVector3(String^ OptionName, String^ Category, Vector3 DefaultValue) { String^ val = GetValueString(OptionName, Category, String::Empty); return Helper::StringToVector3(val, DefaultValue); } Windows::Forms::Keys SettingsFile::GetValueKey(String^ OptionName, String^ Category, Windows::Forms::Keys DefaultValue) { String^ val = GetValueString(OptionName, Category, String::Empty); //if (val->Length == 0) NetHook::Log("Requested setting '"+OptionName+"' not found!"); return Helper::StringToKey(val, DefaultValue); } GTA::Model SettingsFile::GetValueModel(String^ OptionName, String^ Category, GTA::Model DefaultValue) { String^ val = GetValueString(OptionName, Category, String::Empty); return Helper::StringToModel(val,DefaultValue); } void SettingsFile::SetValue(String^ OptionName, String^ Category, String^ Value) { GetCategory(Category)->SetValue(OptionName, Value); bChanged = true; } void SettingsFile::SetValue(String^ OptionName, String^ Category, Vector3 Value) { SetValue(OptionName, Category, Value.ToString(", ", 4)); } void SettingsFile::SetValue(String^ OptionName, String^ Category, bool Value) { SetValue(OptionName, Category, Value.ToString()); } void SettingsFile::SetValue(String^ OptionName, String^ Category, float Value) { SetValue(OptionName, Category, Helper::FloatToString(Value,4)); } void SettingsFile::SetValue(String^ OptionName, String^ Category, int Value) { SetValue(OptionName, Category, Value.ToString()); } void SettingsFile::SetValue(String^ OptionName, String^ Category, Windows::Forms::Keys Value) { SetValue(OptionName, Category, Value.ToString()); } void SettingsFile::SetValue(String^ OptionName, String^ Category, GTA::Model Value) { SetValue(OptionName, Category, Value.ToString()); } //} }
35.702381
143
0.691342
ea7dd9dd3c1b7ac86e0cdb252dae94f7ac696cb1
311
cpp
C++
aql/benchmark/lib_62/class_2.cpp
menify/sandbox
32166c71044f0d5b414335b2b6559adc571f568c
[ "MIT" ]
null
null
null
aql/benchmark/lib_62/class_2.cpp
menify/sandbox
32166c71044f0d5b414335b2b6559adc571f568c
[ "MIT" ]
null
null
null
aql/benchmark/lib_62/class_2.cpp
menify/sandbox
32166c71044f0d5b414335b2b6559adc571f568c
[ "MIT" ]
null
null
null
#include "class_2.h" #include "class_1.h" #include "class_3.h" #include "class_0.h" #include "class_4.h" #include "class_6.h" #include <lib_47/class_0.h> #include <lib_1/class_6.h> #include <lib_11/class_4.h> #include <lib_54/class_5.h> #include <lib_47/class_7.h> class_2::class_2() {} class_2::~class_2() {}
20.733333
27
0.713826
ea80e7c266e18e5c6edc47648b5ddc46e50938b5
740
cpp
C++
1697_hide_and_seek.cpp
harrydrippin/baekjoon
4ee6b6796d9dece8860e777b38cf90c2c6b13132
[ "MIT" ]
null
null
null
1697_hide_and_seek.cpp
harrydrippin/baekjoon
4ee6b6796d9dece8860e777b38cf90c2c6b13132
[ "MIT" ]
null
null
null
1697_hide_and_seek.cpp
harrydrippin/baekjoon
4ee6b6796d9dece8860e777b38cf90c2c6b13132
[ "MIT" ]
1
2020-07-25T07:41:12.000Z
2020-07-25T07:41:12.000Z
#include <iostream> #include <queue> using namespace std; int main() { int m[100001]; fill_n(m, 100001, 100002); int n, k; cin >> n >> k; m[n] = 0; queue<int> q; q.push(n); while (!q.empty()) { int cur = q.front(); q.pop(); if (cur + 1 < 100001 && m[cur + 1] > m[cur] + 1) { m[cur + 1] = m[cur] + 1; q.push(cur + 1); } if (cur - 1 >= 0 && m[cur - 1] > m[cur] + 1) { m[cur - 1] = m[cur] + 1; q.push(cur - 1); } if (cur * 2 < 100001 && cur * 2 != 0 && m[cur * 2] > m[cur] + 1) { m[cur * 2] = m[cur] + 1; q.push(cur * 2); } } cout << m[k]; return 0; }
19.473684
74
0.366216
ea84617d10d67475381a3078add0ceff0b390d4d
141
cpp
C++
Tutorial PNG/Tutorial PNG/DemoApp/main.cpp
0lidaxiang/openGL_homework
895620aad85d750ba9c78ea54fb4ab8bd69bf187
[ "MIT" ]
1
2017-02-04T03:08:40.000Z
2017-02-04T03:08:40.000Z
Tutorial PNG/Tutorial PNG/DemoApp/main.cpp
0lidaxiang/openGL_homework
895620aad85d750ba9c78ea54fb4ab8bd69bf187
[ "MIT" ]
null
null
null
Tutorial PNG/Tutorial PNG/DemoApp/main.cpp
0lidaxiang/openGL_homework
895620aad85d750ba9c78ea54fb4ab8bd69bf187
[ "MIT" ]
null
null
null
#include "DemoApp.h" int main(int *arg, char **argv) { DempApp app; std::cout<<"Enter: Screen Shot"<<std::endl; app.Start(); return 0; }
15.666667
44
0.638298
ea87fcf473d7ffc76b62a509b1dc7059f92b7edf
640
cpp
C++
competitive programming/codeforces/486A - Calculating Function.cpp
sureshmangs/Code
de91ffc7ef06812a31464fb40358e2436734574c
[ "MIT" ]
16
2020-06-02T19:22:45.000Z
2022-02-05T10:35:28.000Z
competitive programming/codeforces/486A - Calculating Function.cpp
codezoned/Code
de91ffc7ef06812a31464fb40358e2436734574c
[ "MIT" ]
null
null
null
competitive programming/codeforces/486A - Calculating Function.cpp
codezoned/Code
de91ffc7ef06812a31464fb40358e2436734574c
[ "MIT" ]
2
2020-08-27T17:40:06.000Z
2022-02-05T10:33:52.000Z
/* For a positive integer n let's define a function f: f(n)?=??-?1?+?2?-?3?+?..?+?(?-?1)nn Your task is to calculate f(n) for a given integer n. Input The single line contains the positive integer n (1?=?n?=?1015). Output Print f(n) in a single line. Examples inputCopy 4 outputCopy 2 inputCopy 5 outputCopy -3 Note f(4)?=??-?1?+?2?-?3?+?4?=?2 f(5)?=??-?1?+?2?-?3?+?4?-?5?=??-?3 */ #include<bits/stdc++.h> using namespace std; int main(){ ios_base::sync_with_stdio(false); cin.tie(NULL); long long n; cin >> n; if (n % 2) { cout << - (n + 1) / 2; } else cout << n / 2; return 0; }
13.061224
63
0.551563
ea881b2fdd8f30bd40268d30f48545131c5d8ad1
19,128
cpp
C++
LibCarla/source/carla/rss/RssCheck.cpp
youngsend/carla
c918f4b73b6b845dc66ccf3ffe3f011e800607ec
[ "MIT" ]
103
2020-03-10T04:21:50.000Z
2022-03-29T13:26:57.000Z
LibCarla/source/carla/rss/RssCheck.cpp
630156145/carla
b9fbbf7fd03ee2a4f3a7baf4343a28381cfe81ef
[ "MIT" ]
12
2020-04-11T11:36:01.000Z
2021-12-09T11:35:56.000Z
LibCarla/source/carla/rss/RssCheck.cpp
630156145/carla
b9fbbf7fd03ee2a4f3a7baf4343a28381cfe81ef
[ "MIT" ]
8
2020-11-21T07:47:12.000Z
2022-03-25T13:41:05.000Z
// Copyright (c) 2019 Intel Corporation // // This work is licensed under the terms of the MIT license. // For a copy, see <https://opensource.org/licenses/MIT>. #include "carla/rss/RssCheck.h" #include "carla/client/Map.h" #include "carla/client/Vehicle.h" #include "carla/client/Waypoint.h" #include "carla/road/element/RoadInfoLaneWidth.h" #include "ad_rss/core/RssResponseResolving.hpp" #include "ad_rss/core/RssResponseTransformation.hpp" #include "ad_rss/core/RssSituationChecking.hpp" #include "ad_rss/core/RssSituationExtraction.hpp" #include "ad_rss/state/RssStateOperation.hpp" #include <algorithm> #include <cmath> #include <vector> namespace carla { namespace rss { namespace csd = carla::sensor::data; // constants for deg-> rad conversion PI / 180 constexpr float toRadians = static_cast<float>(M_PI) / 180.0f; inline float calculateAngleDelta(const float angle1, const float angle2) { float delta = angle1 - angle2; delta -= std::floor((delta + 180.f) / 360.f) * 360.f; return delta; } RssCheck::RssCheck() { _rssSituationExtraction = std::make_shared<::ad_rss::core::RssSituationExtraction>(); _rssSituationChecking = std::make_shared<::ad_rss::core::RssSituationChecking>(); _rssResponseResolving = std::make_shared<::ad_rss::core::RssResponseResolving>(); _egoVehicleDynamics = std::make_shared<::ad_rss::world::RssDynamics>(); _otherVehicleDynamics = std::make_shared<::ad_rss::world::RssDynamics>(); ::ad_rss::world::RssDynamics defaultDynamics; defaultDynamics.alphaLon.accelMax = ::ad_rss::physics::Acceleration(3.5); defaultDynamics.alphaLon.brakeMax = ::ad_rss::physics::Acceleration(8.); defaultDynamics.alphaLon.brakeMin = ::ad_rss::physics::Acceleration(4.); defaultDynamics.alphaLon.brakeMinCorrect = ::ad_rss::physics::Acceleration(3); defaultDynamics.alphaLat.accelMax = ::ad_rss::physics::Acceleration(0.2); defaultDynamics.alphaLat.brakeMin = ::ad_rss::physics::Acceleration(0.8); defaultDynamics.responseTime = ::ad_rss::physics::Duration(1.); *_egoVehicleDynamics = defaultDynamics; *_otherVehicleDynamics = defaultDynamics; } RssCheck::~RssCheck() = default; const ::ad_rss::world::RssDynamics &RssCheck::getEgoVehicleDynamics() const { return *_egoVehicleDynamics; } void RssCheck::setEgoVehicleDynamics(const ::ad_rss::world::RssDynamics &dynamics) { *_egoVehicleDynamics = dynamics; } const ::ad_rss::world::RssDynamics &RssCheck::getOtherVehicleDynamics() const { return *_otherVehicleDynamics; } void RssCheck::setOtherVehicleDynamics(const ::ad_rss::world::RssDynamics &dynamics) { *_otherVehicleDynamics = dynamics; } bool RssCheck::checkObjects(cc::Timestamp const & timestamp, cc::World &world, carla::SharedPtr<cc::ActorList> const & vehicles, carla::SharedPtr<cc::Actor> const & carlaEgoActor, carla::SharedPtr<cc::Map> const & clientMap, ::ad_rss::state::ProperResponse &response, ::ad_rss::world::AccelerationRestriction &accelerationRestriction, ::ad_rss::world::Velocity &rssEgoVelocity, bool visualizeResults) { const auto carlaEgoVehicle = boost::dynamic_pointer_cast<cc::Vehicle>(carlaEgoActor); ::ad_rss::world::WorldModel worldModel; worldModel.timeIndex = timestamp.frame; ::ad_rss::world::Object egoVehicle; ::ad_rss::world::RssDynamics egoDynamics; initVehicle(egoVehicle); initEgoVehicleDynamics(egoDynamics); egoVehicle.objectId = carlaEgoVehicle->GetId(); egoVehicle.objectType = ::ad_rss::world::ObjectType::EgoVehicle; cg::Location egoVehicleLocation = carlaEgoVehicle->GetLocation(); auto egoClientWaypoint = clientMap->GetWaypoint(egoVehicleLocation, false); if (egoClientWaypoint != nullptr) { // ego vehicle is located on a lane marked for driving auto egoWaypointLoc = egoClientWaypoint->GetTransform(); auto egoLaneId = egoClientWaypoint->GetLaneId(); auto egoVelocity = carlaEgoVehicle->GetVelocity(); auto egoVehicleTransform = carlaEgoVehicle->GetTransform(); // calculate driving direction auto yawDiff = calculateAngleDelta(egoWaypointLoc.rotation.yaw, egoVehicleTransform.rotation.yaw); bool drivingInLaneDirection = true; if (std::abs(yawDiff) > 45.f) { drivingInLaneDirection = false; } // calculate road direction bool drivingInRoadDirection = (egoLaneId > 0) ^ drivingInLaneDirection; auto &carlaRoadMap = clientMap->GetMap(); auto egoWaypoint = carlaRoadMap.GetWaypoint(egoVehicleLocation); auto &egoLane = carlaRoadMap.GetLane(*egoWaypoint); auto egoRoad = egoLane.GetRoad(); ::ad_rss::world::RoadArea roadArea; ::ad_rss::world::RoadSegment roadSegment; // generate road area for (auto &laneSection : egoRoad->GetLaneSections()) { for (const auto &pair : laneSection.GetLanes()) { const auto &lane = pair.second; if ((static_cast<uint32_t>(lane.GetType()) & static_cast<uint32_t>(carla::road::Lane::LaneType::Driving)) > 0) { ::ad_rss::world::LaneSegment laneSegment; // assumption: only one segment per road auto laneLength = lane.GetLength(); // evaluate width at lane start double pos = laneSection.GetDistance(); const auto lane_width_info = lane.GetInfo<carla::road::element::RoadInfoLaneWidth>(pos); double laneWidth = 0.0; if (lane_width_info != nullptr) { laneWidth = lane_width_info->GetPolynomial().Evaluate(pos); } convertAndSetLaneSegmentId(lane, laneSegment); if ((lane.GetId() < 0) ^ drivingInRoadDirection) { laneSegment.drivingDirection = ::ad_rss::world::LaneDrivingDirection::Negative; } else { laneSegment.drivingDirection = ::ad_rss::world::LaneDrivingDirection::Positive; } // lane segment is assumed to be strait and evenly wide, so minimum // and maximum length and width are set to the same values laneSegment.length.minimum = ::ad_rss::physics::Distance(laneLength); laneSegment.length.maximum = laneSegment.length.minimum; laneSegment.width.minimum = ::ad_rss::physics::Distance(laneWidth); laneSegment.width.maximum = laneSegment.width.minimum; roadSegment.push_back(laneSegment); } } std::sort( roadSegment.begin(), roadSegment.end(), [&drivingInRoadDirection](::ad_rss::world::LaneSegment const &f, ::ad_rss::world::LaneSegment const &s) { return (f.id <= s.id) ^ drivingInRoadDirection; }); roadArea.push_back(roadSegment); } calculateLatLonVelocities(egoWaypointLoc, egoVelocity, egoVehicle, !drivingInLaneDirection); rssEgoVelocity = egoVehicle.velocity; auto egoBounds = getVehicleBounds(*carlaEgoVehicle); calculateOccupiedRegions(egoBounds, egoVehicle.occupiedRegions, carlaRoadMap, drivingInRoadDirection, egoVehicleTransform); for (const auto &actor : *vehicles) { const auto vehicle = boost::dynamic_pointer_cast<cc::Vehicle>(actor); if (vehicle == nullptr) { continue; } if (vehicle->GetId() == carlaEgoVehicle->GetId()) { continue; } ::ad_rss::world::Object otherVehicle; ::ad_rss::world::RssDynamics otherDynamics; initVehicle(otherVehicle); initOtherVehicleDynamics(otherDynamics); otherVehicle.objectId = vehicle->GetId(); otherVehicle.objectType = ::ad_rss::world::ObjectType::OtherVehicle; auto otherVehicleLoc = vehicle->GetLocation(); auto otherVehicleClientWaypoint = clientMap->GetWaypoint(otherVehicleLoc); // same road if (egoClientWaypoint->GetRoadId() == otherVehicleClientWaypoint->GetRoadId()) { auto otherVehicleTransform = vehicle->GetTransform(); auto otherBounds = getVehicleBounds(*vehicle); auto otherWaypointLoc = otherVehicleClientWaypoint->GetTransform(); auto otherVelocity = vehicle->GetVelocity(); calculateLatLonVelocities(otherWaypointLoc, otherVelocity, otherVehicle, false); ::ad_rss::world::Scene scene; calculateOccupiedRegions(otherBounds, otherVehicle.occupiedRegions, carlaRoadMap, drivingInRoadDirection, otherVehicleTransform); auto vehicleDirectionDiff = calculateAngleDelta(otherVehicleTransform.rotation.yaw, egoVehicleTransform.rotation.yaw); bool drivingInSameDirection = true; if (std::abs(vehicleDirectionDiff) > 90.f) { drivingInSameDirection = false; } if (drivingInSameDirection) { scene.situationType = ad_rss::situation::SituationType::SameDirection; } else { scene.situationType = ad_rss::situation::SituationType::OppositeDirection; } scene.object = otherVehicle; scene.objectRssDynamics = otherDynamics; scene.egoVehicle = egoVehicle; scene.egoVehicleRoad = roadArea; worldModel.scenes.push_back(scene); } } worldModel.egoVehicleRssDynamics = egoDynamics; ::ad_rss::situation::SituationSnapshot situationSnapshot; bool result = _rssSituationExtraction->extractSituations(worldModel, situationSnapshot); ::ad_rss::state::RssStateSnapshot stateSnapshot; if (result) { result = _rssSituationChecking->checkSituations(situationSnapshot, stateSnapshot); } if (result) { result = _rssResponseResolving->provideProperResponse(stateSnapshot, response); } if (result) { result = ::ad_rss::core::RssResponseTransformation::transformProperResponse(worldModel, response, accelerationRestriction); } if (result && visualizeResults) { visualizeRssResults(stateSnapshot, egoVehicleLocation, egoVehicleTransform, world); } return result; } return false; } void RssCheck::initVehicle(::ad_rss::world::Object &vehicle) const { vehicle.velocity.speedLon = ::ad_rss::physics::Speed(0.); vehicle.velocity.speedLat = ::ad_rss::physics::Speed(0.); } void RssCheck::initEgoVehicleDynamics(::ad_rss::world::RssDynamics &egoDynamics) const { egoDynamics = getEgoVehicleDynamics(); } void RssCheck::initOtherVehicleDynamics(::ad_rss::world::RssDynamics &dynamics) const { dynamics = getOtherVehicleDynamics(); } void RssCheck::calculateLatLonVelocities(const cg::Transform &laneLocation, const cg::Vector3D &velocity, ::ad_rss::world::Object &rssObject, bool inverseDirection) const { double roadDirSine = std::sin(laneLocation.rotation.yaw * toRadians); double roadDirCosine = std::cos(laneLocation.rotation.yaw * toRadians); double factor = 1.0; if (inverseDirection) { factor = -1.0; } rssObject.velocity.speedLon = ::ad_rss::physics::Speed(std::abs(roadDirCosine * velocity.x + roadDirSine * velocity.y)); rssObject.velocity.speedLat = ::ad_rss::physics::Speed(factor * (-1.0 * roadDirSine * velocity.x + roadDirCosine * velocity.y)); } void RssCheck::convertAndSetLaneSegmentId(const carla::road::Lane &lane, ::ad_rss::world::LaneSegment &laneSegment) const { uint64_t laneSegmentId = calculateLaneSegmentId(lane); laneSegment.id = laneSegmentId; } // return front right, back right, back left, front left bounds std::array<cg::Location, 4u> RssCheck::getVehicleBounds(const cc::Vehicle &vehicle) const { const auto &box = vehicle.GetBoundingBox(); const auto &transform = vehicle.GetTransform(); const auto location = transform.location + box.location; const auto yaw = transform.rotation.yaw * toRadians; const float cosine = std::cos(yaw); const float sine = std::sin(yaw); cg::Location frontExtent{cosine *box.extent.x, sine *box.extent.x, 0.0f}; cg::Location rightExtent{-sine * box.extent.y, cosine *box.extent.y, 0.0f}; return {location + frontExtent + rightExtent, location - frontExtent + rightExtent, location - frontExtent - rightExtent, location + frontExtent - rightExtent}; } uint64_t RssCheck::calculateLaneSegmentId(const carla::road::Lane &lane) const { uint64_t laneSegmentId = lane.GetRoad()->GetId(); laneSegmentId = laneSegmentId << 32; uint32_t sectionAndLane = lane.GetLaneSection()->GetId(); sectionAndLane <<= 16; int16_t laneId = static_cast<int16_t>(lane.GetId()); sectionAndLane |= (0xffff & (laneId + 256)); laneSegmentId |= sectionAndLane; return laneSegmentId; } void RssCheck::calculateOccupiedRegions(const std::array<cg::Location, 4u> &bounds, ::ad_rss::world::OccupiedRegionVector &occupiedRegions, const carla::road::Map &carlaRoadMap, const bool drivingInRoadDirection, const cg::Transform &vehicleTransform) const { bool regionValid = true; for (const auto &bound : bounds) { auto boundWaypoint = carlaRoadMap.GetWaypoint(bound); if (!boundWaypoint.has_value()) { // vehicle not entirely on road --> stop evaluation regionValid = false; break; } auto &lane = carlaRoadMap.GetLane(*boundWaypoint); auto road = lane.GetRoad(); uint64_t laneSegmentId = calculateLaneSegmentId(carlaRoadMap.GetLane(*boundWaypoint)); auto length = road->GetLength(); auto lonPos = boundWaypoint->s; if (!drivingInRoadDirection) { lonPos = length - lonPos; } double lon = std::max(0.0, std::min(lonPos / length, 1.0)); auto waypointLocation = carlaRoadMap.ComputeTransform(*boundWaypoint); double headingSine = std::sin(waypointLocation.rotation.yaw * toRadians); double headingCosine = std::cos(waypointLocation.rotation.yaw * toRadians); auto yawDelta = calculateAngleDelta(waypointLocation.rotation.yaw, vehicleTransform.rotation.yaw); bool inLaneDirection = true; if (std::abs(yawDelta) > 45.f) { inLaneDirection = false; } auto width = carlaRoadMap.GetLaneWidth(*boundWaypoint); double latOffset = (headingSine * (waypointLocation.location.x - bound.x) - headingCosine * (waypointLocation.location.y - bound.y)); if (!inLaneDirection) { latOffset *= -1.0; } double lat = std::max(0.0, std::min(0.5 + latOffset / width, 1.0)); // find or create occupied region auto regionIt = std::find_if( occupiedRegions.begin(), occupiedRegions.end(), [laneSegmentId](const ::ad_rss::world::OccupiedRegion &region) { return region.segmentId == laneSegmentId; }); if (regionIt == occupiedRegions.end()) { ::ad_rss::world::OccupiedRegion newRegion; newRegion.segmentId = laneSegmentId; newRegion.lonRange.minimum = ::ad_rss::physics::ParametricValue(lon); newRegion.lonRange.maximum = newRegion.lonRange.minimum; newRegion.latRange.minimum = ::ad_rss::physics::ParametricValue(lat); newRegion.latRange.maximum = newRegion.latRange.minimum; occupiedRegions.push_back(newRegion); } else { ::ad_rss::physics::ParametricValue const lonParam(lon); ::ad_rss::physics::ParametricValue const latParam(lat); regionIt->lonRange.minimum = std::min(regionIt->lonRange.minimum, lonParam); regionIt->lonRange.maximum = std::max(regionIt->lonRange.maximum, lonParam); regionIt->latRange.minimum = std::min(regionIt->latRange.minimum, latParam); regionIt->latRange.maximum = std::max(regionIt->latRange.maximum, latParam); } } // expand regions if more than one, ordered from right to left ::ad_rss::physics::ParametricValue lonMinParam(1.0); ::ad_rss::physics::ParametricValue lonMaxParam(0.0); for (auto &region : occupiedRegions) { lonMinParam = std::min(lonMinParam, region.lonRange.minimum); lonMaxParam = std::max(lonMaxParam, region.lonRange.maximum); if (region != occupiedRegions.front()) { // not the most right one, so extend lat maximum region.latRange.maximum = ::ad_rss::physics::ParametricValue(1.0); } if (region != occupiedRegions.back()) { // not the most left one, so extend lat minimum region.latRange.minimum = ::ad_rss::physics::ParametricValue(0.0); } } for (auto &region : occupiedRegions) { region.lonRange.minimum = lonMinParam; region.lonRange.maximum = lonMaxParam; } } void RssCheck::visualizeRssResults(::ad_rss::state::RssStateSnapshot stateSnapshot, const cg::Location &egoVehicleLocation, const cg::Transform &egoVehicleTransform, cc::World &world) const { cc::DebugHelper dh = world.MakeDebugHelper(); for (std::size_t i = 0; i < stateSnapshot.individualResponses.size(); ++i) { ::ad_rss::state::RssState &state = stateSnapshot.individualResponses[i]; carla::rpc::ActorId vehicleId = static_cast<carla::rpc::ActorId>(state.objectId); carla::SharedPtr<cc::ActorList> vehicleList = world.GetActors(std::vector<carla::rpc::ActorId>{vehicleId}); cg::Location egoPoint = egoVehicleLocation; egoPoint.z += 0.05f; const auto yaw = egoVehicleTransform.rotation.yaw; const float cosine = std::cos(yaw * toRadians); const float sine = std::sin(yaw * toRadians); cg::Location lineOffset{-sine * 0.1f, cosine * 0.1f, 0.0f}; for (const auto &actor : *vehicleList) { const auto vehicle = boost::dynamic_pointer_cast<cc::Vehicle>(actor); cg::Location point = vehicle->GetLocation(); point.z += 0.05f; csd::Color lonColor{0u, 255u, 0u}; csd::Color latLColor = lonColor; csd::Color latRColor = lonColor; csd::Color indicatorColor = lonColor; bool dangerous = ::ad_rss::state::isDangerous(state); if (dangerous) { indicatorColor = csd::Color{255u, 0u, 0u}; } if (!state.longitudinalState.isSafe) { lonColor.r = 255u; if (dangerous) { lonColor.g = 0u; } else { lonColor.g = 255u; } } if (!state.lateralStateLeft.isSafe) { latLColor.r = 255u; if (dangerous) { latLColor.g = 0u; } else { latLColor.g = 255u; } } if (!state.lateralStateRight.isSafe) { latRColor.r = 255u; if (dangerous) { latRColor.g = 0u; } else { latRColor.g = 255u; } } dh.DrawLine(egoPoint, point, 0.1f, lonColor, 0.02f, false); dh.DrawLine(egoPoint - lineOffset, point - lineOffset, 0.1f, latLColor, 0.02f, false); dh.DrawLine(egoPoint + lineOffset, point + lineOffset, 0.1f, latRColor, 0.02f, false); point.z += 3.f; dh.DrawPoint(point, 0.2f, indicatorColor, 0.02f, false); } } } } // namespace rss } // namespace carla
41.04721
115
0.672261
ea88234b0e97b18027441b56582f5a64b831d84b
295
cpp
C++
CPP files/win.cpp
jjang32/RPS
2ce861f461f440ac9fadfbb7a1d3676d3c8a9f42
[ "MIT" ]
null
null
null
CPP files/win.cpp
jjang32/RPS
2ce861f461f440ac9fadfbb7a1d3676d3c8a9f42
[ "MIT" ]
null
null
null
CPP files/win.cpp
jjang32/RPS
2ce861f461f440ac9fadfbb7a1d3676d3c8a9f42
[ "MIT" ]
null
null
null
#include "win.h" #include "ui_win.h" #include "mainwindow.h" Win::Win(QWidget *parent) : QDialog(parent), ui(new Ui::Win) { ui->setupUi(this); } Win::~Win() { delete ui; } void Win::on_retry_clicked() { MainWindow *mainwindow = new MainWindow(); mainwindow->show(); }
13.409091
46
0.616949
ea88af00d49222b327902c88695f517acf477c1c
956
cpp
C++
SDIDoc.cpp
chrisoldwood/WCL
608a83f9e41f4c1d2a7ac6991abbcf264d5924e0
[ "MIT" ]
5
2017-10-02T04:10:35.000Z
2021-07-26T04:45:35.000Z
SDIDoc.cpp
chrisoldwood/WCL
608a83f9e41f4c1d2a7ac6991abbcf264d5924e0
[ "MIT" ]
null
null
null
SDIDoc.cpp
chrisoldwood/WCL
608a83f9e41f4c1d2a7ac6991abbcf264d5924e0
[ "MIT" ]
null
null
null
/****************************************************************************** ** (C) Chris Oldwood ** ** MODULE: SDIDOC.CPP ** COMPONENT: Windows C++ Library. ** DESCRIPTION: CSDIDoc class definition. ** ******************************************************************************* */ #include "Common.hpp" #include "SDIDoc.hpp" /****************************************************************************** ** Method: Constructor. ** ** Description: . ** ** Parameters: None. ** ** Returns: Nothing. ** ******************************************************************************* */ CSDIDoc::CSDIDoc() : m_pView(nullptr) { } /****************************************************************************** ** Method: Destructor. ** ** Description: . ** ** Parameters: None. ** ** Returns: Nothing. ** ******************************************************************************* */ CSDIDoc::~CSDIDoc() { ASSERT(m_pView == nullptr); }
20.340426
79
0.303347
ea8d52382b0b5936a612770af237ad24a8b2b2be
8,899
cpp
C++
src/dpp/dispatcher.cpp
luizstudios/DPP
ea546cd10a06a23b62d1667c26a909cd59ca6100
[ "Apache-2.0" ]
null
null
null
src/dpp/dispatcher.cpp
luizstudios/DPP
ea546cd10a06a23b62d1667c26a909cd59ca6100
[ "Apache-2.0" ]
null
null
null
src/dpp/dispatcher.cpp
luizstudios/DPP
ea546cd10a06a23b62d1667c26a909cd59ca6100
[ "Apache-2.0" ]
1
2021-09-26T18:36:18.000Z
2021-09-26T18:36:18.000Z
/************************************************************************************ * * D++, A Lightweight C++ library for Discord * * Copyright 2021 Craig Edwards and D++ contributors * (https://github.com/brainboxdotcc/DPP/graphs/contributors) * * 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 <dpp/discord.h> #include <dpp/slashcommand.h> #include <dpp/dispatcher.h> #include <dpp/cluster.h> #include <dpp/fmt/format.h> #include <variant> namespace dpp { event_dispatch_t::event_dispatch_t(discord_client* client, const std::string &raw) : from(client), raw_event(raw) { } guild_join_request_delete_t::guild_join_request_delete_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw) { } stage_instance_create_t::stage_instance_create_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw) { } stage_instance_delete_t::stage_instance_delete_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw) { } log_t::log_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw) { } voice_state_update_t::voice_state_update_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw) { } interaction_create_t::interaction_create_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw) { } void interaction_create_t::reply(interaction_response_type t, const message & m) const { from->creator->interaction_response_create(this->command.id, this->command.token, dpp::interaction_response(t, m)); } void interaction_create_t::reply(interaction_response_type t, const std::string & mt) const { this->reply(t, dpp::message(this->command.channel_id, mt, mt_application_command)); } const command_value& interaction_create_t::get_parameter(const std::string& name) const { /* Dummy STATIC return value for unknown options so we arent returning a value off the stack */ static command_value dummy_value = {}; const command_interaction& ci = std::get<command_interaction>(command.data); for (auto i = ci.options.begin(); i != ci.options.end(); ++i) { if (i->name == name) { return i->value; } } return dummy_value; } button_click_t::button_click_t(discord_client* client, const std::string &raw) : interaction_create_t(client, raw) { } const command_value& button_click_t::get_parameter(const std::string& name) const { /* Buttons don't have parameters, so override this */ static command_value dummy_b_value = {}; return dummy_b_value; } guild_delete_t::guild_delete_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw) { } channel_delete_t::channel_delete_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw) { } channel_update_t::channel_update_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw) { } ready_t::ready_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw) { } message_delete_t::message_delete_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw) { } application_command_delete_t::application_command_delete_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw) { } application_command_create_t::application_command_create_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw) { } resumed_t::resumed_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw) { } guild_role_create_t::guild_role_create_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw) { } typing_start_t::typing_start_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw) { } message_reaction_add_t::message_reaction_add_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw) { } message_reaction_remove_t::message_reaction_remove_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw) { } guild_create_t::guild_create_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw) { } channel_create_t::channel_create_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw) { } message_reaction_remove_emoji_t::message_reaction_remove_emoji_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw) { } message_delete_bulk_t::message_delete_bulk_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw) { } guild_role_update_t::guild_role_update_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw) { } guild_role_delete_t::guild_role_delete_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw) { } channel_pins_update_t::channel_pins_update_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw) { } message_reaction_remove_all_t::message_reaction_remove_all_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw) { } voice_server_update_t::voice_server_update_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw) { } guild_emojis_update_t::guild_emojis_update_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw) { } presence_update_t::presence_update_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw) { } webhooks_update_t::webhooks_update_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw) { } guild_member_add_t::guild_member_add_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw) { } invite_delete_t::invite_delete_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw) { } guild_update_t::guild_update_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw) { } guild_integrations_update_t::guild_integrations_update_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw) { } guild_member_update_t::guild_member_update_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw) { } application_command_update_t::application_command_update_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw) { } invite_create_t::invite_create_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw) { } message_update_t::message_update_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw) { } user_update_t::user_update_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw) { } message_create_t::message_create_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw) { } guild_ban_add_t::guild_ban_add_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw) { } guild_ban_remove_t::guild_ban_remove_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw) { } integration_create_t::integration_create_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw) { } integration_update_t::integration_update_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw) { } integration_delete_t::integration_delete_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw) { } guild_member_remove_t::guild_member_remove_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw) { } guild_members_chunk_t::guild_members_chunk_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw) { } voice_buffer_send_t::voice_buffer_send_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw) { } voice_user_talking_t::voice_user_talking_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw) { } voice_ready_t::voice_ready_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw) { } voice_receive_t::voice_receive_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw) { } voice_track_marker_t::voice_track_marker_t(discord_client* client, const std::string &raw) : event_dispatch_t(client, raw) { } };
32.126354
144
0.766041
ea8e774c6d9ee684545b00450bf4bca5662de336
2,010
hpp
C++
include/vcd/test/header.hpp
qedalab/vcd_assert
40da307e60600fc4a814d4bba4679001f49f4375
[ "BSD-2-Clause" ]
1
2019-04-30T17:56:23.000Z
2019-04-30T17:56:23.000Z
include/vcd/test/header.hpp
qedalab/vcd_assert
40da307e60600fc4a814d4bba4679001f49f4375
[ "BSD-2-Clause" ]
null
null
null
include/vcd/test/header.hpp
qedalab/vcd_assert
40da307e60600fc4a814d4bba4679001f49f4375
[ "BSD-2-Clause" ]
4
2018-08-01T08:32:00.000Z
2019-12-18T06:34:33.000Z
// ============================================================================ // Copyright 2018 Paul le Roux and Calvin Maree // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // ============================================================================ #ifndef LIBVCD_TEST_HEADER_HPP #define LIBVCD_TEST_HEADER_HPP #include "./scope.hpp" #include "vcd/types/enums.hpp" #include "vcd/types/header_reader.hpp" namespace VCD::Test { struct TestHeader { std::optional<VCD::TimeScale> time_scale; std::optional<std::string> date; std::optional<std::string> version; std::optional<TestScope> root_scope; }; void read_in_test_header(VCD::HeaderReader &reader, TestHeader &test); } // namespace VCD::Test #endif // LIBVCD_TEST_HEADER_HPP
40.2
79
0.706965
ea8f7fce46d40f6ac8156642a026a6bcefcc8d04
1,686
cpp
C++
server.cpp
cadet-007/Mytorrent-basic-peer2peer-file-sharing-system
b5c29b8fc9e58d6fd1d0485f5d50055f396e9686
[ "Apache-2.0" ]
null
null
null
server.cpp
cadet-007/Mytorrent-basic-peer2peer-file-sharing-system
b5c29b8fc9e58d6fd1d0485f5d50055f396e9686
[ "Apache-2.0" ]
null
null
null
server.cpp
cadet-007/Mytorrent-basic-peer2peer-file-sharing-system
b5c29b8fc9e58d6fd1d0485f5d50055f396e9686
[ "Apache-2.0" ]
null
null
null
#include<iostream> #include<stdio.h> #include<stdlib.h> #include<string.h> #include<unistd.h> #include<sys/types.h> #include<sys/socket.h> #include<netinet/in.h> using namespace std; void error(const char *msg) { perror(msg); exit(1); } int main(int argc,char *argv[]) { if(argc<2) { cout<<"Port Number missing.Program terminated.\n"; exit(1); } int sockfd,newsockfd,portno,n; char buffer[1024]; struct sockaddr_in serv_addr,cli_addr; socklen_t clilen; sockfd=socket(AF_INET,SOCK_STREAM,0); if(sockfd<0) { error("ERROR opening Socket"); } bzero((char*) &serv_addr,sizeof(serv_addr)); portno=atoi(argv[1]); serv_addr.sin_family=AF_INET; serv_addr.sin_addr.s_addr=INADDR_ANY; serv_addr.sin_port=htons(portno); if(bind(sockfd,(struct sockaddr*) &serv_addr,sizeof(serv_addr))<0) error("Binding Failed."); listen(sockfd,5); clilen=sizeof(cli_addr); newsockfd=accept(sockfd,(struct sockaddr*) &cli_addr,&clilen); if(newsockfd<0) error("ERROR on Accept"); while(1) { bzero(buffer,1024); n=read(newsockfd,buffer,1024); if(n<0) error("ERROR on Reading."); cout<<"Client: "<<buffer<<endl; bzero(buffer,1024); cin.getline(buffer,1024); n=write(newsockfd,buffer,strlen(buffer)); if(n<0) error("ERROR on Writing."); int i=strncmp("Bye",buffer,3); if(i==0) break; } close(newsockfd); close(sockfd); return 0; }
20.814815
70
0.565243
ea942c5357bd877b134b4d92e147782588e3f3c6
5,051
cpp
C++
source/smeardeformer/SmearHistory.cpp
youdiaozi/c4d-nr-toolbox
ca6c5f737c901e2f74aeb0bc7aa477387d1a5cd6
[ "BSD-3-Clause" ]
16
2018-09-12T10:38:26.000Z
2021-06-28T22:57:30.000Z
source/smeardeformer/SmearHistory.cpp
youdiaozi/c4d-nr-toolbox
ca6c5f737c901e2f74aeb0bc7aa477387d1a5cd6
[ "BSD-3-Clause" ]
10
2018-09-11T17:20:09.000Z
2020-06-02T04:11:01.000Z
source/smeardeformer/SmearHistory.cpp
NiklasRosenstein/c4d-nr-toolbox
28197ea7fcf396b5941277b049168d7faf00bfbf
[ "BSD-3-Clause" ]
6
2018-11-30T23:34:49.000Z
2021-04-02T15:03:23.000Z
/** * Copyright (C) 2013, Niklas Rosenstein * All rights reserved. * * SmearHistory.cpp */ #include "SmearHistory.h" #include "nrUtils/Memory.h" #include "nrUtils/Normals.h" using namespace nr::memory; Bool SmearState::Resize(Int32 count) { Bool success = true; success = success && Realloc<Vector>(original_vertices, count); success = success && Realloc<Vector>(original_normals, count); success = success && Realloc<Vector>(deformed_vertices, count); success = success && Realloc<Vector>(deformed_normals, count); success = success && Realloc<Float32>(weights, count); vertex_count = count; initialized = success; return success; } void SmearState::Flush() { Free(original_vertices); Free(original_normals); Free(deformed_vertices); Free(deformed_normals); vertex_count = 0; initialized = false; } SmearSession* SmearHistory::NewSession(Int32 max_history_count, Bool fake_session) { if (max_history_count < 1) max_history_count = 1; m_level_override = -1; SmearState state; SmearState* ptr = nullptr; if (!fake_session || GetHistoryCount() <= 0) { fake_session = false; // Remove all superfluos history elements. One item is implicit. while (m_states.GetCount() > max_history_count) { if (state.initialized) state.Flush(); m_states.Pop(&state); } iferr (auto&& r = m_states.Insert(0, std::move(state))) return nullptr; ptr = &r; } else { m_level_override = max_history_count + 1; ptr = &m_states[0]; } if (ptr) { return NewObjClear(SmearSession, this, ptr, fake_session); } return nullptr; // memory error } SmearHistory::~SmearHistory() { Reset(); } void SmearHistory::FreeSession(SmearSession*& session) { // If the session was not updated (ie. all data is stored // successfully), we remove the state which has been created for // that sessions. if (!session->IsUpToDate()) { GePrint(String(__FUNCTION__) + ": Smear state is not up to date."); m_states.Pop(0); } DeleteMem(session); session = nullptr; } Int32 SmearHistory::GetHistoryCount() const { Int32 count = m_states.GetCount(); if (m_level_override > 0 && count > m_level_override) { count = m_level_override + 1; } return count; } const SmearState* SmearHistory::GetState(Int32 index) const { if (index < 0 || index >= GetHistoryCount()) { return nullptr; } if (m_level_override > 0 && index >= m_level_override) { return nullptr; } if (!m_enabled && index != 0) { return nullptr; } return &m_states[index]; } void SmearHistory::Reset() { StateArray::Iterator it = m_states.Begin(); for (; it != m_states.End(); it++) { it->Flush(); } m_states.Flush(); } SmearSession::SmearSession(SmearHistory* history, SmearState* state, Bool fake) : m_state(state), m_created(false), m_updated(false), m_vertices(nullptr), m_vertex_count(0), m_faces(nullptr), m_face_count(0), m_fake(fake) { } SmearSession::~SmearSession() { } Bool SmearSession::CreateState( const Matrix& mg, const Vector* vertices, Int32 vertex_count, const CPolygon* faces, Int32 face_count) { if (m_created) { return false; } m_vertices = vertices; m_vertex_count = vertex_count; m_faces = faces; m_face_count = face_count; if (!m_fake) { m_state->mg = mg; if (!m_state->Resize(vertex_count)) { return false; } // Copy the vertices to the storage in the SmearState. for (Int32 i=0; i < vertex_count; i++) { m_state->original_vertices[i] = m_state->mg * vertices[i]; } // And compute the vertex normals. These are independent from // the global position of the vertices as long as their relations // are the same. if (!nr::ComputeVertexNormals( m_vertices, m_vertex_count, m_faces, m_face_count, m_state->original_normals)) { return false; } } m_created = true; return true; } Bool SmearSession::DeformationComplete(const Matrix& mg) { if (!m_created || m_updated) { GePrint(String(__FUNCTION__) + ": Not yet created or already updated."); return false; } // m_state->mg = mg; // Copy the vertices to the deformed storage in the SmearState // using the pointers passed to `CreateState()`. for (Int32 i=0; i < m_vertex_count; i++) { m_state->deformed_vertices[i] = /* m_state-> */ mg * m_vertices[i]; } // And calculate the vertex normals of the deformed points. if (!nr::ComputeVertexNormals( m_vertices, m_vertex_count, m_faces, m_face_count, m_state->deformed_normals)) { GePrint(String(__FUNCTION__) + ": Vertex normals not calculated."); return false; } m_updated = true; return true; }
27.302703
84
0.627005
ea95e1ac0c66d504220f720ff6bdbb4f53d8f4e0
1,290
cpp
C++
DFS/RangeSumBST.cpp
karan2808/Cpp
595f536e33505c5fd079b709d6370bf888043fb3
[ "MIT" ]
1
2021-01-31T03:43:59.000Z
2021-01-31T03:43:59.000Z
DFS/RangeSumBST.cpp
karan2808/Cpp
595f536e33505c5fd079b709d6370bf888043fb3
[ "MIT" ]
null
null
null
DFS/RangeSumBST.cpp
karan2808/Cpp
595f536e33505c5fd079b709d6370bf888043fb3
[ "MIT" ]
1
2021-01-25T14:27:08.000Z
2021-01-25T14:27:08.000Z
#include <iostream> using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode() { val = 0; left = nullptr; right = nullptr; } TreeNode(int x) { val = x; left = nullptr; right = nullptr; } TreeNode(int x, TreeNode *left, TreeNode *right) { val = x; this->left = left; this->right = right; } }; class Solution { public: int rangeSumBST(TreeNode *root, int low, int high) { if (!root) return 0; int sum = 0; // if the root value is within range, set sum to root value if (root->val >= low && root->val <= high) sum = root->val; // add sum of left side and right side to the current sum sum += rangeSumBST(root->left, low, high); sum += rangeSumBST(root->right, low, high); return sum; } }; int main() { Solution mySol; TreeNode *root = new TreeNode(10, new TreeNode(5), new TreeNode(15)); root->left->left = new TreeNode(3); root->left->right = new TreeNode(7); root->right->right = new TreeNode(18); cout << "The range sum of the BST between 7 and 15: " << mySol.rangeSumBST(root, 7, 15) << endl; return 0; }
22.631579
100
0.542636
ea9635dcef6773bb10aa9d56672b48364e959e6e
939
cpp
C++
old/src/riscv/Value.cpp
ClasSun9/riscv-dynamic-taint-analysis
8a96f5ea8d07580315253dc074f60955fc633da9
[ "MIT" ]
null
null
null
old/src/riscv/Value.cpp
ClasSun9/riscv-dynamic-taint-analysis
8a96f5ea8d07580315253dc074f60955fc633da9
[ "MIT" ]
null
null
null
old/src/riscv/Value.cpp
ClasSun9/riscv-dynamic-taint-analysis
8a96f5ea8d07580315253dc074f60955fc633da9
[ "MIT" ]
null
null
null
# include "Value.hpp" namespace riscv { int8_t SignedValue::As8() { return static_cast<int8_t>(_value); } int16_t SignedValue::As16() { return static_cast<int16_t>(_value); } int32_t SignedValue::As32() { return static_cast<int32_t>(_value); } int64_t SignedValue::As64() { return _value; } SignedValue::SignedValue(int64_t value) : _value(value) { } uint8_t UnsignedValue::As8() { return static_cast<uint8_t>(_value); } uint16_t UnsignedValue::As16() { return static_cast<uint16_t>(_value); } uint32_t UnsignedValue::As32() { return static_cast<uint32_t>(_value); } uint64_t UnsignedValue::As64() { return _value; } UnsignedValue::UnsignedValue(uint64_t value) : _value(value) { } SignedValue Value::AsSigned() { return SignedValue(static_cast<int64_t>(_value)); } UnsignedValue Value::AsUnsigned() { return UnsignedValue(_value); } Value::Value(uint64_t value) : _value(value) { } }
18.411765
64
0.7082
ea9ade0c56314e1bfda94a363688fb429a691edd
10,578
cc
C++
centreon-engine/src/configuration/hostextinfo.cc
centreon/centreon-collect
e63fc4d888a120d588a93169e7d36b360616bdee
[ "Unlicense" ]
8
2020-07-26T09:12:02.000Z
2022-03-30T17:24:29.000Z
centreon-engine/src/configuration/hostextinfo.cc
centreon/centreon-collect
e63fc4d888a120d588a93169e7d36b360616bdee
[ "Unlicense" ]
47
2020-06-18T12:11:37.000Z
2022-03-16T10:28:56.000Z
centreon-engine/src/configuration/hostextinfo.cc
centreon/centreon-collect
e63fc4d888a120d588a93169e7d36b360616bdee
[ "Unlicense" ]
5
2020-06-29T14:22:02.000Z
2022-03-17T10:34:10.000Z
/* ** Copyright 2011-2013 Merethis ** ** This file is part of Centreon Engine. ** ** Centreon Engine is free software: you can redistribute it and/or ** modify it under the terms of the GNU General Public License version 2 ** as published by the Free Software Foundation. ** ** Centreon Engine 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 Centreon Engine. If not, see ** <http://www.gnu.org/licenses/>. */ #include "com/centreon/engine/configuration/hostextinfo.hh" #include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/string.hh" using namespace com::centreon; using namespace com::centreon::engine::configuration; #define SETTER(type, method) \ &object::setter<hostextinfo, type, &hostextinfo::method>::generic std::unordered_map<std::string, hostextinfo::setter_func> const hostextinfo::_setters{ {"host_name", SETTER(std::string const&, _set_hosts)}, {"hostgroup", SETTER(std::string const&, _set_hostgroups)}, {"hostgroup_name", SETTER(std::string const&, _set_hostgroups)}, {"notes", SETTER(std::string const&, _set_notes)}, {"notes_url", SETTER(std::string const&, _set_notes_url)}, {"action_url", SETTER(std::string const&, _set_action_url)}, {"icon_image", SETTER(std::string const&, _set_icon_image)}, {"icon_image_alt", SETTER(std::string const&, _set_icon_image_alt)}, {"vrml_image", SETTER(std::string const&, _set_vrml_image)}, {"gd2_image", SETTER(std::string const&, _set_statusmap_image)}, {"statusmap_image", SETTER(std::string const&, _set_statusmap_image)}, {"2d_coords", SETTER(std::string const&, _set_coords_2d)}, {"3d_coords", SETTER(std::string const&, _set_coords_3d)}}; // Default values. static point_2d const default_coords_2d(-1, -1); static point_3d const default_coords_3d(0.0, 0.0, 0.0); /** * Default constructor. */ hostextinfo::hostextinfo() : object(object::hostextinfo), _coords_2d(default_coords_2d), _coords_3d(default_coords_3d) {} /** * Copy constructor. * * @param[in] right The hostextinfo to copy. */ hostextinfo::hostextinfo(hostextinfo const& right) : object(right) { operator=(right); } /** * Destructor. */ hostextinfo::~hostextinfo() throw() {} /** * Copy constructor. * * @param[in] right The hostextinfo to copy. * * @return This hostextinfo. */ hostextinfo& hostextinfo::operator=(hostextinfo const& right) { if (this != &right) { object::operator=(right); _action_url = right._action_url; _coords_2d = right._coords_2d; _coords_3d = right._coords_3d; _hostgroups = right._hostgroups; _hosts = right._hosts; _icon_image = right._icon_image; _icon_image_alt = right._icon_image_alt; _notes = right._notes; _notes_url = right._notes_url; _statusmap_image = right._statusmap_image; _vrml_image = right._vrml_image; } return *this; } /** * Equal operator. * * @param[in] right The hostextinfo to compare. * * @return True if is the same hostextinfo, otherwise false. */ bool hostextinfo::operator==(hostextinfo const& right) const throw() { return (object::operator==(right) && _action_url == right._action_url && _coords_2d == right._coords_2d && _coords_3d == right._coords_3d && _hostgroups == right._hostgroups && _hosts == right._hosts && _icon_image == right._icon_image && _icon_image_alt == right._icon_image_alt && _notes == right._notes && _notes_url == right._notes_url && _statusmap_image == right._statusmap_image && _vrml_image == right._vrml_image); } /** * Equal operator. * * @param[in] right The hostextinfo to compare. * * @return True if is not the same hostextinfo, otherwise false. */ bool hostextinfo::operator!=(hostextinfo const& right) const throw() { return !operator==(right); } /** * @brief Check if the object is valid. * * If the object is not valid, an exception is thrown. */ void hostextinfo::check_validity() const { if (_hostgroups->empty() && _hosts->empty()) throw(engine_error() << "Host extended information is not attached" << " to any host or host group (properties 'host_name' or " << "'hostgroup_name', respectively)"); return; } /** * Merge object. * * @param[in] obj The object to merge. */ void hostextinfo::merge(object const& obj) { if (obj.type() != _type) throw(engine_error() << "Cannot merge host extended information with '" << obj.type() << "'"); hostextinfo const& tmpl(static_cast<hostextinfo const&>(obj)); MRG_DEFAULT(_action_url); MRG_OPTION(_coords_2d); MRG_OPTION(_coords_3d); MRG_INHERIT(_hostgroups); MRG_INHERIT(_hosts); MRG_DEFAULT(_icon_image); MRG_DEFAULT(_icon_image_alt); MRG_DEFAULT(_notes); MRG_DEFAULT(_notes_url); MRG_DEFAULT(_statusmap_image); MRG_DEFAULT(_vrml_image); } /** * Parse and set the hostextinfo property. * * @param[in] key The property name. * @param[in] value The property value. * * @return True on success, otherwise false. */ bool hostextinfo::parse(char const* key, char const* value) { std::unordered_map<std::string, hostextinfo::setter_func>::const_iterator it{ _setters.find(key)}; if (it != _setters.end()) return (it->second)(*this, value); return false; } /** * Get action_url. * * @return The action_url. */ std::string const& hostextinfo::action_url() const throw() { return _action_url; } /** * Get coords_2d. * * @return The coords_2d. */ point_2d const& hostextinfo::coords_2d() const throw() { return _coords_2d.get(); } /** * Get 3d_coords. * * @return The 3d_coords. */ point_3d const& hostextinfo::coords_3d() const throw() { return _coords_3d.get(); } /** * Get hostgroups. * * @return The hostgroups. */ set_string const& hostextinfo::hostgroups() const throw() { return *_hostgroups; } /** * Get hosts. * * @return The hosts. */ set_string const& hostextinfo::hosts() const throw() { return *_hosts; } /** * Get icon_image. * * @return The icon_image. */ std::string const& hostextinfo::icon_image() const throw() { return _icon_image; } /** * Get icon_image_alt. * * @return The icon_image_alt. */ std::string const& hostextinfo::icon_image_alt() const throw() { return _icon_image_alt; } /** * Get notes. * * @return The notes. */ std::string const& hostextinfo::notes() const throw() { return _notes; } /** * Get notes_url. * * @return The notes_url. */ std::string const& hostextinfo::notes_url() const throw() { return _notes_url; } /** * Get statusmap_image. * * @return The statusmap_image. */ std::string const& hostextinfo::statusmap_image() const throw() { return _statusmap_image; } /** * Get vrml_image. * * @return The vrml_image. */ std::string const& hostextinfo::vrml_image() const throw() { return _vrml_image; } /** * Set action_url value. * * @param[in] value The new action_url value. * * @return True on success, otherwise false. */ bool hostextinfo::_set_action_url(std::string const& value) { _action_url = value; return true; } /** * Set coords_2s value. * * @param[in] value The new coords_2d value. * * @return True on success, otherwise false. */ bool hostextinfo::_set_coords_2d(std::string const& value) { std::list<std::string> coords; string::split(value, coords, ','); if (coords.size() != 2) return false; int x; if (!string::to(string::trim(coords.front()).c_str(), x)) return false; coords.pop_front(); int y; if (!string::to(string::trim(coords.front()).c_str(), y)) return false; _coords_2d = point_2d(x, y); return true; } /** * Set coords_3d value. * * @param[in] value The new coords_3d value. * * @return True on success, otherwise false. */ bool hostextinfo::_set_coords_3d(std::string const& value) { std::list<std::string> coords; string::split(value, coords, ','); if (coords.size() != 3) return false; double x; if (!string::to(string::trim(coords.front()).c_str(), x)) return false; coords.pop_front(); double y; if (!string::to(string::trim(coords.front()).c_str(), y)) return false; coords.pop_front(); double z; if (!string::to(string::trim(coords.front()).c_str(), z)) return false; _coords_3d = point_3d(x, y, z); return true; } /** * Set hostgroups value. * * @param[in] value The new hostgroups value. * * @return True on success, otherwise false. */ bool hostextinfo::_set_hostgroups(std::string const& value) { _hostgroups = value; return true; } /** * Set hosts value. * * @param[in] value The new hosts value. * * @return True on success, otherwise false. */ bool hostextinfo::_set_hosts(std::string const& value) { _hosts = value; return true; } /** * Set icon_image value. * * @param[in] value The new icon_image value. * * @return True on success, otherwise false. */ bool hostextinfo::_set_icon_image(std::string const& value) { _icon_image = value; return true; } /** * Set icon_image_alt value. * * @param[in] value The new icon_image_alt value. * * @return True on success, otherwise false. */ bool hostextinfo::_set_icon_image_alt(std::string const& value) { _icon_image_alt = value; return true; } /** * Set notes value. * * @param[in] value The new notes value. * * @return True on success, otherwise false. */ bool hostextinfo::_set_notes(std::string const& value) { _notes = value; return true; } /** * Set notes_url value. * * @param[in] value The new notes_url value. * * @return True on success, otherwise false. */ bool hostextinfo::_set_notes_url(std::string const& value) { _notes_url = value; return true; } /** * Set statusmap_image value. * * @param[in] value The new statusmap_image value. * * @return True on success, otherwise false. */ bool hostextinfo::_set_statusmap_image(std::string const& value) { _statusmap_image = value; return true; } /** * Set vrml_image value. * * @param[in] value The new vrml_image value. * * @return True on success, otherwise false. */ bool hostextinfo::_set_vrml_image(std::string const& value) { _vrml_image = value; return true; }
23.878104
79
0.668179
ea9d4310af354771c1c8338250f75c367b6b6e32
33,490
hpp
C++
include/lfd/GenericDescriptor.hpp
waterben/LineExtraction
d247de45417a1512a3bf5d0ffcd630d40ffb8798
[ "MIT" ]
1
2020-06-12T13:30:56.000Z
2020-06-12T13:30:56.000Z
include/lfd/GenericDescriptor.hpp
waterben/LineExtraction
d247de45417a1512a3bf5d0ffcd630d40ffb8798
[ "MIT" ]
null
null
null
include/lfd/GenericDescriptor.hpp
waterben/LineExtraction
d247de45417a1512a3bf5d0ffcd630d40ffb8798
[ "MIT" ]
null
null
null
/*M/////////////////////////////////////////////////////////////////////////////////////// // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2008-2011, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation 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. // //M*/ // C by Benjamin Wassermann // #ifndef _LFD_GENERICDESCRIPTOR_HPP_ #define _LFD_GENERICDESCRIPTOR_HPP_ #ifdef __cplusplus #include <vector> #include <geometry/line.hpp> #include <utility/mean.hpp> #include <lfd/FeatureDescriptor.hpp> #include <opencv2/imgproc/imgproc.hpp> namespace lsfm { template<class FT> struct RotationAlign { static inline void apply(const Line<FT>& line, const Vec2<FT> &p, Vec2<FT>& ret) { set(ret, line.project(p), line.normalProject(p)); } static inline Vec2<FT> apply(const Line<FT>& line, const Vec2<FT> &p) { return Vec2<FT>(line.project(p),line.normalProject(p)); } }; template<class FT> struct NoAlign { static inline void apply(const Line<FT>& line, const Vec2<FT> &p, Vec2<FT> &ret) { ret = p; } static inline Vec2<FT> apply(const Line<FT>& line, const Vec2<FT> &p) { return p; } }; // Generic Feature Descriptor template<class FT, int cn> struct GenericDescritpor { GenericDescritpor() {} GenericDescritpor(const FT *d) : data() { memcopy(data,d,sizeof(FT) * cn); } FT data[cn]; inline FT distance(const GenericDescritpor<FT,cn>& rhs) const { return static_cast<FT>(norm(cv::_InputArray(data,cn), cv::_InputArray(rhs.data,cn), cv::NORM_L2)); } //! compute distance between two descriptors (static version) static inline FT distance(const GenericDescritpor<FT,cn>& lhs, const GenericDescritpor<FT,cn>& rhs) { return static_cast<FT>(norm(cv::_InputArray(lhs.ata,cn), cv::_InputArray(rhs.data,cn), cv::NORM_L2)); } static inline int size() { return cn; } std::string name() const { return "GENERIC"; } }; // Creator Helper for intensity images using interpolator template<class FT, uint size = 3, uint step = 2, class Interpolator = FastRoundNearestInterpolator<FT, uchar>> struct GchImgInterpolate { static constexpr int numBands = size / step + (size % step ? 1 : 0); static constexpr int dscSize = numBands * 2; static void create(const cv::Mat *data, const LineSegment<FT>& line, FT* dst, FT beg = -1, FT stepDir = 1, FT lstep = 1) { const cv::Mat &img = data[0]; // get line length (floor) uint length = static_cast<uint>(line.length()); if (length < 1) length = 1; // get current line direction cv::Point_<FT> dL = line.direction(); cv::Point_<FT> dN(-dL.y,dL.x); dN *= step * stepDir; dL *= lstep; // coordinates cv::Point_<FT> sCor0, sCor; FT sum, sum2, val; // convert upper left pos in line coords to local coords (rotate + translate) sCor0 = line.line2world(cv::Point_<FT>(-((static_cast<FT>(length) - 1) / 2), static_cast<FT>(beg)), line.centerPoint()); int lineSteps = static_cast<int>(length / lstep); FT norm = static_cast<FT>(1.0 / (lineSteps * numBands)); for (int i = 0; i != numBands; ++i) { sCor = sCor0; sum = 0; sum2 = 0; for (int j = 0; j < lineSteps; ++j) { // access value in mat val = Interpolator::get(img, sCor); //std::cout << sCor << std::endl; sum += val; sum2 += val*val; // next pixel in line dir sCor += dL; } // next row sCor0 += dN; // compute mean dst[0] = val = sum * norm; // compute variance dst[numBands] = std::sqrt(sum2 * norm - val*val); ++dst; } } static std::vector<std::string> inputData() { std::vector<std::string> ret; ret.push_back(std::string("img")); return ret; } }; // Creator Helper for intensity images using interpolator template<class FT, uint size = 3, uint step = 2, class Mean = FastMean<FT, uchar>> struct GchImgMean { static constexpr int numBands = size / step + (size % step ? 1 : 0); static constexpr int dscSize = numBands * 2; static void create(const cv::Mat *data, const LineSegment<FT>& line, FT* dst, FT beg = -1, FT stepDir = 1, FT lstep = 1) { const cv::Mat &img = data[0]; LineSegment<FT> l = line; l.translateOrtho(beg); stepDir *= step; FT norm = static_cast<FT>(1.0 / numBands), variance, mean; for (int i = 0; i != numBands; ++i) { mean = Mean::process(variance, img, l, lstep); // compute mean dst[0] = mean * norm; // compute variance dst[numBands] = std::sqrt(variance * norm); ++dst; // next row l.translateOrtho(stepDir); } } static std::vector<std::string> inputData() { std::vector<std::string> ret; ret.push_back(std::string("img")); return ret; } }; // Creator Helper for intensity images using iterator template<class FT, uint size = 3, uint step = 2, class MT = uchar> struct GchImgIterate { static constexpr int numBands = size / step + (size % step ? 1 : 0); static constexpr int dscSize = numBands * 2; static void create(const cv::Mat *data, const LineSegment<FT>& line, FT* dst, FT beg = -1, FT stepDir = 1, FT lstep = 1) { const cv::Mat &img = data[0]; LineSegment<FT> l = line; l.translateOrtho(beg); cv::Point_<FT> ps, pe; FT sum, sum2, val; for (int i = 0; i != numBands; ++i) { sum = 0; sum2 = 0; ps = l.startPoint(); pe = l.endPoint(); cv::LineIterator it(img, cv::Point(static_cast<int>(std::round(ps.x)),static_cast<int>(std::round(ps.y))), cv::Point(static_cast<int>(std::round(pe.x)),static_cast<int>(std::round(pe.y)))); for (int j = 0; j < it.count; ++j, ++it) { // access value in mat val = img.at<MT>(it.pos()); sum += val; sum2 += val*val; } // next row l.translateOrtho(step * stepDir); // compute mean dst[0] = val = sum / (it.count * numBands); // compute variance dst[numBands] = std::sqrt(sum2 / (it.count * numBands) - val*val); ++dst; } } static std::vector<std::string> inputData() { std::vector<std::string> ret; ret.push_back(std::string("img")); return ret; } }; // Creator Helper for gradient using interpolator template<class FT, uint size = 3, uint step = 2, class Align = RotationAlign<FT>, class Interpolator = FastRoundNearestInterpolator<FT, short>> struct GchGradInterpolate { static constexpr int numBands = size / step + (size % step ? 1 : 0); static constexpr int dscSize = numBands * 8; static void create(const cv::Mat *data, const LineSegment<FT>& line, FT* dst, FT beg = -1, FT stepDir = 1, FT lstep = 1) { const cv::Mat &dx = data[0]; const cv::Mat &dy = data[1]; // get line length (floor) uint length = static_cast<uint>(line.length()); if (length < 1) length = 1; // get current line direction cv::Point_<FT> dL = line.direction(); cv::Point_<FT> dN(-dL.y,dL.x); dN *= step * stepDir; dL *= lstep; // coordinates cv::Point_<FT> sCor0, sCor, val; FT sumXP,sumXN, sumYP, sumYN, sum2XP,sum2XN, sum2YP, sum2YN, tmp; // convert upper left pos in line coords to local coords (rotate + translate) sCor0 = line.line2world(cv::Point_<FT>(-((static_cast<FT>(length) - 1) / 2), static_cast<FT>(beg)), line.centerPoint()); int lineSteps = static_cast<int>(length / lstep); FT norm = static_cast<FT>(1.0 / (lineSteps * numBands)); for (int i = 0; i != numBands; ++i) { sCor = sCor0; sumXP = sumXN = sumYP = sumYN = 0; sum2XP = sum2XN = sum2YP = sum2YN = 0; for (int j = 0; j < lineSteps; ++j) { // access value in grad and do alignment Align::apply(line,cv::Point_<FT>(Interpolator::get(dx, sCor), Interpolator::get(dy, sCor)),val); if (val.x < 0) { sumXN -= val.x; sum2XN += val.x*val.x; } else { sumXP += val.x; sum2XP += val.x*val.x; } if (val.y < 0) { sumYN -= val.y; sum2YN += val.y*val.y; } else { sumYP += val.y; sum2YP += val.y*val.y; } // next pixel in line dir sCor += dL; } // next row sCor0 += dN; // compute mean and compute variance dst[0] = tmp = sumXP * norm; dst[4] = std::sqrt(sum2XP * norm - tmp*tmp); dst[1] = tmp = sumXN * norm; dst[5] = std::sqrt(sum2XN * norm - tmp*tmp); dst[2] = tmp = sumYP * norm; dst[6] = std::sqrt(sum2YP * norm - tmp*tmp); dst[3] = tmp = sumYN * norm; dst[7] = std::sqrt(sum2YN * norm - tmp*tmp); dst += 8; } } static std::vector<std::string> inputData() { std::vector<std::string> ret; ret.push_back(std::string("gx")); ret.push_back(std::string("gy")); return ret; } }; // Creator Helper for intensity images using interator template<class FT, uint size = 3, uint step = 2, class Align = RotationAlign<FT>, class Mean = FastMean<FT, short>> struct GchGradMean { static constexpr int numBands = size / step + (size % step ? 1 : 0); static constexpr int dscSize = numBands * 8; static void create(const cv::Mat *data, const LineSegment<FT>& line, FT* dst, FT beg = -1, FT stepDir = 1, FT lstep = 1) { const cv::Mat &dx = data[0]; const cv::Mat &dy = data[1]; LineSegment<FT> l = line; l.translateOrtho(beg); stepDir *= step; cv::Point_<FT> p; FT sumXP,sumXN, sumYP, sumYN, sum2XP,sum2XN, sum2YP, sum2YN, tmp, norm; std::vector<FT> valX, valY; size_t n; for (int i = 0; i != numBands; ++i) { sumXP = sumXN = sumYP = sumYN = 0; sum2XP = sum2XN = sum2YP = sum2YN = 0; Mean::process(valX,dx,l,lstep); Mean::process(valY,dy,l,lstep); n = valX.size(); for (int j = 0; j < n; ++j) { // access value in grad and do alignment Align::apply(l,cv::Point_<FT>(valX[j],valY[j]),p); if (p.x < 0) { sumXN -= p.x; sum2XN += p.x*p.x; } else { sumXP += p.x; sum2XP += p.x*p.x; } if (p.y < 0) { sumYN -= p.y; sum2YN += p.y*p.y; } else { sumYP += p.y; sum2YP += p.y*p.y; } } // next row l.translateOrtho(stepDir); norm = static_cast<FT>(1) / (n * numBands); // compute mean and compute variance dst[0] = tmp = sumXP * norm; dst[4] = std::sqrt(sum2XP * norm - tmp*tmp); dst[1] = tmp = sumXN * norm; dst[5] = std::sqrt(sum2XN * norm - tmp*tmp); dst[2] = tmp = sumYP * norm; dst[6] = std::sqrt(sum2YP * norm - tmp*tmp); dst[3] = tmp = sumYN * norm; dst[7] = std::sqrt(sum2YN * norm - tmp*tmp); dst += 8; } } static std::vector<std::string> inputData() { std::vector<std::string> ret; ret.push_back(std::string("gx")); ret.push_back(std::string("gy")); return ret; } }; // Creator Helper for intensity images using interator template<class FT, uint size = 3, uint step = 2, class Align = RotationAlign<FT>, class MT = short> struct GchGradIterate { static constexpr int numBands = size / step + (size % step ? 1 : 0); static constexpr int dscSize = numBands * 8; static void create(const cv::Mat *data, const LineSegment<FT>& line, FT* dst, FT beg = -1, FT stepDir = 1, FT lstep = 1) { const cv::Mat &dx = data[0]; const cv::Mat &dy = data[1]; LineSegment<FT> l = line; l.translateOrtho(beg); cv::Point_<FT> ps, pe; FT sumXP,sumXN, sumYP, sumYN, sum2XP,sum2XN, sum2YP, sum2YN, tmp; for (int i = 0; i != numBands; ++i) { sumXP = sumXN = sumYP = sumYN = 0; sum2XP = sum2XN = sum2YP = sum2YN = 0; ps = l.startPoint(); pe = l.endPoint(); cv::LineIterator it(dx, cv::Point(static_cast<int>(std::round(ps.x)),static_cast<int>(std::round(ps.y))), cv::Point(static_cast<int>(std::round(pe.x)),static_cast<int>(std::round(pe.y)))); for (int j = 0; j < it.count; ++j, ++it) { // access value in grad and do alignment Align::apply(l,cv::Point_<FT>(dx.at<MT>(it.pos()),dy.at<MT>(it.pos())),ps); if (ps.x < 0) { sumXN -= ps.x; sum2XN += ps.x*ps.x; } else { sumXP += ps.x; sum2XP += ps.x*ps.x; } if (ps.y < 0) { sumYN -= ps.y; sum2YN += ps.y*ps.y; } else { sumYP += ps.y; sum2YP += ps.y*ps.y; } } // next row l.translateOrtho(step * stepDir); // compute mean and compute variance dst[0] = tmp = sumXP / (it.count * numBands); dst[4] = std::sqrt(sum2XP/(it.count * numBands) - tmp*tmp); dst[1] = tmp = sumXN / (it.count * numBands); dst[5] = std::sqrt(sum2XN/(it.count * numBands) - tmp*tmp); dst[2] = tmp = sumYP / (it.count * numBands); dst[6] = std::sqrt(sum2YP/(it.count * numBands) - tmp*tmp); dst[3] = tmp = sumYN / (it.count * numBands); dst[7] = std::sqrt(sum2YN/(it.count * numBands) - tmp*tmp); dst += 8; } } static std::vector<std::string> inputData() { std::vector<std::string> ret; ret.push_back(std::string("gx")); ret.push_back(std::string("gy")); return ret; } }; // Creator Helper for gradient and image using interpolator template<class FT, uint size = 3, uint step = 2, class Align = RotationAlign<FT>, class InterpolatorG = FastRoundNearestInterpolator<FT, short>, class InterpolatorI = FastRoundNearestInterpolator<FT, uchar>> struct GchGradImgInterpolate { static constexpr int numBands = size / step + (size % step ? 1 : 0); static constexpr int dscSize = numBands * 10; static void create(const cv::Mat *data, const LineSegment<FT>& line, FT* dst, FT beg = -1, FT stepDir = 1, FT lstep = 1) { const cv::Mat &dx = data[0]; const cv::Mat &dy = data[1]; const cv::Mat &img = data[2]; // get line length (floor) uint length = static_cast<uint>(line.length()); if (length < 1) length = 1; // get current line direction Vec2<FT> dL = line.direction(); Vec2<FT> dN(-dL.y(),dL.x()); dN *= step * stepDir; dL *= lstep; // coordinates Vec2<FT> sCor0, sCor, val; FT sumXP,sumXN, sumYP, sumYN, sum2XP,sum2XN, sum2YP, sum2YN, sum, sum2, tmp; // convert upper left pos in line coords to local coords (rotate + translate) sCor0 = line.line2world(Vec2<FT>(-((static_cast<FT>(length) - 1) / 2), static_cast<FT>(beg)), line.centerPoint()); int lineSteps = static_cast<int>(length / lstep); FT norm = static_cast<FT>(1.0 / (lineSteps * numBands)); for (int i = 0; i != numBands; ++i) { sCor = sCor0; sumXP = sumXN = sumYP = sumYN = sum = 0; sum2XP = sum2XN = sum2YP = sum2YN = sum2 = 0; for (int j = 0; j < lineSteps; ++j) { // access value in grad and do alignment Align::apply(line,Vec2<FT>(InterpolatorG::get(dx, sCor), InterpolatorG::get(dy, sCor)),val); if (val.x() < 0) { sumXN -= val.x(); sum2XN += val.x()*val.x(); } else { sumXP += val.x(); sum2XP += val.x()*val.x(); } if (val.y() < 0) { sumYN -= val.y(); sum2YN += val.y()*val.y(); } else { sumYP += val.y(); sum2YP += val.y()*val.y(); } tmp = InterpolatorI::get(img, sCor); sum += tmp; sum2 += tmp * tmp; // next pixel in line dir sCor += dL; } // next row sCor0 += dN; // compute mean and compute variance of grad dst[0] = tmp = sumXP * norm; dst[5] = std::sqrt(sum2XP * norm - tmp*tmp); dst[1] = tmp = sumXN * norm; dst[6] = std::sqrt(sum2XN * norm - tmp*tmp); dst[2] = tmp = sumYP * norm; dst[7] = std::sqrt(sum2YP * norm - tmp*tmp); dst[3] = tmp = sumYN * norm; dst[8] = std::sqrt(sum2YN * norm - tmp*tmp); // compute mean and compute variance of img tmp = sum * norm; dst[4] = tmp * 2; dst[9] = std::sqrt(sum2 * norm - tmp*tmp) * 2; dst += 10; } } static std::vector<std::string> inputData() { std::vector<std::string> ret; ret.push_back(std::string("gx")); ret.push_back(std::string("gy")); ret.push_back(std::string("img")); return ret; } }; // Creator Helper for intensity images using interator template<class FT, uint size = 3, uint step = 2, class Align = RotationAlign<FT>, class MeanG = FastMean<FT, short>, class MeanI = FastMean<FT, uchar>> struct GchGradImgMean { static constexpr int numBands = size / step + (size % step ? 1 : 0); static constexpr int dscSize = numBands * 8; static void create(const cv::Mat *data, const LineSegment<FT>& line, FT* dst, FT beg = -1, FT stepDir = 1, FT lstep = 1) { const cv::Mat &dx = data[0]; const cv::Mat &dy = data[1]; const cv::Mat &img = data[2]; LineSegment<FT> l = line; l.translateOrtho(beg); stepDir *= step; cv::Point_<FT> p; FT sumXP,sumXN, sumYP, sumYN, sum2XP,sum2XN, sum2YP, sum2YN, sum, sum2, tmp, norm; std::vector<FT> valX, valY, valI; size_t n; for (int i = 0; i != numBands; ++i) { sumXP = sumXN = sumYP = sumYN = sum = 0; sum2XP = sum2XN = sum2YP = sum2YN = sum2 = 0; MeanG::process(valX,dx,l,lstep); MeanG::process(valY,dy,l,lstep); MeanI::process(valI,img,l,lstep); n = valX.size(); for (int j = 0; j < n; ++j) { // access value in grad and do alignment Align::apply(l,cv::Point_<FT>(valX[j],valY[j]),p); if (p.x < 0) { sumXN -= p.x; sum2XN += p.x*p.x; } else { sumXP += p.x; sum2XP += p.x*p.x; } if (p.y < 0) { sumYN -= p.y; sum2YN += p.y*p.y; } else { sumYP += p.y; sum2YP += p.y*p.y; } tmp = valI[j]; sum += tmp; sum2 += tmp * tmp; } // next row l.translateOrtho(stepDir); norm = static_cast<FT>(1) / (n * numBands); // compute mean and compute variance dst[0] = tmp = sumXP * norm; dst[5] = std::sqrt(sum2XP * norm - tmp*tmp); dst[1] = tmp = sumXN * norm; dst[6] = std::sqrt(sum2XN * norm - tmp*tmp); dst[2] = tmp = sumYP * norm; dst[7] = std::sqrt(sum2YP * norm - tmp*tmp); dst[3] = tmp = sumYN * norm; dst[9] = std::sqrt(sum2YN * norm - tmp*tmp); // compute mean and compute variance of img tmp = sum * norm; dst[4] = tmp * 2; dst[9] = std::sqrt(sum2 * norm - tmp*tmp) * 2; dst += 10; } } static std::vector<std::string> inputData() { std::vector<std::string> ret; ret.push_back(std::string("gx")); ret.push_back(std::string("gy")); ret.push_back(std::string("img")); return ret; } }; // Creator Helper for intensity images using interator template<class FT, uint size = 3, uint step = 2, class Align = RotationAlign<FT>, class MTG = short, class MTI = uchar> struct GchGradImgIterate { static constexpr int numBands = size / step + (size % step ? 1 : 0); static constexpr int dscSize = numBands * 10; static void create(const cv::Mat *data, const LineSegment<FT>& line, FT* dst, FT beg = -1, FT stepDir = 1, FT lstep = 1) { const cv::Mat &dx = data[0]; const cv::Mat &dy = data[1]; const cv::Mat &img = data[2]; LineSegment<FT> l = line; l.translateOrtho(beg); cv::Point_<FT> ps, pe; FT sumXP,sumXN, sumYP, sumYN, sum2XP,sum2XN, sum2YP, sum2YN, sum, sum2, tmp; for (int i = 0; i != numBands; ++i) { sumXP = sumXN = sumYP = sumYN = sum = 0; sum2XP = sum2XN = sum2YP = sum2YN = sum2 = 0; ps = l.startPoint(); pe = l.endPoint(); cv::LineIterator it(dx, cv::Point(static_cast<int>(std::round(ps.x)),static_cast<int>(std::round(ps.y))), cv::Point(static_cast<int>(std::round(pe.x)),static_cast<int>(std::round(pe.y)))); for (int j = 0; j < it.count; ++j, ++it) { // access value in grad and do alignment Align::apply(l,cv::Point_<FT>(dx.at<MTG>(it.pos()),dy.at<MTG>(it.pos())),ps); if (ps.x < 0) { sumXN -= ps.x; sum2XN += ps.x*ps.x; } else { sumXP += ps.x; sum2XP += ps.x*ps.x; } if (ps.y < 0) { sumYN -= ps.y; sum2YN += ps.y*ps.y; } else { sumYP += ps.y; sum2YP += ps.y*ps.y; } tmp = img.at<MTI>(it.pos()); sum += tmp; sum2 += tmp * tmp; } // next row l.translateOrtho(step * stepDir); // compute mean and compute variance of grad dst[0] = tmp = sumXP / (it.count * numBands); dst[5] = std::sqrt(sum2XP/(it.count * numBands) - tmp*tmp); dst[1] = tmp = sumXN / (it.count * numBands); dst[6] = std::sqrt(sum2XN/(it.count * numBands) - tmp*tmp); dst[2] = tmp = sumYP / (it.count * numBands); dst[7] = std::sqrt(sum2YP/(it.count * numBands) - tmp*tmp); dst[3] = tmp = sumYN / (it.count * numBands); dst[8] = std::sqrt(sum2YN/(it.count * numBands) - tmp*tmp); // compute mean and compute variance of img tmp = sum / (it.count * numBands); dst[4] = tmp * 2; dst[9] = std::sqrt(sum2/(it.count * numBands) - tmp*tmp) * 2; dst += 10; } } static std::vector<std::string> inputData() { std::vector<std::string> ret; ret.push_back(std::string("gx")); ret.push_back(std::string("gy")); ret.push_back(std::string("img")); return ret; } }; // Generic Feature Descriptor creator for gradient template<class FT, class GT = LineSegment<FT>, class Helper = GchImgInterpolate<FT>> class FdcGeneric : public Fdc<FT, GT, GenericDescritpor<FT,Helper::dscSize>> { public: typedef typename Fdc <FT, GT, GenericDescritpor<FT,Helper::dscSize> >::Ptr FdcPtr; typedef typename FdcObj <FT, GT, GenericDescritpor<FT,Helper::dscSize>>::Ptr CustomFdcPtr; typedef typename FdcMat < FT, GT>::Ptr SimpleFdcPtr; typedef GenericDescritpor<FT,Helper::dscSize> descriptor_type; FdcGeneric(const MatMap& data, FT pos = -1, FT stepDir = 1, FT lstep = 1) : pos_(pos), stepDir_(stepDir), lstep_(lstep) { data_.resize(Helper::inputData().size()); this->setData(data); } static FdcPtr createFdc(const MatMap& data, FT pos = -1, FT stepDir = 1, FT lstep = 1) { return FdcPtr(new FdcGeneric<FT, GT, Helper>(data, pos, stepDir, lstep)); } using FdcMatI<FT, GT>::create; using FdcObjI<FT, GT, GenericDescritpor<FT,Helper::dscSize>>::create; //! create single descriptor from single geometric object virtual void create(const GT& input, descriptor_type& dst) { Helper::create(data_.data(), input, dst.data, pos_, stepDir_, lstep_); } //! create single simple descriptor from geometric object virtual void create(const GT& input, cv::Mat& dst) { if (dst.empty() || dst.cols != descriptor_type::size()) dst.create(1, descriptor_type::size(), cv::DataType<FT>::type); Helper::create(data_.data(), input, dst.template ptr<FT>(), pos_, stepDir_, lstep_); } //! get size of single descriptor (cols in cv::Mat) virtual size_t size() const { return static_cast<size_t>(descriptor_type::size()); } //! allow to set internal processing data after init virtual void setData(const MatMap& data) { MatMap::const_iterator f; auto input = Helper::inputData(); for (size_t i = 0; i != input.size(); ++i) { f = data.find(input[i]); if (f != data.end()) data_[i] = f->second; } } // input std::vector<cv::Mat> data_; FT pos_, stepDir_, lstep_; protected: virtual void create(const GT& input, FT* dst) { Helper::create(data_.data(), input, dst, pos_, stepDir_, lstep_); } }; template<class FT, class GT = LineSegment<FT>, class Helper = GchImgInterpolate<FT>> typename Fdc <FT, GT, GenericDescritpor<FT,Helper::dscSize> >::Ptr createGenericFdc(const cv::Mat& img, FT pos = -1, FT stepDir = 1, FT lstep = 1) { MatMap tmp; tmp["img"] = img; return typename Fdc <FT, GT, GenericDescritpor<FT,Helper::dscSize> >::Ptr(new FdcGeneric<FT, GT, Helper>(tmp, pos, stepDir, lstep)); } template<class FT, class GT = LineSegment<FT>, class Helper = GchGradInterpolate<FT>> typename Fdc <FT, GT, GenericDescritpor<FT,Helper::dscSize> >::Ptr createGenericFdc(const cv::Mat& gx, const cv::Mat& gy, FT pos = -1, FT stepDir = 1, FT lstep = 1) { MatMap tmp; tmp["gx"] = gx; tmp["gy"] = gy; return typename Fdc <FT, GT, GenericDescritpor<FT,Helper::dscSize> >::Ptr(new FdcGeneric<FT, GT, Helper>(tmp, pos, stepDir, lstep)); } template<class FT, class GT = LineSegment<FT>, class Helper = GchGradImgInterpolate<FT>> typename Fdc <FT, GT, GenericDescritpor<FT,Helper::dscSize> >::Ptr createGenericFdc(const cv::Mat& gx, const cv::Mat& gy, const cv::Mat& img, FT pos = -1, FT stepDir = 1, FT lstep = 1) { MatMap tmp; tmp["gx"] = gx; tmp["gy"] = gy; tmp["img"] = img; return typename Fdc <FT, GT, GenericDescritpor<FT,Helper::dscSize> >::Ptr(new FdcGeneric<FT, GT, Helper>(tmp, pos, stepDir, lstep)); } } #endif #endif
40.742092
212
0.478173
eaa157c6d083c996a9d2b3fc57a64871f43db283
15,614
cpp
C++
projects/atLib/source/IO/Mesh/atFBXReader.cpp
mbatc/atLib
7e3a69515f504a05a312d234291f02863e291631
[ "MIT" ]
1
2019-09-17T18:02:16.000Z
2019-09-17T18:02:16.000Z
projects/atLib/source/IO/Mesh/atFBXReader.cpp
mbatc/atLib
7e3a69515f504a05a312d234291f02863e291631
[ "MIT" ]
null
null
null
projects/atLib/source/IO/Mesh/atFBXReader.cpp
mbatc/atLib
7e3a69515f504a05a312d234291f02863e291631
[ "MIT" ]
null
null
null
#include "atFBXParser.h" #include "atFBXCommon.h" #include "atHashMap.h" struct _atFbxParseContext { atMesh *pMesh; // Node ptr to bone index atHashMap<int64_t, int64_t> boneLookup; int64_t poseID = -1; // ID of the active pos }; FbxAMatrix _GetGeometry(FbxNode *pNode) { FbxDouble3 pivotTrans = pNode->GetGeometricTranslation(FbxNode::eSourcePivot); FbxDouble3 pivotRot = pNode->GetGeometricRotation(FbxNode::eSourcePivot); FbxDouble3 pivotScl = pNode->GetGeometricScaling(FbxNode::eSourcePivot); return FbxAMatrix(pivotTrans, pivotRot, pivotScl); } template<typename T> int64_t _GetMappedIndex(T *pElementArray, const int64_t &controlPoint, const int64_t &polyVert, const int64_t &polyIdx) { if (!pElementArray) return -1; // Get the base index int64_t indirectIdx = -1; switch (pElementArray->GetMappingMode()) { case FbxGeometryElement::eByPolygonVertex: indirectIdx = polyVert; break; case FbxGeometryElement::eByControlPoint: indirectIdx = controlPoint; break; case FbxGeometryElement::eByPolygon: indirectIdx = polyIdx; break; } int64_t directIdx = indirectIdx; // Convert indirect index to a direct index if (pElementArray->GetReferenceMode() != FbxGeometryElement::eDirect) directIdx = pElementArray->GetIndexArray().GetAt((int)indirectIdx); return directIdx; } template<typename Vec, typename T> Vec _ExtractElements(T *pElementArray, const int64_t &controlPoint, const int64_t &polyVert, const int64_t &polyIdx) { typedef decltype(pElementArray->GetDirectArray().GetAt(0)) FbxElement; // Fbx element array item type int64_t directIdx = _GetMappedIndex(pElementArray, controlPoint, polyVert, polyIdx); // Get the item from the element array FbxElement item = pElementArray->GetDirectArray().GetAt((int)directIdx); Vec ret = { 0 }; for (int64_t i = 0; i < Vec::ElementCount; ++i) ret[i] = item[(int)i]; return ret; } static void _LoadTextures(const char *name, FbxSurfaceMaterial *pMaterial, atVector<atFilename> *pTextures) { FbxProperty prop = pMaterial->FindProperty(name); for (int64_t i = 0; i < prop.GetSrcObjectCount<FbxTexture>(); ++i) { FbxFileTexture *pTex = prop.GetSrcObject<FbxFileTexture>((int)i); if (pTex) pTextures->push_back(pTex->GetFileName()); } } static atVec4D _GetColour(const FbxPropertyT<FbxDouble3> &colour, const double &factor) { FbxDouble3 val = colour.Get(); return atVec4D(val[0], val[1], val[2], factor); } static atVec4D _GetColour(const FbxPropertyT<FbxDouble3> &colour, const FbxPropertyT<FbxDouble> &factor) { return _GetColour(colour, factor.Get()); } static atMaterial _LoadMaterial(FbxSurfaceMaterial *pMaterial) { atMaterial mat; mat.m_name = pMaterial->GetName(); bool isPhong = pMaterial->GetClassId() == FbxSurfacePhong::ClassId; bool isLambert = isPhong || pMaterial->GetClassId() == FbxSurfaceLambert::ClassId; if (isLambert) { FbxSurfaceLambert *pLambert = (FbxSurfaceLambert*)pMaterial; mat.m_cDiffuse = _GetColour(pLambert->Diffuse, pLambert->DiffuseFactor); mat.m_cAmbient = _GetColour(pLambert->Ambient, pLambert->AmbientFactor); mat.m_alpha = pLambert->TransparencyFactor.Get(); _LoadTextures(FbxSurfaceMaterial::sDiffuse, pMaterial, &mat.m_tDiffuse); _LoadTextures(FbxSurfaceMaterial::sAmbientFactor, pMaterial, &mat.m_tAmbient); _LoadTextures(FbxSurfaceMaterial::sTransparencyFactor, pMaterial, &mat.m_tAlpha); _LoadTextures(FbxSurfaceMaterial::sDisplacementFactor, pMaterial, &mat.m_tDisplacement); } if (isPhong) { FbxSurfacePhong *pPhong = (FbxSurfacePhong*)pMaterial; mat.m_cSpecular = _GetColour(pPhong->Specular, pPhong->SpecularFactor); mat.m_specularPower = pPhong->SpecularFactor; _LoadTextures(FbxSurfaceMaterial::sSpecular, pMaterial, &mat.m_tSpecular); } return mat; } static bool _ParseDeformer(_atFbxParseContext *pCtx, FbxNode *pNode, FbxMesh *pFbxMesh, FbxSkin *pSkin) { if (!pSkin) return false; FbxAMatrix geom = _GetGeometry(pNode); for (int64_t clusterIndex = 0; clusterIndex < (int64_t)pSkin->GetClusterCount(); ++clusterIndex) { FbxCluster *pCluster = pSkin->GetCluster((int)clusterIndex); int64_t *pBoneID = pCtx->boneLookup.TryGet((int64_t)pCluster->GetLink()); if (!pBoneID) continue; if (pCtx->poseID == -1) { pCtx->poseID = pCtx->pMesh->m_skeleton.GetPoseCount(); pCtx->pMesh->m_skeleton.AddPose(false); } atPose &pose = pCtx->pMesh->m_skeleton.GetPose(pCtx->poseID); atMesh::VertexDeformer deformer; FbxAMatrix clusterTransform; FbxAMatrix bonePoseTransform; FbxAMatrix associateMatrix; pCluster->GetTransformAssociateModelMatrix(associateMatrix); pCluster->GetTransformLinkMatrix(bonePoseTransform); pCluster->GetTransformMatrix(clusterTransform); // Set the cluster transform atAssign(deformer.transform, clusterTransform * geom); deformer.inverseTransform = deformer.transform.Inverse(); // Set the bone bind position pose.SetTransform(*pBoneID, atAssign<atMat4D>(bonePoseTransform)); deformer.boneID = *pBoneID; int *pIndices = pCluster->GetControlPointIndices(); double *pWeights = pCluster->GetControlPointWeights(); for (int64_t vert = 0; vert < (int64_t)pCluster->GetControlPointIndicesCount(); ++vert) { deformer.vertices.push_back(pIndices[vert]); deformer.weights.push_back(pWeights[vert]); } pCtx->pMesh->m_deformationGroups.push_back(deformer); } return true; } static bool _ParseDeformer(_atFbxParseContext *pCtx, FbxNode *pNode, FbxMesh *pFbxMesh, FbxVertexCacheDeformer *pCache) { if (!pCache) return false; atUnused(pCtx, pNode, pFbxMesh, pCache); return false; } static bool _ParseDeformer(_atFbxParseContext *pCtx, FbxNode *pNode, FbxMesh *pFbxMesh, FbxBlendShape *pBlend) { if (!pBlend) return false; atUnused(pCtx, pNode, pFbxMesh, pBlend); return false; } static void _ParseMesh(_atFbxParseContext *pCtx, FbxNode *pNode, FbxMesh *pFbxMesh) { atMesh mesh; // Copy control points mesh.m_positions.reserve(pFbxMesh->GetControlPointsCount()); for (const FbxVector4 &pos : atIterate(pFbxMesh->GetControlPoints(), pFbxMesh->GetControlPointsCount())) mesh.m_positions.push_back(atVec3D(pos[0], pos[1], pos[2])); // Get geometry element arrays FbxGeometryElementNormal *pNormals = pFbxMesh->GetElementNormal(); FbxGeometryElementUV *pUVs = pFbxMesh->GetElementUV(); FbxGeometryElementVertexColor *pVertexColor = pFbxMesh->GetElementVertexColor(); FbxGeometryElementMaterial *pMaterials = pFbxMesh->GetElementMaterial(); // Extract geometry elements int64_t polyVertIndex = 0; int64_t polyCount = pFbxMesh->GetPolygonCount(); atVector<int64_t> materialLookup; mesh.m_materials.reserve(pNode->GetMaterialCount()); materialLookup.resize(pNode->GetMaterialCount(), -1); int64_t defaultMaterial = -1; for (int64_t polygonIdx = 0; polygonIdx < polyCount; ++polygonIdx) { atMesh::Triangle tri; int64_t materialID = _GetMappedIndex(pMaterials, pFbxMesh->GetPolygonVertex((int)polygonIdx, 0), polyVertIndex, polygonIdx); if (materialID != -1) { int64_t &index = materialLookup[materialID]; if (index == -1) { // Material has not been loaded yet index = mesh.m_materials.size(); mesh.m_materials.push_back(_LoadMaterial(pNode->GetMaterial((int)materialID))); } tri.mat = index; } else { if (defaultMaterial == -1) { defaultMaterial = mesh.m_materials.size(); mesh.m_materials.emplace_back(); } tri.mat = defaultMaterial; } int64_t vertCount = pFbxMesh->GetPolygonSize((int)polygonIdx); for (int64_t vertIdx = 0; vertIdx < vertCount; ++vertIdx) { int64_t controlPointIdx = pFbxMesh->GetPolygonVertex((int)polygonIdx, (int)vertIdx); tri.verts[vertIdx].position = controlPointIdx; if (pNormals) { tri.verts[vertIdx].normal = mesh.m_normals.size(); mesh.m_normals.push_back(_ExtractElements<atVec3D>(pNormals, controlPointIdx, polyVertIndex, polygonIdx)); } if (pUVs) { tri.verts[vertIdx].texCoord = mesh.m_texCoords.size(); mesh.m_texCoords.push_back(_ExtractElements<atVec2D>(pUVs, controlPointIdx, polyVertIndex, polygonIdx)); } if (pVertexColor) { tri.verts[vertIdx].color = mesh.m_colors.size(); mesh.m_colors.push_back(_ExtractElements<atVec4D>(pVertexColor, controlPointIdx, polyVertIndex, polygonIdx)); } ++polyVertIndex; } mesh.m_triangles.push_back(tri); } for (int64_t i = 0; i < (int64_t)pFbxMesh->GetDeformerCount(); ++i) { if (!_ParseDeformer(pCtx, pNode, pFbxMesh, (FbxSkin*)pFbxMesh->GetDeformer((int)i, FbxDeformer::eSkin))) if (!_ParseDeformer(pCtx, pNode, pFbxMesh, (FbxVertexCacheDeformer*)pFbxMesh->GetDeformer((int)i, FbxDeformer::eVertexCache))) if (!_ParseDeformer(pCtx, pNode, pFbxMesh, (FbxBlendShape*)pFbxMesh->GetDeformer((int)i, FbxDeformer::eBlendShape))) continue; } FbxAMatrix pivot = _GetGeometry(pNode); mesh.SpatialTransform(atAssign<atMat4D>(pNode->EvaluateGlobalTransform() * pivot)); atAssign(pCtx->pMesh->m_skeleton.Get(atHierarchy_RootNodeID).localTransform, pivot); pCtx->pMesh->Combine(mesh); } static void _ParseSkeleton(_atFbxParseContext *pCtx, FbxNode *pNode, FbxSkeleton *pFbxSkeleton) { int64_t *pParentBone = pCtx->boneLookup.TryGet((int64_t)pNode->GetParent()); atBone bone; bone.name = pNode->GetName(); bool isRoot = pFbxSkeleton->IsSkeletonRoot(); FbxAMatrix localTransform = pNode->EvaluateLocalTransform(); FbxAMatrix globalTransform = pNode->EvaluateGlobalTransform(); atAssign(bone.localTransform, localTransform); atAssign(bone.globalTransform, globalTransform); bone.modified = true; int64_t boneID = pCtx->pMesh->m_skeleton.Add(bone, pParentBone ? *pParentBone : atHierarchy_RootNodeID); pCtx->boneLookup.Add((int64_t)pNode, boneID); } static void _ParsePatch(_atFbxParseContext *pCtx, FbxNode *pNode, FbxPatch *pFbxPatch) { } static void _ParseShape(_atFbxParseContext *pCtx, FbxNode *pNode, FbxShape *pFbxShape) { } static void _ParseNurbs(_atFbxParseContext *pCtx, FbxNode *pNode, FbxNurbs *pFbxNurbs) { } static void _ParseNode(_atFbxParseContext *pCtx, FbxNode *pNode, const FbxNodeAttribute::EType &type = FbxNodeAttribute::eUnknown) { for (int64_t i = 0; i < (int64_t)pNode->GetNodeAttributeCount(); ++i) { FbxNodeAttribute *pAttribute = pNode->GetNodeAttributeByIndex((int)i); FbxNodeAttribute::EType attrType = pAttribute->GetAttributeType(); if (type != FbxNodeAttribute::eUnknown && attrType != type) continue; switch (pAttribute->GetAttributeType()) { case FbxNodeAttribute::eMesh: _ParseMesh(pCtx, pNode, (FbxMesh*)pAttribute); break; case FbxNodeAttribute::eNurbs: _ParseNurbs(pCtx, pNode, (FbxNurbs*)pAttribute); break; case FbxNodeAttribute::ePatch: _ParsePatch(pCtx, pNode, (FbxPatch*)pAttribute); break; case FbxNodeAttribute::eShape: _ParseShape(pCtx, pNode, (FbxShape*)pAttribute); break; case FbxNodeAttribute::eSkeleton: _ParseSkeleton(pCtx, pNode, (FbxSkeleton*)pAttribute); break; default: break; } } for (int64_t i = 0; i < (int64_t)pNode->GetChildCount(); ++i) _ParseNode(pCtx, pNode->GetChild((int)i), type); } static atAnimationCurve _ConvertCurve(FbxAnimCurve *pFbxCurve, const double &factor = 1) { if (!pFbxCurve) return atAnimationCurve(); atAnimationCurve converted; int keyCount = pFbxCurve->KeyGetCount(); for (int i = 0; i < keyCount; ++i) { FbxAnimCurveKey fbxKey = pFbxCurve->KeyGet(i); atAnimationKey key; key.SetValue(fbxKey.GetValue() * factor); switch (fbxKey.GetInterpolation()) { case FbxAnimCurveDef::eInterpolationConstant: key.SetInterpolation(atAnimationKey::Constant); break; case FbxAnimCurveDef::eInterpolationLinear: key.SetInterpolation(atAnimationKey::Linear); break; case FbxAnimCurveDef::eInterpolationCubic: key.SetInterpolation(atAnimationKey::Cubic); break; } converted.SetKey(atMilliSeconds(fbxKey.GetTime().GetMilliSeconds()), key); } return converted; } static void _ExtractCurveXYZ(FbxProperty *pProp, FbxAnimLayer *pLayer, atAnimationCurve *pCurveX = nullptr, atAnimationCurve *pCurveY = nullptr, atAnimationCurve *pCurveZ = nullptr, const double &factor = 1) { if (pCurveX) *pCurveX = _ConvertCurve(pProp->GetCurve(pLayer, FBXSDK_CURVENODE_COMPONENT_X), factor); if (pCurveY) *pCurveY = _ConvertCurve(pProp->GetCurve(pLayer, FBXSDK_CURVENODE_COMPONENT_Y), factor); if (pCurveZ) *pCurveZ = _ConvertCurve(pProp->GetCurve(pLayer, FBXSDK_CURVENODE_COMPONENT_Z), factor); } static void _ParseAnimations(_atFbxParseContext *pCtx, FbxScene *pScene) { int numStacks = pScene->GetSrcObjectCount<FbxAnimStack>(); for (int stackIdx = 0; stackIdx < numStacks; ++stackIdx) { FbxAnimStack *pStack = pScene->GetSrcObject<FbxAnimStack>(stackIdx); int numLayers = pStack->GetMemberCount<FbxAnimLayer>(); atMesh::AnimTake take; take.anim.SetName(pStack->GetName()); take.startTime = atMilliSeconds(pStack->GetLocalTimeSpan().GetStart().GetMilliSeconds()); take.endTime = atMilliSeconds(pStack->GetLocalTimeSpan().GetStop().GetMilliSeconds()); int64_t animGroupID = pCtx->pMesh->m_takes.size(); for (int layerIdx = 0; layerIdx < numLayers; ++layerIdx) { // For each layer extract the animations for the bones FbxAnimLayer *pLayer = pStack->GetMember<FbxAnimLayer>(layerIdx); for (const atKeyValue<int64_t, int64_t> &kvp : pCtx->boneLookup) { int64_t animID = take.anim.AddAnimation(); atAnimation *pAnimation = take.anim.GetAnimation(animID); FbxNode *pFbxBone = (FbxNode*)kvp.m_key; _ExtractCurveXYZ(&pFbxBone->LclTranslation, pLayer, pAnimation->GetCurve(atAnimationKeySet::atAnim_KS_TranslationX), pAnimation->GetCurve(atAnimationKeySet::atAnim_KS_TranslationY), pAnimation->GetCurve(atAnimationKeySet::atAnim_KS_TranslationZ)); _ExtractCurveXYZ(&pFbxBone->LclRotation, pLayer, pAnimation->GetCurve(atAnimationKeySet::atAnim_KS_RotationX), pAnimation->GetCurve(atAnimationKeySet::atAnim_KS_RotationY), pAnimation->GetCurve(atAnimationKeySet::atAnim_KS_RotationZ), atPi / 180.0); _ExtractCurveXYZ(&pFbxBone->LclScaling, pLayer, pAnimation->GetCurve(atAnimationKeySet::atAnim_KS_ScaleX), pAnimation->GetCurve(atAnimationKeySet::atAnim_KS_ScaleY), pAnimation->GetCurve(atAnimationKeySet::atAnim_KS_ScaleZ)); take.links.Add(kvp.m_val, animID); } } pCtx->pMesh->m_takes.push_back(take); } } bool atFBXReader::Read(const atFilename &file, atMesh *pMesh) { // Clear the mesh *pMesh = atMesh(); // Load the FBXScene atFBXCommon fbx; FbxScene *pScene = fbx.Import(file); // Triangulate the meshes FbxGeometryConverter converter(fbx.GetManager()); converter.Triangulate(pScene, true); if (!pScene) return false; // Create a fresh FBX mesh parser context _atFbxParseContext ctx; ctx.pMesh = pMesh; // Only skeletons and meshes are supported so far _ParseNode(&ctx, pScene->GetRootNode(), FbxNodeAttribute::eSkeleton); _ParseNode(&ctx, pScene->GetRootNode(), FbxNodeAttribute::eMesh); // Extract animations after loading the geometry _ParseAnimations(&ctx, pScene); return true; }
35.486364
207
0.723389
eaa35451e1076cf3995c60c038e843d3042dd589
5,278
inl
C++
TwitchQt/twitchvideoreply.inl
jkbz64/TwitchQt
9bfddd9b48eea9eb25ae5f05239c0739c0bdfb12
[ "MIT" ]
9
2019-09-16T22:28:43.000Z
2022-03-06T22:57:56.000Z
TwitchQt/twitchvideoreply.inl
jkbz64/TwitchQt
9bfddd9b48eea9eb25ae5f05239c0739c0bdfb12
[ "MIT" ]
5
2020-10-11T15:01:09.000Z
2021-10-11T05:39:28.000Z
TwitchQt/twitchvideoreply.inl
jkbz64/TwitchQt
9bfddd9b48eea9eb25ae5f05239c0739c0bdfb12
[ "MIT" ]
2
2020-10-11T14:38:24.000Z
2020-10-11T14:45:34.000Z
inline void VideoReply::parseData(const JSON& json) { if (json.find("data") != json.end()) { const auto& data = json["data"]; if (!data.empty()) { const auto& video = data.front(); QList<MutedSegment> mutedSegmentsList; if (video.find("muted_segments") != video.end()) { const auto& mutedSegments = video["muted_segments"]; for (const auto& segment : mutedSegments) { if (segment.find("duration") == segment.end()) { continue; } MutedSegment ms; ms.duration = segment.value("duration", -1); ms.offset = segment.value("offset", -1); mutedSegmentsList.append(ms); } } QString typeStr = video["type"]; Video::VideoType type; if (typeStr == "upload") type = Video::VideoType::Upload; else if (typeStr == "archive") type = Video::VideoType::Archive; else if (typeStr == "highlight") type = Video::VideoType::Highlight; QString createdAt = video["created_at"]; QString publishedAt = video["published_at"]; m_data.setValue(Video{video.value("id", QString("-1")), video.value("stream_id", QString("-1")), video.value("user_id", QString("-1")), video.value("user_login", QString("")), video.value("user_name", QString("")), video.value("title", QString()), video.value("description", QString("")), QDateTime::fromString(createdAt, Qt::ISODate), QDateTime::fromString(publishedAt, Qt::ISODate), video.value("url", QString("")), video.value("thumbnail_url", QString("")), video.value("viewable", QString("")), video.value("view_count", -1), video.value("language", QString("")), type, video.value("duration", QString("")), mutedSegmentsList}); } else { // ??? } } } inline void VideosReply::parseData(const JSON& json) { Videos videos; if (json.find("data") != json.end()) { const auto& data = json["data"]; for (const auto& video : data) { QList<MutedSegment> mutedSegmentsList; if (video.find("muted_segments") != video.end()) { const auto& mutedSegments = video["muted_segments"]; for (const auto& segment : mutedSegments) { if (segment.find("duration") == segment.end()) { continue; } MutedSegment ms; ms.duration = segment.value("duration", -1); ms.offset = segment.value("offset", -1); mutedSegmentsList.append(ms); } } QString typeStr = video["type"]; Video::VideoType type; if (typeStr == "upload") type = Video::VideoType::Upload; else if (typeStr == "archive") type = Video::VideoType::Archive; else if (typeStr == "highlight") type = Video::VideoType::Highlight; QString createdAt = video["created_at"]; QString publishedAt = video["published_at"]; videos.push_back({video.value("id", QString("-1")), video.value("stream_id", QString("-1")), video.value("user_id", QString("-1")), video.value("user_login", QString("")), video.value("user_name", QString("")), video.value("title", QString()), video.value("description", QString("")), QDateTime::fromString(createdAt, Qt::ISODate), QDateTime::fromString(publishedAt, Qt::ISODate), video.value("url", QString("")), video.value("thumbnail_url", QString("")), video.value("viewable", QString("")), video.value("view_count", -1), video.value("language", QString("")), type, video.value("duration", QString("")), mutedSegmentsList}); } } m_data.setValue(videos); } inline int VideosReply::combinedViewerCount() const { return m_combinedViewerCount; } inline Twitch::Video Twitch::VideoReply::video() { return m_data.value<Twitch::Video>(); } inline Twitch::Videos Twitch::VideosReply::videos() { return m_data.value<Twitch::Videos>(); }
41.559055
82
0.448844
eaa463011f86ef63641021cc9893c2f867c3b735
140
cpp
C++
synthesizer/lang/macro/lowercase.cpp
SleepyToDeath/NetQRE
0176a31afa45faa4877974a4a0575a4e60534090
[ "MIT" ]
2
2021-03-30T15:25:44.000Z
2021-05-14T07:22:25.000Z
synthesizer/lang/macro/lowercase.cpp
SleepyToDeath/NetQRE
0176a31afa45faa4877974a4a0575a4e60534090
[ "MIT" ]
null
null
null
synthesizer/lang/macro/lowercase.cpp
SleepyToDeath/NetQRE
0176a31afa45faa4877974a4a0575a4e60534090
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int main() { for (char c='a'; c<='z'; c++) cout<<"[ \""<<c<<"\" ], "; cout<<"[ \"\\c\" ]"; }
12.727273
30
0.435714
eaa6a10f28cdaef13cf59c82ed744c420fb4370d
2,535
cpp
C++
Area.cpp
irrollforwardable/ascii_game_draft
e3658ed886aa944cf65ce2a9d742f39504028439
[ "MIT" ]
null
null
null
Area.cpp
irrollforwardable/ascii_game_draft
e3658ed886aa944cf65ce2a9d742f39504028439
[ "MIT" ]
null
null
null
Area.cpp
irrollforwardable/ascii_game_draft
e3658ed886aa944cf65ce2a9d742f39504028439
[ "MIT" ]
null
null
null
#include "Area.h" Area::Area(const std::string& t_Source) { // TODO calculate width and height from t_Source m_W = 25; m_H = 10; // Resize 2D grid accordingly m_Parts.resize(m_W); for (size_t x = 0; x < m_Parts.size(); x++) { m_Parts[x].resize(m_H); } // TODO Generate Wholes from t_Source m_Wholes.push_back(std::make_unique<Whole>(0, 0, *this)); // TODO Add parts to the 2D grid for (const auto& whole : m_Wholes) { for (const auto& part : whole->getParts()) { m_Parts[part->getX()][part->getY()] = part; } } // Resize m_Ascii based on area w and h and fill it with empty characters and new line characters std::string tmpEmptyStr(m_W * m_H + 2 * m_H, EMPTY_CHR); // + 2 because each line ends with '\n' and '\r' chars m_Ascii = tmpEmptyStr; for (size_t i = m_W; i < m_Ascii.size(); i += (m_W + 2)) { m_Ascii[i] = NEWLINE_CHR; m_Ascii[i+1] = CARRET_CHR; } m_CleanScreen = m_Ascii; } void Area::update(Direction direction) { // For testing only: moves only player size_t x_diff = 0, y_diff = 0; switch (direction) { case UP: x_diff = 0; y_diff = -1; break; case DOWN: x_diff = 0; y_diff = 1; break; case LEFT: x_diff = -1; y_diff = 0; break; case RIGHT: x_diff = 1; y_diff = 0; break; default: x_diff = 0; y_diff = 0; } for (const auto& whole : m_Wholes) { // TODO check whether game object resides within the borders of the Area whole->move(whole->getX() + x_diff, whole->getY() + y_diff, true); } } std::string& Area::render() { auto t1 = std::chrono::high_resolution_clock::now(); // TODO remove performance measurement m_Ascii = m_CleanScreen; for (const auto& partsX : m_Parts) { for (const auto& part : partsX) { if (part != nullptr) { m_Ascii[part->getX() + part->getY() * (m_W + 2)] = part->getSymbol(); } } } // TODO remove performance measurement auto t2 = std::chrono::high_resolution_clock::now(); auto duration = std::chrono::duration_cast<std::chrono::microseconds>( t2 - t1 ).count(); std::cout << "Duration: " << duration << " msec" << std::endl; return m_Ascii; }
26.40625
116
0.530572
eaa70dd8d8b82f080b7e5fdcd4f02e19749a841e
10,254
cpp
C++
Framework/Util/Thread.cpp
dengwenyi88/Deferred_Lighting
b45b6590150a3119b0c2365f4795d93b3b4f0748
[ "MIT" ]
110
2017-06-23T17:12:28.000Z
2022-02-22T19:11:38.000Z
RunTest/Framework3/Util/Thread.cpp
dtrebilco/ECSAtto
86a04f0bdc521c79f758df94250c1898c39213c8
[ "MIT" ]
null
null
null
RunTest/Framework3/Util/Thread.cpp
dtrebilco/ECSAtto
86a04f0bdc521c79f758df94250c1898c39213c8
[ "MIT" ]
3
2018-02-12T00:16:18.000Z
2018-02-18T11:12:35.000Z
/* * * * * * * * * * * * * Author's note * * * * * * * * * * * *\ * _ _ _ _ _ _ _ _ _ _ _ _ * * |_| |_| |_| |_| |_|_ _|_| |_| |_| _|_|_|_|_| * * |_|_ _ _|_| |_| |_| |_|_|_|_|_| |_| |_| |_|_ _ _ * * |_|_|_|_|_| |_| |_| |_| |_| |_| |_| |_| |_|_|_|_ * * |_| |_| |_|_ _ _|_| |_| |_| |_|_ _ _|_| _ _ _ _|_| * * |_| |_| |_|_|_| |_| |_| |_|_|_| |_|_|_|_| * * * * http://www.humus.name * * * * This file is a part of the work done by Humus. You are free to * * use the code in any way you like, modified, unmodified or copied * * into your own work. However, I expect you to respect these points: * * - If you use this file and its contents unmodified, or use a major * * part of this file, please credit the author and leave this note. * * - For use in anything commercial, please request my approval. * * - Share your work and ideas too as much as you can. * * * \* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #include "Thread.h" #ifdef _WIN32 ThreadHandle createThread(ThreadProc startProc, void *param){ return CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) startProc, param, 0, NULL); } void deleteThread(ThreadHandle thread){ CloseHandle(thread); } void waitOnThread(const ThreadHandle threadID){ WaitForSingleObject(threadID, INFINITE); } void waitOnAllThreads(const ThreadHandle *threads, const int nThreads){ WaitForMultipleObjects(nThreads, threads, TRUE, INFINITE); } void waitOnAnyThread(const ThreadHandle *threads, const int nThreads){ WaitForMultipleObjects(nThreads, threads, FALSE, INFINITE); } void createMutex(Mutex &mutex){ mutex = CreateMutex(NULL, FALSE, NULL); } void deleteMutex(Mutex &mutex){ CloseHandle(mutex); } void lockMutex(Mutex &mutex){ WaitForSingleObject(mutex, INFINITE); } void unlockMutex(Mutex &mutex){ ReleaseMutex(mutex); } void createCondition(Condition &condition){ condition.waiters_count = 0; condition.was_broadcast = false; condition.sema = CreateSemaphore(NULL, 0, 0x7fffffff, NULL); InitializeCriticalSection(&condition.waiters_count_lock); condition.waiters_done = CreateEvent(NULL, FALSE, FALSE, NULL); } void deleteCondition(Condition &condition){ CloseHandle(condition.sema); DeleteCriticalSection(&condition.waiters_count_lock); CloseHandle(condition.waiters_done); } void waitCondition(Condition &condition, Mutex &mutex){ EnterCriticalSection(&condition.waiters_count_lock); condition.waiters_count++; LeaveCriticalSection(&condition.waiters_count_lock); SignalObjectAndWait(mutex, condition.sema, INFINITE, FALSE); EnterCriticalSection(&condition.waiters_count_lock); // We're no longer waiting... condition.waiters_count--; // Check to see if we're the last waiter after broadcast. bool last_waiter = condition.was_broadcast && (condition.waiters_count == 0); LeaveCriticalSection(&condition.waiters_count_lock); // If we're the last waiter thread during this particular broadcast then let all the other threads proceed. if (last_waiter){ // This call atomically signals the <waiters_done> event and waits until // it can acquire the <mutex>. This is required to ensure fairness. SignalObjectAndWait(condition.waiters_done, mutex, INFINITE, FALSE); } else { // Always regain the external mutex since that's the guarantee we give to our callers. WaitForSingleObject(mutex, INFINITE); } } void signalCondition(Condition &condition){ EnterCriticalSection(&condition.waiters_count_lock); bool have_waiters = (condition.waiters_count > 0); LeaveCriticalSection(&condition.waiters_count_lock); // If there aren't any waiters, then this is a no-op. if (have_waiters){ ReleaseSemaphore(condition.sema, 1, 0); } } void broadcastCondition(Condition &condition){ // This is needed to ensure that <waiters_count> and <was_broadcast> are consistent relative to each other. EnterCriticalSection(&condition.waiters_count_lock); bool have_waiters = false; if (condition.waiters_count > 0){ // We are broadcasting, even if there is just one waiter... // Record that we are broadcasting, which helps optimize // <pthread_cond_wait> for the non-broadcast case. condition.was_broadcast = true; have_waiters = true; } if (have_waiters){ // Wake up all the waiters atomically. ReleaseSemaphore(condition.sema, condition.waiters_count, 0); LeaveCriticalSection(&condition.waiters_count_lock); // Wait for all the awakened threads to acquire the counting semaphore. WaitForSingleObject(condition.waiters_done, INFINITE); // This assignment is okay, even without the <waiters_count_lock> held // because no other waiter threads can wake up to access it. condition.was_broadcast = false; } else { LeaveCriticalSection(&condition.waiters_count_lock); } } #else ThreadHandle createThread(ThreadProc startProc, void *param){ pthread_t th; pthread_create(&th, NULL, (void *(*)(void *)) startProc, param); return th; } void deleteThread(ThreadHandle thread){ } void waitOnThread(const ThreadHandle threadID){ pthread_join(threadID, NULL); } void createMutex(Mutex &mutex){ pthread_mutex_init(&mutex, NULL); } void deleteMutex(Mutex &mutex){ pthread_mutex_destroy(&mutex); } void lockMutex(Mutex &mutex){ pthread_mutex_lock(&mutex); } void unlockMutex(Mutex &mutex){ pthread_mutex_unlock(&mutex); } void createCondition(Condition &condition){ pthread_cond_init(&condition, NULL); } void deleteCondition(Condition &condition){ pthread_cond_destroy(&condition); } void waitCondition(Condition &condition, Mutex &mutex){ pthread_cond_wait(&condition, &mutex); } void signalCondition(Condition &condition){ pthread_cond_signal(&condition); } void broadcastCondition(Condition &condition){ pthread_cond_broadcast(&condition); } #endif //#include <stdio.h> struct ThreadParam { Thread *thread; int threadInstance; }; #ifdef _WIN32 DWORD WINAPI threadStarter(void *param){ // ((Thread *) startFunc)->mainFunc(0); Thread *thread = ((ThreadParam *) param)->thread; int instance = ((ThreadParam *) param)->threadInstance; delete param; thread->mainFunc(instance); return 0; } void Thread::startThreads(const int threadCount){ nThreads = threadCount; threadHandles = new HANDLE[threadCount]; threadIDs = new DWORD[threadCount]; for (int i = 0; i < threadCount; i++){ ThreadParam *param = new ThreadParam; param->thread = this; param->threadInstance = i; threadHandles[i] = CreateThread(NULL, 0, threadStarter, param, 0, &threadIDs[i]); } } void Thread::postMessage(const int thread, const int message, void *data, const int size){ int msg = WM_USER + message; int start, end; if (thread < 0){ start = 0; end = nThreads; } else { start = thread; end = start + 1; } for (int i = start; i < end; i++){ char *msgData = new char[size]; memcpy(msgData, data, size); while (!PostThreadMessage(threadIDs[i], msg, size, (LPARAM) msgData)){ //printf("PostThreadMessage failed\n"); Sleep(1); } } } void Thread::mainFunc(const int thread){ MSG msg; while (GetMessage(&msg, NULL, 0, 0) > 0){ processMessage(thread, msg.message - WM_USER, (void *) msg.lParam, (const int) msg.wParam); } } void Thread::waitForExit(){ delete threadIDs; // WaitForSingleObject(threadHandle, INFINITE); WaitForMultipleObjects(nThreads, threadHandles, TRUE, INFINITE); delete threadHandles; } #else #include <string.h> void *threadStarter(void *param){ ThreadParam *tp = (ThreadParam *) param; Thread *thread = tp->thread; int instance = tp->threadInstance; delete tp; thread->mainFunc(instance); return NULL; } void Thread::startThreads(const int threadCount){ /* first = last = NULL; pthread_mutex_init(&mutex, NULL); pthread_cond_init(&pending, NULL); pthread_create(&thread, NULL, threadStarter, this); */ nThreads = threadCount; queues = new MessageQueue[threadCount]; threadHandles = new pthread_t[threadCount]; for (int i = 0; i < threadCount; i++){ queues[i].first = NULL; queues[i].last = NULL; pthread_mutex_init(&queues[i].mutex, NULL); pthread_cond_init(&queues[i].pending, NULL); ThreadParam *param = new ThreadParam; param->thread = this; param->threadInstance = i; pthread_create(&threadHandles[i], NULL, threadStarter, param); } } void Thread::postMessage(const int thread, const int message, void *data, const int size){ int start, end; if (thread < 0){ start = 0; end = nThreads; } else { start = thread; end = start + 1; } for (int i = start; i < end; i++){ MessageQueue *queue = queues + i; pthread_mutex_lock(&queue->mutex); Message *msg = new Message; msg->message = message; if (data){ msg->data = new char[size]; memcpy(msg->data, data, size); } else { msg->data = NULL; } msg->size = size; msg->next = NULL; if (queue->first == NULL){ queue->first = queue->last = msg; } else { queue->last->next = msg; queue->last = msg; } pthread_mutex_unlock(&queue->mutex); pthread_cond_signal(&queue->pending); } } void Thread::mainFunc(const int thread){ bool done = false; do { Message *msg = getMessage(thread); if (msg->message < 0){ done = true; } else { processMessage(thread, msg->message, msg->data, msg->size); } delete msg->data; delete msg; } while (!done); pthread_mutex_destroy(&queues[thread].mutex); pthread_cond_destroy(&queues[thread].pending); // printf("Done\n"); } void Thread::waitForExit(){ for (int i = 0; i < nThreads; i++){ pthread_join(threadHandles[i], NULL); } } Message *Thread::getMessage(const int thread){ MessageQueue *queue = queues + thread; pthread_mutex_lock(&queue->mutex); while (queue->first == NULL){ pthread_cond_wait(&queue->pending, &queue->mutex); } Message *ret = queue->first; queue->first = queue->first->next; if (queue->first == NULL) queue->last = NULL; pthread_mutex_unlock(&queue->mutex); return ret; } #endif // !_WIN32
25.444169
108
0.676712
eaa7ce23241ef9d19e386ea6aaeb0caa567a66d4
231
cpp
C++
test/llvm_test_code/call_graphs/global_ctor_dtor_4.cpp
ga0/phasar
b9ecb9a1f0353501376021fab67057a713fa70dc
[ "MIT" ]
581
2018-06-10T10:37:55.000Z
2022-03-30T14:56:53.000Z
test/llvm_test_code/call_graphs/global_ctor_dtor_4.cpp
meret-boe/phasar
2b394d5611b107e4fd3d8eec37f26abca8ef1e9a
[ "MIT" ]
172
2018-06-13T12:33:26.000Z
2022-03-26T07:21:41.000Z
test/llvm_test_code/call_graphs/global_ctor_dtor_4.cpp
meret-boe/phasar
2b394d5611b107e4fd3d8eec37f26abca8ef1e9a
[ "MIT" ]
137
2018-06-10T10:31:14.000Z
2022-03-06T11:53:56.000Z
__attribute__((constructor)) void before_main(); __attribute__((destructor)) void after_main(); void before_main() {} void after_main() {} struct S { int data; S(int data) : data(data) {} ~S() {} }; S s(0); int main() {}
14.4375
48
0.632035
eaabbda163a454e1416e67830d8336efb40a3bad
1,476
cpp
C++
VC2010Samples/MFC/Visual C++ 2008 Feature Pack/RollupPane/InfoBar.cpp
alonmm/VCSamples
6aff0b4902f5027164d593540fcaa6601a0407c3
[ "MIT" ]
300
2019-05-09T05:32:33.000Z
2022-03-31T20:23:24.000Z
VC2010Samples/MFC/Visual C++ 2008 Feature Pack/RollupPane/InfoBar.cpp
JaydenChou/VCSamples
9e1d4475555b76a17a3568369867f1d7b6cc6126
[ "MIT" ]
9
2016-09-19T18:44:26.000Z
2018-10-26T10:20:05.000Z
VC2010Samples/MFC/Visual C++ 2008 Feature Pack/RollupPane/InfoBar.cpp
JaydenChou/VCSamples
9e1d4475555b76a17a3568369867f1d7b6cc6126
[ "MIT" ]
633
2019-05-08T07:34:12.000Z
2022-03-30T04:38:28.000Z
// This is a part of the Microsoft Foundation Classes C++ library. // Copyright (C) Microsoft Corporation // All rights reserved. // // This source code is only intended as a supplement to the // Microsoft Foundation Classes Reference and related // electronic documentation provided with the library. // See these sources for detailed information regarding the // Microsoft Foundation Classes product. #include "stdafx.h" #include "RollupPane.h" #include "InfoBar.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CInfoBar CInfoBar::CInfoBar() { } CInfoBar::~CInfoBar() { } BEGIN_MESSAGE_MAP(CInfoBar, CDockablePane) //{{AFX_MSG_MAP(CInfoBar) ON_WM_PAINT() //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CInfoBar message handlers void CInfoBar::OnPaint() { CPaintDC dc(this); // device context for painting CRect rectClient; GetClientRect (rectClient); dc.FillSolidRect (rectClient, ::GetSysColor (COLOR_3DHILIGHT)); dc.Draw3dRect (rectClient, ::GetSysColor (COLOR_3DSHADOW), ::GetSysColor (COLOR_3DLIGHT)); dc.SetBkMode (TRANSPARENT); dc.SetTextColor (::GetSysColor (COLOR_BTNTEXT)); CFont* pOldFont = (CFont*) dc.SelectStockObject (DEFAULT_GUI_FONT); CString str = _T("Information..."); dc.TextOut (10, 10, str); dc.SelectObject (pOldFont); }
23.428571
77
0.667344
eaad671f1b22cc1c7ff643fabefdcc78702fd9d4
852
cpp
C++
codeforces/354/C/test.cpp
rdragos/work
aed4c9ace3fad6b0c63caadee69de2abde108b40
[ "MIT" ]
2
2020-05-30T17:11:47.000Z
2021-09-25T08:16:48.000Z
codeforces/354/C/test.cpp
rdragos/work
aed4c9ace3fad6b0c63caadee69de2abde108b40
[ "MIT" ]
null
null
null
codeforces/354/C/test.cpp
rdragos/work
aed4c9ace3fad6b0c63caadee69de2abde108b40
[ "MIT" ]
1
2021-09-24T11:14:27.000Z
2021-09-24T11:14:27.000Z
#include <cstdio> #include <algorithm> #include <fstream> #include <iostream> #include <vector> #include <queue> #include <map> #include <cstring> #include <string> #include <set> #include <stack> #define pb push_back #define mp make_pair #define f first #define s second #define ll long long using namespace std; int main() { /* ifstream cin("test.in"); ofstream cout("test.out"); */ int N, K; cin >> N >> K; string S; cin >> S; int answer = 0; vector <char> sel{'a', 'b'}; for (auto x: sel) { queue <int> Q; int cur_begin = 0; for (int i = 0; i < N; ++i) { if (S[i] != x) { Q.push(i); } while(Q.size() > K) { int el = Q.front(); Q.pop(); cur_begin = el + 1; } answer = max(answer, i - cur_begin + 1); } } cout << answer << "\n"; return 0; }
16.384615
46
0.539906
eaaee55d560d16a2957b2c5fb53f02afae059dec
2,406
cpp
C++
src/zmqConsumerPoll.cpp
tompatman/zmqplus
efea491f2e9ca8f531ec7e102564fb56b1d62e0f
[ "MIT" ]
null
null
null
src/zmqConsumerPoll.cpp
tompatman/zmqplus
efea491f2e9ca8f531ec7e102564fb56b1d62e0f
[ "MIT" ]
null
null
null
src/zmqConsumerPoll.cpp
tompatman/zmqplus
efea491f2e9ca8f531ec7e102564fb56b1d62e0f
[ "MIT" ]
null
null
null
/* * zmqConsumerPoll.cpp * * Created on: May 31, 2013 * Author: service */ #include "../include/zmqConsumerPoll.h" using std::string; zmqConsumerPoll::zmqConsumerPoll(ppcLogger *log, uint num_consumers_to_poll, int timeout_ms) : _log(log) , _num_consumers(num_consumers_to_poll) , _timeout_ms(timeout_ms) { _items = (zmq::pollitem_t *) new zmq::pollitem_t[_num_consumers]; } zmqConsumerPoll::~zmqConsumerPoll() { delete[] _items; } void zmqConsumerPoll::Add(iConsumer *a_consumer) { uint idx = _consumer_list.size(); poco_assert(idx < _num_consumers); _consumer_list.push_back(a_consumer); _items[idx].events = ZMQ_POLLIN; _items[idx].fd = 0; _items[idx].socket = a_consumer->get_sub_socket_for_poll(); } int zmqConsumerPoll::Poll() { poco_assert(_consumer_list.size() == _num_consumers); int number_signaled = zmq::poll(_items, _num_consumers, _timeout_ms); if(number_signaled > 0) // Any updates { int count = 0; for (uint i = 0; i < _num_consumers; ++i) { if(_items[i].revents & ZMQ_POLLIN) { if(!_consumer_list[i]->update_data_share()) _items[i].revents = 0; // Remove the signal if it does not return true. count++; } } poco_assert(count == number_signaled); // Better be the same. } if(number_signaled < 0) { _log->log(LG_ERR, "zmq::poll returned error[%d]:", zmq_errno(), zmq_strerror(zmq_errno())); throw Poco::RuntimeException(string("zmq::poll returned error[]:") + zmq_strerror(zmq_errno())); } return number_signaled; } bool zmqConsumerPoll::WasSignaled(uint consumer_idx) { poco_assert(consumer_idx < _num_consumers); return (_items[consumer_idx].revents & ZMQ_POLLIN); } bool zmqConsumerPoll::WasSignaled(iConsumer *a_consumer) { bool was_signaled = false; uint i = 0; for (; i < _num_consumers; ++i) { if(_consumer_list[i] == a_consumer) { was_signaled = (_items[i].revents & ZMQ_POLLIN); break; } } if(i == _num_consumers) { _log->log(LG_ERR, "The consumer was not found in the list!"); throw Poco::RuntimeException("WasSignaled() : The consumer was not found in the list!"); } return was_signaled; }
23.588235
112
0.620116
eaaf2f4745d98ff1b2d861e75db041301a3a0122
2,341
cpp
C++
midterm_mbghazi.cpp
mbghazi/Data-Structures
4703488686d2a78267fcd5a6adcbeda36ac10703
[ "MIT" ]
null
null
null
midterm_mbghazi.cpp
mbghazi/Data-Structures
4703488686d2a78267fcd5a6adcbeda36ac10703
[ "MIT" ]
null
null
null
midterm_mbghazi.cpp
mbghazi/Data-Structures
4703488686d2a78267fcd5a6adcbeda36ac10703
[ "MIT" ]
null
null
null
/* ** PROGRAM: Matrix Multiply ** ** PURPOSE: This is a simple matrix multiply program. ** It will compute the product ** ** C = A * B ** ** A and B are set to constant matrices so we ** can make a quick test of the multiplication. ** ** USAGE: Right now, I hardwire the martix dimensions. ** later, I'll take them from the command line. ** ** HISTORY: Written by Tim Mattson, Nov 1999. */ #include <iostream> #include <omp.h> using namespace std; #define ORDER 500 #define AVAL 3.0 #define BVAL 5.0 #define TOL 0.001 #define Ndim ORDER #define Pdim ORDER #define Mdim ORDER #define NUM_THREADS 4//added int main(int argc, char **argv) { double A[Ndim][Pdim], B[Pdim][Mdim], C[Ndim][Mdim]; int i,j,k; //double *A, *B, *C, double cval, tmp, err, errsq; double dN, mflops; double start_time, run_time; double sum; omp_set_num_threads(NUM_THREADS); start_time = omp_get_wtime(); /* Initialize matrices */ for (i=0; i<Ndim; i++) for (j=0; j<Pdim; j++) A[i][j] = AVAL; for (i=0; i<Pdim; i++) for (j=0; j<Mdim; j++) B[i][j] = BVAL; for (i=0; i<Ndim; i++) for (j=0; j<Mdim; j++) C[i][j] = 0.0; /* Do the matrix product */ #pragma parallel for schedule(dynamic) lastprivate(sum) red(-tmp) for (i=0; i<Ndim; i++){ //added //#pragma parallel for for (j=0; j<Mdim; j++){ tmp = 0.0; //#pragma parallel for schedule(dynamic) lastprivate(tmp) for(k=0;k<Pdim;k++){ /* C(i,j) = sum(over k) A(i,k) * B(k,j) */ tmp += A[i][k] * B[k][j]; } C[i][j] = tmp; sum += tmp; } } /* Check the answer */ cout << "Summary is " << sum << endl; cval = Pdim * AVAL * BVAL; errsq = 0.0; for (i=0; i<Ndim; i++){ for (j=0; j<Mdim; j++){ err = C[i][j] - cval; errsq += err * err; } } errsq += sum - cval*Ndim*Mdim; if (errsq > TOL) cout << "Errors in multiplication: "<< errsq<< endl; else cout << "Hey, it worked! Error is: " << errsq << endl; run_time = omp_get_wtime() - start_time; cout << "Order " << ORDER << " multiplication in " << run_time << " seconds "<< endl; dN = (double)ORDER; mflops = 2.0 * dN * dN * dN/(1000000.0* run_time); cout << "Order " << " multiplication at " << mflops << " mflops" << endl; cout << "All done "<< endl; return 0; }
22.509615
86
0.564289
eab068770436f9db993275b1ce35ad8d8dba1c8d
1,444
cc
C++
src/boson/test/queues_weakrb.cc
duckie/boson
f3eb787f385c86b7735fcd7bc0ac0dc6a8fb7b1a
[ "MIT" ]
174
2016-10-10T12:47:01.000Z
2022-03-09T16:06:59.000Z
src/boson/test/queues_weakrb.cc
duckie/boson
f3eb787f385c86b7735fcd7bc0ac0dc6a8fb7b1a
[ "MIT" ]
5
2017-02-01T21:30:14.000Z
2018-09-09T10:02:00.000Z
src/boson/test/queues_weakrb.cc
duckie/boson
f3eb787f385c86b7735fcd7bc0ac0dc6a8fb7b1a
[ "MIT" ]
13
2016-10-10T12:19:14.000Z
2021-12-04T08:23:26.000Z
#include <iostream> #include <limits> #include <random> #include <thread> #include "boson/queues/weakrb.h" #include "catch.hpp" TEST_CASE("Queues - WeakRB - serial random integers", "[queues][weakrb]") { constexpr size_t const sample_size = 1e4; std::random_device seed; std::mt19937_64 generator{seed()}; std::uniform_int_distribution<int> distribution(std::numeric_limits<int>::min(), std::numeric_limits<int>::max()); std::vector<int> sample; sample.reserve(sample_size); for (size_t index = 0; index < sample_size; ++index) sample.emplace_back(distribution(generator)); // Create the buffer std::vector<int> destination; destination.reserve(sample_size); boson::queues::weakrb<int> queue(1); std::thread t1([&sample, &queue]() { for (auto v : sample) { bool success = false; int value = v; // Ugly spin lock, osef while (!success) { success = queue.write(value); std::this_thread::yield(); } } }); std::thread t2([&destination, &queue]() { for (size_t index = 0; index < sample_size; ++index) { bool success = false; int result{}; // Ugly spin lock, osef while (!success) { success = queue.read(result); std::this_thread::yield(); } destination.emplace_back(result); } }); t1.join(); t2.join(); CHECK(sample == destination); }
25.333333
83
0.605956
eab334692c7e899abd7ef97fc35637752d552cba
64,611
cpp
C++
src/slg/film/film.cpp
DavidBluecame/LuxRays
be0f5228b8b65268278a6c6a1c98564ebdc27c05
[ "Apache-2.0" ]
null
null
null
src/slg/film/film.cpp
DavidBluecame/LuxRays
be0f5228b8b65268278a6c6a1c98564ebdc27c05
[ "Apache-2.0" ]
null
null
null
src/slg/film/film.cpp
DavidBluecame/LuxRays
be0f5228b8b65268278a6c6a1c98564ebdc27c05
[ "Apache-2.0" ]
null
null
null
/*************************************************************************** * Copyright 1998-2015 by authors (see AUTHORS.txt) * * * * This file is part of LuxRender. * * * * 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 <limits> #include <algorithm> #include <exception> #include <boost/lexical_cast.hpp> #include <boost/foreach.hpp> #include <OpenImageIO/imageio.h> #include <OpenImageIO/imagebuf.h> OIIO_NAMESPACE_USING #include "luxrays/core/geometry/point.h" #include "luxrays/utils/properties.h" #include "slg/film/film.h" #include "slg/film/filters/gaussian.h" #include "slg/editaction.h" using namespace std; using namespace luxrays; using namespace slg; typedef unsigned char BYTE; //------------------------------------------------------------------------------ // FilmOutput //------------------------------------------------------------------------------ void FilmOutputs::Add(const FilmOutputType type, const string &fileName, const Properties *p) { types.push_back(type); fileNames.push_back(fileName); if (p) props.push_back(*p); else props.push_back(Properties()); } //------------------------------------------------------------------------------ // Film //------------------------------------------------------------------------------ Film::Film(const u_int w, const u_int h) { initialized = false; width = w; height = h; radianceGroupCount = 1; channel_ALPHA = NULL; channel_RGB_TONEMAPPED = NULL; channel_DEPTH = NULL; channel_POSITION = NULL; channel_GEOMETRY_NORMAL = NULL; channel_SHADING_NORMAL = NULL; channel_MATERIAL_ID = NULL; channel_DIRECT_DIFFUSE = NULL; channel_DIRECT_GLOSSY = NULL; channel_EMISSION = NULL; channel_INDIRECT_DIFFUSE = NULL; channel_INDIRECT_GLOSSY = NULL; channel_INDIRECT_SPECULAR = NULL; channel_DIRECT_SHADOW_MASK = NULL; channel_INDIRECT_SHADOW_MASK = NULL; channel_UV = NULL; channel_RAYCOUNT = NULL; channel_IRRADIANCE = NULL; convTest = NULL; enabledOverlappedScreenBufferUpdate = true; rgbTonemapUpdate = true; imagePipeline = NULL; filter = NULL; filterLUTs = NULL; SetFilter(new GaussianFilter(1.5f, 1.5f, 2.f)); } Film::~Film() { delete imagePipeline; delete convTest; for (u_int i = 0; i < channel_RADIANCE_PER_PIXEL_NORMALIZEDs.size(); ++i) delete channel_RADIANCE_PER_PIXEL_NORMALIZEDs[i]; for (u_int i = 0; i < channel_RADIANCE_PER_SCREEN_NORMALIZEDs.size(); ++i) delete channel_RADIANCE_PER_SCREEN_NORMALIZEDs[i]; delete channel_ALPHA; delete channel_RGB_TONEMAPPED; delete channel_DEPTH; delete channel_POSITION; delete channel_GEOMETRY_NORMAL; delete channel_SHADING_NORMAL; delete channel_MATERIAL_ID; delete channel_DIRECT_DIFFUSE; delete channel_DIRECT_GLOSSY; delete channel_EMISSION; delete channel_INDIRECT_DIFFUSE; delete channel_INDIRECT_GLOSSY; delete channel_INDIRECT_SPECULAR; for (u_int i = 0; i < channel_MATERIAL_ID_MASKs.size(); ++i) delete channel_MATERIAL_ID_MASKs[i]; delete channel_DIRECT_SHADOW_MASK; delete channel_INDIRECT_SHADOW_MASK; delete channel_UV; delete channel_RAYCOUNT; for (u_int i = 0; i < channel_BY_MATERIAL_IDs.size(); ++i) delete channel_BY_MATERIAL_IDs[i]; delete channel_IRRADIANCE; delete filterLUTs; delete filter; } void Film::AddChannel(const FilmChannelType type, const Properties *prop) { if (initialized) throw runtime_error("It is only possible to add a channel to a Film before initialization"); channels.insert(type); switch (type) { case MATERIAL_ID_MASK: { const u_int id = prop->Get(Property("id")(255)).Get<u_int>(); if (count(maskMaterialIDs.begin(), maskMaterialIDs.end(), id) == 0) maskMaterialIDs.push_back(id); break; } case BY_MATERIAL_ID: { const u_int id = prop->Get(Property("id")(255)).Get<u_int>(); if (count(byMaterialIDs.begin(), byMaterialIDs.end(), id) == 0) byMaterialIDs.push_back(id); break; } default: break; } } void Film::RemoveChannel(const FilmChannelType type) { if (initialized) throw runtime_error("It is only possible to remove a channel from a Film before initialization"); channels.erase(type); } void Film::Init() { if (initialized) throw runtime_error("A Film can not be initialized multiple times"); initialized = true; Resize(width, height); } void Film::Resize(const u_int w, const u_int h) { width = w; height = h; pixelCount = w * h; delete convTest; convTest = NULL; // Delete all already allocated channels for (u_int i = 0; i < channel_RADIANCE_PER_PIXEL_NORMALIZEDs.size(); ++i) delete channel_RADIANCE_PER_PIXEL_NORMALIZEDs[i]; channel_RADIANCE_PER_PIXEL_NORMALIZEDs.clear(); for (u_int i = 0; i < channel_RADIANCE_PER_SCREEN_NORMALIZEDs.size(); ++i) delete channel_RADIANCE_PER_SCREEN_NORMALIZEDs[i]; channel_RADIANCE_PER_SCREEN_NORMALIZEDs.clear(); delete channel_ALPHA; delete channel_RGB_TONEMAPPED; delete channel_DEPTH; delete channel_POSITION; delete channel_GEOMETRY_NORMAL; delete channel_SHADING_NORMAL; delete channel_MATERIAL_ID; delete channel_DIRECT_DIFFUSE; delete channel_DIRECT_GLOSSY; delete channel_EMISSION; delete channel_INDIRECT_DIFFUSE; delete channel_INDIRECT_GLOSSY; delete channel_INDIRECT_SPECULAR; for (u_int i = 0; i < channel_MATERIAL_ID_MASKs.size(); ++i) delete channel_MATERIAL_ID_MASKs[i]; channel_MATERIAL_ID_MASKs.clear(); delete channel_DIRECT_SHADOW_MASK; delete channel_INDIRECT_SHADOW_MASK; delete channel_UV; delete channel_RAYCOUNT; for (u_int i = 0; i < channel_BY_MATERIAL_IDs.size(); ++i) delete channel_BY_MATERIAL_IDs[i]; channel_BY_MATERIAL_IDs.clear(); delete channel_IRRADIANCE; // Allocate all required channels hasDataChannel = false; hasComposingChannel = false; if (HasChannel(RADIANCE_PER_PIXEL_NORMALIZED)) { channel_RADIANCE_PER_PIXEL_NORMALIZEDs.resize(radianceGroupCount, NULL); for (u_int i = 0; i < radianceGroupCount; ++i) { channel_RADIANCE_PER_PIXEL_NORMALIZEDs[i] = new GenericFrameBuffer<4, 1, float>(width, height); channel_RADIANCE_PER_PIXEL_NORMALIZEDs[i]->Clear(); } } if (HasChannel(RADIANCE_PER_SCREEN_NORMALIZED)) { channel_RADIANCE_PER_SCREEN_NORMALIZEDs.resize(radianceGroupCount, NULL); for (u_int i = 0; i < radianceGroupCount; ++i) { channel_RADIANCE_PER_SCREEN_NORMALIZEDs[i] = new GenericFrameBuffer<3, 0, float>(width, height); channel_RADIANCE_PER_SCREEN_NORMALIZEDs[i]->Clear(); } } if (HasChannel(ALPHA)) { channel_ALPHA = new GenericFrameBuffer<2, 1, float>(width, height); channel_ALPHA->Clear(); } if (HasChannel(RGB_TONEMAPPED)) { channel_RGB_TONEMAPPED = new GenericFrameBuffer<3, 0, float>(width, height); channel_RGB_TONEMAPPED->Clear(); convTest = new ConvergenceTest(width, height); } if (HasChannel(DEPTH)) { channel_DEPTH = new GenericFrameBuffer<1, 0, float>(width, height); channel_DEPTH->Clear(numeric_limits<float>::infinity()); hasDataChannel = true; } if (HasChannel(POSITION)) { channel_POSITION = new GenericFrameBuffer<3, 0, float>(width, height); channel_POSITION->Clear(numeric_limits<float>::infinity()); hasDataChannel = true; } if (HasChannel(GEOMETRY_NORMAL)) { channel_GEOMETRY_NORMAL = new GenericFrameBuffer<3, 0, float>(width, height); channel_GEOMETRY_NORMAL->Clear(numeric_limits<float>::infinity()); hasDataChannel = true; } if (HasChannel(SHADING_NORMAL)) { channel_SHADING_NORMAL = new GenericFrameBuffer<3, 0, float>(width, height); channel_SHADING_NORMAL->Clear(numeric_limits<float>::infinity()); hasDataChannel = true; } if (HasChannel(MATERIAL_ID)) { channel_MATERIAL_ID = new GenericFrameBuffer<1, 0, u_int>(width, height); channel_MATERIAL_ID->Clear(numeric_limits<u_int>::max()); hasDataChannel = true; } if (HasChannel(DIRECT_DIFFUSE)) { channel_DIRECT_DIFFUSE = new GenericFrameBuffer<4, 1, float>(width, height); channel_DIRECT_DIFFUSE->Clear(); hasComposingChannel = true; } if (HasChannel(DIRECT_GLOSSY)) { channel_DIRECT_GLOSSY = new GenericFrameBuffer<4, 1, float>(width, height); channel_DIRECT_GLOSSY->Clear(); hasComposingChannel = true; } if (HasChannel(EMISSION)) { channel_EMISSION = new GenericFrameBuffer<4, 1, float>(width, height); channel_EMISSION->Clear(); hasComposingChannel = true; } if (HasChannel(INDIRECT_DIFFUSE)) { channel_INDIRECT_DIFFUSE = new GenericFrameBuffer<4, 1, float>(width, height); channel_INDIRECT_DIFFUSE->Clear(); hasComposingChannel = true; } if (HasChannel(INDIRECT_GLOSSY)) { channel_INDIRECT_GLOSSY = new GenericFrameBuffer<4, 1, float>(width, height); channel_INDIRECT_GLOSSY->Clear(); hasComposingChannel = true; } if (HasChannel(INDIRECT_SPECULAR)) { channel_INDIRECT_SPECULAR = new GenericFrameBuffer<4, 1, float>(width, height); channel_INDIRECT_SPECULAR->Clear(); hasComposingChannel = true; } if (HasChannel(MATERIAL_ID_MASK)) { for (u_int i = 0; i < maskMaterialIDs.size(); ++i) { GenericFrameBuffer<2, 1, float> *buf = new GenericFrameBuffer<2, 1, float>(width, height); buf->Clear(); channel_MATERIAL_ID_MASKs.push_back(buf); } hasComposingChannel = true; } if (HasChannel(DIRECT_SHADOW_MASK)) { channel_DIRECT_SHADOW_MASK = new GenericFrameBuffer<2, 1, float>(width, height); channel_DIRECT_SHADOW_MASK->Clear(); hasComposingChannel = true; } if (HasChannel(INDIRECT_SHADOW_MASK)) { channel_INDIRECT_SHADOW_MASK = new GenericFrameBuffer<2, 1, float>(width, height); channel_INDIRECT_SHADOW_MASK->Clear(); hasComposingChannel = true; } if (HasChannel(UV)) { channel_UV = new GenericFrameBuffer<2, 0, float>(width, height); channel_UV->Clear(numeric_limits<float>::infinity()); hasDataChannel = true; } if (HasChannel(RAYCOUNT)) { channel_RAYCOUNT = new GenericFrameBuffer<1, 0, float>(width, height); channel_RAYCOUNT->Clear(); hasDataChannel = true; } if (HasChannel(BY_MATERIAL_ID)) { for (u_int i = 0; i < byMaterialIDs.size(); ++i) { GenericFrameBuffer<4, 1, float> *buf = new GenericFrameBuffer<4, 1, float>(width, height); buf->Clear(); channel_BY_MATERIAL_IDs.push_back(buf); } hasComposingChannel = true; } if (HasChannel(IRRADIANCE)) { channel_IRRADIANCE = new GenericFrameBuffer<4, 1, float>(width, height); channel_IRRADIANCE->Clear(); hasComposingChannel = true; } // Initialize the stats statsTotalSampleCount = 0.0; statsAvgSampleSec = 0.0; statsStartSampleTime = WallClockTime(); } void Film::SetFilter(Filter *flt) { delete filterLUTs; filterLUTs = NULL; delete filter; filter = flt; if (filter) { const u_int size = Max<u_int>(4, Max(filter->xWidth, filter->yWidth) + 1); filterLUTs = new FilterLUTs(*filter, size); } } void Film::Reset() { if (HasChannel(RADIANCE_PER_PIXEL_NORMALIZED)) { for (u_int i = 0; i < radianceGroupCount; ++i) channel_RADIANCE_PER_PIXEL_NORMALIZEDs[i]->Clear(); } if (HasChannel(RADIANCE_PER_SCREEN_NORMALIZED)) { for (u_int i = 0; i < radianceGroupCount; ++i) channel_RADIANCE_PER_SCREEN_NORMALIZEDs[i]->Clear(); } if (HasChannel(ALPHA)) channel_ALPHA->Clear(); if (HasChannel(DEPTH)) channel_DEPTH->Clear(numeric_limits<float>::infinity()); if (HasChannel(POSITION)) channel_POSITION->Clear(numeric_limits<float>::infinity()); if (HasChannel(GEOMETRY_NORMAL)) channel_GEOMETRY_NORMAL->Clear(numeric_limits<float>::infinity()); if (HasChannel(SHADING_NORMAL)) channel_SHADING_NORMAL->Clear(numeric_limits<float>::infinity()); if (HasChannel(MATERIAL_ID)) channel_MATERIAL_ID->Clear(numeric_limits<float>::max()); if (HasChannel(DIRECT_DIFFUSE)) channel_DIRECT_DIFFUSE->Clear(); if (HasChannel(DIRECT_GLOSSY)) channel_DIRECT_GLOSSY->Clear(); if (HasChannel(EMISSION)) channel_EMISSION->Clear(); if (HasChannel(INDIRECT_DIFFUSE)) channel_INDIRECT_DIFFUSE->Clear(); if (HasChannel(INDIRECT_GLOSSY)) channel_INDIRECT_GLOSSY->Clear(); if (HasChannel(INDIRECT_SPECULAR)) channel_INDIRECT_SPECULAR->Clear(); if (HasChannel(MATERIAL_ID_MASK)) { for (u_int i = 0; i < channel_MATERIAL_ID_MASKs.size(); ++i) channel_MATERIAL_ID_MASKs[i]->Clear(); } if (HasChannel(DIRECT_SHADOW_MASK)) channel_DIRECT_SHADOW_MASK->Clear(); if (HasChannel(INDIRECT_SHADOW_MASK)) channel_INDIRECT_SHADOW_MASK->Clear(); if (HasChannel(UV)) channel_UV->Clear(); if (HasChannel(RAYCOUNT)) channel_RAYCOUNT->Clear(); if (HasChannel(BY_MATERIAL_ID)) { for (u_int i = 0; i < channel_BY_MATERIAL_IDs.size(); ++i) channel_BY_MATERIAL_IDs[i]->Clear(); } if (HasChannel(IRRADIANCE)) channel_IRRADIANCE->Clear(); // convTest has to be reset explicitly statsTotalSampleCount = 0.0; statsAvgSampleSec = 0.0; statsStartSampleTime = WallClockTime(); } void Film::AddFilm(const Film &film, const u_int srcOffsetX, const u_int srcOffsetY, const u_int srcWidth, const u_int srcHeight, const u_int dstOffsetX, const u_int dstOffsetY) { statsTotalSampleCount += film.statsTotalSampleCount; if (HasChannel(RADIANCE_PER_PIXEL_NORMALIZED) && film.HasChannel(RADIANCE_PER_PIXEL_NORMALIZED)) { for (u_int i = 0; i < Min(radianceGroupCount, film.radianceGroupCount); ++i) { for (u_int y = 0; y < srcHeight; ++y) { for (u_int x = 0; x < srcWidth; ++x) { const float *srcPixel = film.channel_RADIANCE_PER_PIXEL_NORMALIZEDs[i]->GetPixel(srcOffsetX + x, srcOffsetY + y); channel_RADIANCE_PER_PIXEL_NORMALIZEDs[i]->AddPixel(dstOffsetX + x, dstOffsetY + y, srcPixel); } } } } if (HasChannel(RADIANCE_PER_SCREEN_NORMALIZED) && film.HasChannel(RADIANCE_PER_SCREEN_NORMALIZED)) { for (u_int i = 0; i < Min(radianceGroupCount, film.radianceGroupCount); ++i) { for (u_int y = 0; y < srcHeight; ++y) { for (u_int x = 0; x < srcWidth; ++x) { const float *srcPixel = film.channel_RADIANCE_PER_SCREEN_NORMALIZEDs[i]->GetPixel(srcOffsetX + x, srcOffsetY + y); channel_RADIANCE_PER_SCREEN_NORMALIZEDs[i]->AddPixel(dstOffsetX + x, dstOffsetY + y, srcPixel); } } } } if (HasChannel(ALPHA) && film.HasChannel(ALPHA)) { for (u_int y = 0; y < srcHeight; ++y) { for (u_int x = 0; x < srcWidth; ++x) { const float *srcPixel = film.channel_ALPHA->GetPixel(srcOffsetX + x, srcOffsetY + y); channel_ALPHA->AddPixel(dstOffsetX + x, dstOffsetY + y, srcPixel); } } } if (HasChannel(POSITION) && film.HasChannel(POSITION)) { if (HasChannel(DEPTH) && film.HasChannel(DEPTH)) { // Used DEPTH information to merge Films for (u_int y = 0; y < srcHeight; ++y) { for (u_int x = 0; x < srcWidth; ++x) { if (film.channel_DEPTH->GetPixel(srcOffsetX + x, srcOffsetY + y)[0] < channel_DEPTH->GetPixel(dstOffsetX + x, dstOffsetY + y)[0]) { const float *srcPixel = film.channel_POSITION->GetPixel(srcOffsetX + x, srcOffsetY + y); channel_POSITION->SetPixel(dstOffsetX + x, dstOffsetY + y, srcPixel); } } } } else { for (u_int y = 0; y < srcHeight; ++y) { for (u_int x = 0; x < srcWidth; ++x) { const float *srcPixel = film.channel_POSITION->GetPixel(srcOffsetX + x, srcOffsetY + y); channel_POSITION->SetPixel(dstOffsetX + x, dstOffsetY + y, srcPixel); } } } } if (HasChannel(GEOMETRY_NORMAL) && film.HasChannel(GEOMETRY_NORMAL)) { if (HasChannel(DEPTH) && film.HasChannel(DEPTH)) { // Used DEPTH information to merge Films for (u_int y = 0; y < srcHeight; ++y) { for (u_int x = 0; x < srcWidth; ++x) { if (film.channel_DEPTH->GetPixel(srcOffsetX + x, srcOffsetY + y)[0] < channel_DEPTH->GetPixel(dstOffsetX + x, dstOffsetY + y)[0]) { const float *srcPixel = film.channel_GEOMETRY_NORMAL->GetPixel(srcOffsetX + x, srcOffsetY + y); channel_GEOMETRY_NORMAL->SetPixel(dstOffsetX + x, dstOffsetY + y, srcPixel); } } } } else { for (u_int y = 0; y < srcHeight; ++y) { for (u_int x = 0; x < srcWidth; ++x) { const float *srcPixel = film.channel_GEOMETRY_NORMAL->GetPixel(srcOffsetX + x, srcOffsetY + y); channel_GEOMETRY_NORMAL->SetPixel(dstOffsetX + x, dstOffsetY + y, srcPixel); } } } } if (HasChannel(SHADING_NORMAL) && film.HasChannel(SHADING_NORMAL)) { if (HasChannel(DEPTH) && film.HasChannel(DEPTH)) { // Used DEPTH information to merge Films for (u_int y = 0; y < srcHeight; ++y) { for (u_int x = 0; x < srcWidth; ++x) { if (film.channel_DEPTH->GetPixel(srcOffsetX + x, srcOffsetY + y)[0] < channel_DEPTH->GetPixel(dstOffsetX + x, dstOffsetY + y)[0]) { const float *srcPixel = film.channel_SHADING_NORMAL->GetPixel(srcOffsetX + x, srcOffsetY + y); channel_SHADING_NORMAL->SetPixel(dstOffsetX + x, dstOffsetY + y, srcPixel); } } } } else { for (u_int y = 0; y < srcHeight; ++y) { for (u_int x = 0; x < srcWidth; ++x) { const float *srcPixel = film.channel_SHADING_NORMAL->GetPixel(srcOffsetX + x, srcOffsetY + y); channel_SHADING_NORMAL->SetPixel(dstOffsetX + x, dstOffsetY + y, srcPixel); } } } } if (HasChannel(MATERIAL_ID) && film.HasChannel(MATERIAL_ID)) { if (HasChannel(DEPTH) && film.HasChannel(DEPTH)) { // Used DEPTH information to merge Films for (u_int y = 0; y < srcHeight; ++y) { for (u_int x = 0; x < srcWidth; ++x) { if (film.channel_DEPTH->GetPixel(srcOffsetX + x, srcOffsetY + y)[0] < channel_DEPTH->GetPixel(dstOffsetX + x, dstOffsetY + y)[0]) { const u_int *srcPixel = film.channel_MATERIAL_ID->GetPixel(srcOffsetX + x, srcOffsetY + y); channel_MATERIAL_ID->SetPixel(dstOffsetX + x, dstOffsetY + y, srcPixel); } } } } else { for (u_int y = 0; y < srcHeight; ++y) { for (u_int x = 0; x < srcWidth; ++x) { const u_int *srcPixel = film.channel_MATERIAL_ID->GetPixel(srcOffsetX + x, srcOffsetY + y); channel_MATERIAL_ID->SetPixel(dstOffsetX + x, dstOffsetY + y, srcPixel); } } } } if (HasChannel(DIRECT_DIFFUSE) && film.HasChannel(DIRECT_DIFFUSE)) { for (u_int y = 0; y < srcHeight; ++y) { for (u_int x = 0; x < srcWidth; ++x) { const float *srcPixel = film.channel_DIRECT_DIFFUSE->GetPixel(srcOffsetX + x, srcOffsetY + y); channel_DIRECT_DIFFUSE->AddPixel(dstOffsetX + x, dstOffsetY + y, srcPixel); } } } if (HasChannel(DIRECT_GLOSSY) && film.HasChannel(DIRECT_GLOSSY)) { for (u_int y = 0; y < srcHeight; ++y) { for (u_int x = 0; x < srcWidth; ++x) { const float *srcPixel = film.channel_DIRECT_GLOSSY->GetPixel(srcOffsetX + x, srcOffsetY + y); channel_DIRECT_GLOSSY->AddPixel(dstOffsetX + x, dstOffsetY + y, srcPixel); } } } if (HasChannel(EMISSION) && film.HasChannel(EMISSION)) { for (u_int y = 0; y < srcHeight; ++y) { for (u_int x = 0; x < srcWidth; ++x) { const float *srcPixel = film.channel_EMISSION->GetPixel(srcOffsetX + x, srcOffsetY + y); channel_EMISSION->AddPixel(dstOffsetX + x, dstOffsetY + y, srcPixel); } } } if (HasChannel(INDIRECT_DIFFUSE) && film.HasChannel(INDIRECT_DIFFUSE)) { for (u_int y = 0; y < srcHeight; ++y) { for (u_int x = 0; x < srcWidth; ++x) { const float *srcPixel = film.channel_INDIRECT_DIFFUSE->GetPixel(srcOffsetX + x, srcOffsetY + y); channel_INDIRECT_DIFFUSE->AddPixel(dstOffsetX + x, dstOffsetY + y, srcPixel); } } } if (HasChannel(INDIRECT_GLOSSY) && film.HasChannel(INDIRECT_GLOSSY)) { for (u_int y = 0; y < srcHeight; ++y) { for (u_int x = 0; x < srcWidth; ++x) { const float *srcPixel = film.channel_INDIRECT_GLOSSY->GetPixel(srcOffsetX + x, srcOffsetY + y); channel_INDIRECT_GLOSSY->AddPixel(dstOffsetX + x, dstOffsetY + y, srcPixel); } } } if (HasChannel(INDIRECT_SPECULAR) && film.HasChannel(INDIRECT_SPECULAR)) { for (u_int y = 0; y < srcHeight; ++y) { for (u_int x = 0; x < srcWidth; ++x) { const float *srcPixel = film.channel_INDIRECT_SPECULAR->GetPixel(srcOffsetX + x, srcOffsetY + y); channel_INDIRECT_SPECULAR->AddPixel(dstOffsetX + x, dstOffsetY + y, srcPixel); } } } if (HasChannel(MATERIAL_ID_MASK) && film.HasChannel(MATERIAL_ID_MASK)) { for (u_int i = 0; i < channel_MATERIAL_ID_MASKs.size(); ++i) { for (u_int j = 0; j < film.maskMaterialIDs.size(); ++j) { if (maskMaterialIDs[i] == film.maskMaterialIDs[j]) { for (u_int y = 0; y < srcHeight; ++y) { for (u_int x = 0; x < srcWidth; ++x) { const float *srcPixel = film.channel_MATERIAL_ID_MASKs[j]->GetPixel(srcOffsetX + x, srcOffsetY + y); channel_MATERIAL_ID_MASKs[i]->AddPixel(dstOffsetX + x, dstOffsetY + y, srcPixel); } } } } } } if (HasChannel(DIRECT_SHADOW_MASK) && film.HasChannel(DIRECT_SHADOW_MASK)) { for (u_int y = 0; y < srcHeight; ++y) { for (u_int x = 0; x < srcWidth; ++x) { const float *srcPixel = film.channel_DIRECT_SHADOW_MASK->GetPixel(srcOffsetX + x, srcOffsetY + y); channel_DIRECT_SHADOW_MASK->AddPixel(dstOffsetX + x, dstOffsetY + y, srcPixel); } } } if (HasChannel(INDIRECT_SHADOW_MASK) && film.HasChannel(INDIRECT_SHADOW_MASK)) { for (u_int y = 0; y < srcHeight; ++y) { for (u_int x = 0; x < srcWidth; ++x) { const float *srcPixel = film.channel_INDIRECT_SHADOW_MASK->GetPixel(srcOffsetX + x, srcOffsetY + y); channel_INDIRECT_SHADOW_MASK->AddPixel(dstOffsetX + x, dstOffsetY + y, srcPixel); } } } if (HasChannel(UV) && film.HasChannel(UV)) { if (HasChannel(DEPTH) && film.HasChannel(DEPTH)) { // Used DEPTH information to merge Films for (u_int y = 0; y < srcHeight; ++y) { for (u_int x = 0; x < srcWidth; ++x) { if (film.channel_DEPTH->GetPixel(srcOffsetX + x, srcOffsetY + y)[0] < channel_DEPTH->GetPixel(dstOffsetX + x, dstOffsetY + y)[0]) { const float *srcPixel = film.channel_UV->GetPixel(srcOffsetX + x, srcOffsetY + y); channel_UV->SetPixel(dstOffsetX + x, dstOffsetY + y, srcPixel); } } } } else { for (u_int y = 0; y < srcHeight; ++y) { for (u_int x = 0; x < srcWidth; ++x) { const float *srcPixel = film.channel_UV->GetPixel(srcOffsetX + x, srcOffsetY + y); channel_UV->SetPixel(dstOffsetX + x, dstOffsetY + y, srcPixel); } } } } if (HasChannel(RAYCOUNT) && film.HasChannel(RAYCOUNT)) { for (u_int y = 0; y < srcHeight; ++y) { for (u_int x = 0; x < srcWidth; ++x) { const float *srcPixel = film.channel_RAYCOUNT->GetPixel(srcOffsetX + x, srcOffsetY + y); channel_RAYCOUNT->AddPixel(dstOffsetX + x, dstOffsetY + y, srcPixel); } } } if (HasChannel(BY_MATERIAL_ID) && film.HasChannel(BY_MATERIAL_ID)) { for (u_int i = 0; i < channel_BY_MATERIAL_IDs.size(); ++i) { for (u_int j = 0; j < film.byMaterialIDs.size(); ++j) { if (byMaterialIDs[i] == film.byMaterialIDs[j]) { for (u_int y = 0; y < srcHeight; ++y) { for (u_int x = 0; x < srcWidth; ++x) { const float *srcPixel = film.channel_BY_MATERIAL_IDs[j]->GetPixel(srcOffsetX + x, srcOffsetY + y); channel_BY_MATERIAL_IDs[i]->AddPixel(dstOffsetX + x, dstOffsetY + y, srcPixel); } } } } } } if (HasChannel(IRRADIANCE) && film.HasChannel(IRRADIANCE)) { for (u_int y = 0; y < srcHeight; ++y) { for (u_int x = 0; x < srcWidth; ++x) { const float *srcPixel = film.channel_IRRADIANCE->GetPixel(srcOffsetX + x, srcOffsetY + y); channel_IRRADIANCE->AddPixel(dstOffsetX + x, dstOffsetY + y, srcPixel); } } } // NOTE: update DEPTH channel last because it is used to merge other channels if (HasChannel(DEPTH) && film.HasChannel(DEPTH)) { for (u_int y = 0; y < srcHeight; ++y) { for (u_int x = 0; x < srcWidth; ++x) { const float *srcPixel = film.channel_DEPTH->GetPixel(srcOffsetX + x, srcOffsetY + y); channel_DEPTH->MinPixel(dstOffsetX + x, dstOffsetY + y, srcPixel); } } } } u_int Film::GetChannelCount(const FilmChannelType type) const { switch (type) { case RADIANCE_PER_PIXEL_NORMALIZED: return channel_RADIANCE_PER_PIXEL_NORMALIZEDs.size(); case RADIANCE_PER_SCREEN_NORMALIZED: return channel_RADIANCE_PER_SCREEN_NORMALIZEDs.size(); case ALPHA: return channel_ALPHA ? 1 : 0; case RGB_TONEMAPPED: return channel_RGB_TONEMAPPED ? 1 : 0; case DEPTH: return channel_DEPTH ? 1 : 0; case POSITION: return channel_POSITION ? 1 : 0; case GEOMETRY_NORMAL: return channel_GEOMETRY_NORMAL ? 1 : 0; case SHADING_NORMAL: return channel_SHADING_NORMAL ? 1 : 0; case MATERIAL_ID: return channel_MATERIAL_ID ? 1 : 0; case DIRECT_DIFFUSE: return channel_DIRECT_DIFFUSE ? 1 : 0; case DIRECT_GLOSSY: return channel_DIRECT_GLOSSY ? 1 : 0; case EMISSION: return channel_EMISSION ? 1 : 0; case INDIRECT_DIFFUSE: return channel_INDIRECT_DIFFUSE ? 1 : 0; case INDIRECT_GLOSSY: return channel_INDIRECT_GLOSSY ? 1 : 0; case INDIRECT_SPECULAR: return channel_INDIRECT_SPECULAR ? 1 : 0; case MATERIAL_ID_MASK: return channel_MATERIAL_ID_MASKs.size(); case DIRECT_SHADOW_MASK: return channel_DIRECT_SHADOW_MASK ? 1 : 0; case INDIRECT_SHADOW_MASK: return channel_INDIRECT_SHADOW_MASK ? 1 : 0; case UV: return channel_UV ? 1 : 0; case RAYCOUNT: return channel_RAYCOUNT ? 1 : 0; case BY_MATERIAL_ID: return channel_BY_MATERIAL_IDs.size(); case IRRADIANCE: return channel_IRRADIANCE ? 1 : 0; default: throw runtime_error("Unknown FilmOutputType in Film::GetChannelCount>(): " + ToString(type)); } } size_t Film::GetOutputSize(const FilmOutputs::FilmOutputType type) const { switch (type) { case FilmOutputs::RGB: return 3 * pixelCount; case FilmOutputs::RGBA: return 4 * pixelCount; case FilmOutputs::RGB_TONEMAPPED: return 3 * pixelCount; case FilmOutputs::RGBA_TONEMAPPED: return 4 * pixelCount; case FilmOutputs::ALPHA: return pixelCount; case FilmOutputs::DEPTH: return pixelCount; case FilmOutputs::POSITION: return 3 * pixelCount; case FilmOutputs::GEOMETRY_NORMAL: return 3 * pixelCount; case FilmOutputs::SHADING_NORMAL: return 3 * pixelCount; case FilmOutputs::MATERIAL_ID: return pixelCount; case FilmOutputs::DIRECT_DIFFUSE: return 3 * pixelCount; case FilmOutputs::DIRECT_GLOSSY: return 3 * pixelCount; case FilmOutputs::EMISSION: return 3 * pixelCount; case FilmOutputs::INDIRECT_DIFFUSE: return 3 * pixelCount; case FilmOutputs::INDIRECT_GLOSSY: return 3 * pixelCount; case FilmOutputs::INDIRECT_SPECULAR: return 3 * pixelCount; case FilmOutputs::MATERIAL_ID_MASK: return pixelCount; case FilmOutputs::DIRECT_SHADOW_MASK: return pixelCount; case FilmOutputs::INDIRECT_SHADOW_MASK: return pixelCount; case FilmOutputs::RADIANCE_GROUP: return 3 * pixelCount; case FilmOutputs::UV: return 2 * pixelCount; case FilmOutputs::RAYCOUNT: return pixelCount; case FilmOutputs::BY_MATERIAL_ID: return 3 * pixelCount; case FilmOutputs::IRRADIANCE: return 3 * pixelCount; default: throw runtime_error("Unknown FilmOutputType in Film::GetOutputSize(): " + ToString(type)); } } bool Film::HasOutput(const FilmOutputs::FilmOutputType type) const { switch (type) { case FilmOutputs::RGB: return HasChannel(RADIANCE_PER_PIXEL_NORMALIZED) || HasChannel(RADIANCE_PER_SCREEN_NORMALIZED); case FilmOutputs::RGB_TONEMAPPED: return HasChannel(RGB_TONEMAPPED); case FilmOutputs::RGBA: return (HasChannel(RADIANCE_PER_PIXEL_NORMALIZED) || HasChannel(RADIANCE_PER_SCREEN_NORMALIZED)) && HasChannel(ALPHA); case FilmOutputs::RGBA_TONEMAPPED: return HasChannel(RGB_TONEMAPPED) && HasChannel(ALPHA); case FilmOutputs::ALPHA: return HasChannel(ALPHA); case FilmOutputs::DEPTH: return HasChannel(DEPTH); case FilmOutputs::POSITION: return HasChannel(POSITION); case FilmOutputs::GEOMETRY_NORMAL: return HasChannel(GEOMETRY_NORMAL); case FilmOutputs::SHADING_NORMAL: return HasChannel(SHADING_NORMAL); case FilmOutputs::MATERIAL_ID: return HasChannel(MATERIAL_ID); case FilmOutputs::DIRECT_DIFFUSE: return HasChannel(DIRECT_DIFFUSE); case FilmOutputs::DIRECT_GLOSSY: return HasChannel(DIRECT_GLOSSY); case FilmOutputs::EMISSION: return HasChannel(EMISSION); case FilmOutputs::INDIRECT_DIFFUSE: return HasChannel(INDIRECT_DIFFUSE); case FilmOutputs::INDIRECT_GLOSSY: return HasChannel(INDIRECT_GLOSSY); case FilmOutputs::INDIRECT_SPECULAR: return HasChannel(INDIRECT_SPECULAR); case FilmOutputs::MATERIAL_ID_MASK: return HasChannel(MATERIAL_ID_MASK); case FilmOutputs::DIRECT_SHADOW_MASK: return HasChannel(DIRECT_SHADOW_MASK); case FilmOutputs::INDIRECT_SHADOW_MASK: return HasChannel(INDIRECT_SHADOW_MASK); case FilmOutputs::RADIANCE_GROUP: return true; case FilmOutputs::UV: return HasChannel(UV); case FilmOutputs::RAYCOUNT: return HasChannel(RAYCOUNT); case FilmOutputs::BY_MATERIAL_ID: return HasChannel(BY_MATERIAL_ID); case FilmOutputs::IRRADIANCE: return HasChannel(IRRADIANCE); default: throw runtime_error("Unknown film output type in Film::HasOutput(): " + ToString(type)); } } void Film::Output(const FilmOutputs &filmOutputs) { for (u_int i = 0; i < filmOutputs.GetCount(); ++i) Output(filmOutputs.GetType(i), filmOutputs.GetFileName(i), &filmOutputs.GetProperties(i)); } void Film::Output(const FilmOutputs::FilmOutputType type, const string &fileName, const Properties *props) { u_int maskMaterialIDsIndex = 0; u_int byMaterialIDsIndex = 0; u_int radianceGroupIndex = 0; u_int channelCount = 3; switch (type) { case FilmOutputs::RGB: if (!HasChannel(RADIANCE_PER_PIXEL_NORMALIZED) && !HasChannel(RADIANCE_PER_SCREEN_NORMALIZED)) return; break; case FilmOutputs::RGB_TONEMAPPED: if (!HasChannel(RGB_TONEMAPPED)) return; ExecuteImagePipeline(); break; case FilmOutputs::RGBA: if ((!HasChannel(RADIANCE_PER_PIXEL_NORMALIZED) && !HasChannel(RADIANCE_PER_SCREEN_NORMALIZED)) || !HasChannel(ALPHA)) return; channelCount = 4; break; case FilmOutputs::RGBA_TONEMAPPED: if (!HasChannel(RGB_TONEMAPPED) || !HasChannel(ALPHA)) return; ExecuteImagePipeline(); channelCount = 4; break; case FilmOutputs::ALPHA: if (!HasChannel(ALPHA)) return; channelCount = 1; break; case FilmOutputs::DEPTH: if (!HasChannel(DEPTH)) return; channelCount = 1; break; case FilmOutputs::POSITION: if (!HasChannel(POSITION)) return; break; case FilmOutputs::GEOMETRY_NORMAL: if (!HasChannel(GEOMETRY_NORMAL)) return; break; case FilmOutputs::SHADING_NORMAL: if (!HasChannel(SHADING_NORMAL)) return; break; case FilmOutputs::MATERIAL_ID: if (!HasChannel(MATERIAL_ID)) return; break; case FilmOutputs::DIRECT_DIFFUSE: if (!HasChannel(DIRECT_DIFFUSE)) return; break; case FilmOutputs::DIRECT_GLOSSY: if (!HasChannel(DIRECT_GLOSSY)) return; break; case FilmOutputs::EMISSION: if (!HasChannel(EMISSION)) return; break; case FilmOutputs::INDIRECT_DIFFUSE: if (!HasChannel(INDIRECT_DIFFUSE)) return; break; case FilmOutputs::INDIRECT_GLOSSY: if (!HasChannel(INDIRECT_GLOSSY)) return; break; case FilmOutputs::INDIRECT_SPECULAR: if (!HasChannel(INDIRECT_SPECULAR)) return; break; case FilmOutputs::MATERIAL_ID_MASK: if (HasChannel(MATERIAL_ID_MASK) && props) { channelCount = 1; // Look for the material mask ID index const u_int id = props->Get(Property("id")(255)).Get<u_int>(); bool found = false; for (u_int i = 0; i < maskMaterialIDs.size(); ++i) { if (maskMaterialIDs[i] == id) { maskMaterialIDsIndex = i; found = true; break; } } if (!found) return; } else return; break; case FilmOutputs::DIRECT_SHADOW_MASK: if (!HasChannel(DIRECT_SHADOW_MASK)) return; channelCount = 1; break; case FilmOutputs::INDIRECT_SHADOW_MASK: if (!HasChannel(INDIRECT_SHADOW_MASK)) return; channelCount = 1; break; case FilmOutputs::RADIANCE_GROUP: if (!props) return; radianceGroupIndex = props->Get(Property("id")(0)).Get<u_int>(); if (radianceGroupIndex >= radianceGroupCount) return; break; case FilmOutputs::UV: if (!HasChannel(UV)) return; break; case FilmOutputs::RAYCOUNT: if (!HasChannel(RAYCOUNT)) return; channelCount = 1; break; case FilmOutputs::BY_MATERIAL_ID: if (HasChannel(BY_MATERIAL_ID) && props) { // Look for the material mask ID index const u_int id = props->Get(Property("id")(255)).Get<u_int>(); bool found = false; for (u_int i = 0; i < byMaterialIDs.size(); ++i) { if (byMaterialIDs[i] == id) { byMaterialIDsIndex = i; found = true; break; } } if (!found) return; } else return; break; case FilmOutputs::IRRADIANCE: if (!HasChannel(IRRADIANCE)) return; break; default: throw runtime_error("Unknown film output type in Film::Output(): " + ToString(type)); } ImageBuf buffer; SLG_LOG("Outputting film: " << fileName << " type: " << ToString(type)); if (type == FilmOutputs::MATERIAL_ID) { // For material IDs we must copy into int buffer first or risk screwing up the ID ImageSpec spec(width, height, channelCount, TypeDesc::UINT8); buffer.reset(spec); for (ImageBuf::ConstIterator<BYTE> it(buffer); !it.done(); ++it) { u_int x = it.x(); u_int y = it.y(); BYTE *pixel = (BYTE *)buffer.pixeladdr(x, y, 0); y = height - y - 1; if (pixel == NULL) throw runtime_error("Error while unpacking film data, could not address buffer!"); const u_int *src = channel_MATERIAL_ID->GetPixel(x, y); pixel[0] = (BYTE)src[0]; pixel[1] = (BYTE)src[1]; pixel[2] = (BYTE)src[2]; } } else { // OIIO 1 channel EXR output is apparently not working, I write 3 channels as // temporary workaround // For all others copy into float buffer first and let OIIO figure out the conversion on write ImageSpec spec(width, height, (channelCount == 1) ? 3 : channelCount, TypeDesc::FLOAT); buffer.reset(spec); for (ImageBuf::ConstIterator<float> it(buffer); !it.done(); ++it) { u_int x = it.x(); u_int y = it.y(); float *pixel = (float *)buffer.pixeladdr(x, y, 0); y = height - y - 1; if (pixel == NULL) throw runtime_error("Error while unpacking film data, could not address buffer!"); switch (type) { case FilmOutputs::RGB: { // Accumulate all light groups GetPixelFromMergedSampleBuffers(x, y, pixel); break; } case FilmOutputs::RGB_TONEMAPPED: { channel_RGB_TONEMAPPED->GetWeightedPixel(x, y, pixel); break; } case FilmOutputs::RGBA: { // Accumulate all light groups GetPixelFromMergedSampleBuffers(x, y, pixel); channel_ALPHA->GetWeightedPixel(x, y, &pixel[3]); break; } case FilmOutputs::RGBA_TONEMAPPED: { channel_RGB_TONEMAPPED->GetWeightedPixel(x, y, pixel); channel_ALPHA->GetWeightedPixel(x, y, &pixel[3]); break; } case FilmOutputs::ALPHA: { channel_ALPHA->GetWeightedPixel(x, y, pixel); break; } case FilmOutputs::DEPTH: { channel_DEPTH->GetWeightedPixel(x, y, pixel); break; } case FilmOutputs::POSITION: { channel_POSITION->GetWeightedPixel(x, y, pixel); break; } case FilmOutputs::GEOMETRY_NORMAL: { channel_GEOMETRY_NORMAL->GetWeightedPixel(x, y, pixel); break; } case FilmOutputs::SHADING_NORMAL: { channel_SHADING_NORMAL->GetWeightedPixel(x, y, pixel); break; } case FilmOutputs::DIRECT_DIFFUSE: { channel_DIRECT_DIFFUSE->GetWeightedPixel(x, y, pixel); break; } case FilmOutputs::DIRECT_GLOSSY: { channel_DIRECT_GLOSSY->GetWeightedPixel(x, y, pixel); break; } case FilmOutputs::EMISSION: { channel_EMISSION->GetWeightedPixel(x, y, pixel); break; } case FilmOutputs::INDIRECT_DIFFUSE: { channel_INDIRECT_DIFFUSE->GetWeightedPixel(x, y, pixel); break; } case FilmOutputs::INDIRECT_GLOSSY: { channel_INDIRECT_GLOSSY->GetWeightedPixel(x, y, pixel); break; } case FilmOutputs::INDIRECT_SPECULAR: { channel_INDIRECT_SPECULAR->GetWeightedPixel(x, y, pixel); break; } case FilmOutputs::MATERIAL_ID_MASK: { channel_MATERIAL_ID_MASKs[maskMaterialIDsIndex]->GetWeightedPixel(x, y, pixel); break; } case FilmOutputs::DIRECT_SHADOW_MASK: { channel_DIRECT_SHADOW_MASK->GetWeightedPixel(x, y, pixel); break; } case FilmOutputs::INDIRECT_SHADOW_MASK: { channel_INDIRECT_SHADOW_MASK->GetWeightedPixel(x, y, pixel); break; } case FilmOutputs::RADIANCE_GROUP: { // Accumulate all light groups if (radianceGroupIndex < channel_RADIANCE_PER_PIXEL_NORMALIZEDs.size()) channel_RADIANCE_PER_PIXEL_NORMALIZEDs[radianceGroupIndex]->AccumulateWeightedPixel(x, y, pixel); if (radianceGroupIndex < channel_RADIANCE_PER_SCREEN_NORMALIZEDs.size()) channel_RADIANCE_PER_SCREEN_NORMALIZEDs[radianceGroupIndex]->AccumulateWeightedPixel(x, y, pixel); break; } case FilmOutputs::UV: { channel_UV->GetWeightedPixel(x, y, pixel); pixel[2] = 0.f; break; } case FilmOutputs::RAYCOUNT: { channel_RAYCOUNT->GetWeightedPixel(x, y, pixel); break; } case FilmOutputs::BY_MATERIAL_ID: { channel_BY_MATERIAL_IDs[byMaterialIDsIndex]->GetWeightedPixel(x, y, pixel); break; } case FilmOutputs::IRRADIANCE: { channel_IRRADIANCE->GetWeightedPixel(x, y, pixel); break; } default: throw runtime_error("Unknown film output type in Film::Output(): " + ToString(type)); } // OIIO 1 channel EXR output is apparently not working, I write 3 channels as // temporary workaround if (channelCount == 1) { pixel[1] = pixel[0]; pixel[2] = pixel[0]; } } } buffer.write(fileName); } template<> const float *Film::GetChannel<float>(const FilmChannelType type, const u_int index) { switch (type) { case RADIANCE_PER_PIXEL_NORMALIZED: return channel_RADIANCE_PER_PIXEL_NORMALIZEDs[index]->GetPixels(); case RADIANCE_PER_SCREEN_NORMALIZED: return channel_RADIANCE_PER_SCREEN_NORMALIZEDs[index]->GetPixels(); case ALPHA: return channel_ALPHA->GetPixels(); case RGB_TONEMAPPED: { ExecuteImagePipeline(); return channel_RGB_TONEMAPPED->GetPixels(); } case DEPTH: return channel_DEPTH->GetPixels(); case POSITION: return channel_POSITION->GetPixels(); case GEOMETRY_NORMAL: return channel_GEOMETRY_NORMAL->GetPixels(); case SHADING_NORMAL: return channel_SHADING_NORMAL->GetPixels(); case DIRECT_DIFFUSE: return channel_DIRECT_DIFFUSE->GetPixels(); case DIRECT_GLOSSY: return channel_DIRECT_GLOSSY->GetPixels(); case EMISSION: return channel_EMISSION->GetPixels(); case INDIRECT_DIFFUSE: return channel_INDIRECT_DIFFUSE->GetPixels(); case INDIRECT_GLOSSY: return channel_INDIRECT_GLOSSY->GetPixels(); case INDIRECT_SPECULAR: return channel_INDIRECT_SPECULAR->GetPixels(); case MATERIAL_ID_MASK: return channel_MATERIAL_ID_MASKs[index]->GetPixels(); case DIRECT_SHADOW_MASK: return channel_DIRECT_SHADOW_MASK->GetPixels(); case INDIRECT_SHADOW_MASK: return channel_INDIRECT_SHADOW_MASK->GetPixels(); case UV: return channel_UV->GetPixels(); case RAYCOUNT: return channel_RAYCOUNT->GetPixels(); case BY_MATERIAL_ID: return channel_BY_MATERIAL_IDs[index]->GetPixels(); case IRRADIANCE: return channel_IRRADIANCE->GetPixels(); default: throw runtime_error("Unknown FilmOutputType in Film::GetChannel<float>(): " + ToString(type)); } } template<> const u_int *Film::GetChannel<u_int>(const FilmChannelType type, const u_int index) { switch (type) { case MATERIAL_ID: return channel_MATERIAL_ID->GetPixels(); default: throw runtime_error("Unknown FilmOutputType in Film::GetChannel<u_int>(): " + ToString(type)); } } template<> void Film::GetOutput<float>(const FilmOutputs::FilmOutputType type, float *buffer, const u_int index) { switch (type) { case FilmOutputs::RGB: { for (u_int i = 0; i < pixelCount; ++i) GetPixelFromMergedSampleBuffers(i, &buffer[i * 3]); break; } case FilmOutputs::RGB_TONEMAPPED: ExecuteImagePipeline(); copy(channel_RGB_TONEMAPPED->GetPixels(), channel_RGB_TONEMAPPED->GetPixels() + pixelCount * 3, buffer); break; case FilmOutputs::RGBA: { for (u_int i = 0; i < pixelCount; ++i) { const u_int offset = i * 4; GetPixelFromMergedSampleBuffers(i, &buffer[offset]); channel_ALPHA->GetWeightedPixel(i, &buffer[offset + 3]); } break; } case FilmOutputs::RGBA_TONEMAPPED: { ExecuteImagePipeline(); float *srcRGB = channel_RGB_TONEMAPPED->GetPixels(); float *dst = buffer; for (u_int i = 0; i < pixelCount; ++i) { *dst++ = *srcRGB++; *dst++ = *srcRGB++; *dst++ = *srcRGB++; channel_ALPHA->GetWeightedPixel(i, dst++); } break; } case FilmOutputs::ALPHA: { for (u_int i = 0; i < pixelCount; ++i) channel_ALPHA->GetWeightedPixel(i, &buffer[i]); break; } case FilmOutputs::DEPTH: copy(channel_DEPTH->GetPixels(), channel_DEPTH->GetPixels() + pixelCount, buffer); break; case FilmOutputs::POSITION: copy(channel_POSITION->GetPixels(), channel_POSITION->GetPixels() + pixelCount * 3, buffer); break; case FilmOutputs::GEOMETRY_NORMAL: copy(channel_GEOMETRY_NORMAL->GetPixels(), channel_GEOMETRY_NORMAL->GetPixels() + pixelCount * 3, buffer); break; case FilmOutputs::SHADING_NORMAL: copy(channel_SHADING_NORMAL->GetPixels(), channel_SHADING_NORMAL->GetPixels() + pixelCount * 3, buffer); break; case FilmOutputs::DIRECT_DIFFUSE: { for (u_int i = 0; i < pixelCount; ++i) channel_DIRECT_DIFFUSE->GetWeightedPixel(i, &buffer[i * 3]); break; } case FilmOutputs::DIRECT_GLOSSY: { for (u_int i = 0; i < pixelCount; ++i) channel_DIRECT_GLOSSY->GetWeightedPixel(i, &buffer[i * 3]); break; } case FilmOutputs::EMISSION: { for (u_int i = 0; i < pixelCount; ++i) channel_EMISSION->GetWeightedPixel(i, &buffer[i * 3]); break; } case FilmOutputs::INDIRECT_DIFFUSE: { for (u_int i = 0; i < pixelCount; ++i) channel_INDIRECT_DIFFUSE->GetWeightedPixel(i, &buffer[i * 3]); break; } case FilmOutputs::INDIRECT_GLOSSY: { for (u_int i = 0; i < pixelCount; ++i) channel_INDIRECT_GLOSSY->GetWeightedPixel(i, &buffer[i * 3]); break; } case FilmOutputs::INDIRECT_SPECULAR: { for (u_int i = 0; i < pixelCount; ++i) channel_INDIRECT_SPECULAR->GetWeightedPixel(i, &buffer[i * 3]); break; } case FilmOutputs::MATERIAL_ID_MASK: { for (u_int i = 0; i < pixelCount; ++i) channel_MATERIAL_ID_MASKs[index]->GetWeightedPixel(i, &buffer[i]); break; } case FilmOutputs::DIRECT_SHADOW_MASK: { for (u_int i = 0; i < pixelCount; ++i) channel_DIRECT_SHADOW_MASK->GetWeightedPixel(i, &buffer[i]); break; } case FilmOutputs::INDIRECT_SHADOW_MASK: { for (u_int i = 0; i < pixelCount; ++i) channel_INDIRECT_SHADOW_MASK->GetWeightedPixel(i, &buffer[i]); break; } case FilmOutputs::RADIANCE_GROUP: { fill(buffer, buffer + 3 * pixelCount, 0.f); if (index < channel_RADIANCE_PER_PIXEL_NORMALIZEDs.size()) { float *dst = buffer; for (u_int i = 0; i < pixelCount; ++i) { Spectrum c; channel_RADIANCE_PER_PIXEL_NORMALIZEDs[index]->AccumulateWeightedPixel(i, c.c); *dst++ += c.c[0]; *dst++ += c.c[1]; *dst++ += c.c[2]; } } if (index < channel_RADIANCE_PER_SCREEN_NORMALIZEDs.size()) { float *dst = buffer; for (u_int i = 0; i < pixelCount; ++i) { Spectrum c; channel_RADIANCE_PER_SCREEN_NORMALIZEDs[index]->AccumulateWeightedPixel(i, c.c); *dst++ += c.c[0]; *dst++ += c.c[1]; *dst++ += c.c[2]; } } break; } case FilmOutputs::UV: copy(channel_UV->GetPixels(), channel_UV->GetPixels() + pixelCount * 2, buffer); break; case FilmOutputs::RAYCOUNT: copy(channel_RAYCOUNT->GetPixels(), channel_RAYCOUNT->GetPixels() + pixelCount, buffer); break; case FilmOutputs::BY_MATERIAL_ID: { for (u_int i = 0; i < pixelCount; ++i) channel_BY_MATERIAL_IDs[index]->GetWeightedPixel(i, &buffer[i * 3]); break; } case FilmOutputs::IRRADIANCE: { for (u_int i = 0; i < pixelCount; ++i) channel_IRRADIANCE->GetWeightedPixel(i, &buffer[i]); break; } default: throw runtime_error("Unknown film output type in Film::GetOutput<float>(): " + ToString(type)); } } template<> void Film::GetOutput<u_int>(const FilmOutputs::FilmOutputType type, u_int *buffer, const u_int index) { switch (type) { case FilmOutputs::MATERIAL_ID: copy(channel_MATERIAL_ID->GetPixels(), channel_MATERIAL_ID->GetPixels() + pixelCount, buffer); break; default: throw runtime_error("Unknown film output type in Film::GetOutput<u_int>(): " + ToString(type)); } } void Film::GetPixelFromMergedSampleBuffers(const u_int index, float *c) const { c[0] = 0.f; c[1] = 0.f; c[2] = 0.f; for (u_int i = 0; i < channel_RADIANCE_PER_PIXEL_NORMALIZEDs.size(); ++i) channel_RADIANCE_PER_PIXEL_NORMALIZEDs[i]->AccumulateWeightedPixel(index, c); if (channel_RADIANCE_PER_SCREEN_NORMALIZEDs.size() > 0) { const float factor = statsTotalSampleCount / pixelCount; for (u_int i = 0; i < channel_RADIANCE_PER_SCREEN_NORMALIZEDs.size(); ++i) { const float *src = channel_RADIANCE_PER_SCREEN_NORMALIZEDs[i]->GetPixel(index); c[0] += src[0] * factor; c[1] += src[1] * factor; c[2] += src[2] * factor; } } } void Film::ExecuteImagePipeline() { if (!rgbTonemapUpdate || (!HasChannel(RADIANCE_PER_PIXEL_NORMALIZED) && !HasChannel(RADIANCE_PER_SCREEN_NORMALIZED)) || !HasChannel(RGB_TONEMAPPED)) { // Nothing to do return; } // Merge all buffers Spectrum *p = (Spectrum *)channel_RGB_TONEMAPPED->GetPixels(); const u_int pixelCount = width * height; vector<bool> frameBufferMask(pixelCount, false); MergeSampleBuffers(p, frameBufferMask); // Apply the image pipeline if I have one if (imagePipeline) imagePipeline->Apply(*this, p, frameBufferMask); } void Film::MergeSampleBuffers(Spectrum *p, vector<bool> &frameBufferMask) const { const u_int pixelCount = width * height; // Merge RADIANCE_PER_PIXEL_NORMALIZED and RADIANCE_PER_SCREEN_NORMALIZED buffers if (HasChannel(RADIANCE_PER_PIXEL_NORMALIZED)) { for (u_int i = 0; i < radianceGroupCount; ++i) { for (u_int j = 0; j < pixelCount; ++j) { const float *sp = channel_RADIANCE_PER_PIXEL_NORMALIZEDs[i]->GetPixel(j); if (sp[3] > 0.f) { if (frameBufferMask[j]) p[j] += Spectrum(sp) / sp[3]; else p[j] = Spectrum(sp) / sp[3]; frameBufferMask[j] = true; } } } } if (HasChannel(RADIANCE_PER_SCREEN_NORMALIZED)) { const float factor = pixelCount / statsTotalSampleCount; for (u_int i = 0; i < radianceGroupCount; ++i) { for (u_int j = 0; j < pixelCount; ++j) { const Spectrum s(channel_RADIANCE_PER_SCREEN_NORMALIZEDs[i]->GetPixel(j)); if (!s.Black()) { if (frameBufferMask[j]) p[j] += s * factor; else p[j] = s * factor; frameBufferMask[j] = true; } } } } if (!enabledOverlappedScreenBufferUpdate) { for (u_int i = 0; i < pixelCount; ++i) { if (!frameBufferMask[i]) p[i] = Spectrum(); } } } void Film::AddSampleResultColor(const u_int x, const u_int y, const SampleResult &sampleResult, const float weight) { if ((channel_RADIANCE_PER_PIXEL_NORMALIZEDs.size() > 0) && sampleResult.HasChannel(RADIANCE_PER_PIXEL_NORMALIZED)) { for (u_int i = 0; i < Min(sampleResult.radiancePerPixelNormalized.size(), channel_RADIANCE_PER_PIXEL_NORMALIZEDs.size()); ++i) { if (sampleResult.radiancePerPixelNormalized[i].IsNaN() || sampleResult.radiancePerPixelNormalized[i].IsInf()) continue; channel_RADIANCE_PER_PIXEL_NORMALIZEDs[i]->AddWeightedPixel(x, y, sampleResult.radiancePerPixelNormalized[i].c, weight); } } // Faster than HasChannel(channel_RADIANCE_PER_SCREEN_NORMALIZED) if ((channel_RADIANCE_PER_SCREEN_NORMALIZEDs.size() > 0) && sampleResult.HasChannel(RADIANCE_PER_SCREEN_NORMALIZED)) { for (u_int i = 0; i < Min(sampleResult.radiancePerScreenNormalized.size(), channel_RADIANCE_PER_SCREEN_NORMALIZEDs.size()); ++i) { if (sampleResult.radiancePerScreenNormalized[i].IsNaN() || sampleResult.radiancePerScreenNormalized[i].IsInf()) continue; channel_RADIANCE_PER_SCREEN_NORMALIZEDs[i]->AddWeightedPixel(x, y, sampleResult.radiancePerScreenNormalized[i].c, weight); } } // Faster than HasChannel(ALPHA) if (channel_ALPHA && sampleResult.HasChannel(ALPHA)) channel_ALPHA->AddWeightedPixel(x, y, &sampleResult.alpha, weight); if (hasComposingChannel) { // Faster than HasChannel(DIRECT_DIFFUSE) if (channel_DIRECT_DIFFUSE && sampleResult.HasChannel(DIRECT_DIFFUSE)) channel_DIRECT_DIFFUSE->AddWeightedPixel(x, y, sampleResult.directDiffuse.c, weight); // Faster than HasChannel(DIRECT_GLOSSY) if (channel_DIRECT_GLOSSY && sampleResult.HasChannel(DIRECT_GLOSSY)) channel_DIRECT_GLOSSY->AddWeightedPixel(x, y, sampleResult.directGlossy.c, weight); // Faster than HasChannel(EMISSION) if (channel_EMISSION && sampleResult.HasChannel(EMISSION)) channel_EMISSION->AddWeightedPixel(x, y, sampleResult.emission.c, weight); // Faster than HasChannel(INDIRECT_DIFFUSE) if (channel_INDIRECT_DIFFUSE && sampleResult.HasChannel(INDIRECT_DIFFUSE)) channel_INDIRECT_DIFFUSE->AddWeightedPixel(x, y, sampleResult.indirectDiffuse.c, weight); // Faster than HasChannel(INDIRECT_GLOSSY) if (channel_INDIRECT_GLOSSY && sampleResult.HasChannel(INDIRECT_GLOSSY)) channel_INDIRECT_GLOSSY->AddWeightedPixel(x, y, sampleResult.indirectGlossy.c, weight); // Faster than HasChannel(INDIRECT_SPECULAR) if (channel_INDIRECT_SPECULAR && sampleResult.HasChannel(INDIRECT_SPECULAR)) channel_INDIRECT_SPECULAR->AddWeightedPixel(x, y, sampleResult.indirectSpecular.c, weight); // This is MATERIAL_ID_MASK and BY_MATERIAL_ID if (sampleResult.HasChannel(MATERIAL_ID)) { // MATERIAL_ID_MASK for (u_int i = 0; i < maskMaterialIDs.size(); ++i) { float pixel[2]; pixel[0] = (sampleResult.materialID == maskMaterialIDs[i]) ? weight : 0.f; pixel[1] = weight; channel_MATERIAL_ID_MASKs[i]->AddPixel(x, y, pixel); } // BY_MATERIAL_ID if ((channel_RADIANCE_PER_PIXEL_NORMALIZEDs.size() > 0) && sampleResult.HasChannel(RADIANCE_PER_PIXEL_NORMALIZED)) { for (u_int index = 0; index < byMaterialIDs.size(); ++index) { Spectrum c; if (sampleResult.materialID == byMaterialIDs[index]) { // Merge all radiance groups for (u_int i = 0; i < Min(sampleResult.radiancePerPixelNormalized.size(), channel_RADIANCE_PER_PIXEL_NORMALIZEDs.size()); ++i) { if (sampleResult.radiancePerPixelNormalized[i].IsNaN() || sampleResult.radiancePerPixelNormalized[i].IsInf()) continue; c += sampleResult.radiancePerPixelNormalized[i]; } } channel_BY_MATERIAL_IDs[index]->AddWeightedPixel(x, y, c.c, weight); } } } // Faster than HasChannel(DIRECT_SHADOW) if (channel_DIRECT_SHADOW_MASK && sampleResult.HasChannel(DIRECT_SHADOW_MASK)) channel_DIRECT_SHADOW_MASK->AddWeightedPixel(x, y, &sampleResult.directShadowMask, weight); // Faster than HasChannel(INDIRECT_SHADOW_MASK) if (channel_INDIRECT_SHADOW_MASK && sampleResult.HasChannel(INDIRECT_SHADOW_MASK)) channel_INDIRECT_SHADOW_MASK->AddWeightedPixel(x, y, &sampleResult.indirectShadowMask, weight); // Faster than HasChannel(IRRADIANCE) if (channel_IRRADIANCE && sampleResult.HasChannel(IRRADIANCE)) channel_IRRADIANCE->AddWeightedPixel(x, y, sampleResult.irradiance.c, weight); } } void Film::AddSampleResultData(const u_int x, const u_int y, const SampleResult &sampleResult) { bool depthWrite = true; // Faster than HasChannel(DEPTH) if (channel_DEPTH && sampleResult.HasChannel(DEPTH)) depthWrite = channel_DEPTH->MinPixel(x, y, &sampleResult.depth); if (depthWrite) { // Faster than HasChannel(POSITION) if (channel_POSITION && sampleResult.HasChannel(POSITION)) channel_POSITION->SetPixel(x, y, &sampleResult.position.x); // Faster than HasChannel(GEOMETRY_NORMAL) if (channel_GEOMETRY_NORMAL && sampleResult.HasChannel(GEOMETRY_NORMAL)) channel_GEOMETRY_NORMAL->SetPixel(x, y, &sampleResult.geometryNormal.x); // Faster than HasChannel(SHADING_NORMAL) if (channel_SHADING_NORMAL && sampleResult.HasChannel(SHADING_NORMAL)) channel_SHADING_NORMAL->SetPixel(x, y, &sampleResult.shadingNormal.x); // Faster than HasChannel(MATERIAL_ID) if (channel_MATERIAL_ID && sampleResult.HasChannel(MATERIAL_ID)) channel_MATERIAL_ID->SetPixel(x, y, &sampleResult.materialID); // Faster than HasChannel(UV) if (channel_UV && sampleResult.HasChannel(UV)) channel_UV->SetPixel(x, y, &sampleResult.uv.u); } if (channel_RAYCOUNT && sampleResult.HasChannel(RAYCOUNT)) channel_RAYCOUNT->AddPixel(x, y, &sampleResult.rayCount); } void Film::AddSample(const u_int x, const u_int y, const SampleResult &sampleResult, const float weight) { AddSampleResultColor(x, y, sampleResult, weight); if (hasDataChannel) AddSampleResultData(x, y, sampleResult); } void Film::SplatSample(const SampleResult &sampleResult, const float weight) { if (!filter) { const int x = Ceil2Int(sampleResult.filmX - .5f); const int y = Ceil2Int(sampleResult.filmY - .5f); if ((x >= 0) && (x < (int)width) && (y >= 0) && (y < (int)height)) { AddSampleResultColor(x, y, sampleResult, weight); if (hasDataChannel) AddSampleResultData(x, y, sampleResult); } } else { //---------------------------------------------------------------------- // Add all data related information (not filtered) //---------------------------------------------------------------------- if (hasDataChannel) { const int x = Ceil2Int(sampleResult.filmX - .5f); const int y = Ceil2Int(sampleResult.filmY - .5f); if ((x >= 0.f) && (x < (int)width) && (y >= 0.f) && (y < (int)height)) AddSampleResultData(x, y, sampleResult); } //---------------------------------------------------------------------- // Add all color related information (filtered) //---------------------------------------------------------------------- // Compute sample's raster extent const float dImageX = sampleResult.filmX - .5f; const float dImageY = sampleResult.filmY - .5f; const FilterLUT *filterLUT = filterLUTs->GetLUT(dImageX - floorf(sampleResult.filmX), dImageY - floorf(sampleResult.filmY)); const float *lut = filterLUT->GetLUT(); const int x0 = Ceil2Int(dImageX - filter->xWidth); const int x1 = x0 + filterLUT->GetWidth(); const int y0 = Ceil2Int(dImageY - filter->yWidth); const int y1 = y0 + filterLUT->GetHeight(); for (int iy = y0; iy < y1; ++iy) { if (iy < 0) { lut += filterLUT->GetWidth(); continue; } else if(iy >= (int)height) break; for (int ix = x0; ix < x1; ++ix) { const float filterWeight = *lut++; if ((ix < 0) || (ix >= (int)width)) continue; const float filteredWeight = weight * filterWeight; AddSampleResultColor(ix, iy, sampleResult, filteredWeight); } } } } void Film::ResetConvergenceTest() { if (convTest) convTest->Reset(); } u_int Film::RunConvergenceTest() { // Required in order to have a valid convergence test ExecuteImagePipeline(); return convTest->Test((const float *)channel_RGB_TONEMAPPED->GetPixels()); } Film::FilmChannelType Film::String2FilmChannelType(const std::string &type) { if (type == "RADIANCE_PER_PIXEL_NORMALIZED") return RADIANCE_PER_PIXEL_NORMALIZED; else if (type == "RADIANCE_PER_SCREEN_NORMALIZED") return RADIANCE_PER_SCREEN_NORMALIZED; else if (type == "ALPHA") return ALPHA; else if (type == "DEPTH") return DEPTH; else if (type == "POSITION") return POSITION; else if (type == "GEOMETRY_NORMAL") return GEOMETRY_NORMAL; else if (type == "SHADING_NORMAL") return SHADING_NORMAL; else if (type == "MATERIAL_ID") return MATERIAL_ID; else if (type == "DIRECT_DIFFUSE") return DIRECT_DIFFUSE; else if (type == "DIRECT_GLOSSY") return DIRECT_GLOSSY; else if (type == "EMISSION") return EMISSION; else if (type == "INDIRECT_DIFFUSE") return INDIRECT_DIFFUSE; else if (type == "INDIRECT_GLOSSY") return INDIRECT_GLOSSY; else if (type == "INDIRECT_SPECULAR") return INDIRECT_SPECULAR; else if (type == "INDIRECT_SPECULAR") return INDIRECT_SPECULAR; else if (type == "MATERIAL_ID_MASK") return MATERIAL_ID_MASK; else if (type == "DIRECT_SHADOW_MASK") return DIRECT_SHADOW_MASK; else if (type == "INDIRECT_SHADOW_MASK") return INDIRECT_SHADOW_MASK; else if (type == "UV") return UV; else if (type == "RAYCOUNT") return RAYCOUNT; else if (type == "BY_MATERIAL_ID") return BY_MATERIAL_ID; else if (type == "IRRADIANCE") return IRRADIANCE; else throw runtime_error("Unknown film output type in Film::String2FilmChannelType(): " + type); } const std::string Film::FilmChannelType2String(const Film::FilmChannelType type) { switch (type) { case Film::RADIANCE_PER_PIXEL_NORMALIZED: return "RADIANCE_PER_PIXEL_NORMALIZED"; case Film::RADIANCE_PER_SCREEN_NORMALIZED: return "RADIANCE_PER_SCREEN_NORMALIZED"; case Film::ALPHA: return "ALPHA"; case Film::DEPTH: return "DEPTH"; case Film::POSITION: return "POSITION"; case Film::GEOMETRY_NORMAL: return "GEOMETRY_NORMAL"; case Film::SHADING_NORMAL: return "SHADING_NORMAL"; case Film::MATERIAL_ID: return "MATERIAL_ID"; case Film::DIRECT_DIFFUSE: return "DIRECT_DIFFUSE"; case Film::DIRECT_GLOSSY: return "DIRECT_GLOSSY"; case Film::EMISSION: return "EMISSION"; case Film::INDIRECT_DIFFUSE: return "INDIRECT_DIFFUSE"; case Film::INDIRECT_GLOSSY: return "INDIRECT_GLOSSY"; case Film::INDIRECT_SPECULAR: return "INDIRECT_SPECULAR"; case Film::MATERIAL_ID_MASK: return "MATERIAL_ID_MASK"; case Film::DIRECT_SHADOW_MASK: return "DIRECT_SHADOW_MASK"; case Film::INDIRECT_SHADOW_MASK: return "INDIRECT_SHADOW_MASK"; case Film::UV: return "UV"; case Film::RAYCOUNT: return "RAYCOUNT"; case Film::BY_MATERIAL_ID: return "BY_MATERIAL_ID"; case Film::IRRADIANCE: return "IRRADIANCE"; default: throw runtime_error("Unknown film output type in Film::FilmChannelType2String(): " + ToString(type)); } } template<> void Film::load<boost::archive::binary_iarchive>(boost::archive::binary_iarchive &ar, const u_int version) { ar >> channel_RADIANCE_PER_PIXEL_NORMALIZEDs; ar >> channel_RADIANCE_PER_SCREEN_NORMALIZEDs; ar >> channel_ALPHA; ar >> channel_RGB_TONEMAPPED; ar >> channel_DEPTH; ar >> channel_POSITION; ar >> channel_GEOMETRY_NORMAL; ar >> channel_SHADING_NORMAL; ar >> channel_MATERIAL_ID; ar >> channel_DIRECT_DIFFUSE; ar >> channel_DIRECT_GLOSSY; ar >> channel_EMISSION; ar >> channel_INDIRECT_DIFFUSE; ar >> channel_INDIRECT_GLOSSY; ar >> channel_INDIRECT_SPECULAR; ar >> channel_MATERIAL_ID_MASKs; ar >> channel_DIRECT_SHADOW_MASK; ar >> channel_INDIRECT_SHADOW_MASK; ar >> channel_UV; ar >> channel_RAYCOUNT; ar >> channel_BY_MATERIAL_IDs; ar >> channel_IRRADIANCE; ar >> channels; ar >> width; ar >> height; ar >> pixelCount; ar >> radianceGroupCount; ar >> maskMaterialIDs; ar >> byMaterialIDs; ar >> statsTotalSampleCount; ar >> statsStartSampleTime; ar >> statsAvgSampleSec; ar >> imagePipeline; ar >> convTest; ar >> filter; // filterLUTs is re-built at load time if (filter) { const u_int size = Max<u_int>(4, Max(filter->xWidth, filter->yWidth) + 1); filterLUTs = new FilterLUTs(*filter, size); } else filterLUTs = NULL; ar >> initialized; ar >> enabledOverlappedScreenBufferUpdate; ar >> rgbTonemapUpdate; } template<> void Film::save<boost::archive::binary_oarchive>(boost::archive::binary_oarchive &ar, const u_int version) const { ar << channel_RADIANCE_PER_PIXEL_NORMALIZEDs; ar << channel_RADIANCE_PER_SCREEN_NORMALIZEDs; ar << channel_ALPHA; ar << channel_RGB_TONEMAPPED; ar << channel_DEPTH; ar << channel_POSITION; ar << channel_GEOMETRY_NORMAL; ar << channel_SHADING_NORMAL; ar << channel_MATERIAL_ID; ar << channel_DIRECT_DIFFUSE; ar << channel_DIRECT_GLOSSY; ar << channel_EMISSION; ar << channel_INDIRECT_DIFFUSE; ar << channel_INDIRECT_GLOSSY; ar << channel_INDIRECT_SPECULAR; ar << channel_MATERIAL_ID_MASKs; ar << channel_DIRECT_SHADOW_MASK; ar << channel_INDIRECT_SHADOW_MASK; ar << channel_UV; ar << channel_RAYCOUNT; ar << channel_BY_MATERIAL_IDs; ar << channel_IRRADIANCE; ar << channels; ar << width; ar << height; ar << pixelCount; ar << radianceGroupCount; ar << maskMaterialIDs; ar << byMaterialIDs; ar << statsTotalSampleCount; ar << statsStartSampleTime; ar << statsAvgSampleSec; ar << imagePipeline; ar << convTest; ar << filter; // filterLUTs is re-built at load time ar << initialized; ar << enabledOverlappedScreenBufferUpdate; ar << rgbTonemapUpdate; } //------------------------------------------------------------------------------ // SampleResult //------------------------------------------------------------------------------ void SampleResult::AddEmission(const u_int lightID, const Spectrum &pathThroughput, const Spectrum &incomingRadiance) { const Spectrum radiance = pathThroughput * incomingRadiance; radiancePerPixelNormalized[lightID] += radiance; if (firstPathVertex) emission += radiance; else { indirectShadowMask = 0.f; if (firstPathVertexEvent & DIFFUSE) indirectDiffuse += radiance; else if (firstPathVertexEvent & GLOSSY) indirectGlossy += radiance; else if (firstPathVertexEvent & SPECULAR) indirectSpecular += radiance; } } void SampleResult::AddDirectLight(const u_int lightID, const BSDFEvent bsdfEvent, const Spectrum &pathThroughput, const Spectrum &incomingRadiance, const float lightScale) { const Spectrum radiance = pathThroughput * incomingRadiance; radiancePerPixelNormalized[lightID] += radiance; if (firstPathVertex) { // directShadowMask is supposed to be initialized to 1.0 directShadowMask = Max(0.f, directShadowMask - lightScale); if (bsdfEvent & DIFFUSE) directDiffuse += radiance; else directGlossy += radiance; } else { // indirectShadowMask is supposed to be initialized to 1.0 indirectShadowMask = Max(0.f, indirectShadowMask - lightScale); if (firstPathVertexEvent & DIFFUSE) indirectDiffuse += radiance; else if (firstPathVertexEvent & GLOSSY) indirectGlossy += radiance; else if (firstPathVertexEvent & SPECULAR) indirectSpecular += radiance; irradiance += irradiancePathThroughput * incomingRadiance; } } void SampleResult::AddSampleResult(std::vector<SampleResult> &sampleResults, const float filmX, const float filmY, const Spectrum &radiancePPN, const float alpha) { assert(!radiancePPN.IsInf() || !radiancePPN.IsNaN()); assert(!isinf(alpha) || !isnan(alpha)); const u_int size = sampleResults.size(); sampleResults.resize(size + 1); sampleResults[size].Init(Film::RADIANCE_PER_PIXEL_NORMALIZED | Film::ALPHA, 1); sampleResults[size].filmX = filmX; sampleResults[size].filmY = filmY; sampleResults[size].radiancePerPixelNormalized[0] = radiancePPN; sampleResults[size].alpha = alpha; } void SampleResult::AddSampleResult(std::vector<SampleResult> &sampleResults, const float filmX, const float filmY, const Spectrum &radiancePSN) { assert(!radiancePSN.IsInf() || !radiancePSN.IsNaN()); const u_int size = sampleResults.size(); sampleResults.resize(size + 1); sampleResults[size].Init(Film::RADIANCE_PER_SCREEN_NORMALIZED, 1); sampleResults[size].filmX = filmX; sampleResults[size].filmY = filmY; sampleResults[size].radiancePerScreenNormalized[0] = radiancePSN; }
33.339009
136
0.693148
eab95df009eeed45149bf914d5a1f84f0370f35c
934
cpp
C++
src/071.simplify_path/code.cpp
cloudzfy/leetcode
9d32090429ef297e1f62877382bff582d247266a
[ "MIT" ]
1
2016-07-02T17:44:10.000Z
2016-07-02T17:44:10.000Z
src/071.simplify_path/code.cpp
cloudzfy/leetcode
9d32090429ef297e1f62877382bff582d247266a
[ "MIT" ]
null
null
null
src/071.simplify_path/code.cpp
cloudzfy/leetcode
9d32090429ef297e1f62877382bff582d247266a
[ "MIT" ]
1
2019-12-21T04:57:15.000Z
2019-12-21T04:57:15.000Z
class Solution { public: string simplifyPath(string path) { stack<string> s; string ans; int len = path.length(); if (len == 0) return ans; int start, end; for (int i = 0; i < len; i++) { if (i > 0 && path[i] != '/' && path[i - 1] == '/') { start = i - 1; } if (path[i] != '/' && ((i + 1 < len && path[i + 1] == '/') || (i == len - 1))) { end = i; string tmp = path.substr(start, end - start + 1); if (tmp == "/.") continue; else if (tmp == "/..") { if (!s.empty()) s.pop(); } else { s.push(tmp); } } } while(!s.empty()) { ans = s.top() + ans; s.pop(); } if (ans == "") ans = "/"; return ans; } };
28.30303
92
0.313704
eab9870e3fd5d0d35a46824b7c7a469cf4a9f334
362
cpp
C++
array/Kth Row of Pascal's Triangle.cpp
1aman1/practice-InterviewBit
cafb841bd57f74f8fc3690a7f7830e6ca9fda916
[ "MIT" ]
1
2019-08-14T05:46:57.000Z
2019-08-14T05:46:57.000Z
array/Kth Row of Pascal's Triangle.cpp
1aman1/practice
cafb841bd57f74f8fc3690a7f7830e6ca9fda916
[ "MIT" ]
null
null
null
array/Kth Row of Pascal's Triangle.cpp
1aman1/practice
cafb841bd57f74f8fc3690a7f7830e6ca9fda916
[ "MIT" ]
null
null
null
/* A0-> 1 A1-> 1 1 A2-> 1 2 1 A3-> 1 3 3 1 for A, pascal triangle will have A+1 elements */ vector<int> Solution::getRow(int A) { vector<int> result; int value = 1, index; for( index = 0; index <= A ; index++){ result.push_back(value); value = value * (A - index)/(index + 1); } return result; }
21.294118
52
0.508287
eab9ea26b789a8deb87fcc31f169ada82a197dc8
44,492
cpp
C++
core/sql/parser/StmtDDLNode.cpp
sandhyasun/trafodion
db1a8a73b7b3b4767d5dec60ae091df891cfceee
[ "Apache-2.0" ]
null
null
null
core/sql/parser/StmtDDLNode.cpp
sandhyasun/trafodion
db1a8a73b7b3b4767d5dec60ae091df891cfceee
[ "Apache-2.0" ]
null
null
null
core/sql/parser/StmtDDLNode.cpp
sandhyasun/trafodion
db1a8a73b7b3b4767d5dec60ae091df891cfceee
[ "Apache-2.0" ]
null
null
null
/* -*-C++-*- // @@@ START COPYRIGHT @@@ // // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. // // @@@ END COPYRIGHT @@@ ***************************************************************************** * * File: StmtDDLNode.C * Description: member functions for classes StmtDDLNode, StmtDDLGrant, * StmtDDLGrantArray, StmtDDLInitializeSQL, StmtDDLRevoke, * StmtDDLSchRevoke, StmtDDLPublish * * Created: 3/9/95 * Language: C++ * * * * ***************************************************************************** */ #include "BaseTypes.h" #include "ComOperators.h" #include "ElemDDLPrivileges.h" #include "ElemDDLGrantee.h" #include "StmtDDLNode.h" #include "StmtDDLGrant.h" #include "StmtDDLGrantComponentPrivilege.h" #include "StmtDDLGrantArray.h" #include "StmtDDLSchGrant.h" #include "StmtDDLSchGrantArray.h" #include "StmtDDLPublish.h" #include "StmtDDLInitializeSQL.h" #include "StmtDDLRevoke.h" #include "StmtDDLSchRevoke.h" #include "StmtDDLReInitializeSQL.h" void StmtDDLInitializeSQL_visitRegisterUserElement(ElemDDLNode * pInitSQLNode, CollIndex /* index */, ElemDDLNode * pElement); // ----------------------------------------------------------------------- // member functions for class StmtDDLNode // ----------------------------------------------------------------------- StmtDDLNode::StmtDDLNode(OperatorTypeEnum otype) : ElemDDLNode(otype), tableType_(COM_REGULAR_TABLE), objectClass_(COM_CLASS_USER_TABLE), isVolatile_(FALSE), exeUtil_(FALSE), isGhostObject_(FALSE), inMemoryObjectDefn_(FALSE), isExternal_(FALSE), ddlXns_(FALSE) { ddlXns_ = (CmpCommon::getDefault(DDL_TRANSACTIONS) == DF_ON); } // virtual destructor // To improve performance, do not use inline with virtual destructor StmtDDLNode::~StmtDDLNode() { } // // cast virtual functions // StmtDDLNode * StmtDDLNode::castToStmtDDLNode() { return this; } const StmtDDLNode * StmtDDLNode::castToStmtDDLNode() const { return this; } // // methods for tracing // const NAString StmtDDLNode::getText() const { NAAbort("StmtDDLNode.C", __LINE__, "internal logic error"); return "StmtDDLNode"; } void StmtDDLNode::unparse(NAString &result, PhaseEnum /*phase*/, UnparseFormatEnum /*form*/, TableDesc * tabId) const { result += "a DDL statement"; } NABoolean StmtDDLNode::performParallelOp(Lng32 numPartitions) { // PerformParallelOp NABoolean ppo = FALSE; // The CQD USE_PARALLEL_FOR_NUM_PARTITIONS specifies the number of // partitions that must exist before // performing the create in parallel. Lng32 numParts = CmpCommon::getDefaultLong(USE_PARALLEL_FOR_NUM_PARTITIONS); NAString pos; CmpCommon::getDefault(POS, pos, 0); // Parallel Create logic should be executed only if POS and // ATTEMPT_ESP_PARALLELISM are not turned OFF and table involved has // multiple partitions. if ((CmpCommon::getDefault(POS) != DF_OFF) && (!IsNAStringSpaceOrEmpty(pos)) && (CmpCommon::getDefault(ATTEMPT_ESP_PARALLELISM) != DF_OFF) && (numPartitions >= numParts) && (numPartitions > 1)) { // Check to see if parallel creation of labels is required // Parallel creations should not happen if POS_NUM_OF_PARTNS is set // to 1 ( single partition table). if (CmpCommon::getDefault(POS_NUM_OF_PARTNS,0) == DF_SYSTEM ) ppo = TRUE; else { // Not DF_SYSTEM - get numeric POS_NUM_OF_PARTNS Lng32 posnumpartns = CmpCommon::getDefaultLong(POS_NUM_OF_PARTNS); if (posnumpartns > 1) ppo = TRUE; } } return ppo; } // ----------------------------------------------------------------------- // member functions for class StmtDDLGrant // ----------------------------------------------------------------------- // // constructor // StmtDDLGrant::StmtDDLGrant(ElemDDLNode * pPrivileges, const QualifiedName & objectName, ElemDDLNode * pGranteeList, ElemDDLNode * pWithGrantOption, ElemDDLNode * pByGrantorOption, QualifiedName * actionName, CollHeap * heap) : StmtDDLNode(DDL_GRANT), objectName_(heap), objectQualName_(objectName, heap), isAllPrivileges_(FALSE), isWithGrantOptionSpec_(FALSE), privActArray_(heap), actionQualName_(actionName), granteeArray_(heap), isByGrantorOptionSpec_(FALSE), byGrantor_(NULL) { setChild(INDEX_PRIVILEGES, pPrivileges); setChild(INDEX_GRANTEE_LIST, pGranteeList); setChild(INDEX_WITH_GRANT_OPTION, pWithGrantOption); setChild(INDEX_BY_GRANTOR_OPTION, pByGrantorOption); objectName_ = objectQualName_.getQualifiedNameAsAnsiString(); // // inserts pointers to parse nodes representing privilege // actions to privActArray_ so the user can access the // information about privilege actions easier. // ComASSERT(pPrivileges NEQ NULL); ElemDDLPrivileges * pPrivsNode = pPrivileges->castToElemDDLPrivileges(); ComASSERT(pPrivsNode NEQ NULL); if (pPrivsNode->isAllPrivileges()) { isAllPrivileges_ = TRUE; } else { ElemDDLNode * pPrivActs = pPrivsNode->getPrivilegeActionList(); for (CollIndex i = 0; i < pPrivActs->entries(); i++) { ElemDDLPrivAct *pPrivAct = (*pPrivActs)[i]->castToElemDDLPrivAct(); privActArray_.insert(pPrivAct); if (pPrivAct->isDDLPriv()) privActArray_.setHasDDLPriv(TRUE); } } // // copies pointers to parse nodes representing grantee // to granteeArray_ so the user can access the information // easier. // ComASSERT(pGranteeList NEQ NULL); for (CollIndex i = 0; i < pGranteeList->entries(); i++) { granteeArray_.insert((*pGranteeList)[i]->castToElemDDLGrantee()); } // // looks for With Grant option phrase // if (pWithGrantOption NEQ NULL) { isWithGrantOptionSpec_ = TRUE; } if ( pByGrantorOption NEQ NULL ) { isByGrantorOptionSpec_ = TRUE; byGrantor_ = pByGrantorOption->castToElemDDLGrantee(); } } // StmtDDLGrant::StmtDDLGrant() // virtual destructor StmtDDLGrant::~StmtDDLGrant() { // delete all children for (Int32 i = 0; i < getArity(); i++) { delete getChild(i); } } // cast StmtDDLGrant * StmtDDLGrant::castToStmtDDLGrant() { return this; } // // accessors // Int32 StmtDDLGrant::getArity() const { return MAX_STMT_DDL_GRANT_ARITY; } ExprNode * StmtDDLGrant::getChild(Lng32 index) { ComASSERT(index >= 0 AND index < getArity()); return children_[index]; } // // mutators // void StmtDDLGrant::setChild(Lng32 index, ExprNode * pChildNode) { ComASSERT(index >= 0 AND index < getArity()); if (pChildNode NEQ NULL) { ComASSERT(pChildNode->castToElemDDLNode() NEQ NULL); children_[index] = pChildNode->castToElemDDLNode(); } else { children_[index] = NULL; } } // // methods for tracing // const NAString StmtDDLGrant::displayLabel1() const { return NAString("Object name: ") + getObjectName(); } NATraceList StmtDDLGrant::getDetailInfo() const { NAString detailText; NATraceList detailTextList; // // object name // detailTextList.append(displayLabel1()); // object name // // privileges // StmtDDLGrant * localThis = (StmtDDLGrant *)this; detailTextList.append(localThis->getChild(INDEX_PRIVILEGES) ->castToElemDDLNode() ->castToElemDDLPrivileges() ->getDetailInfo()); // // grantee list // const ElemDDLGranteeArray & granteeArray = getGranteeArray(); detailText = "Grantee list ["; detailText += LongToNAString((Lng32)granteeArray.entries()); detailText += " element(s)]"; detailTextList.append(detailText); for (CollIndex i = 0; i < granteeArray.entries(); i++) { detailText = "[grantee "; detailText += LongToNAString((Lng32)i); detailText += "]"; detailTextList.append(detailText); ComASSERT(granteeArray[i] NEQ NULL AND granteeArray[i]->castToElemDDLGrantee() NEQ NULL); detailTextList.append(" ", granteeArray[i]->castToElemDDLGrantee() ->getDetailInfo()); } // // with grant option // detailText = "is with grant option? "; detailText += YesNo(localThis->getChild(INDEX_WITH_GRANT_OPTION) NEQ NULL); detailTextList.append(detailText); return detailTextList; } // StmtDDLGrant::getDetailInfo const NAString StmtDDLGrant::getText() const { return "StmtDDLGrant"; } // ----------------------------------------------------------------------- // methods for class StmtDDLGrantArray // ----------------------------------------------------------------------- // virtual destructor StmtDDLGrantArray::~StmtDDLGrantArray() { } // ----------------------------------------------------------------------- // member functions for class StmtDDLSchGrant // ----------------------------------------------------------------------- StmtDDLSchGrant::StmtDDLSchGrant(ElemDDLNode * pPrivileges, const ElemDDLSchemaName & aSchemaNameParseNode, ElemDDLNode * pGranteeList, ElemDDLNode * pWithGrantOption, ElemDDLNode * pByGrantorOption, CollHeap * heap) : StmtDDLNode(DDL_GRANT_SCHEMA), schemaName_(heap), schemaQualName_(aSchemaNameParseNode.getSchemaName(), heap), isAllDMLPrivileges_(FALSE), isAllDDLPrivileges_(FALSE), isAllOtherPrivileges_(FALSE), isWithGrantOptionSpec_(FALSE), privActArray_(heap), granteeArray_(heap), isByGrantorOptionSpec_(FALSE), byGrantor_(NULL) { if (schemaQualName_.getSchemaName().isNull()) { schemaQualName_ = ActiveSchemaDB()->getDefaultSchema(); } setChild(INDEX_PRIVILEGES, pPrivileges); setChild(INDEX_GRANTEE_LIST, pGranteeList); setChild(INDEX_WITH_GRANT_OPTION, pWithGrantOption); setChild(INDEX_BY_GRANTOR_OPTION, pByGrantorOption); //objectName_ = objectQualName_.getQualifiedNameAsAnsiString(); // // inserts pointers to parse nodes representing privilege // actions to privActArray_ so the user can access the // information about privilege actions easier. // ComASSERT(pPrivileges NEQ NULL); ElemDDLPrivileges * pPrivsNode = pPrivileges->castToElemDDLPrivileges(); ComASSERT(pPrivsNode NEQ NULL); if (pPrivsNode->isAllPrivileges()) { isAllDMLPrivileges_ = TRUE; isAllDDLPrivileges_ = TRUE; isAllOtherPrivileges_ = TRUE; } if (pPrivsNode->isAllDMLPrivileges()) { isAllDMLPrivileges_ = TRUE; } if (pPrivsNode->isAllDDLPrivileges()) { isAllDDLPrivileges_ = TRUE; } if (pPrivsNode->isAllOtherPrivileges()) { isAllOtherPrivileges_ = TRUE; } ElemDDLNode * pPrivActs = pPrivsNode->getPrivilegeActionList(); if (pPrivActs) { for (CollIndex i = 0; i < pPrivActs->entries(); i++) { privActArray_.insert((*pPrivActs)[i]->castToElemDDLPrivAct()); } } // // copies pointers to parse nodes representing grantee // to granteeArray_ so the user can access the information // easier. // ComASSERT(pGranteeList NEQ NULL); for (CollIndex i = 0; i < pGranteeList->entries(); i++) { granteeArray_.insert((*pGranteeList)[i]->castToElemDDLGrantee()); } // // looks for With Grant option phrase // if (pWithGrantOption NEQ NULL) { isWithGrantOptionSpec_ = TRUE; } if ( pByGrantorOption NEQ NULL ) { isByGrantorOptionSpec_ = TRUE; byGrantor_ = pByGrantorOption->castToElemDDLGrantee(); } } // StmtDDLSchGrant::StmtDDLSchGrant() // virtual destructor StmtDDLSchGrant::~StmtDDLSchGrant() { // delete all children for (Int32 i = 0; i < getArity(); i++) { delete getChild(i); } } // cast StmtDDLSchGrant * StmtDDLSchGrant::castToStmtDDLSchGrant() { return this; } // // accessors // Int32 StmtDDLSchGrant::getArity() const { return MAX_STMT_DDL_GRANT_ARITY; } ExprNode * StmtDDLSchGrant::getChild(Lng32 index) { ComASSERT(index >= 0 AND index < getArity()); return children_[index]; } // // mutators // void StmtDDLSchGrant::setChild(Lng32 index, ExprNode * pChildNode) { ComASSERT(index >= 0 AND index < getArity()); if (pChildNode NEQ NULL) { ComASSERT(pChildNode->castToElemDDLNode() NEQ NULL); children_[index] = pChildNode->castToElemDDLNode(); } else { children_[index] = NULL; } } // // methods for tracing // const NAString StmtDDLSchGrant::displayLabel1() const { return NAString("Schema Name ") + getSchemaName(); } NATraceList StmtDDLSchGrant::getDetailInfo() const { NAString detailText; NATraceList detailTextList; // // object name // detailTextList.append(displayLabel1()); // object name // // privileges // StmtDDLSchGrant * localThis = (StmtDDLSchGrant *)this; detailTextList.append(localThis->getChild(INDEX_PRIVILEGES) ->castToElemDDLNode() ->castToElemDDLPrivileges() ->getDetailInfo()); // // grantee list // const ElemDDLGranteeArray & granteeArray = getGranteeArray(); detailText = "Grantee list ["; detailText += LongToNAString((Lng32)granteeArray.entries()); detailText += " element(s)]"; detailTextList.append(detailText); for (CollIndex i = 0; i < granteeArray.entries(); i++) { detailText = "[grantee "; detailText += LongToNAString((Lng32)i); detailText += "]"; detailTextList.append(detailText); ComASSERT(granteeArray[i] NEQ NULL AND granteeArray[i]->castToElemDDLGrantee() NEQ NULL); detailTextList.append(" ", granteeArray[i]->castToElemDDLGrantee() ->getDetailInfo()); } // // with grant option // detailText = "is with grant option? "; detailText += YesNo(localThis->getChild(INDEX_WITH_GRANT_OPTION) NEQ NULL); detailTextList.append(detailText); return detailTextList; } // StmtDDLGrant::getDetailInfo const NAString StmtDDLSchGrant::getText() const { return "StmtDDLSchGrant"; } // ----------------------------------------------------------------------- // methods for class StmtDDLSchGrantArray // ----------------------------------------------------------------------- // virtual destructor StmtDDLSchGrantArray::~StmtDDLSchGrantArray() { } // ----------------------------------------------------------------------- // methods for class StmtDDLGrantComponentPrivilege // ----------------------------------------------------------------------- // // constructor // StmtDDLGrantComponentPrivilege::StmtDDLGrantComponentPrivilege (const ConstStringList * pComponentPrivilegeNameList, const NAString & componentName, const NAString & userRoleName, const NABoolean isWithGrantOptionClauseSpecified, ElemDDLNode * pOptionalGrantedBy, CollHeap * heap) // default is PARSERHEAP() : StmtDDLNode(DDL_GRANT_COMPONENT_PRIVILEGE), pComponentPrivilegeNameList_(pComponentPrivilegeNameList), componentName_(componentName, heap), userRoleName_(userRoleName, heap), isWithGrantOptionSpec_(isWithGrantOptionClauseSpecified), grantedBy_(NULL) { if ( pOptionalGrantedBy NEQ NULL ) { grantedBy_ = pOptionalGrantedBy->castToElemDDLGrantee(); } } // // virtual destructor // StmtDDLGrantComponentPrivilege::~StmtDDLGrantComponentPrivilege() { if (pComponentPrivilegeNameList_ NEQ NULL) delete pComponentPrivilegeNameList_; } // virtual safe cast-down function StmtDDLGrantComponentPrivilege * StmtDDLGrantComponentPrivilege::castToStmtDDLGrantComponentPrivilege() { return this; } // // methods for tracing // // LCOV_EXCL_START const NAString StmtDDLGrantComponentPrivilege::displayLabel1() const { NAString aLabel("Component name: "); aLabel += getComponentName(); return aLabel; } const NAString StmtDDLGrantComponentPrivilege::displayLabel2() const { NAString aLabel("User role name: "); aLabel += getUserRoleName(); return aLabel; } NATraceList StmtDDLGrantComponentPrivilege::getDetailInfo() const { NAString detailText; NATraceList detailTextList; // // component name // detailTextList.append(displayLabel1()); // component name // // user role name // detailTextList.append(displayLabel2()); // user role name // // component privilege name list // const ConstStringList & privs = getComponentPrivilegeNameList(); detailText = "Component Privilege Name List ["; detailText += LongToNAString((Lng32)privs.entries()); detailText += " element(s)]"; detailTextList.append(detailText); for (CollIndex i = 0; i < privs.entries(); i++) { detailText = "["; detailText += LongToNAString((Lng32)i); detailText += "] "; detailText += *privs[i]; detailTextList.append(detailText); } // // with grant option // detailText = "is with grant option? "; detailText += YesNo(isWithGrantOptionSpecified()); detailTextList.append(detailText); return detailTextList; } // StmtDDLGrantComponentPrivilege::getDetailInfo const NAString StmtDDLGrantComponentPrivilege::getText() { return "StmtDDLGrantComponentPrivilege"; } // LCOV_EXCL_STOP // ----------------------------------------------------------------------- // methods for class StmtDDLRevokeComponentPrivilege // ----------------------------------------------------------------------- // // constructor // StmtDDLRevokeComponentPrivilege::StmtDDLRevokeComponentPrivilege (const ConstStringList * pComponentPrivilegeNameList, const NAString & componentName, const NAString & userRoleName, const NABoolean isGrantOptionForClauseSpecified, ElemDDLNode * pOptionalGrantedBy, CollHeap * heap) // default is PARSERHEAP() : StmtDDLNode(DDL_REVOKE_COMPONENT_PRIVILEGE), pComponentPrivilegeNameList_(pComponentPrivilegeNameList), // shallow copy componentName_(componentName, heap), // deep copy userRoleName_(userRoleName, heap), // deep copy isGrantOptionForSpec_(isGrantOptionForClauseSpecified), grantedBy_(NULL) { if ( pOptionalGrantedBy NEQ NULL ) { grantedBy_ = pOptionalGrantedBy->castToElemDDLGrantee(); } } // // virtual destructor // StmtDDLRevokeComponentPrivilege::~StmtDDLRevokeComponentPrivilege() { if (pComponentPrivilegeNameList_ NEQ NULL) delete pComponentPrivilegeNameList_; } // virtual safe cast-down function StmtDDLRevokeComponentPrivilege * StmtDDLRevokeComponentPrivilege::castToStmtDDLRevokeComponentPrivilege() { return this; } // // methods for tracing // // LCOV_EXCL_START const NAString StmtDDLRevokeComponentPrivilege::displayLabel1() const { NAString aLabel("Component name: "); aLabel += getComponentName(); return aLabel; } const NAString StmtDDLRevokeComponentPrivilege::displayLabel2() const { NAString aLabel("User rol name: "); aLabel += getUserRoleName(); return aLabel; } NATraceList StmtDDLRevokeComponentPrivilege::getDetailInfo() const { NAString detailText; NATraceList detailTextList; // // component name // detailTextList.append(displayLabel1()); // component name // // user role name // detailTextList.append(displayLabel2()); // user role name // // component privilege name list // const ConstStringList & privs = getComponentPrivilegeNameList(); detailText = "Component Privilege Name List ["; detailText += LongToNAString((Lng32)privs.entries()); detailText += " element(s)]"; detailTextList.append(detailText); for (CollIndex i = 0; i < privs.entries(); i++) { detailText = "["; detailText += LongToNAString((Lng32)i); detailText += "] "; detailText += *privs[i]; detailTextList.append(detailText); } // // with revoke option // detailText = "is Grant Option For clause specified? "; detailText += YesNo(isGrantOptionForSpecified()); detailTextList.append(detailText); return detailTextList; } // StmtDDLRevokeComponentPrivilege::getDetailInfo const NAString StmtDDLRevokeComponentPrivilege::getText() { return "StmtDDLRevokeComponentPrivilege"; } // LCOV_EXCL_STOP // ----------------------------------------------------------------------- // methodsn for class StmtDDLReInitializeSQL // ----------------------------------------------------------------------- // // constructor // StmtDDLReInitializeSQL::StmtDDLReInitializeSQL() : StmtDDLNode(DDL_REINITIALIZE_SQL) {} StmtDDLReInitializeSQL::~StmtDDLReInitializeSQL() {} const NAString StmtDDLReInitializeSQL::getText() const { return "StmtDDLReInitializeSQL"; } // // cast // StmtDDLReInitializeSQL * StmtDDLReInitializeSQL::castToStmtDDLReInitializeSQL() { return this; } // ----------------------------------------------------------------------- // member functions for class StmtDDLInitializeSQL // ----------------------------------------------------------------------- // // constructor // StmtDDLInitializeSQL::StmtDDLInitializeSQL( ElemDDLNode *pCreateRoleList, ElemDDLNode *pRegisterUserList, CollHeap *heap) : StmtDDLNode(DDL_INITIALIZE_SQL) , registerUserArray_(heap) , createRoleArray_(heap) { setChild(INDEX_REGISTER_USER_LIST, pRegisterUserList); setChild(INDEX_CREATE_ROLE_LIST, pCreateRoleList); } // // virtual destructor // StmtDDLInitializeSQL::~StmtDDLInitializeSQL() { // delete all children for (Int32 i = 0; i < getArity(); i++) { delete getChild(i); } } // // cast // StmtDDLInitializeSQL * StmtDDLInitializeSQL::castToStmtDDLInitializeSQL() { return this; } Int32 StmtDDLInitializeSQL::getArity() const { return MAX_STMT_DDL_INITIALIZE_SQL_ARITY; } ExprNode * StmtDDLInitializeSQL::getChild(Lng32 index) { ComASSERT ((index >= 0) && index < getArity()); return children_[index]; } // // mutators // void StmtDDLInitializeSQL::setChild(Lng32 index, ExprNode * pChildNode) { ComASSERT ((index >= 0) && index < getArity()); if (pChildNode NEQ NULL) children_[index] = pChildNode->castToElemDDLNode(); else children_[index] = NULL; } void StmtDDLInitializeSQL_visitRegisterUserElement(ElemDDLNode * pInitSQLNode, CollIndex /* index */, ElemDDLNode * pElement) { ComASSERT(pInitSQLNode NEQ NULL AND pInitSQLNode->castToStmtDDLInitializeSQL() NEQ NULL AND pElement NEQ NULL AND pElement->getOperatorType() == DDL_REGISTER_USER); StmtDDLInitializeSQL * pInitializeSQL = pInitSQLNode->castToStmtDDLInitializeSQL(); StmtDDLRegisterUser *pRegisterUser = pElement->castToStmtDDLRegisterUser(); ComASSERT(pRegisterUser NEQ NULL); pInitializeSQL->registerUserArray_.insert(pRegisterUser); } void StmtDDLInitializeSQL_visitCreateRoleElement(ElemDDLNode * pInitSQLNode, CollIndex /* index */, ElemDDLNode * pElement) { ComASSERT(pInitSQLNode NEQ NULL AND pInitSQLNode->castToStmtDDLInitializeSQL() NEQ NULL AND pElement NEQ NULL AND pElement->getOperatorType() == DDL_CREATE_ROLE); StmtDDLInitializeSQL * pInitializeSQL = pInitSQLNode->castToStmtDDLInitializeSQL(); StmtDDLCreateRole *pCreateRole = pElement->castToStmtDDLCreateRole(); ComASSERT(pCreateRole NEQ NULL); pInitializeSQL->createRoleArray_.insert(pCreateRole); } void StmtDDLInitializeSQL::synthesize(void) { // Traverses the element list that contains parse nodes // representing register user commands. Collects pointers to // these parse nodes and saves them in the corresponding array. if (getChild(INDEX_REGISTER_USER_LIST) NEQ NULL) { ElemDDLNode *pElemList = getChild(INDEX_REGISTER_USER_LIST)->castToElemDDLNode(); ComASSERT(pElemList NEQ NULL); pElemList->traverseList(this, StmtDDLInitializeSQL_visitRegisterUserElement); } if (getChild(INDEX_CREATE_ROLE_LIST) NEQ NULL) { ElemDDLNode *pElemList = getChild(INDEX_CREATE_ROLE_LIST)->castToElemDDLNode(); ComASSERT(pElemList NEQ NULL); pElemList->traverseList(this, StmtDDLInitializeSQL_visitCreateRoleElement); } } // // methods for tracing // NATraceList StmtDDLInitializeSQL::getDetailInfo() const { NATraceList detailTextList; return detailTextList; } // StmtDDLInitializeSQL::getDetailInfo() const NAString StmtDDLInitializeSQL::getText() const { return "StmtDDLInitializeSQL"; } // ----------------------------------------------------------------------- // member functions for class StmtDDLRevoke // ----------------------------------------------------------------------- // // constructor // StmtDDLRevoke::StmtDDLRevoke(NABoolean isGrantOptionFor, ElemDDLNode * pPrivileges, const QualifiedName & objectName, ElemDDLNode * pGranteeList, ComDropBehavior dropBehavior, ElemDDLNode * pByGrantorOption, QualifiedName * actionName, CollHeap * heap) : StmtDDLNode(DDL_REVOKE), objectName_(heap), objectQualName_(objectName, heap), isAllPrivileges_(FALSE), isGrantOptionForSpec_(isGrantOptionFor), dropBehavior_(dropBehavior), privActArray_(heap), actionQualName_(actionName), granteeArray_(heap), isByGrantorOptionSpec_(FALSE), byGrantor_(NULL) { setChild(INDEX_PRIVILEGES, pPrivileges); setChild(INDEX_GRANTEE_LIST, pGranteeList); setChild(INDEX_BY_GRANTOR_OPTION, pByGrantorOption); // // Fully expand the name. // objectName_ = objectQualName_.getQualifiedNameAsAnsiString(); // // inserts pointers to parse nodes representing privilege // actions to privActArray_ so the user can access the // information about privilege actions easier. // ComASSERT(pPrivileges NEQ NULL); ElemDDLPrivileges * pPrivsNode = pPrivileges->castToElemDDLPrivileges(); ComASSERT(pPrivsNode NEQ NULL); if (pPrivsNode->isAllPrivileges()) { isAllPrivileges_ = TRUE; } else { ElemDDLNode * pPrivActs = pPrivsNode->getPrivilegeActionList(); for (CollIndex i = 0; i < pPrivActs->entries(); i++) { ElemDDLPrivAct *pPrivAct = (*pPrivActs)[i]->castToElemDDLPrivAct(); privActArray_.insert(pPrivAct); if (pPrivAct->isDDLPriv()) privActArray_.setHasDDLPriv(TRUE); } } // // copies pointers to parse nodes representing grantee // to granteeArray_ so the user can access the information // easier. // ComASSERT(pGranteeList NEQ NULL); for (CollIndex i = 0; i < pGranteeList->entries(); i++) { granteeArray_.insert((*pGranteeList)[i]->castToElemDDLGrantee()); } if ( pByGrantorOption NEQ NULL ) { isByGrantorOptionSpec_ = TRUE; byGrantor_ = pByGrantorOption->castToElemDDLGrantee(); } } // StmtDDLRevoke::StmtDDLRevoke() // virtual destructor StmtDDLRevoke::~StmtDDLRevoke() { // delete all children for (Int32 i = 0; i < getArity(); i++) { delete getChild(i); } } // cast StmtDDLRevoke * StmtDDLRevoke::castToStmtDDLRevoke() { return this; } // // accessors // Int32 StmtDDLRevoke::getArity() const { return MAX_STMT_DDL_REVOKE_ARITY; } ExprNode * StmtDDLRevoke::getChild(Lng32 index) { ComASSERT(index >= 0 AND index < getArity()); return children_[index]; } // // mutators // void StmtDDLRevoke::setChild(Lng32 index, ExprNode * pChildNode) { ComASSERT(index >= 0 AND index < getArity()); if (pChildNode NEQ NULL) { ComASSERT(pChildNode->castToElemDDLNode() NEQ NULL); children_[index] = pChildNode->castToElemDDLNode(); } else { children_[index] = NULL; } } // // methods for tracing // const NAString StmtDDLRevoke::displayLabel1() const { return NAString("Object name: ") + getObjectName(); } const NAString StmtDDLRevoke::displayLabel2() const { NAString label2("Drop behavior: "); switch (getDropBehavior()) { case COM_CASCADE_DROP_BEHAVIOR : return label2 + "Cascade"; case COM_RESTRICT_DROP_BEHAVIOR : return label2 + "Restrict"; default : ABORT("internal logic error"); return NAString(); } } NATraceList StmtDDLRevoke::getDetailInfo() const { NAString detailText; NATraceList detailTextList; // // object name // detailTextList.append(displayLabel1()); // object name // // privileges // StmtDDLRevoke * localThis = (StmtDDLRevoke *)this; detailTextList.append(localThis->getChild(INDEX_PRIVILEGES) ->castToElemDDLNode() ->castToElemDDLPrivileges() ->getDetailInfo()); // // grantee list // const ElemDDLGranteeArray & granteeArray = getGranteeArray(); detailText = "Grantee list ["; detailText += LongToNAString((Lng32)granteeArray.entries()); detailText += " element(s)]"; detailTextList.append(detailText); for (CollIndex i = 0; i < granteeArray.entries(); i++) { detailText = "[grantee "; detailText += LongToNAString((Lng32)i); detailText += "]"; detailTextList.append(detailText); ComASSERT(granteeArray[i] NEQ NULL AND granteeArray[i]->castToElemDDLGrantee() NEQ NULL); detailTextList.append(" ", granteeArray[i]->castToElemDDLGrantee() ->getDetailInfo()); } // // grant option for // detailText = "is grant option for? "; detailText += YesNo(isGrantOptionForSpecified()); detailTextList.append(detailText); // // drop behavior // detailTextList.append(displayLabel2()); // drop behavior return detailTextList; } // StmtDDLRevoke::getDetailInfo const NAString StmtDDLRevoke::getText() const { return "StmtDDLRevoke"; } // ----------------------------------------------------------------------- // member functions for class StmtDDLSchRevoke // ----------------------------------------------------------------------- // // constructor // StmtDDLSchRevoke::StmtDDLSchRevoke(NABoolean isGrantOptionFor, ElemDDLNode * pPrivileges, const ElemDDLSchemaName & aSchemaNameParseNode, ElemDDLNode * pGranteeList, ComDropBehavior dropBehavior, ElemDDLNode * pByGrantorOption, CollHeap * heap) : StmtDDLNode(DDL_REVOKE_SCHEMA), schemaName_(heap), schemaQualName_(aSchemaNameParseNode.getSchemaName(), heap), isAllDDLPrivileges_(FALSE), isAllDMLPrivileges_(FALSE), isAllOtherPrivileges_(FALSE), isGrantOptionForSpec_(isGrantOptionFor), dropBehavior_(dropBehavior), privActArray_(heap), granteeArray_(heap), isByGrantorOptionSpec_(FALSE), byGrantor_(NULL) { setChild(INDEX_PRIVILEGES, pPrivileges); setChild(INDEX_GRANTEE_LIST, pGranteeList); setChild(INDEX_BY_GRANTOR_OPTION, pByGrantorOption); // // inserts pointers to parse nodes representing privilege // actions to privActArray_ so the user can access the // information about privilege actions easier. // ComASSERT(pPrivileges NEQ NULL); ElemDDLPrivileges * pPrivsNode = pPrivileges->castToElemDDLPrivileges(); ComASSERT(pPrivsNode NEQ NULL); if (pPrivsNode->isAllPrivileges()) { isAllDDLPrivileges_ = TRUE; isAllDMLPrivileges_ = TRUE; isAllOtherPrivileges_ = TRUE; } if (pPrivsNode->isAllDDLPrivileges()) { isAllDDLPrivileges_ = TRUE; } if (pPrivsNode->isAllDMLPrivileges()) { isAllDMLPrivileges_ = TRUE; } if (pPrivsNode->isAllOtherPrivileges()) { isAllOtherPrivileges_ = TRUE; } ElemDDLNode * pPrivActs = pPrivsNode->getPrivilegeActionList(); if (pPrivActs) { for (CollIndex i = 0; i < pPrivActs->entries(); i++) { privActArray_.insert((*pPrivActs)[i]->castToElemDDLPrivAct()); } } // // copies pointers to parse nodes representing grantee // to granteeArray_ so the user can access the information // easier. // ComASSERT(pGranteeList NEQ NULL); for (CollIndex i = 0; i < pGranteeList->entries(); i++) { granteeArray_.insert((*pGranteeList)[i]->castToElemDDLGrantee()); } if ( pByGrantorOption NEQ NULL ) { isByGrantorOptionSpec_ = TRUE; byGrantor_ = pByGrantorOption->castToElemDDLGrantee(); } } // StmtDDLSchRevoke::StmtDDLSchRevoke() // virtual destructor StmtDDLSchRevoke::~StmtDDLSchRevoke() { // delete all children for (Int32 i = 0; i < getArity(); i++) { delete getChild(i); } } // cast StmtDDLSchRevoke * StmtDDLSchRevoke::castToStmtDDLSchRevoke() { return this; } // // accessors // Int32 StmtDDLSchRevoke::getArity() const { return MAX_STMT_DDL_REVOKE_ARITY; } ExprNode * StmtDDLSchRevoke::getChild(Lng32 index) { ComASSERT(index >= 0 AND index < getArity()); return children_[index]; } // // mutators // void StmtDDLSchRevoke::setChild(Lng32 index, ExprNode * pChildNode) { ComASSERT(index >= 0 AND index < getArity()); if (pChildNode NEQ NULL) { ComASSERT(pChildNode->castToElemDDLNode() NEQ NULL); children_[index] = pChildNode->castToElemDDLNode(); } else { children_[index] = NULL; } } // // methods for tracing // // LCOV_EXCL_START const NAString StmtDDLSchRevoke::displayLabel1() const { return NAString("Schema name: ") + getSchemaName(); } const NAString StmtDDLSchRevoke::displayLabel2() const { NAString label2("Drop behavior: "); switch (getDropBehavior()) { case COM_CASCADE_DROP_BEHAVIOR : return label2 + "Cascade"; case COM_RESTRICT_DROP_BEHAVIOR : return label2 + "Restrict"; default : ABORT("internal logic error"); return NAString(); } } NATraceList StmtDDLSchRevoke::getDetailInfo() const { NAString detailText; NATraceList detailTextList; // // object name // detailTextList.append(displayLabel1()); // object name // // privileges // StmtDDLSchRevoke * localThis = (StmtDDLSchRevoke *)this; detailTextList.append(localThis->getChild(INDEX_PRIVILEGES) ->castToElemDDLNode() ->castToElemDDLPrivileges() ->getDetailInfo()); // // grantee list // const ElemDDLGranteeArray & granteeArray = getGranteeArray(); detailText = "Grantee list ["; detailText += LongToNAString((Lng32)granteeArray.entries()); detailText += " element(s)]"; detailTextList.append(detailText); for (CollIndex i = 0; i < granteeArray.entries(); i++) { detailText = "[grantee "; detailText += LongToNAString((Lng32)i); detailText += "]"; detailTextList.append(detailText); ComASSERT(granteeArray[i] NEQ NULL AND granteeArray[i]->castToElemDDLGrantee() NEQ NULL); detailTextList.append(" ", granteeArray[i]->castToElemDDLGrantee() ->getDetailInfo()); } // // grant option for // detailText = "is grant option for? "; detailText += YesNo(isGrantOptionForSpecified()); detailTextList.append(detailText); // // drop behavior // detailTextList.append(displayLabel2()); // drop behavior return detailTextList; } // StmtDDLSchRevoke::getDetailInfo const NAString StmtDDLSchRevoke::getText() const { return "StmtDDLSchRevoke"; } // LCOV_EXCL_STOP // ----------------------------------------------------------------------- // member functions for class StmtDDLPublish // ----------------------------------------------------------------------- // // constructor // StmtDDLPublish::StmtDDLPublish(ElemDDLNode * pPrivileges, const QualifiedName & objectName, const NAString & synonymName, ComBoolean isRole, ElemDDLNode * pGranteeList, ComBoolean isPublish, CollHeap * heap) : StmtDDLNode(DDL_PUBLISH), objectName_(heap), objectQualName_(objectName, heap), synonymName_(synonymName, heap), isSynonymNameSpec_(FALSE), isRoleList_(isRole), isPublish_(isPublish), isAllPrivileges_(FALSE), privActArray_(heap), granteeArray_(heap) { setChild(PUBLISH_PRIVILEGES, pPrivileges); setChild(PUBLISH_GRANTEE_LIST, pGranteeList); objectName_ = objectQualName_.getQualifiedNameAsAnsiString(); if (!synonymName.isNull()) isSynonymNameSpec_ = TRUE; // // inserts pointers to parse nodes representing privilege // actions to privActArray_ so the user can access the // information about privilege actions easier. // ComASSERT(pPrivileges NEQ NULL); ElemDDLPrivileges * pPrivsNode = pPrivileges->castToElemDDLPrivileges(); ComASSERT(pPrivsNode NEQ NULL); if (pPrivsNode->isAllPrivileges()) { isAllPrivileges_ = TRUE; } else { ElemDDLNode * pPrivActs = pPrivsNode->getPrivilegeActionList(); for (CollIndex i = 0; i < pPrivActs->entries(); i++) { ElemDDLPrivAct *pPrivAct = (*pPrivActs)[i]->castToElemDDLPrivAct(); privActArray_.insert(pPrivAct); } } // // copies pointers to parse nodes representing grantee // to granteeArray_ so the user can access the information // easier. // ComASSERT(pGranteeList NEQ NULL); for (CollIndex i = 0; i < pGranteeList->entries(); i++) { granteeArray_.insert((*pGranteeList)[i]->castToElemDDLGrantee()); } } // StmtDDLPublish::StmtDDLPublish() // virtual destructor StmtDDLPublish::~StmtDDLPublish() { // delete all children for (Int32 i = 0; i < getArity(); i++) { delete getChild(i); } } // cast StmtDDLPublish * StmtDDLPublish::castToStmtDDLPublish() { return this; } // // accessors // Int32 StmtDDLPublish::getArity() const { return MAX_STMT_DDL_PUBLISH_ARITY; } ExprNode * StmtDDLPublish::getChild(Lng32 index) { ComASSERT(index >= 0 AND index < getArity()); return children_[index]; } // // mutators // void StmtDDLPublish::setChild(Lng32 index, ExprNode * pChildNode) { ComASSERT(index >= 0 AND index < getArity()); if (pChildNode NEQ NULL) { ComASSERT(pChildNode->castToElemDDLNode() NEQ NULL); children_[index] = pChildNode->castToElemDDLNode(); } else { children_[index] = NULL; } } // // methods for tracing // // LCOV_EXCL_START const NAString StmtDDLPublish::displayLabel1() const { return NAString("Object name: ") + getObjectName(); } NATraceList StmtDDLPublish::getDetailInfo() const { NAString detailText; NATraceList detailTextList; // // object name // detailTextList.append(displayLabel1()); // object name // // privileges // StmtDDLPublish * localThis = (StmtDDLPublish *)this; detailTextList.append(localThis->getChild(PUBLISH_PRIVILEGES) ->castToElemDDLNode() ->castToElemDDLPrivileges() ->getDetailInfo()); // grantee list // const ElemDDLGranteeArray & granteeArray = getGranteeArray(); detailText = "Grantee list ["; detailText += LongToNAString((Lng32)granteeArray.entries()); detailText += " element(s)]"; detailTextList.append(detailText); for (CollIndex i = 0; i < granteeArray.entries(); i++) { detailText = "[grantee "; detailText += LongToNAString((Lng32)i); detailText += "]"; detailTextList.append(detailText); ComASSERT(granteeArray[i] NEQ NULL AND granteeArray[i]->castToElemDDLGrantee() NEQ NULL); detailTextList.append(" ", granteeArray[i]->castToElemDDLGrantee() ->getDetailInfo()); } return detailTextList; } // StmtDDLPublish::getDetailInfo const NAString StmtDDLPublish::getText() const { return "StmtDDLPublish"; } // LCOV_EXCL_STOP // ----------------------------------------------------------------------- // methods for class StmtDDLRegisterComponent // ----------------------------------------------------------------------- // // constructors used for (UN)REGISTER COMPONENT // StmtDDLRegisterComponent::StmtDDLRegisterComponent(StmtDDLRegisterComponent::RegisterComponentType eRegComponentParseNodeType, const NAString & sComponentName, const NABoolean isSystem, const NAString & sDetailInfo, CollHeap * heap) : StmtDDLNode(DDL_REGISTER_COMPONENT), registerComponentType_(eRegComponentParseNodeType), componentName_(sComponentName, heap), isSystem_(isSystem), componentDetailInfo_(sDetailInfo, heap) { } StmtDDLRegisterComponent::StmtDDLRegisterComponent(StmtDDLRegisterComponent::RegisterComponentType eRegComponentParseNodeType, const NAString & sComponentName, ComDropBehavior dropBehavior, CollHeap * heap) : StmtDDLNode(DDL_REGISTER_COMPONENT), registerComponentType_(eRegComponentParseNodeType), componentName_(sComponentName, heap), dropBehavior_(dropBehavior), componentDetailInfo_(heap) { } // // virtual destructor // StmtDDLRegisterComponent::~StmtDDLRegisterComponent() { } // // cast // StmtDDLRegisterComponent * StmtDDLRegisterComponent::castToStmtDDLRegisterComponent() { return this; } // // methods for tracing // // LCOV_EXCL_START const NAString StmtDDLRegisterComponent::displayLabel1() const { NAString aLabel("UNREGISTER COMPONENT"); if (getRegisterComponentType() == StmtDDLRegisterComponent::REGISTER_COMPONENT) { aLabel = "REGISTER COMPONENT"; if (isSystem()) aLabel += " (SYSTEM)"; } aLabel += " - External Component name: "; aLabel += getExternalComponentName(); if (getRegisterComponentType() == StmtDDLRegisterComponent::UNREGISTER_COMPONENT) { aLabel += " Drop behavior: "; if (dropBehavior_ == COM_CASCADE_DROP_BEHAVIOR) aLabel += "CASCADE"; else aLabel += "RESTRICT"; } return aLabel; } const NAString StmtDDLRegisterComponent::displayLabel2() const { if (NOT getRegisterComponentDetailInfo().isNull()) { return NAString("Detail Information: ") + getRegisterComponentDetailInfo(); } else { return NAString("No Detail Information (i.e., an empty string)."); } } const NAString StmtDDLRegisterComponent::getText() const { return "StmtDDLRegisterComponent"; } // LCOV_EXCL_STOP // // End of File //
24.540541
126
0.634384
eabc05816776c1a659881280881d2cda272183b6
5,497
cpp
C++
STM32_Resources/Default/NES/mapper/083.cpp
Shuzhengz/Projects-Code
1b9608004a682b1da4e31f3160736e5b2c52fb33
[ "MIT" ]
14
2019-01-14T08:16:55.000Z
2021-06-14T11:56:56.000Z
STM32_Resources/Default/NES/mapper/083.cpp
Shuzhengz/Projects-Code
1b9608004a682b1da4e31f3160736e5b2c52fb33
[ "MIT" ]
null
null
null
STM32_Resources/Default/NES/mapper/083.cpp
Shuzhengz/Projects-Code
1b9608004a682b1da4e31f3160736e5b2c52fb33
[ "MIT" ]
4
2019-01-14T08:16:32.000Z
2021-12-05T05:53:06.000Z
///////////////////////////////////////////////////////////////////// // Mapper 83 void NES_mapper83::Reset() { regs[0] = regs[1] = regs[2] = 0; // set CPU bank pointers if(num_8k_ROM_banks >= 32) { set_CPU_banks(0,1,30,31); regs[1] = 0x30; } else { set_CPU_banks(0,1,num_8k_ROM_banks-2,num_8k_ROM_banks-1); } // set PPU bank pointers if(num_1k_VROM_banks) { set_PPU_banks(0,1,2,3,4,5,6,7); } irq_enabled = 0; irq_counter = 0; } uint8 NES_mapper83::MemoryReadLow(uint32 addr) { if((addr & 0x5100) == 0x5100) { return regs[2]; } else { return addr >> 8; } } void NES_mapper83::MemoryWriteLow(uint32 addr, uint8 data) { switch(addr) { case 0x5101: case 0x5102: case 0x5103: { regs[2] = data; } break; } } void NES_mapper83::MemoryWrite(uint32 addr, uint8 data) { switch(addr) { case 0x8000: case 0xB000: case 0xB0FF: case 0xB1FF: { regs[0] = data; set_CPU_bank4(data*2+0); set_CPU_bank5(data*2+1); set_CPU_bank6(((data&0x30)|0x0F)*2+0); set_CPU_bank7(((data&0x30)|0x0F)*2+1); } break; case 0x8100: { if(num_1k_VROM_banks <= 32*8) { regs[1] = data; } if((data & 0x03) == 0x00) { set_mirroring(NES_PPU::MIRROR_VERT); } else if((data & 0x03) == 0x01) { set_mirroring(NES_PPU::MIRROR_HORIZ); } else if((data & 0x03) == 0x02) { set_mirroring(0,0,0,0); } else { set_mirroring(1,1,1,1); } } break; case 0x8200: { irq_counter = (irq_counter & 0xFF00) | (uint32)data; } break; case 0x8201: { irq_counter = (irq_counter & 0x00FF) | ((uint32)data << 8); irq_enabled = data; } break; case 0x8300: { set_CPU_bank4(data); } break; case 0x8301: { set_CPU_bank5(data); } break; case 0x8302: { set_CPU_bank6(data); } break; case 0x8310: { if((regs[1] & 0x30) == 0x30) { set_PPU_bank0(((data & 0x30) << 4)^data); } else if((regs[1] & 0x30) == 0x10 || (regs[1] & 0x30) == 0x20) { set_PPU_bank0((((data & 0x30) << 4)^data)*2+0); set_PPU_bank1((((data & 0x30) << 4)^data)*2+1); } } break; case 0x8311: { if((regs[1] & 0x30) == 0x30) { set_PPU_bank1(((data & 0x30) << 4)^data); } else if((regs[1] & 0x30) == 0x10 || (regs[1] & 0x30) == 0x20) { set_PPU_bank2((((data & 0x30) << 4)^data)*2+0); set_PPU_bank3((((data & 0x30) << 4)^data)*2+1); } } break; case 0x8312: { if((regs[1] & 0x30) == 0x30) { set_PPU_bank2(((data & 0x30) << 4)^data); } else if((regs[1] & 0x30) == 0x10 || (regs[1] & 0x30) == 0x20) { set_PPU_bank4((((data & 0x30) << 4)^data)*2+0); set_PPU_bank5((((data & 0x30) << 4)^data)*2+1); } } break; case 0x8313: { if((regs[1] & 0x30) == 0x30) { set_PPU_bank3(((data & 0x30) << 4)^data); } else if((regs[1] & 0x30) == 0x10 || (regs[1] & 0x30) == 0x20) { set_PPU_bank6((((data & 0x30) << 4)^data)*2+0); set_PPU_bank7((((data & 0x30) << 4)^data)*2+1); } } break; case 0x8314: { if((regs[1] & 0x30) == 0x30) { set_PPU_bank4(((data & 0x30) << 4)^data); } else if((regs[1] & 0x30) == 0x10 || (regs[1] & 0x30) == 0x20) { set_PPU_bank4((((data & 0x30) << 4)^data)*2+0); set_PPU_bank5((((data & 0x30) << 4)^data)*2+1); } } break; case 0x8315: { if((regs[1] & 0x30) == 0x30) { set_PPU_bank5(((data & 0x30) << 4)^data); } else if((regs[1] & 0x30) == 0x10 || (regs[1] & 0x30) == 0x20) { set_PPU_bank6((((data & 0x30) << 4)^data)*2+0); set_PPU_bank7((((data & 0x30) << 4)^data)*2+1); } } break; case 0x8316: { if((regs[1] & 0x30) == 0x30) { set_PPU_bank6(((data & 0x30) << 4)^data); } else if((regs[1] & 0x30) == 0x10 || (regs[1] & 0x30) == 0x20) { set_PPU_bank4((((data & 0x30) << 4)^data)*2+0); set_PPU_bank5((((data & 0x30) << 4)^data)*2+1); } } break; case 0x8317: { if((regs[1] & 0x30) == 0x30) { set_PPU_bank7(((data & 0x30) << 4)^data); } else if((regs[1] & 0x30) == 0x10 || (regs[1] & 0x30) == 0x20) { set_PPU_bank6((((data & 0x30) << 4)^data)*2+0); set_PPU_bank7((((data & 0x30) << 4)^data)*2+1); } } break; case 0x8318: { set_CPU_bank4(((regs[0]&0x30)|data)*2+0); set_CPU_bank5(((regs[0]&0x30)|data)*2+1); } break; } } void NES_mapper83::HSync(uint32 scanline) { if(irq_enabled) { if(irq_counter <= 114) { parent_NES->cpu->DoIRQ(); irq_enabled = 0; } else { irq_counter -= 114; } } } /////////////////////////////////////////////////////////////////////
20.588015
69
0.433873
eabef1dd8733d3b75f83cffbbeb0509d369503f5
103
cpp
C++
addresslab.cpp
CaQtiml/CaQ-s-NOOB-LAB
a6cd2a730f2b2e6a834b1b39521052c5125150b5
[ "MIT" ]
null
null
null
addresslab.cpp
CaQtiml/CaQ-s-NOOB-LAB
a6cd2a730f2b2e6a834b1b39521052c5125150b5
[ "MIT" ]
null
null
null
addresslab.cpp
CaQtiml/CaQ-s-NOOB-LAB
a6cd2a730f2b2e6a834b1b39521052c5125150b5
[ "MIT" ]
null
null
null
#include "stdio.h" int main() { int b=8; int &a=b; printf("%d",a); b+=2; printf("%d",a); }
11.444444
19
0.466019
eac4248c774fa43b3fac2efa59431b406736dfbb
8,112
cpp
C++
aws-cpp-sdk-securityhub/source/model/AwsEc2VpcEndpointServiceDetails.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-02-12T08:09:30.000Z
2022-02-12T08:09:30.000Z
aws-cpp-sdk-securityhub/source/model/AwsEc2VpcEndpointServiceDetails.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2021-10-14T16:57:00.000Z
2021-10-18T10:47:24.000Z
aws-cpp-sdk-securityhub/source/model/AwsEc2VpcEndpointServiceDetails.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-11-09T11:58:03.000Z
2021-11-09T11:58:03.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/securityhub/model/AwsEc2VpcEndpointServiceDetails.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace SecurityHub { namespace Model { AwsEc2VpcEndpointServiceDetails::AwsEc2VpcEndpointServiceDetails() : m_acceptanceRequired(false), m_acceptanceRequiredHasBeenSet(false), m_availabilityZonesHasBeenSet(false), m_baseEndpointDnsNamesHasBeenSet(false), m_managesVpcEndpoints(false), m_managesVpcEndpointsHasBeenSet(false), m_gatewayLoadBalancerArnsHasBeenSet(false), m_networkLoadBalancerArnsHasBeenSet(false), m_privateDnsNameHasBeenSet(false), m_serviceIdHasBeenSet(false), m_serviceNameHasBeenSet(false), m_serviceStateHasBeenSet(false), m_serviceTypeHasBeenSet(false) { } AwsEc2VpcEndpointServiceDetails::AwsEc2VpcEndpointServiceDetails(JsonView jsonValue) : m_acceptanceRequired(false), m_acceptanceRequiredHasBeenSet(false), m_availabilityZonesHasBeenSet(false), m_baseEndpointDnsNamesHasBeenSet(false), m_managesVpcEndpoints(false), m_managesVpcEndpointsHasBeenSet(false), m_gatewayLoadBalancerArnsHasBeenSet(false), m_networkLoadBalancerArnsHasBeenSet(false), m_privateDnsNameHasBeenSet(false), m_serviceIdHasBeenSet(false), m_serviceNameHasBeenSet(false), m_serviceStateHasBeenSet(false), m_serviceTypeHasBeenSet(false) { *this = jsonValue; } AwsEc2VpcEndpointServiceDetails& AwsEc2VpcEndpointServiceDetails::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("AcceptanceRequired")) { m_acceptanceRequired = jsonValue.GetBool("AcceptanceRequired"); m_acceptanceRequiredHasBeenSet = true; } if(jsonValue.ValueExists("AvailabilityZones")) { Array<JsonView> availabilityZonesJsonList = jsonValue.GetArray("AvailabilityZones"); for(unsigned availabilityZonesIndex = 0; availabilityZonesIndex < availabilityZonesJsonList.GetLength(); ++availabilityZonesIndex) { m_availabilityZones.push_back(availabilityZonesJsonList[availabilityZonesIndex].AsString()); } m_availabilityZonesHasBeenSet = true; } if(jsonValue.ValueExists("BaseEndpointDnsNames")) { Array<JsonView> baseEndpointDnsNamesJsonList = jsonValue.GetArray("BaseEndpointDnsNames"); for(unsigned baseEndpointDnsNamesIndex = 0; baseEndpointDnsNamesIndex < baseEndpointDnsNamesJsonList.GetLength(); ++baseEndpointDnsNamesIndex) { m_baseEndpointDnsNames.push_back(baseEndpointDnsNamesJsonList[baseEndpointDnsNamesIndex].AsString()); } m_baseEndpointDnsNamesHasBeenSet = true; } if(jsonValue.ValueExists("ManagesVpcEndpoints")) { m_managesVpcEndpoints = jsonValue.GetBool("ManagesVpcEndpoints"); m_managesVpcEndpointsHasBeenSet = true; } if(jsonValue.ValueExists("GatewayLoadBalancerArns")) { Array<JsonView> gatewayLoadBalancerArnsJsonList = jsonValue.GetArray("GatewayLoadBalancerArns"); for(unsigned gatewayLoadBalancerArnsIndex = 0; gatewayLoadBalancerArnsIndex < gatewayLoadBalancerArnsJsonList.GetLength(); ++gatewayLoadBalancerArnsIndex) { m_gatewayLoadBalancerArns.push_back(gatewayLoadBalancerArnsJsonList[gatewayLoadBalancerArnsIndex].AsString()); } m_gatewayLoadBalancerArnsHasBeenSet = true; } if(jsonValue.ValueExists("NetworkLoadBalancerArns")) { Array<JsonView> networkLoadBalancerArnsJsonList = jsonValue.GetArray("NetworkLoadBalancerArns"); for(unsigned networkLoadBalancerArnsIndex = 0; networkLoadBalancerArnsIndex < networkLoadBalancerArnsJsonList.GetLength(); ++networkLoadBalancerArnsIndex) { m_networkLoadBalancerArns.push_back(networkLoadBalancerArnsJsonList[networkLoadBalancerArnsIndex].AsString()); } m_networkLoadBalancerArnsHasBeenSet = true; } if(jsonValue.ValueExists("PrivateDnsName")) { m_privateDnsName = jsonValue.GetString("PrivateDnsName"); m_privateDnsNameHasBeenSet = true; } if(jsonValue.ValueExists("ServiceId")) { m_serviceId = jsonValue.GetString("ServiceId"); m_serviceIdHasBeenSet = true; } if(jsonValue.ValueExists("ServiceName")) { m_serviceName = jsonValue.GetString("ServiceName"); m_serviceNameHasBeenSet = true; } if(jsonValue.ValueExists("ServiceState")) { m_serviceState = jsonValue.GetString("ServiceState"); m_serviceStateHasBeenSet = true; } if(jsonValue.ValueExists("ServiceType")) { Array<JsonView> serviceTypeJsonList = jsonValue.GetArray("ServiceType"); for(unsigned serviceTypeIndex = 0; serviceTypeIndex < serviceTypeJsonList.GetLength(); ++serviceTypeIndex) { m_serviceType.push_back(serviceTypeJsonList[serviceTypeIndex].AsObject()); } m_serviceTypeHasBeenSet = true; } return *this; } JsonValue AwsEc2VpcEndpointServiceDetails::Jsonize() const { JsonValue payload; if(m_acceptanceRequiredHasBeenSet) { payload.WithBool("AcceptanceRequired", m_acceptanceRequired); } if(m_availabilityZonesHasBeenSet) { Array<JsonValue> availabilityZonesJsonList(m_availabilityZones.size()); for(unsigned availabilityZonesIndex = 0; availabilityZonesIndex < availabilityZonesJsonList.GetLength(); ++availabilityZonesIndex) { availabilityZonesJsonList[availabilityZonesIndex].AsString(m_availabilityZones[availabilityZonesIndex]); } payload.WithArray("AvailabilityZones", std::move(availabilityZonesJsonList)); } if(m_baseEndpointDnsNamesHasBeenSet) { Array<JsonValue> baseEndpointDnsNamesJsonList(m_baseEndpointDnsNames.size()); for(unsigned baseEndpointDnsNamesIndex = 0; baseEndpointDnsNamesIndex < baseEndpointDnsNamesJsonList.GetLength(); ++baseEndpointDnsNamesIndex) { baseEndpointDnsNamesJsonList[baseEndpointDnsNamesIndex].AsString(m_baseEndpointDnsNames[baseEndpointDnsNamesIndex]); } payload.WithArray("BaseEndpointDnsNames", std::move(baseEndpointDnsNamesJsonList)); } if(m_managesVpcEndpointsHasBeenSet) { payload.WithBool("ManagesVpcEndpoints", m_managesVpcEndpoints); } if(m_gatewayLoadBalancerArnsHasBeenSet) { Array<JsonValue> gatewayLoadBalancerArnsJsonList(m_gatewayLoadBalancerArns.size()); for(unsigned gatewayLoadBalancerArnsIndex = 0; gatewayLoadBalancerArnsIndex < gatewayLoadBalancerArnsJsonList.GetLength(); ++gatewayLoadBalancerArnsIndex) { gatewayLoadBalancerArnsJsonList[gatewayLoadBalancerArnsIndex].AsString(m_gatewayLoadBalancerArns[gatewayLoadBalancerArnsIndex]); } payload.WithArray("GatewayLoadBalancerArns", std::move(gatewayLoadBalancerArnsJsonList)); } if(m_networkLoadBalancerArnsHasBeenSet) { Array<JsonValue> networkLoadBalancerArnsJsonList(m_networkLoadBalancerArns.size()); for(unsigned networkLoadBalancerArnsIndex = 0; networkLoadBalancerArnsIndex < networkLoadBalancerArnsJsonList.GetLength(); ++networkLoadBalancerArnsIndex) { networkLoadBalancerArnsJsonList[networkLoadBalancerArnsIndex].AsString(m_networkLoadBalancerArns[networkLoadBalancerArnsIndex]); } payload.WithArray("NetworkLoadBalancerArns", std::move(networkLoadBalancerArnsJsonList)); } if(m_privateDnsNameHasBeenSet) { payload.WithString("PrivateDnsName", m_privateDnsName); } if(m_serviceIdHasBeenSet) { payload.WithString("ServiceId", m_serviceId); } if(m_serviceNameHasBeenSet) { payload.WithString("ServiceName", m_serviceName); } if(m_serviceStateHasBeenSet) { payload.WithString("ServiceState", m_serviceState); } if(m_serviceTypeHasBeenSet) { Array<JsonValue> serviceTypeJsonList(m_serviceType.size()); for(unsigned serviceTypeIndex = 0; serviceTypeIndex < serviceTypeJsonList.GetLength(); ++serviceTypeIndex) { serviceTypeJsonList[serviceTypeIndex].AsObject(m_serviceType[serviceTypeIndex].Jsonize()); } payload.WithArray("ServiceType", std::move(serviceTypeJsonList)); } return payload; } } // namespace Model } // namespace SecurityHub } // namespace Aws
31.937008
158
0.784147
eac6d42b898df62950c863b4f09fa22c958e6892
1,974
cpp
C++
PnC/DracoPnC/DracoStateMachine/Initialize.cpp
BharathMasetty/PnC
3800bd7e3c5dd5ffa00e6a5f09d48d21c405206f
[ "MIT" ]
null
null
null
PnC/DracoPnC/DracoStateMachine/Initialize.cpp
BharathMasetty/PnC
3800bd7e3c5dd5ffa00e6a5f09d48d21c405206f
[ "MIT" ]
null
null
null
PnC/DracoPnC/DracoStateMachine/Initialize.cpp
BharathMasetty/PnC
3800bd7e3c5dd5ffa00e6a5f09d48d21c405206f
[ "MIT" ]
null
null
null
#include <PnC/DracoPnC/DracoCtrlArchitecture/DracoCtrlArchitecture.hpp> #include <PnC/DracoPnC/DracoStateMachine/Initialize.hpp> Initialize::Initialize(const StateIdentifier state_identifier_in, DracoControlArchitecture* _ctrl_arch, RobotSystem* _robot) : StateMachine(state_identifier_in, _robot) { myUtils::pretty_constructor(2, "SM: Initialize"); // Set Pointer to Control Architecture ctrl_arch_ = ((DracoControlArchitecture*)_ctrl_arch); taf_container_ = ctrl_arch_->taf_container_; // Get State Provider sp_ = DracoStateProvider::getStateProvider(robot_); } Initialize::~Initialize() {} void Initialize::firstVisit() { std::cout << "[Initialize]" << std::endl; ctrl_start_time_ = sp_->curr_time; ctrl_arch_->joint_trajectory_manager_->initializeJointTrajectory( 0., end_time_, target_pos_); } void Initialize::_taskUpdate() { // ========================================================================= // Joint // ========================================================================= ctrl_arch_->joint_trajectory_manager_->updateJointDesired( state_machine_time_); } void Initialize::oneStep() { state_machine_time_ = sp_->curr_time - ctrl_start_time_; _taskUpdate(); } void Initialize::lastVisit() {} bool Initialize::endOfState() { if (state_machine_time_ > end_time_) { return true; } return false; } StateIdentifier Initialize::getNextState() { return DRACO_STATES::STAND; } void Initialize::initialization(const YAML::Node& node) { try { myUtils::readParameter(node, "target_pos_duration", end_time_); myUtils::readParameter(node, "smoothing_duration", smoothing_dur_); myUtils::readParameter(node, "target_pos", target_pos_); } catch (std::runtime_error& e) { std::cout << "Error reading parameter [" << e.what() << "] at file: [" << __FILE__ << "]" << std::endl << std::endl; exit(0); } }
31.333333
78
0.644883
ead1b640546a3846870ddb6afb1cc99741fe7a51
1,788
cc
C++
core/user.cc
DaYeSquad/worktiledemo
1dd0a14255fc006824c896ea236120cd3ce32a6c
[ "MIT" ]
36
2016-04-04T03:10:45.000Z
2020-12-31T07:03:28.000Z
core/user.cc
DaYeSquad/worktiledemo
1dd0a14255fc006824c896ea236120cd3ce32a6c
[ "MIT" ]
null
null
null
core/user.cc
DaYeSquad/worktiledemo
1dd0a14255fc006824c896ea236120cd3ce32a6c
[ "MIT" ]
6
2016-04-12T08:48:17.000Z
2021-07-24T08:15:00.000Z
// // user.cpp // HelloWorktile // // Created by Frank Lin on 3/23/16. // Copyright © 2016 Frank Lin. All rights reserved. // #include "user.h" #include "json11/json11.hpp" using std::string; using std::unique_ptr; NS_WTC_BEGIN //////////////////////////////////////////////////////////////////////////////// // User, public: // Creation and lifetime -------------------------------------------------------- void User::Init(const std::string &uid, const std::string &username, const std::string &display_name, worktile::User::Status status) { uid_ = uid; username_ = username; display_name_ = display_name; status_ = status; } bool User::InitWithJsonOrDie(const std::string& json) { /* worktile 示例中的 json (https://open.worktile.com/wiki/user_info.html#/user) { "uid":"679efdf3960d45a0b8679693098135ff", "name":"gonglinjie", "display_name":"龚林杰", "email":"gonglinjie@worktile.com", "desc":"", "avatar":"https://api.worktile.com/avatar/80/ae2805fc-9aca-4f3b-8ac4-320c5d664db7.png", "status":3, "online":0 } */ string error; json11::Json json_obj = json11::Json::parse(json, error); if (!error.empty()) { return false; } uid_ = json_obj["uid"].string_value(); username_ = json_obj["name"].string_value(); display_name_ = json_obj["display_name"].string_value(); status_ = static_cast<User::Status>(json_obj["status"].int_value()); return true; } std::unique_ptr<User> User::Clone() const { unique_ptr<User> user(new User()); user->Init(uid_, username_, display_name_, status_); return user; } // Utils -------------------------------------------------------- std::string User::StatusDescription() const { return display_name_ + " is " + std::to_string(static_cast<int>(status_)); } NS_WTC_END
25.183099
134
0.604586
ead37173e91c5524dd8f41d266b05b0590ff2d40
5,763
cpp
C++
emulator/src/mame/video/pcw.cpp
rjw57/tiw-computer
5ef1c79893165b8622d1114d81cd0cded58910f0
[ "MIT" ]
1
2022-01-15T21:38:38.000Z
2022-01-15T21:38:38.000Z
emulator/src/mame/video/pcw.cpp
rjw57/tiw-computer
5ef1c79893165b8622d1114d81cd0cded58910f0
[ "MIT" ]
null
null
null
emulator/src/mame/video/pcw.cpp
rjw57/tiw-computer
5ef1c79893165b8622d1114d81cd0cded58910f0
[ "MIT" ]
null
null
null
// license:GPL-2.0+ // copyright-holders:Kevin Thacker /*************************************************************************** pcw.c Functions to emulate the video hardware of the Amstrad PCW. ***************************************************************************/ #include "emu.h" #include "includes/pcw.h" #include "machine/ram.h" inline void pcw_state::pcw_plot_pixel(bitmap_ind16 &bitmap, int x, int y, uint32_t color) { bitmap.pix16(y, x) = (uint16_t)color; } /*************************************************************************** Start the video hardware emulation. ***************************************************************************/ void pcw_state::video_start() { rectangle rect(0, PCW_PRINTER_WIDTH - 1, 0, PCW_PRINTER_HEIGHT - 1); m_prn_output = std::make_unique<bitmap_ind16>(PCW_PRINTER_WIDTH,PCW_PRINTER_HEIGHT); m_prn_output->fill(1, rect); } #if 0 /* two colours */ static const unsigned short pcw_colour_table[PCW_NUM_COLOURS] = { 0, 1 }; #endif /* black/white */ static const rgb_t pcw_palette[PCW_NUM_COLOURS] = { rgb_t(0x000, 0x000, 0x000), rgb_t(0x0ff, 0x0ff, 0x0ff) }; /* Initialise the palette */ PALETTE_INIT_MEMBER(pcw_state, pcw) { palette.set_pen_colors(0, pcw_palette, ARRAY_LENGTH(pcw_palette)); } /*************************************************************************** Draw the game screen in the given bitmap_ind16. Do NOT call osd_update_display() from this function, it will be called by the main emulation engine. ***************************************************************************/ uint32_t pcw_state::screen_update_pcw(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect) { int x,y,b; unsigned short roller_ram_offs; unsigned char *roller_ram_ptr; int pen0,pen1; pen0 = 0; pen1 = 1; /* invert? */ if (m_vdu_video_control_register & (1<<7)) { /* yes */ pen1^=1; pen0^=1; } /* video enable? */ if ((m_vdu_video_control_register & (1<<6))!=0) { /* render top border */ rectangle rect(0, PCW_SCREEN_WIDTH, 0, PCW_BORDER_HEIGHT); bitmap.fill(pen0, rect); /* render bottom border */ rect.set(0, PCW_SCREEN_WIDTH, PCW_BORDER_HEIGHT + PCW_DISPLAY_HEIGHT, PCW_BORDER_HEIGHT + PCW_DISPLAY_HEIGHT + PCW_BORDER_HEIGHT); bitmap.fill(pen0, rect); /* offset to start in table */ roller_ram_offs = (m_roller_ram_offset<<1); for (y=0; y<256; y++) { int by; unsigned short line_data; unsigned char *line_ptr; x = PCW_BORDER_WIDTH; roller_ram_ptr = m_ram->pointer() + m_roller_ram_addr + roller_ram_offs; /* get line address */ /* b16-14 control which bank the line is to be found in, b13-3 the address in the bank (in 16-byte units), and b2-0 the offset. Thus a roller RAM address bbbxxxxxxxxxxxyyy indicates bank bbb, address 00xxxxxxxxxxx0yyy. */ line_data = ((unsigned char *)roller_ram_ptr)[0] | (((unsigned char *)roller_ram_ptr)[1]<<8); /* calculate address of pixel data */ line_ptr = m_ram->pointer() + ((line_data & 0x0e000)<<1) + ((line_data & 0x01ff8)<<1) + (line_data & 0x07); for (by=0; by<90; by++) { unsigned char byte; byte = line_ptr[0]; for (b=0; b<8; b++) { if (byte & 0x080) { pcw_plot_pixel(bitmap,x+b, y+PCW_BORDER_HEIGHT, pen1); } else { pcw_plot_pixel(bitmap,x+b, y+PCW_BORDER_HEIGHT, pen0); } byte = byte<<1; } x = x + 8; line_ptr = line_ptr+8; } /* update offset, wrap within 512 byte range */ roller_ram_offs+=2; roller_ram_offs&=511; } /* render border */ /* 8 pixels either side of display */ for (y=0; y<256; y++) { pcw_plot_pixel(bitmap, 0, y+PCW_BORDER_HEIGHT, pen0); pcw_plot_pixel(bitmap, 1, y+PCW_BORDER_HEIGHT, pen0); pcw_plot_pixel(bitmap, 2, y+PCW_BORDER_HEIGHT, pen0); pcw_plot_pixel(bitmap, 3, y+PCW_BORDER_HEIGHT, pen0); pcw_plot_pixel(bitmap, 4, y+PCW_BORDER_HEIGHT, pen0); pcw_plot_pixel(bitmap, 5, y+PCW_BORDER_HEIGHT, pen0); pcw_plot_pixel(bitmap, 6, y+PCW_BORDER_HEIGHT, pen0); pcw_plot_pixel(bitmap, 7, y+PCW_BORDER_HEIGHT, pen0); pcw_plot_pixel(bitmap, PCW_BORDER_WIDTH+PCW_DISPLAY_WIDTH+0, y+PCW_BORDER_HEIGHT, pen0); pcw_plot_pixel(bitmap, PCW_BORDER_WIDTH+PCW_DISPLAY_WIDTH+1, y+PCW_BORDER_HEIGHT, pen0); pcw_plot_pixel(bitmap, PCW_BORDER_WIDTH+PCW_DISPLAY_WIDTH+2, y+PCW_BORDER_HEIGHT, pen0); pcw_plot_pixel(bitmap, PCW_BORDER_WIDTH+PCW_DISPLAY_WIDTH+3, y+PCW_BORDER_HEIGHT, pen0); pcw_plot_pixel(bitmap, PCW_BORDER_WIDTH+PCW_DISPLAY_WIDTH+4, y+PCW_BORDER_HEIGHT, pen0); pcw_plot_pixel(bitmap, PCW_BORDER_WIDTH+PCW_DISPLAY_WIDTH+5, y+PCW_BORDER_HEIGHT, pen0); pcw_plot_pixel(bitmap, PCW_BORDER_WIDTH+PCW_DISPLAY_WIDTH+6, y+PCW_BORDER_HEIGHT, pen0); pcw_plot_pixel(bitmap, PCW_BORDER_WIDTH+PCW_DISPLAY_WIDTH+7, y+PCW_BORDER_HEIGHT, pen0); } } else { /* not video - render whole lot in pen 0 */ rectangle rect(0, PCW_SCREEN_WIDTH, 0, PCW_SCREEN_HEIGHT); bitmap.fill(pen0, rect); } return 0; } uint32_t pcw_state::screen_update_pcw_printer(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect) { // printer output int32_t feed; rectangle rect(0, PCW_PRINTER_WIDTH - 1, 0, PCW_PRINTER_HEIGHT - 1); feed = -(m_paper_feed / 2); copyscrollbitmap(bitmap,*m_prn_output,0,nullptr,1,&feed,rect); bitmap.pix16(PCW_PRINTER_HEIGHT-1, m_printer_headpos) = 0; bitmap.pix16(PCW_PRINTER_HEIGHT-2, m_printer_headpos) = 0; bitmap.pix16(PCW_PRINTER_HEIGHT-3, m_printer_headpos) = 0; bitmap.pix16(PCW_PRINTER_HEIGHT-1, m_printer_headpos-1) = 0; bitmap.pix16(PCW_PRINTER_HEIGHT-2, m_printer_headpos-1) = 0; bitmap.pix16(PCW_PRINTER_HEIGHT-1, m_printer_headpos+1) = 0; bitmap.pix16(PCW_PRINTER_HEIGHT-2, m_printer_headpos+1) = 0; return 0; }
30.654255
224
0.660246
ead3d66d94475c5d960d55fe1aeb92b8886dbad6
127
hpp
C++
KGE/Core/Audio/ComponentAudioClip.hpp
jkeywo/KGE
5ad2619a4e205dd549cdf638854db356a80694ea
[ "MIT" ]
1
2016-08-10T14:03:29.000Z
2016-08-10T14:03:29.000Z
KGE/Core/Audio/ComponentAudioClip.hpp
jkeywo/KGE
5ad2619a4e205dd549cdf638854db356a80694ea
[ "MIT" ]
null
null
null
KGE/Core/Audio/ComponentAudioClip.hpp
jkeywo/KGE
5ad2619a4e205dd549cdf638854db356a80694ea
[ "MIT" ]
null
null
null
#pragma once #include "Core/Components/Component.hpp" namespace KGE { class ComponentAudioClip : public Component { }; };
11.545455
44
0.732283
ead4598d77cfe0fbd446e38a2eafd58c6ec87e49
4,866
cc
C++
training/mr_em_map_adapter.cc
agesmundo/FasterCubePruning
f80150140b5273fd1eb0dfb34bdd789c4cbd35e6
[ "BSD-3-Clause-LBNL", "Apache-2.0" ]
1
2019-06-03T00:44:01.000Z
2019-06-03T00:44:01.000Z
training/mr_em_map_adapter.cc
jhclark/cdec
237ddc67ffa61da310e19710f902d4771dc323c2
[ "BSD-3-Clause-LBNL", "Apache-2.0" ]
null
null
null
training/mr_em_map_adapter.cc
jhclark/cdec
237ddc67ffa61da310e19710f902d4771dc323c2
[ "BSD-3-Clause-LBNL", "Apache-2.0" ]
1
2021-02-19T12:44:54.000Z
2021-02-19T12:44:54.000Z
#include <iostream> #include <fstream> #include <cassert> #include <cmath> #include <boost/utility.hpp> #include <boost/program_options.hpp> #include <boost/program_options/variables_map.hpp> #include "boost/tuple/tuple.hpp" #include "fdict.h" #include "sparse_vector.h" using namespace std; namespace po = boost::program_options; // useful for EM models parameterized by a bunch of multinomials // this converts event counts (returned from cdec as feature expectations) // into different keys and values (which are lists of all the events, // conditioned on the key) for summing and normalization by a reducer void InitCommandLine(int argc, char** argv, po::variables_map* conf) { po::options_description opts("Configuration options"); opts.add_options() ("buffer_size,b", po::value<int>()->default_value(1), "Buffer size (in # of counts) before emitting counts") ("format,f",po::value<string>()->default_value("b64"), "Encoding of the input (b64 or text)"); po::options_description clo("Command line options"); clo.add_options() ("config", po::value<string>(), "Configuration file") ("help,h", "Print this help message and exit"); po::options_description dconfig_options, dcmdline_options; dconfig_options.add(opts); dcmdline_options.add(opts).add(clo); po::store(parse_command_line(argc, argv, dcmdline_options), *conf); if (conf->count("config")) { ifstream config((*conf)["config"].as<string>().c_str()); po::store(po::parse_config_file(config, dconfig_options), *conf); } po::notify(*conf); if (conf->count("help")) { cerr << dcmdline_options << endl; exit(1); } } struct EventMapper { int Map(int fid) { int& cv = map_[fid]; if (!cv) { cv = GetConditioningVariable(fid); } return cv; } void Clear() { map_.clear(); } protected: virtual int GetConditioningVariable(int fid) const = 0; private: map<int, int> map_; }; struct LexAlignEventMapper : public EventMapper { protected: virtual int GetConditioningVariable(int fid) const { const string& str = FD::Convert(fid); size_t pos = str.rfind("_"); if (pos == string::npos || pos == 0 || pos >= str.size() - 1) { cerr << "Bad feature for EM adapter: " << str << endl; abort(); } return FD::Convert(str.substr(0, pos)); } }; int main(int argc, char** argv) { po::variables_map conf; InitCommandLine(argc, argv, &conf); const bool use_b64 = conf["format"].as<string>() == "b64"; const int buffer_size = conf["buffer_size"].as<int>(); const string s_obj = "**OBJ**"; // 0<TAB>**OBJ**=12.2;Feat1=2.3;Feat2=-0.2; // 0<TAB>**OBJ**=1.1;Feat1=1.0; EventMapper* event_mapper = new LexAlignEventMapper; map<int, SparseVector<double> > counts; size_t total = 0; while(cin) { string line; getline(cin, line); if (line.empty()) continue; int feat; double val; size_t i = line.find("\t"); assert(i != string::npos); ++i; SparseVector<double> g; double obj = 0; if (use_b64) { if (!B64::Decode(&obj, &g, &line[i], line.size() - i)) { cerr << "B64 decoder returned error, skipping!\n"; continue; } } else { // text encoding - your counts will not be accurate! while (i < line.size()) { size_t start = i; while (line[i] != '=' && i < line.size()) ++i; if (i == line.size()) { cerr << "FORMAT ERROR\n"; break; } string fname = line.substr(start, i - start); if (fname == s_obj) { feat = -1; } else { feat = FD::Convert(line.substr(start, i - start)); } ++i; start = i; while (line[i] != ';' && i < line.size()) ++i; if (i - start == 0) continue; val = atof(line.substr(start, i - start).c_str()); ++i; if (feat == -1) { obj = val; } else { g.set_value(feat, val); } } } //cerr << "OBJ: " << obj << endl; const SparseVector<double>& cg = g; for (SparseVector<double>::const_iterator it = cg.begin(); it != cg.end(); ++it) { const int cond_var = event_mapper->Map(it->first); SparseVector<double>& cond_counts = counts[cond_var]; int delta = cond_counts.size(); cond_counts.add_value(it->first, it->second); delta = cond_counts.size() - delta; total += delta; } if (total > buffer_size) { for (map<int, SparseVector<double> >::iterator it = counts.begin(); it != counts.end(); ++it) { const SparseVector<double>& cc = it->second; cout << FD::Convert(it->first) << '\t'; if (use_b64) { B64::Encode(0.0, cc, &cout); } else { abort(); } cout << endl; } cout << flush; total = 0; counts.clear(); } } return 0; }
30.223602
116
0.59104
ead6a6563593a425e9fc1fd361c2c6fc2abc5b05
1,404
cpp
C++
thirdparty/sfs2x/Bitswarm/BBox/BBEvent.cpp
godot-addons/godot-sfs2x
a8d52aa9d548f6d45bbb64bfdaacab0df10e67c1
[ "MIT" ]
2
2020-05-14T07:48:32.000Z
2021-02-03T14:58:11.000Z
thirdparty/sfs2x/Bitswarm/BBox/BBEvent.cpp
godot-addons/godot-sfs2x
a8d52aa9d548f6d45bbb64bfdaacab0df10e67c1
[ "MIT" ]
1
2020-05-28T16:39:20.000Z
2020-05-28T16:39:20.000Z
thirdparty/sfs2x/Bitswarm/BBox/BBEvent.cpp
godot-addons/godot-sfs2x
a8d52aa9d548f6d45bbb64bfdaacab0df10e67c1
[ "MIT" ]
2
2018-07-07T20:15:00.000Z
2018-10-26T05:18:30.000Z
// =================================================================== // // Description // Contains the implementation of BBEvent // // Revision history // Date Description // 30-Nov-2012 First version // // =================================================================== #include "BBEvent.h" namespace Sfs2X { namespace Bitswarm { namespace BBox { boost::shared_ptr<string> BBEvent::CONNECT (new string("bb-connect")); boost::shared_ptr<string> BBEvent::DISCONNECT (new string("bb-disconnect")); boost::shared_ptr<string> BBEvent::DATA (new string("bb-data")); boost::shared_ptr<string> BBEvent::IO_ERROR (new string("bb-ioError")); boost::shared_ptr<string> BBEvent::SECURITY_ERROR (new string("bb-securityError")); // ------------------------------------------------------------------- // Constructor // ------------------------------------------------------------------- BBEvent::BBEvent(boost::shared_ptr<string> type) : BaseEvent (type, boost::shared_ptr<map<string, boost::shared_ptr<void> > >()) { } // ------------------------------------------------------------------- // Constructor // ------------------------------------------------------------------- BBEvent::BBEvent(boost::shared_ptr<string> type, boost::shared_ptr<map<string, boost::shared_ptr<void> > > arguments) : BaseEvent (type, arguments) { } } // namespace BBox } // namespace Bitswarm } // namespace Sfs2X
31.909091
117
0.504274
ead740e181fb132ccf2430f21f427346276b1b97
1,883
hpp
C++
include/IStreamSocket.hpp
lordio/insanity
7dfbf398fe08968f40a32280bf2b16cca2b476a1
[ "MIT" ]
1
2015-02-05T10:41:14.000Z
2015-02-05T10:41:14.000Z
include/IStreamSocket.hpp
lordio/insanity
7dfbf398fe08968f40a32280bf2b16cca2b476a1
[ "MIT" ]
1
2015-02-04T20:47:52.000Z
2015-02-05T07:43:05.000Z
include/IStreamSocket.hpp
lordio/insanity
7dfbf398fe08968f40a32280bf2b16cca2b476a1
[ "MIT" ]
null
null
null
#ifndef INSANITY_INTERFACE_STREAM_SOCKET #define INSANITY_INTERFACE_STREAM_SOCKET #include "Constants.hpp" #include "IObject.hpp" namespace Insanity { class IByteArray; class INSANITY_API IStreamSocket : public virtual IObject { public: //================================================= //Create a new StreamSocket // Attempts to connect to host, at port. // Will return an unconnected IStreamSocket if connection fails. //================================================= static IStreamSocket * Create(char const * host, u16 port); //================================================= //Communicate with remote peer. // Silently ignores request if unconnected. //================================================= virtual void Send(IByteArray const * arr) = 0; virtual void Receive(IByteArray * arr) = 0; //================================================= //Attempt to connect to host, at port. // Returns false if the connection fails, true otherwise. // Will Close() the socket if it is open. //================================================= virtual bool Connect(const char * host, u16 port) = 0; //================================================= //Stops communications on the socket. // Returns false if socket was already not open, true otherwise. //================================================= virtual bool Close() = 0; //================================================= //Returns false if the socket is not open, or if there is no pending data. // True otherwise. //================================================= virtual bool HasPendingData() const = 0; //================================================= //Returns true if the socket is connected to a server // false otherwise. //================================================= virtual bool IsConnected() const = 0; }; } #endif
34.236364
76
0.478492
ead785b9cb2a4cac33dff6d2858fa848750a70e0
344
cpp
C++
projects/client/input/haft/source/haft/Input_Configuration.cpp
silentorb/mythic-cpp
97319d158800d77e1a944c47c13523662bc07e08
[ "MIT" ]
null
null
null
projects/client/input/haft/source/haft/Input_Configuration.cpp
silentorb/mythic-cpp
97319d158800d77e1a944c47c13523662bc07e08
[ "MIT" ]
null
null
null
projects/client/input/haft/source/haft/Input_Configuration.cpp
silentorb/mythic-cpp
97319d158800d77e1a944c47c13523662bc07e08
[ "MIT" ]
null
null
null
#include "Input_Configuration.h" namespace haft { Device *Input_Configuration::get_device(const std::string name) const { for (auto &device: devices) { if (device->get_name() == name) return device.get(); } return nullptr; // throw runtime_error(string("Invalid device name ") + name + "."); } }
24.571429
74
0.613372
ead7da1fbb8c0d130dd44346123a6ba87c889f8b
1,276
cc
C++
chrome/browser/commerce/coupons/coupon_service_factory.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
76
2020-09-02T03:05:41.000Z
2022-03-30T04:40:55.000Z
chrome/browser/commerce/coupons/coupon_service_factory.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
45
2020-09-02T03:21:37.000Z
2022-03-31T22:19:45.000Z
chrome/browser/commerce/coupons/coupon_service_factory.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
8
2020-07-22T18:49:18.000Z
2022-02-08T10:27:16.000Z
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/commerce/coupons/coupon_service_factory.h" #include "chrome/browser/commerce/coupons/coupon_db.h" #include "chrome/browser/commerce/coupons/coupon_service.h" #include "components/keyed_service/content/browser_context_dependency_manager.h" #include "content/public/browser/storage_partition.h" // static CouponServiceFactory* CouponServiceFactory::GetInstance() { static base::NoDestructor<CouponServiceFactory> factory; return factory.get(); } // static CouponService* CouponServiceFactory::GetForProfile(Profile* profile) { return static_cast<CouponService*>( GetInstance()->GetServiceForBrowserContext(profile, true)); } CouponServiceFactory::CouponServiceFactory() : BrowserContextKeyedServiceFactory( "CouponService", BrowserContextDependencyManager::GetInstance()) {} CouponServiceFactory::~CouponServiceFactory() = default; KeyedService* CouponServiceFactory::BuildServiceInstanceFor( content::BrowserContext* context) const { DCHECK(!context->IsOffTheRecord()); return new CouponService(std::make_unique<CouponDB>(context)); }
34.486486
80
0.78605
ead9c3a8781669f4af03b5db8a78491a045a2aef
1,523
cpp
C++
cpp/exercises.cpp
StrubT/ProgressorDefaultExercises
1237c4f8fe7007dd815f4cc6656512a72e409de0
[ "MIT" ]
2
2016-11-19T12:05:11.000Z
2016-11-22T17:00:52.000Z
cpp/exercises.cpp
StrubT/ProgressorDefaultExercises
1237c4f8fe7007dd815f4cc6656512a72e409de0
[ "MIT" ]
4
2017-09-21T13:11:34.000Z
2017-09-22T09:24:45.000Z
cpp/exercises.cpp
StrubT/ProgressorDefaultExercises
1237c4f8fe7007dd815f4cc6656512a72e409de0
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include <regex> #include <algorithm> using namespace std; string helloWorld() { return "Hello, World!"; } string alternate(string first, string second) { string result; int i; for (i = 0; i < first.length() && i < second.length(); i++) result += first.substr(i, 1) + second.substr(i, 1); result += first.substr(i) + second.substr(i); return result; } char *swapEncrypt(char *toSwap, int length) { for (int i = 0; i + 1 < length; i += 2) { char tmp = toSwap[i]; toSwap[i] = toSwap[i + 1]; toSwap[i + 1] = tmp; } return toSwap; } bool isPalindrome(string palindrome) { string clean = regex_replace(palindrome, regex("[^A-Za-z]"), "", regex_constants::format_default); transform(clean.begin(), clean.end(), clean.begin(), ::tolower); for (int i = 0, j = clean.length() - 1; i < j; i++, j--) if (clean[i] != clean[j]) return false; return true; } int fibonacci(int num) { if (num < 1) return 0; if (num == 1) return 1; return fibonacci(num - 2) + fibonacci(num - 1); } int main() { cout << helloWorld() << endl; cout << alternate("Hlo ol!", "el,Wrd") << endl; cout << swapEncrypt(new char[11] {'H','e','l','l','o',' ','W','o','r','l','d'}, 11) << endl; cout << swapEncrypt(new char[11] {'e','H','l','l',' ','o','o','W','l','r','d'}, 11) << endl; cout << isPalindrome("Hello, World!") << endl; cout << isPalindrome("A Santa dog lived as a devil God at NASA.") << endl; for (auto i = 0; i < 10; i++) cout << fibonacci(i) << endl; }
27.690909
99
0.589626
eae6573fae791d2658baadcd206a819f238030ff
5,179
hxx
C++
main/sc/inc/hints.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
679
2015-01-06T06:34:58.000Z
2022-03-30T01:06:03.000Z
main/sc/inc/hints.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
102
2017-11-07T08:51:31.000Z
2022-03-17T12:13:49.000Z
main/sc/inc/hints.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
331
2015-01-06T11:40:55.000Z
2022-03-14T04:07:51.000Z
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ #ifndef SC_HINTS_HXX #define SC_HINTS_HXX #include "global.hxx" #include "address.hxx" #include <svl/hint.hxx> // --------------------------------------------------------------------------- class ScPaintHint : public SfxHint { ScRange aRange; sal_uInt16 nParts; sal_Bool bPrint; // Flag, ob auch Druck/Vorschau betroffen ist ScPaintHint(); // disabled public: TYPEINFO(); ScPaintHint( const ScRange& rRng, sal_uInt16 nPaint = PAINT_ALL ); ~ScPaintHint(); void SetPrintFlag(sal_Bool bSet) { bPrint = bSet; } const ScRange& GetRange() const { return aRange; } SCCOL GetStartCol() const { return aRange.aStart.Col(); } SCROW GetStartRow() const { return aRange.aStart.Row(); } SCTAB GetStartTab() const { return aRange.aStart.Tab(); } SCCOL GetEndCol() const { return aRange.aEnd.Col(); } SCROW GetEndRow() const { return aRange.aEnd.Row(); } SCTAB GetEndTab() const { return aRange.aEnd.Tab(); } sal_uInt16 GetParts() const { return nParts; } sal_Bool GetPrintFlag() const { return bPrint; } }; class ScUpdateRefHint : public SfxHint { UpdateRefMode eUpdateRefMode; ScRange aRange; SCsCOL nDx; SCsROW nDy; SCsTAB nDz; public: TYPEINFO(); ScUpdateRefHint( UpdateRefMode eMode, const ScRange& rR, SCsCOL nX, SCsROW nY, SCsTAB nZ ); ~ScUpdateRefHint(); UpdateRefMode GetMode() const { return eUpdateRefMode; } const ScRange& GetRange() const { return aRange; } SCsCOL GetDx() const { return nDx; } SCsROW GetDy() const { return nDy; } SCsTAB GetDz() const { return nDz; } }; #define SC_POINTERCHANGED_NUMFMT 1 class ScPointerChangedHint : public SfxHint { sal_uInt16 nFlags; public: TYPEINFO(); //UNUSED2008-05 ScPointerChangedHint( sal_uInt16 nF ); ~ScPointerChangedHint(); sal_uInt16 GetFlags() const { return nFlags; } }; //! move ScLinkRefreshedHint to a different file? #define SC_LINKREFTYPE_NONE 0 #define SC_LINKREFTYPE_SHEET 1 #define SC_LINKREFTYPE_AREA 2 #define SC_LINKREFTYPE_DDE 3 class ScLinkRefreshedHint : public SfxHint { sal_uInt16 nLinkType; // SC_LINKREFTYPE_... String aUrl; // used for sheet links String aDdeAppl; // used for dde links: String aDdeTopic; String aDdeItem; sal_uInt8 nDdeMode; ScAddress aDestPos; // used to identify area links //! also use source data for area links? public: TYPEINFO(); ScLinkRefreshedHint(); ~ScLinkRefreshedHint(); void SetSheetLink( const String& rSourceUrl ); void SetDdeLink( const String& rA, const String& rT, const String& rI, sal_uInt8 nM ); void SetAreaLink( const ScAddress& rPos ); sal_uInt16 GetLinkType() const { return nLinkType; } const String& GetUrl() const { return aUrl; } const String& GetDdeAppl() const { return aDdeAppl; } const String& GetDdeTopic() const { return aDdeTopic; } const String& GetDdeItem() const { return aDdeItem; } sal_uInt8 GetDdeMode() const { return nDdeMode; } const ScAddress& GetDestPos() const { return aDestPos; } }; //! move ScAutoStyleHint to a different file? class ScAutoStyleHint : public SfxHint { ScRange aRange; String aStyle1; String aStyle2; sal_uLong nTimeout; public: TYPEINFO(); ScAutoStyleHint( const ScRange& rR, const String& rSt1, sal_uLong nT, const String& rSt2 ); ~ScAutoStyleHint(); const ScRange& GetRange() const { return aRange; } const String& GetStyle1() const { return aStyle1; } sal_uInt32 GetTimeout() const { return nTimeout; } const String& GetStyle2() const { return aStyle2; } }; class ScDBRangeRefreshedHint : public SfxHint { ScImportParam aParam; public: TYPEINFO(); ScDBRangeRefreshedHint( const ScImportParam& rP ); ~ScDBRangeRefreshedHint(); const ScImportParam& GetImportParam() const { return aParam; } }; class ScDataPilotModifiedHint : public SfxHint { String maName; public: TYPEINFO(); ScDataPilotModifiedHint( const String& rName ); ~ScDataPilotModifiedHint(); const String& GetName() const { return maName; } }; #endif
28.456044
89
0.659394
eae87783473a79a689454e4b2011efe263c479f9
726
cpp
C++
Flinty/Flinty/src/fl/Core.cpp
TheCherno/AnimatedSpriteCompression
012dc267c59a7921defed868d235533afa630b6b
[ "Apache-2.0" ]
11
2016-08-10T18:16:29.000Z
2021-11-20T12:09:28.000Z
Flinty/Flinty/src/fl/Core.cpp
TheCherno/AnimatedSpriteCompression
012dc267c59a7921defed868d235533afa630b6b
[ "Apache-2.0" ]
null
null
null
Flinty/Flinty/src/fl/Core.cpp
TheCherno/AnimatedSpriteCompression
012dc267c59a7921defed868d235533afa630b6b
[ "Apache-2.0" ]
3
2019-05-16T15:37:34.000Z
2020-04-10T01:05:03.000Z
#include "Core.h" #include <iostream> #include "gl.h" #if defined(FL_PLATFORM_ANDROID) #include "platform/android/AndroidSystem.h" #endif namespace fl { #if defined(FL_PLATFORM_WINDOWS) void Init() { } #elif defined(FL_PLATFORM_ANDROID) void Init(void* env, void* mainView) { AndroidSystem::Init((JNIEnv*)env, (jobject)mainView); } #endif inline GLenum GLCheckError() { return glGetError(); } void GLClearError() { GLCheckError(); } bool GLLogCall(const char* function, const char* file, int line) { while (GLenum error = GLCheckError()) { std::cout << "[OpenGL Error] (" << error << "): " << function << " " << file << ":" << line << std::endl; return false; } return true; } }
15.446809
109
0.646006
eaea8280c75f22a6557e0fc2c795457539db1e20
2,044
hpp
C++
GazeEstimationCpp/PinholeCameraModel.hpp
dmikushin/RemoteEye
f467594e8d0246d7cc87bf843da1d09e105fcca7
[ "MIT" ]
9
2020-05-10T15:40:10.000Z
2022-01-26T19:58:55.000Z
GazeEstimationCpp/PinholeCameraModel.hpp
dmikushin/RemoteEye
f467594e8d0246d7cc87bf843da1d09e105fcca7
[ "MIT" ]
5
2020-08-08T22:22:51.000Z
2021-01-18T12:18:37.000Z
GazeEstimationCpp/PinholeCameraModel.hpp
dmikushin/RemoteEye
f467594e8d0246d7cc87bf843da1d09e105fcca7
[ "MIT" ]
2
2020-08-08T09:31:59.000Z
2020-12-14T05:49:33.000Z
#ifndef PINHOLE_CAMERA_MODEL_HPP_INCLUDED #define PINHOLE_CAMERA_MODEL_HPP_INCLUDED #include "MathTypes.hpp" namespace gazeestimation{ class PinholeCameraModel { private: Vec3 camera_angles; Mat3x3 actual_rotation_matrix; public: // camera intrinsic double principal_point_x; double principal_point_y; double pixel_size_cm_x; double pixel_size_cm_y; double effective_focal_length_cm; /// the position in WCS Vec3 position; PinholeCameraModel(): camera_angles(make_vec3(0,0,0)), actual_rotation_matrix(identity_matrix3x3()), principal_point_x(0), principal_point_y(0), pixel_size_cm_x(0), pixel_size_cm_y(0), effective_focal_length_cm(0) { } void set_camera_angles(double x, double y, double z) { camera_angles = make_vec3(x, y, z); actual_rotation_matrix = calculate_extrinsic_rotation_matrix(camera_angles[0], camera_angles[1], camera_angles[2]); } /// Returns the rotation matrix for this camera. Mat3x3 rotation_matrix() const { return actual_rotation_matrix; } /// Transforms the given vector in this camera's image coordinate system to /// the camera coordinate system Vec3 ics_to_ccs(const Vec2& pos) const { return make_vec3( (pos[0] - principal_point_x) * pixel_size_cm_x, (pos[1] - principal_point_y) * pixel_size_cm_y, -effective_focal_length_cm ); } Vec3 ccs_to_wcs(const Vec3& pos) const { return rotation_matrix() * pos + position; } Vec3 ics_to_wcs(const Vec2& pos) const { return ccs_to_wcs(ics_to_ccs(pos)); } double camera_angle_x() const { return camera_angles[0]; } double camera_angle_y() const { return camera_angles[1]; } double camera_angle_z() const { return camera_angles[2]; } void set_camera_angle_x(double angle) { set_camera_angles(angle, camera_angles[1], camera_angles[2]); } void set_camera_angle_y(double angle) { set_camera_angles(camera_angles[0], angle, camera_angles[2]); } void set_camera_angle_z(double angle) { set_camera_angles(camera_angles[0], camera_angles[1], angle); } }; } #endif
20.44
117
0.751957
eaeaee7f2c260beb4af190c606e353fb56f190f5
1,356
cpp
C++
IndependentSet.cpp
manoelstilpen/clique_problem
bf1c9711128b9173301d9ff4d1ad2f837f7f523e
[ "MIT" ]
null
null
null
IndependentSet.cpp
manoelstilpen/clique_problem
bf1c9711128b9173301d9ff4d1ad2f837f7f523e
[ "MIT" ]
null
null
null
IndependentSet.cpp
manoelstilpen/clique_problem
bf1c9711128b9173301d9ff4d1ad2f837f7f523e
[ "MIT" ]
1
2019-07-02T13:55:23.000Z
2019-07-02T13:55:23.000Z
#include "IndependentSet.hpp" IndependentSet::IndependentSet(){ definedGraph = false; } IndependentSet::IndependentSet(Graph _graph){ setGraph(_graph); } int IndependentSet::searchLargestIndependentSet(){ for(int k=0 ; k<graph.getNVertex() ; k++){ vector<int> vertex_list(graph.getNVertex()); iota(vertex_list.begin(), vertex_list.end(), 0); // crescent ordering sort(vertex_list.begin(), vertex_list.end(), [&](const int& a, const int& b){ return graph.getNAdjacencyOf(a) > graph.getNAdjacencyOf(b); }); for(int i=k ; i<vertex_list.size()+k ; i++){ int index; if(i >= vertex_list.size()) index = vertex_list[i-vertex_list.size()]; else index = vertex_list[i]; for(int j=0 ; j<vertex_list.size() ; j++){ } } /* for(int j=0 ; j<tam_list ; j++){ if(graph->complement[index][vertex_list[j]] == 1){ if(j < i) i--; remove_index(vertex_list,tam_list,j); graph->nAdjacencies[vertex_list[j]]--; tam_list--; j--; } } } if(tam_list > max){ max = tam_list; history = copy_array(vertex_list, tam_list); } free(vertex_list); */ } } void IndependentSet::setGraph(Graph _graph){ graph = _graph; }
22.229508
85
0.558997
eaeb3528d0718695e61d2dc99b3bd35a908a30d4
225
hpp
C++
include/LIEF/span.hpp
rafael-santiago/LIEF
f230094d5877dd63d40915dc944c53c2a4be5ed9
[ "Apache-2.0" ]
1
2022-02-26T00:28:52.000Z
2022-02-26T00:28:52.000Z
include/LIEF/span.hpp
rafael-santiago/LIEF
f230094d5877dd63d40915dc944c53c2a4be5ed9
[ "Apache-2.0" ]
null
null
null
include/LIEF/span.hpp
rafael-santiago/LIEF
f230094d5877dd63d40915dc944c53c2a4be5ed9
[ "Apache-2.0" ]
null
null
null
#ifndef LIEF_SPAN_H #define LIEF_SPAN_H #include <LIEF/third-party/span.hpp> namespace LIEF { template <typename ElementType, std::size_t Extent = tcb::dynamic_extent> using span = tcb::span<ElementType, Extent>; } #endif
18.75
73
0.764444
eaebe3caf007b66f13294eaa39c997be945f32c1
1,067
cc
C++
chrome/browser/locale_tests_uitest.cc
zachlatta/chromium
c4625eefca763df86471d798ee5a4a054b4716ae
[ "BSD-3-Clause" ]
1
2021-09-24T22:49:10.000Z
2021-09-24T22:49:10.000Z
chrome/browser/locale_tests_uitest.cc
changbai1980/chromium
c4625eefca763df86471d798ee5a4a054b4716ae
[ "BSD-3-Clause" ]
null
null
null
chrome/browser/locale_tests_uitest.cc
changbai1980/chromium
c4625eefca763df86471d798ee5a4a054b4716ae
[ "BSD-3-Clause" ]
null
null
null
// 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 "chrome/test/ui/ui_test.h" class LocaleTestsDa : public UITest { public: LocaleTestsDa() : UITest() { launch_arguments_.AppendSwitchWithValue(L"lang", L"da"); } }; class LocaleTestsHe : public UITest { public: LocaleTestsHe() : UITest() { launch_arguments_.AppendSwitchWithValue(L"lang", L"he"); } }; class LocaleTestsZhTw : public UITest { public: LocaleTestsZhTw() : UITest() { launch_arguments_.AppendSwitchWithValue(L"lang", L"zh-TW"); } }; #if defined(OS_WIN) || defined(OS_LINUX) // These 3 tests started failing between revisions 13115 and 13120. // See bug 9758. TEST_F(LocaleTestsDa, TestStart) { // Just making sure we can start/shutdown cleanly. } TEST_F(LocaleTestsHe, TestStart) { // Just making sure we can start/shutdown cleanly. } TEST_F(LocaleTestsZhTw, TestStart) { // Just making sure we can start/shutdown cleanly. } #endif
24.813953
73
0.719775
eaf0865ae2f420e0b3dd47bcee0fa3c845fbd082
953
cpp
C++
Ruminate/src/HelperFiles/a_funcs.cpp
Riku32/Ruminate
0855384c2abb24f2552688561ff90bd555ef3c07
[ "MIT" ]
null
null
null
Ruminate/src/HelperFiles/a_funcs.cpp
Riku32/Ruminate
0855384c2abb24f2552688561ff90bd555ef3c07
[ "MIT" ]
null
null
null
Ruminate/src/HelperFiles/a_funcs.cpp
Riku32/Ruminate
0855384c2abb24f2552688561ff90bd555ef3c07
[ "MIT" ]
null
null
null
#include "HelperFiles/a_funcs.hpp" //relu inline float Relu(float x) { return (x > 0) * x; } inline float ReluPrime(float x) { return x > 0; } //leaky relu inline float ReluLeaky(float x) { if (x < 0) { return x * A; } else { return x; } } inline float ReluLeakyPrime(float x) { if (x < 0) { return A; } else { return 1; } } //tanh inline float Tanh(float x) { return tanh(x); } inline float TanhPrime(float x) { return sinh(x) / cosh(x); } //sigmoid inline float Sigmoid(float x) { return 1 / (1 + exp(-x)); } inline float SigmoidPrime(float x) { return exp(-x) / std::pow(1 + exp(-x), 2); } //swish inline float Swish(float x) { return x * Sigmoid(x); } inline float SwishPrime(float x) { return (exp(x) * (exp(x) + x + 1)) / std::pow(exp(x) + 1, 2); }
12.878378
66
0.499475
eaf608c4845378c97f1a955f5533efa1e5c2b962
8,845
cpp
C++
src/corder.cpp
Cetus-K/corder
cd635c3bf49f578952d65393270a9a980841299e
[ "MIT" ]
null
null
null
src/corder.cpp
Cetus-K/corder
cd635c3bf49f578952d65393270a9a980841299e
[ "MIT" ]
null
null
null
src/corder.cpp
Cetus-K/corder
cd635c3bf49f578952d65393270a9a980841299e
[ "MIT" ]
null
null
null
#include "corder.h" // corder destructor corder::~corder() { vector < int > ().swap(l); vector < int > ().swap(item); vector < int > ().swap(sitem); vector < vector < int > > ().swap(stypeindex); vector < vector < int > > ().swap(stypelist); vector < string > ().swap(mode); vector < string > ().swap(type); vector < vector < string > > ().swap(stype); stypelist.clear(); } // the type of i-th index ion int corder::mytype ( int idx ) { int itype,cnt = 0; for ( itype=0; itype<ntypes; itype++ ) { cnt += item[itype]; if ( idx < cnt ) break; } return itype; } // the address that start itype ion indices // range: [ mystart(a), mystart(a)+item[a] ) int corder::mystart ( int itype ) { int cnt = 0; for ( int a=0; a<itype; a++ ) cnt += item[a]; return cnt; } // update double corder::update ( double prev, double add ) { return ( (double)(itr-f0)/df*prev+add )/((double)(itr-f0)/df+1.0); } // main control int main(int argc, char* argv[]){ // declare int rank,nmpi; // mpi rank ans its size double scale; // lattice scale double beg,time,prog; // progress map < string,bool > mode; // calc mode vec cfg(3); // vector and matrix class ifstream ifs; // fstream istringstream iss; string str; corder co; // corder basis class // set corder parameter co.set_param(); // calculation mode mode["gofr"] = false; // g(r),gab(r) mode["sofq"] = false; // s(q),sab(q) mode["dfc"] = false; // msd,msda,<v>,<va> mode["lboo"] = false; // ql,wl,qlab,wlab mode["bacf"] = false; // gl(r),glabab(r) mode["pofqw"] = false; // p(ql),p(wl),p(qlab),p(wlab) mode["bofree"] = false; // f,fl,fll,fab,flab,fllab mode["povoro"] = false; // dump trajectory as pov-ray format mode["csform"] = false; // counting each sharing formations // dependence parameter mode["covoro"] = false; // engine for lboo/bacf/pofqw/bofree/voro mode["coqhull"] = false; // engine for ... mode["instant"] = false; // instantsneous calculation for write out for ( int i=0; i<(int)co.mode.size(); i++ ) mode[co.mode[i]] = true; // dependency mode["sofq"] = mode["sofq"] and mode["gofr"]; mode["covoro"] = mode["lboo"] or mode["bacf"] or mode["pofqw"] or mode["bofree"] or mode["csform"] or mode["povoro"] or mode["csform"]; mode["instant"] = !( mode["bacf"] or mode["pofqw"] or mode["bofree"] or mode["csform"] ); // check read if ( co.f1 < co.f0 ) co.f1 = grep_c("XDATCAR","Direct"); // memory allocation: co.config.resize(co.nions); for ( int i=0; i<co.nions; i++ ) co.config[i].resize(3); // initialize // each class related to mode // create copy constructor by refference handling gofr co_gofr(co); co_gofr.init(); sofq co_sofq(co); co_sofq.init(); dfc co_dfc(co); co_dfc.init(); covoro co_covoro(co); co_covoro.init(); lboo co_lboo(co,co_covoro); co_lboo.init(); bacf co_bacf(co,co_covoro); co_bacf.init(); pofqw co_pofqw(co,co_covoro); co_pofqw.init(); bofree co_bofree(co,co_covoro); co_bofree.init(); povoro co_povoro(co,co_covoro); coqhull co_coqhull(co); co_coqhull.init(); coqhull co_cv_coqhull(co,co_covoro); co_cv_coqhull.init(); csform co_csform(co,co_covoro,co_cv_coqhull); co_csform.init(); // MPI environment MPI_Init(&argc,&argv); MPI_Comm_rank(MPI_COMM_WORLD,&rank); MPI_Comm_size(MPI_COMM_WORLD,&nmpi); MPI_Barrier(MPI_COMM_WORLD); beg = prog = MPI_Wtime(); // read XDATCAR and skip initial lines without axis at latdyn = false ifs.open("XDATCAR",ios::in); if ( !co.latdyn ) for ( int i=0; i<7; i++ ) getline(ifs,str); // dump system information if ( rank == 0 ) { co.info(); cout << endl; cout << "------------------" << endl; cout << " Progress" << endl; cout << "------------------" << endl; cout << endl; cout << "Iteration ( completion [%] ) : 1 dump-step cpu time ( total ) [s]" << endl; cout << "-----------------------------------------------------------------" << endl; } MPI_Barrier(MPI_COMM_WORLD); // iterator init co.itr = 0; while ( co.itr<=co.f1 && !ifs.eof() ) { co.itr ++; if ( ( co.f0<=co.itr && co.itr<=co.f1 && (co.itr-co.f0)%co.df==0 ) || co.itr==co.f1 ) { // if lattice dynamics is true // read lattice system if ( co.latdyn ) { // label getline(ifs,str); // scale getline(ifs,str); iss.str(str); iss >> scale; iss.clear(); // lattice vector >> transform matrix getline(ifs,str); iss.str(str); iss >> co.a1(0) >> co.a1(1) >> co.a1(2); iss.clear(); co.a1 *= scale; getline(ifs,str); iss.str(str); iss >> co.a2(0) >> co.a2(1) >> co.a2(2); iss.clear(); co.a2 *= scale; getline(ifs,str); iss.str(str); iss >> co.a3(0) >> co.a3(1) >> co.a3(2); iss.clear(); co.a3 *= scale; for ( int i=0; i<3; i++ ) co.latmat(i,0) = co.a1(i); for ( int i=0; i<3; i++ ) co.latmat(i,1) = co.a2(i); for ( int i=0; i<3; i++ ) co.latmat(i,2) = co.a3(i); // type ands item for ( int i=0; i<2; i++ ) getline(ifs,str); } // axis line getline(ifs,str); // configuration for ( int i=0; i<co.nions; i++ ) { getline(ifs,str); iss.str(str); for ( int j=0; j<3; j++ ) iss >> cfg(j); co.config[i] = co.latmat*cfg; iss.clear(); } MPI_Barrier(MPI_COMM_WORLD); // update mode if ( mode["gofr"] ) { co_gofr.set(co); co_gofr.update(rank,nmpi); } MPI_Barrier(MPI_COMM_WORLD); // not using so far // if ( mode["sofq"] ) { // co_sofq.set(co); // MPI_Barrier(MPI_COMM_WORLD); // } if ( mode["dfc"] && rank == 0 ) { co_dfc.set(co); co_dfc.update(); } MPI_Barrier(MPI_COMM_WORLD); if ( mode["covoro"] && !mode["instant"] ) { co_covoro.set(co); co_covoro.get(); for ( int a=0; a<co.ntypes; a++ ) { for ( int b=0; b<co.ntypes; b++ ) { co_covoro.pget(a,b); } } for ( int spa=0; spa<co.nstypes; spa++ ) { for ( int spb=0; spb<co.nstypes; spb++ ) { co_covoro.spget(spa,spb); } } } MPI_Barrier(MPI_COMM_WORLD); // not using so far // if ( mode["lboo"] && rank == 0 ) { // co_lboo.set(co,co_covoro); // MPI_Barrier(MPI_COMM_WORLD); // } if ( mode["bacf"] ) { co_bacf.set(co,co_covoro); co_bacf.update(rank,nmpi); } MPI_Barrier(MPI_COMM_WORLD); if ( mode["pofqw"] && rank == 0 ) { co_pofqw.set(co,co_covoro); co_pofqw.update(); } MPI_Barrier(MPI_COMM_WORLD); if ( mode["bofree"] && ( (co.itr-co.f0) % (co.df*co.dump) == 0 || co.itr==co.f1 ) ) { co_bofree.set(co,co_covoro); co_bofree.update(rank,nmpi); } MPI_Barrier(MPI_COMM_WORLD); if ( mode["csform"] ) { co_cv_coqhull.set(co,co_covoro); co_csform.get(); co_csform.pget(); co_csform.spget(); co_csform.update(rank,nmpi); } MPI_Barrier(MPI_COMM_WORLD); // write out if ( ( (co.itr-co.f0) % (co.df*co.dump) == 0 || co.itr==co.f1 ) && rank == 0 ) { // write out if ( mode["gofr"] ) co_gofr.write("gofr"); if ( mode["sofq"] ) { co_sofq.set(co); co_sofq.write("sofq",&co_gofr); } if ( mode["dfc"] ) co_dfc.write("dfc"); if ( mode["lboo"] ) { if ( mode["covoro"] && mode["instant"] ) { co_covoro.set(co); co_covoro.get(); for ( int a=0; a<co.ntypes; a++ ) { for ( int b=0; b<co.ntypes; b++ ) { co_covoro.pget(a,b); } } for ( int spa=0; spa<co.nstypes; spa++ ) { for ( int spb=0; spb<co.nstypes; spb++ ) { co_covoro.spget(spa,spb); } } } co_lboo.set(co,co_covoro); co_lboo.write("lboo"); } if ( mode["bacf"] ) co_bacf.write("bacf"); if ( mode["pofqw"] ) co_pofqw.write("pofqw"); if ( mode["bofree"] ) co_bofree.write("bofree"); if ( mode["povoro"] ) { if ( mode["covoro"] && mode["instant"] ) { co_covoro.set(co); co_covoro.get(); for ( int a=0; a<co.ntypes; a++ ) { for ( int b=0; b<co.ntypes; b++ ) { co_covoro.pget(a,b); } } for ( int spa=0; spa<co.nstypes; spa++ ) { for ( int spb=0; spb<co.nstypes; spb++ ) { co_covoro.spget(spa,spb); } } } co_povoro.set(co,co_covoro); co_povoro.write("povoro"); for ( int a=0; a<co.ntypes; a++ ) { for ( int b=0; b<co.ntypes; b++ ) { co_povoro.pwrite("povoro",a,b); } } } if ( mode["csform"] ) { co_csform.write("csform"); } // dump progress time = MPI_Wtime(); cout << co.itr << " ( " << (double)(co.itr-co.f0+1)/(double)(co.f1-co.f0+1)*100.0 << " )"; cout << " : " << time-prog << " ( " << time-beg << " )" << endl; prog = time; } MPI_Barrier(MPI_COMM_WORLD); } else { // skip if ( co.latdyn ) for ( int i=0; i<7; i++ ) getline(ifs,str); getline(ifs,str); // axis for ( int i=0; i<co.nions; i++ ) getline(ifs,str); } } MPI_Barrier(MPI_COMM_WORLD); ifs.close(); MPI_Finalize(); // free mode.clear(); return 0; }
28.905229
136
0.5645
46aeb29ba723d04d05eb80ed696f5532ce9ed1c5
767
cpp
C++
intermediate/funciones/vectorAddFunctions.cpp
eduardorasgado/CppZerotoAdvance2018
909cc0f0e1521fd9ca83795bf84cbb9f725d9d4f
[ "MIT" ]
1
2019-06-20T17:51:10.000Z
2019-06-20T17:51:10.000Z
intermediate/funciones/vectorAddFunctions.cpp
eduardorasgado/CppZerotoAdvance2018
909cc0f0e1521fd9ca83795bf84cbb9f725d9d4f
[ "MIT" ]
2
2018-10-01T08:14:01.000Z
2018-10-06T05:27:26.000Z
intermediate/funciones/vectorAddFunctions.cpp
eduardorasgado/CppZerotoAdvance2018
909cc0f0e1521fd9ca83795bf84cbb9f725d9d4f
[ "MIT" ]
1
2018-10-05T10:54:10.000Z
2018-10-05T10:54:10.000Z
#include <iostream> using namespace std; int suma(int vector1[], int N); void dataRequest(); void showVector(); int N, vector[100]; int main(int argc, char** argv) { // pidiendo los datos al usuario dataRequest(); showVector(); int addition = suma(vector, N); cout << "La suma de todos los numeros del vector es: " << addition << endl; return 0; } int suma(int vector1[], int N) { int addition = 0; for(int i = 0;i < N;i++) addition += vector[i]; return addition; } void dataRequest() { cout << "De que tamaño es su vector: ", cin >> N; for(int i = 0;i < N;i++) cout << "vector[" << i << "]: ", cin >> vector[i]; cout << endl; } void showVector() { for(int i = 0;i < N;i++) cout << "vector[" << i << "]: " << vector[i] << endl; cout << endl; }
18.707317
79
0.591917
46b1ee6ba3c748a62174ce31a4ffc4613f29cef5
13,087
cpp
C++
fileAudioEncoder.cpp
rzumer/BeatFinder
ef1c4e9f48c8524d0980d650d58e66ec75afa13a
[ "MIT" ]
5
2019-02-18T01:17:27.000Z
2020-02-17T01:50:11.000Z
fileAudioEncoder.cpp
rzumer/BeatFinder
ef1c4e9f48c8524d0980d650d58e66ec75afa13a
[ "MIT" ]
null
null
null
fileAudioEncoder.cpp
rzumer/BeatFinder
ef1c4e9f48c8524d0980d650d58e66ec75afa13a
[ "MIT" ]
1
2019-02-22T01:32:20.000Z
2019-02-22T01:32:20.000Z
#pragma comment (lib, "avfilter.lib") #pragma comment (lib, "avformat.lib") #pragma comment (lib, "avcodec.lib") #pragma comment (lib, "avutil.lib") #include "fileAudioEncoder.h"; using namespace std; void fileAudioEncoder::cleanUp() { if (this->codecContext) { avcodec_close(this->codecContext); avcodec_free_context(&this->codecContext); } // Causes access exceptions /*if (this->ioContext) { avio_close(this->ioContext); avio_context_free(&this->ioContext); } if (this->formatContext) { avformat_free_context(this->formatContext); }*/ if (this->filterGraph) { avfilter_free(this->filterSource); avfilter_free(this->filterSink); avfilter_graph_free(&filterGraph); } if (this->frame) { av_frame_free(&this->frame); } if (this->packet) { av_packet_free(&this->packet); } } int fileAudioEncoder::encodeFrame(AVFrame *frame) { this->frame = frame; int gotPacket = -1; int gotFrame = -1; if (!(this->packet = av_packet_alloc())) { cout << "Error allocating packet memory." << endl; return -1; } if (this->frame) { this->frame->format = this->codecParameters->format; this->frame->channels = this->codecParameters->channels; this->frame->channel_layout = this->codecParameters->channel_layout; this->frame->sample_rate = this->codecParameters->sample_rate; if (this->filterGraph) { if (av_buffersrc_add_frame(this->filterSource, this->frame) < 0) { // Need more frames. return 0; } gotFrame = av_buffersink_get_frame(this->filterSink, this->frame); if (gotFrame == AVERROR(EAGAIN)) { // Need more frames. return 0; } if (!avcodec_is_open(this->codecContext)) { this->codecContext->sample_fmt = (AVSampleFormat)this->frame->format; this->codecContext->channel_layout = this->frame->channel_layout; this->codecContext->channels = this->frame->channels; this->codecContext->sample_rate = this->frame->sample_rate; if (avcodec_open2(this->codecContext, this->codec, NULL) < 0) { cout << "Error opening the codec." << endl; this->cleanUp(); return -1; } #ifdef _DEBUG char channelLayout[64]; av_get_channel_layout_string(channelLayout, sizeof(channelLayout), 0, this->codecContext->channel_layout); cout << "Negotiated channel layout: " << channelLayout << endl; cout << "Negotiated sample format: " << av_get_sample_fmt_name(this->codecContext->sample_fmt) << endl; cout << "Negotiated sample rate: " << this->codecContext->sample_rate << endl; #endif } } gotFrame = avcodec_send_frame(this->codecContext, this->frame); if (gotFrame != 0) { cout << "Error sending frame to encoder." << endl; return -1; } } gotPacket = avcodec_receive_packet(this->codecContext, this->packet); if (gotPacket == 0) { return 0; } else if (gotPacket == AVERROR(EAGAIN)) { // Need more frames. return 0; } else if (gotPacket = AVERROR_EOF) { this->finished = 1; return 1; } else { #if _DEBUG char errbuf[AV_ERROR_MAX_STRING_SIZE]; char *err = av_make_error_string(errbuf, AV_ERROR_MAX_STRING_SIZE, gotPacket); cout << err << endl; #endif cout << "Error receiving decoded frame." << endl; return -1; } } int fileAudioEncoder::init(const char *filePath, const vector<AVCodecID> *codecIDs, AVCodecParameters *parameters) { this->codecID = AV_CODEC_ID_NONE; this->finished = 0; this->codecParameters = parameters; this->frame = NULL; this->packet = av_packet_alloc(); this->filterGraph = NULL; this->filterSource = NULL; this->filterSink = NULL; // Initialize output format context if an output file name was provided. if (filePath) { if (avio_open2(&this->ioContext, filePath, AVIO_FLAG_WRITE, NULL, NULL) < 0) { cout << "Error opening file for writing." << endl; this->cleanUp(); return -1; } const size_t fileExtensionLength = 16; const size_t fileNameLength = 1024 - fileExtensionLength; char *fileName = new char[fileNameLength + fileExtensionLength]; char *fileExtension = new char[fileExtensionLength]; _splitpath_s(filePath, NULL, 0, NULL, 0, fileName, fileNameLength, fileExtension, fileExtensionLength); sprintf(fileName + strlen(fileName), "%s", fileExtension); if (avformat_alloc_output_context2(&this->formatContext, NULL, NULL, fileName) < 0) { cout << "Error allocating output format context." << endl; this->cleanUp(); return -1; } this->formatContext->pb = ioContext; for (int i = 0; i < codecIDs->size(); i++) { if (avformat_query_codec(this->formatContext->oformat, codecIDs->at(i), FF_COMPLIANCE_NORMAL)) { #ifdef _DEBUG cout << "Negotiated codec: " << avcodec_get_name(codecIDs->at(i)) << endl; #endif this->codecID = codecIDs->at(i); break; } } if (this->codecID == AV_CODEC_ID_NONE) { cout << "Unsupported codecs offered for the given output format." << endl; this->cleanUp(); return -1; } this->formatContext->oformat->audio_codec = this->codecID; this->codec = avcodec_find_encoder(this->codecID); this->codecContext = avcodec_alloc_context3(this->codec); if (this->formatContext->oformat->flags & AVFMT_GLOBALHEADER) { this->formatContext->flags |= CODEC_FLAG_GLOBAL_HEADER; } if (!(this->stream = avformat_new_stream(this->formatContext, this->codec))) { cout << "Error allocating output stream." << endl; this->cleanUp(); return -1; } this->codecContext = avcodec_alloc_context3(this->codec); this->codecContext->bit_rate = parameters->bit_rate; this->codecContext->channels = parameters->channels; this->codecContext->channel_layout = parameters->channel_layout; this->codecContext->sample_fmt = (AVSampleFormat)parameters->format; this->codecContext->sample_rate = parameters->sample_rate; avcodec_parameters_from_context(this->stream->codecpar, this->codecContext); if (avformat_init_output(this->formatContext, NULL) < 0) { cout << "Error initializing output format context." << endl; this->cleanUp(); return -1; } } else { this->codecID = codecIDs->at(0); this->codec = avcodec_find_encoder(this->codecID); this->codecContext = avcodec_alloc_context3(this->codec); this->codecContext->bit_rate = parameters->bit_rate; this->codecContext->channels = parameters->channels; this->codecContext->channel_layout = parameters->channel_layout; this->codecContext->sample_fmt = (AVSampleFormat)parameters->format; this->codecContext->sample_rate = parameters->sample_rate; } if (!codec) { cout << "Error finding encoder." << endl; this->cleanUp(); return -1; } const enum AVSampleFormat *format = this->codec->sample_fmts; AVSampleFormat requestedFormat = (AVSampleFormat)parameters->format; while (*format != AV_SAMPLE_FMT_NONE) { if (*format == requestedFormat) { this->codecContext->sample_fmt = requestedFormat; break; } format++; } // If no viable codec was found for encoding, set up a filtergraph for format conversion. if (*format == AV_SAMPLE_FMT_NONE) { avfilter_register_all(); AVFilterGraph *filterGraph = avfilter_graph_alloc(); if (!filterGraph) { cout << "Error allocating memory for the filter graph." << endl; this->cleanUp(); return -1; } AVFilter *bufferFilter = avfilter_get_by_name("abuffer"); AVFilter *formatFilter = avfilter_get_by_name("aformat"); AVFilter *bufferSinkFilter = avfilter_get_by_name("abuffersink"); if (!bufferFilter || !formatFilter || !bufferSinkFilter) { cout << "Error retrieving filter." << endl; this->cleanUp(); return -1; } AVFilterContext *bufferContext = avfilter_graph_alloc_filter(filterGraph, bufferFilter, "abuffer"); AVFilterContext *formatContext = avfilter_graph_alloc_filter(filterGraph, formatFilter, "aformat"); AVFilterContext *bufferSinkContext = avfilter_graph_alloc_filter(filterGraph, bufferSinkFilter, "abuffersink"); if (!bufferContext || !formatContext || !bufferSinkContext) { cout << "Error allocating format filter context." << endl; this->cleanUp(); return -1; } char channelLayout[64]; av_get_channel_layout_string(channelLayout, sizeof(channelLayout), 0, this->codecParameters->channel_layout); av_opt_set(bufferContext, "channel_layout", channelLayout, AV_OPT_SEARCH_CHILDREN); av_opt_set_sample_fmt(bufferContext, "sample_fmt", (AVSampleFormat)this->codecParameters->format, AV_OPT_SEARCH_CHILDREN); av_opt_set_q(bufferContext, "time_base", AVRational{ 1, this->codecParameters->sample_rate }, AV_OPT_SEARCH_CHILDREN); av_opt_set_int(bufferContext, "sample_rate", this->codecParameters->sample_rate, AV_OPT_SEARCH_CHILDREN); if (avfilter_init_str(bufferContext, NULL)) { cout << "Error initializing the buffer filter." << endl; this->cleanUp(); return -1; } char channelLayouts[3072] = {}; const uint64_t *layout = this->codec->channel_layouts; if (layout) { while (*layout) { av_get_channel_layout_string(channelLayout, sizeof(channelLayout), 0, *layout); sprintf(channelLayouts + strlen(channelLayouts), "%s|", channelLayout); layout++; } // Erase the last separator. sprintf(channelLayouts + strlen(channelLayouts) - 1, "\0"); } else { av_get_channel_layout_string(channelLayout, sizeof(channelLayout), 0, this->codecParameters->channel_layout); sprintf(channelLayouts, "%s", channelLayout); } #ifdef _DEBUG cout << "Negotiated channel layouts: " << channelLayouts << endl; #endif char sampleFormats[3072] = {}; const enum AVSampleFormat *sampleFormat = this->codec->sample_fmts; if (sampleFormat) { while (*sampleFormat != -1) { sprintf(sampleFormats + strlen(sampleFormats), "%s|", av_get_sample_fmt_name(*sampleFormat)); sampleFormat++; } // Erase the last separator. sprintf(sampleFormats + strlen(sampleFormats) - 1, "\0"); } else { sprintf(sampleFormats, "%s", av_get_sample_fmt_name((AVSampleFormat)this->codecParameters->format)); } #ifdef _DEBUG cout << "Negotiated sample formats: " << sampleFormats << endl; #endif char sampleRates[3072] = {}; const int *sampleRate = this->codec->supported_samplerates; if (sampleRate) { while (*sampleRate) { sprintf(sampleRates + strlen(sampleRates), "%i|", *sampleRate); sampleRate++; } // Erase the last separator. sprintf(sampleRates + strlen(sampleRates) - 1, "\0"); } else { sprintf(sampleRates, "%i", this->codecParameters->sample_rate); } #ifdef _DEBUG cout << "Negotiated sample rates: " << sampleRates << endl; #endif av_opt_set(formatContext, "channel_layouts", channelLayouts, AV_OPT_SEARCH_CHILDREN); av_opt_set(formatContext, "sample_fmts", sampleFormats, AV_OPT_SEARCH_CHILDREN); av_opt_set_q(formatContext, "time_base", AVRational{ 1, this->codecParameters->sample_rate }, AV_OPT_SEARCH_CHILDREN); av_opt_set(formatContext, "sample_rates", sampleRates, AV_OPT_SEARCH_CHILDREN); if (avfilter_init_str(formatContext, NULL)) { cout << "Error initializing the format filter." << endl; this->cleanUp(); return -1; } if (avfilter_init_str(bufferSinkContext, NULL)) { cout << "Error initializing the buffer sink filter." << endl; this->cleanUp(); return -1; } if (avfilter_link(bufferContext, 0, formatContext, 0) < 0 || avfilter_link(formatContext, 0, bufferSinkContext, 0) < 0) { cout << "Error connecting filters." << endl; this->cleanUp(); return -1; } if (avfilter_graph_config(filterGraph, NULL) < 0) { cout << "Error configuring filter graph." << endl; this->cleanUp(); return -1; } this->filterGraph = filterGraph; this->filterSource = bufferContext; this->filterSink = bufferSinkContext; } else { if (avcodec_open2(this->codecContext, this->codec, NULL) < 0) { cout << "Error opening the codec." << endl; this->cleanUp(); return -1; } } return 0; } int fileAudioEncoder::writeHeader() { if (!avcodec_is_open(this->codecContext)) { cout << "Codec context is closed." << endl; return -1; } if (avformat_write_header(this->formatContext, NULL) < 0) { cout << "Error writing output file header." << endl; return -1; } return 0; } int fileAudioEncoder::writeEncodedPacket(AVPacket *toWrite) { if (!avcodec_is_open(this->codecContext)) { cout << "Codec context is closed." << endl; return -1; } int result = av_interleaved_write_frame(this->formatContext, toWrite); if (result < 0) { cout << "Error writing encoded packet." << endl; return -1; } return result; } int fileAudioEncoder::writeTrailer() { if (!avcodec_is_open(this->codecContext)) { cout << "Codec context is closed." << endl; return -1; } if (av_write_trailer(this->formatContext) < 0) { cout << "Error writing output file trailer." << endl; return -1; } return 0; } AVPacket *fileAudioEncoder::getEncodedPacket(AVFrame *toEncode) { if (!finished) { int state = this->encodeFrame(toEncode); if (state != 0) { this->cleanUp(); } if (state >= 0) { return this->packet; } } return NULL; }
25.41165
124
0.693818
46b40baa8e59380f4e8a72608b3c243189d2daef
2,446
cpp
C++
rohm-sensor-hal/source/I2CCommonArduinoHardwareLib.cpp
MikkoZ-Rohm/rohm-bm1383-hello-arduino
573a45bb8d6c640234dc6f7dd65f3af73219199e
[ "Apache-2.0" ]
null
null
null
rohm-sensor-hal/source/I2CCommonArduinoHardwareLib.cpp
MikkoZ-Rohm/rohm-bm1383-hello-arduino
573a45bb8d6c640234dc6f7dd65f3af73219199e
[ "Apache-2.0" ]
null
null
null
rohm-sensor-hal/source/I2CCommonArduinoHardwareLib.cpp
MikkoZ-Rohm/rohm-bm1383-hello-arduino
573a45bb8d6c640234dc6f7dd65f3af73219199e
[ "Apache-2.0" ]
null
null
null
/* Copyright 2016 Rohm Semiconductor 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 "../rohm-sensor-hal/rohm_hal.h" //types, USE_ARDUINO_HARDWARE_I2C, rohmhal_print* #ifdef USE_ARDUINO_HARDWARE_I2C #include "../rohm-sensor-hal/I2CCommon.h" //prototypes #include <Wire.h> //i2c Wire //Note that I2CCommonBegin() must be called in .ino setup() -function before using these functions. bool I2CCommonBegin(){ Wire.begin(); return( true ); //always succeeds } /* i2c common functions */ uint8_t read_register(uint8_t sad, uint8_t reg, uint8_t* buf, uint8_t buf_len) { int incoming; uint8_t received_bytes; Wire.beginTransmission(sad); Wire.write(reg); Wire.endTransmission(); Wire.requestFrom(sad, (uint8_t) buf_len, (uint8_t) true); received_bytes = 0; while( Wire.available() && ( buf_len > received_bytes ) ){ incoming = Wire.read(); buf[received_bytes] = (uint8_t) ( incoming & 0xff ); received_bytes++; } return( received_bytes ); } void write_registers(uint8_t sad, uint8_t reg, uint8_t* data, uint8_t data_len) { Wire.beginTransmission(sad); Wire.write(reg); Wire.write(data, data_len); Wire.endTransmission(); } void write_register(uint8_t sad, uint8_t reg, uint8_t data) { Wire.beginTransmission(sad); Wire.write(reg); Wire.write(data); Wire.endTransmission(); } bool change_bits(uint8_t sad, uint8_t reg, uint8_t mask, uint8_t bits){ uint8_t value, read_bytes; read_bytes = read_register(sad, reg, &value, 1); if( read_bytes != 0 ){ value = value & ~mask; value = value | (bits & mask); write_register(sad, reg, value); return true; } else{ //rohmhal_printf("Read before change_bits() failed."); return false; } } #endif /* USE_ARDUINO_HARDWARE_I2C */
32.613333
100
0.663123
46b43bc1bab7a5347fc5971471ee38be4705587b
1,072
cc
C++
Fireworks/Core/src/FWParameterizable.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
3
2018-08-24T19:10:26.000Z
2019-02-19T11:45:32.000Z
Fireworks/Core/src/FWParameterizable.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
3
2018-08-23T13:40:24.000Z
2019-12-05T21:16:03.000Z
Fireworks/Core/src/FWParameterizable.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
5
2018-08-21T16:37:52.000Z
2020-01-09T13:33:17.000Z
// -*- C++ -*- // // Package: Core // Class : FWParameterizable // // Implementation: // <Notes on implementation> // // Original Author: Chris Jones // Created: Sat Feb 23 13:36:27 EST 2008 // // system include files // user include files #include "Fireworks/Core/interface/FWParameterizable.h" // // constants, enums and typedefs // // // static data member definitions // // // constructors and destructor // FWParameterizable::FWParameterizable() { } // FWParameterizable::FWParameterizable(const FWParameterizable& rhs) // { // // do actual copying here; // } FWParameterizable::~FWParameterizable() { } // // assignment operators // // const FWParameterizable& FWParameterizable::operator=(const FWParameterizable& rhs) // { // //An exception safe implementation is // FWParameterizable temp(rhs); // swap(rhs); // // return *this; // } // // member functions // void FWParameterizable::add(FWParameterBase* iParam) { m_parameters.push_back(iParam); } // // const member functions // // // static member functions //
15.098592
86
0.66791
46b5d3784f9e433cd01c0fbe1309174e2bf29a04
2,093
cc
C++
src/ui/scenic/lib/gfx/tests/has_renderable_content_visitor_unittest.cc
casey/fuchsia
2b965e9a1e8f2ea346db540f3611a5be16bb4d6b
[ "BSD-3-Clause" ]
14
2020-10-25T05:48:36.000Z
2021-09-20T02:46:20.000Z
src/ui/scenic/lib/gfx/tests/has_renderable_content_visitor_unittest.cc
DamieFC/fuchsia
f78a4a1326f4a4bb5834500918756173c01bab4f
[ "BSD-2-Clause" ]
1
2022-01-14T23:38:40.000Z
2022-01-14T23:38:40.000Z
src/ui/scenic/lib/gfx/tests/has_renderable_content_visitor_unittest.cc
DamieFC/fuchsia
f78a4a1326f4a4bb5834500918756173c01bab4f
[ "BSD-2-Clause" ]
4
2020-12-28T17:04:45.000Z
2022-03-12T03:20:44.000Z
// Copyright 2020 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "src/ui/scenic/lib/gfx/resources/has_renderable_content_visitor.h" #include <lib/ui/scenic/cpp/commands.h> #include <gtest/gtest.h> #include "src/ui/scenic/lib/gfx/resources/camera.h" #include "src/ui/scenic/lib/gfx/resources/compositor/layer.h" #include "src/ui/scenic/lib/gfx/resources/material.h" #include "src/ui/scenic/lib/gfx/resources/nodes/entity_node.h" #include "src/ui/scenic/lib/gfx/resources/nodes/scene.h" #include "src/ui/scenic/lib/gfx/resources/nodes/shape_node.h" #include "src/ui/scenic/lib/gfx/resources/renderers/renderer.h" #include "src/ui/scenic/lib/gfx/tests/session_test.h" namespace scenic_impl::gfx::test { using HasRenderableContentUnittest = SessionTest; TEST_F(HasRenderableContentUnittest, ReturnsTrueForShapeNodeWithMaterial) { HasRenderableContentVisitor visitor; ResourceId next_id = 1; auto layer = fxl::MakeRefCounted<Layer>(session(), session()->id(), next_id++); auto renderer = fxl::MakeRefCounted<Renderer>(session(), session()->id(), next_id++); layer->SetRenderer(renderer); auto scene = fxl::MakeRefCounted<Scene>(session(), session()->id(), next_id++, fxl::WeakPtr<ViewTreeUpdater>(), event_reporter()->GetWeakPtr()); auto camera = fxl::MakeRefCounted<Camera>(session(), session()->id(), next_id++, scene); renderer->SetCamera(camera); auto node = fxl::MakeRefCounted<EntityNode>(session(), session()->id(), next_id++); scene->AddChild(node, error_reporter()); auto shape_node = fxl::MakeRefCounted<ShapeNode>(session(), session()->id(), next_id++); node->AddChild(shape_node, error_reporter()); visitor.Visit(layer.get()); EXPECT_FALSE(visitor.HasRenderableContent()); auto material = fxl::MakeRefCounted<Material>(session(), next_id++); shape_node->SetMaterial(material); visitor.Visit(layer.get()); EXPECT_TRUE(visitor.HasRenderableContent()); } } // namespace scenic_impl::gfx::test
40.25
98
0.731964
46bf4a0966c2e91a134128a667d39e6c9919746f
8,978
cpp
C++
src/terark/io/MemStream.cpp
rockeet/terark-zip
3235373d04b7cf5d584259111b3a057c45cc1708
[ "BSD-3-Clause" ]
44
2020-12-21T05:14:38.000Z
2022-03-15T11:27:32.000Z
src/terark/io/MemStream.cpp
rockeet/terark-zip
3235373d04b7cf5d584259111b3a057c45cc1708
[ "BSD-3-Clause" ]
2
2020-12-28T10:42:03.000Z
2021-05-21T07:22:47.000Z
src/terark/io/MemStream.cpp
rockeet/terark-zip
3235373d04b7cf5d584259111b3a057c45cc1708
[ "BSD-3-Clause" ]
21
2020-12-22T09:40:16.000Z
2021-12-07T18:16:00.000Z
/* vim: set tabstop=4 : */ #include "MemStream.hpp" #include <stdlib.h> #include <algorithm> #include <stdexcept> #include <typeinfo> #include <errno.h> #if defined(_MSC_VER) # include <intrin.h> #pragma intrinsic(_BitScanReverse) //#pragma intrinsic(_BitScanReverse64) #endif #include <boost/predef/other/endian.h> #include <terark/num_to_str.hpp> #include <stdarg.h> #include "var_int.hpp" namespace terark { //void MemIO_Base::skip(ptrdiff_t diff) void throw_EndOfFile(const char* func, size_t want, size_t available) { string_appender<> oss; oss << "in " << func << ", want=" << want << ", available=" << available // << ", tell=" << tell() << ", size=" << size() ; throw EndOfFileException(oss.str().c_str()); } void throw_OutOfSpace(const char* func, size_t want, size_t available) { string_appender<> oss; oss << "in " << func << ", want=" << want << ", available=" << available // << ", tell=" << tell() << ", size=" << size() ; throw OutOfSpaceException(oss.str().c_str()); } void MemIO::throw_EndOfFile(const char* func, size_t want) { terark::throw_EndOfFile(func, want, remain()); } void MemIO::throw_OutOfSpace(const char* func, size_t want) { terark::throw_OutOfSpace(func, want, remain()); } ////////////////////////////////////////////////////////////////////////// void SeekableMemIO::seek(ptrdiff_t newPos) { assert(newPos >= 0); if (newPos < 0 || newPos > m_end - m_beg) { string_appender<> oss; size_t curr_size = m_end - m_beg; oss << "in " << BOOST_CURRENT_FUNCTION << "[newPos=" << newPos << ", size=" << curr_size << "]"; // errno = EINVAL; throw std::invalid_argument(oss.str()); } m_pos = m_beg + newPos; } void SeekableMemIO::seek(ptrdiff_t offset, int origin) { size_t pos; switch (origin) { default: { string_appender<> oss; oss << "in " << BOOST_CURRENT_FUNCTION << "[offset=" << offset << ", origin=" << origin << "(invalid)]"; // errno = EINVAL; throw std::invalid_argument(oss.str().c_str()); } case 0: pos = (size_t)(0 + offset); break; case 1: pos = (size_t)(tell() + offset); break; case 2: pos = (size_t)(size() + offset); break; } seek(pos); } // rarely used methods.... // std::pair<byte*, byte*> SeekableMemIO::range(size_t ibeg, size_t iend) const { assert(ibeg <= iend); assert(ibeg <= size()); assert(iend <= size()); if (ibeg <= iend && ibeg <= size() && iend <= size()) { return std::pair<byte*, byte*>(m_beg + ibeg, m_beg + iend); } string_appender<> oss; oss << BOOST_CURRENT_FUNCTION << ": size=" << size() << ", tell=" << tell() << ", ibeg=" << ibeg << ", iend=" << iend ; throw std::invalid_argument(oss.str()); } ////////////////////////////////////////////////////////////////////////// AutoGrownMemIO::AutoGrownMemIO(size_t size) { if (size) { m_beg = (byte*)malloc(size); if (NULL == m_beg) { #ifdef _MSC_VER_FUCK char szMsg[128]; sprintf(szMsg , "AutoGrownMemIO::AutoGrownMemIO(size=%lu)" , (unsigned long)size ); throw std::bad_alloc(szMsg); #else throw std::bad_alloc(); #endif } m_end = m_beg + size; m_pos = m_beg; } else m_pos = m_end = m_beg = NULL; } AutoGrownMemIO::~AutoGrownMemIO() { if (m_beg) free(m_beg); } void AutoGrownMemIO::clone(const AutoGrownMemIO& src) { AutoGrownMemIO t(src.size()); memcpy(t.begin(), src.begin(), src.size()); this->swap(t); } /** @brief 改变 buffer 尺寸 不改变 buffer 中的已存内容,不改变 pos @note must m_pos <= newsize */ void AutoGrownMemIO::resize(size_t newsize) { assert(tell() <= newsize); if (newsize < tell()) { THROW_STD(length_error, "newsize=%zd is less than tell()=%zd", newsize, tell()); } #ifdef _MSC_VER size_t oldsize = size(); #endif byte* newbeg = (byte*)realloc(m_beg, newsize); if (newbeg) { m_pos = newbeg + (m_pos - m_beg); m_end = newbeg + newsize; m_beg = newbeg; } else { #ifdef _MSC_VER_FUCK string_appender<> oss; oss << "realloc failed in \"void AutoGrownMemIO::resize(size[new=" << newsize << ", old=" << oldsize << "])\", the AutoGrownMemIO object is not mutated!"; throw std::bad_alloc(oss.str().c_str()); #else throw std::bad_alloc(); #endif } } void AutoGrownMemIO::grow(size_t nGrow) { size_t oldsize = m_end - m_beg; size_t newsize = oldsize + nGrow; size_t newcap = std::max<size_t>(32, oldsize); while (newcap < newsize) newcap *= 2; resize(newcap); } /** @brief 释放原先的空间并重新分配 相当于按新尺寸重新构造一个新 AutoGrownMemIO 不需要把旧内容拷贝到新地址 */ void AutoGrownMemIO::init(size_t newsize) { #ifdef _MSC_VER size_t oldsize = (size_t)(m_beg - m_beg); #endif if (m_beg) ::free(m_beg); if (newsize) { m_beg = (byte*)::malloc(newsize); if (NULL == m_beg) { m_pos = m_end = NULL; #ifdef _MSC_VER_FUCK char szMsg[128]; sprintf(szMsg , "malloc failed in AutoGrownMemIO::init(newsize=%lu), oldsize=%lu" , (unsigned long)newsize , (unsigned long)oldsize ); throw std::bad_alloc(szMsg); #else throw std::bad_alloc(); #endif } m_pos = m_beg; m_end = m_beg + newsize; } else m_pos = m_end = m_beg = NULL; } void AutoGrownMemIO::growAndWrite(const void* data, size_t length) { using namespace std; size_t nSize = size(); size_t nGrow = max(length, nSize); resize(max(nSize + nGrow, (size_t)64u)); memcpy(m_pos, data, length); m_pos += length; } void AutoGrownMemIO::growAndWriteByte(byte b) { using namespace std; resize(max(2u * size(), (size_t)64u)); *m_pos++ = b; } void AutoGrownMemIO::clear() { if (this->m_beg) { ::free(this->m_beg); this->m_beg = NULL; this->m_end = NULL; this->m_pos = NULL; } else { assert(NULL == this->m_end); assert(NULL == this->m_pos); } } /** * shrink allocated memory to fit this->tell() */ void AutoGrownMemIO::shrink_to_fit() { if (NULL == m_beg) { assert(NULL == m_pos); assert(NULL == m_end); } else { assert(m_beg <= m_pos); assert(m_pos <= m_end); size_t realsize = m_pos - m_beg; if (0 == realsize) { ::free(m_beg); m_beg = m_end = m_pos = NULL; } else { byte* newbeg = (byte*)realloc(m_beg, realsize); assert(NULL != newbeg); if (NULL == newbeg) { // realloc should always success on shrink abort(); } m_end = m_pos = newbeg + realsize; m_beg = newbeg; } } } size_t AutoGrownMemIO::printf(const char* format, ...) { va_list ap; size_t n; va_start(ap, format); n = this->vprintf(format, ap); va_end(ap); return n; } size_t AutoGrownMemIO::vprintf(const char* format, va_list ap) { if (m_end - m_pos < 64) { this->resize(std::max<size_t>(64, (m_end-m_beg)*2)); } while (1) { ptrdiff_t n, size = m_end - m_pos; #if defined(va_copy) va_list ap_copy; va_copy(ap_copy, ap); n = ::vsnprintf((char*)m_pos, size, format, ap_copy); va_end(ap_copy); #else n = ::vsnprintf((char*)m_pos, size, format, ap); #endif /* If that worked, return the written bytes. */ if (n > -1 && n < size) { m_pos += n; return n; } /* Else try again with more space. */ if (n > -1) /* glibc 2.1 */ size = n+1; /* precisely what is needed */ else /* glibc 2.0 */ size *= 2; /* twice the old size */ this->resize((m_pos - m_beg + size) * 2); } } /////////////////////////////////////////////////////// // #if defined(__GLIBC__) || defined(__CYGWIN__) ssize_t MemIO_FILE_read(void *cookie, char *buf, size_t size) { MemIO* input = (MemIO*)cookie; return input->read(buf, size); } ssize_t AutoGrownMemIO_FILE_write(void *cookie, const char *buf, size_t size) { AutoGrownMemIO* output = (AutoGrownMemIO*)cookie; return output->write(buf, size); } #if defined(__CYGWIN__) int AutoGrownMemIO_FILE_seek(void* cookie, _off64_t* offset, int whence) #else int AutoGrownMemIO_FILE_seek(void* cookie, off64_t* offset, int whence) #endif { AutoGrownMemIO* output = (AutoGrownMemIO*)cookie; try { output->seek(*offset, whence); *offset = output->tell(); return 0; } catch (const std::exception& e) { errno = EINVAL; return -1; } } /** * @note must call fclose after use of returned FILE */ FILE* MemIO::forInputFILE() { cookie_io_functions_t func = { MemIO_FILE_read, NULL, NULL, NULL }; void* cookie = this; assert(cookie); FILE* fp = fopencookie(cookie,"r", func); if (fp == NULL) { perror("fopencookie@MemIO::getInputFILE"); return NULL; } return fp; } /** * @note must call fclose after use of returned FILE */ FILE* AutoGrownMemIO::forFILE(const char* mode) { cookie_io_functions_t func = { MemIO_FILE_read, AutoGrownMemIO_FILE_write, AutoGrownMemIO_FILE_seek, NULL }; void* cookie = this; assert(cookie); FILE* fp = fopencookie(cookie, mode, func); if (fp == NULL) { perror("fopencookie@AutoGrownMemIO::forOutputFILE"); return NULL; } return fp; } #endif #define STREAM_READER MinMemIO #define STREAM_WRITER MinMemIO #include "var_int_io.hpp" #define STREAM_READER MemIO #define STREAM_WRITER MemIO #include "var_int_io.hpp" #define STREAM_WRITER AutoGrownMemIO #include "var_int_io.hpp" } // namespace terark
21.124706
102
0.631989
46c1b7bcb666e58c1852e1291d3dcfb7d7afb797
5,706
cpp
C++
BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryTestExpression.cpp
danielknorr/MITK
b1b9780b2a6671d8118313c5ef71e9aa128362be
[ "BSD-3-Clause" ]
1
2017-03-05T05:29:32.000Z
2017-03-05T05:29:32.000Z
BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryTestExpression.cpp
danielknorr/MITK
b1b9780b2a6671d8118313c5ef71e9aa128362be
[ "BSD-3-Clause" ]
null
null
null
BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryTestExpression.cpp
danielknorr/MITK
b1b9780b2a6671d8118313c5ef71e9aa128362be
[ "BSD-3-Clause" ]
2
2020-10-27T06:51:00.000Z
2020-10-27T06:51:01.000Z
/*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berryTestExpression.h" #include "berryExpressions.h" #include "berryPlatform.h" #include <berryObjectString.h> #include <Poco/Hash.h> namespace berry { const char TestExpression::PROP_SEP = '.'; const std::string TestExpression::ATT_PROPERTY = "property"; const std::string TestExpression::ATT_ARGS = "args"; const std::string TestExpression::ATT_FORCE_PLUGIN_ACTIVATION = "forcePluginActivation"; TypeExtensionManager TestExpression::fgTypeExtensionManager("propertyTesters"); const std::size_t TestExpression::HASH_INITIAL= Poco::hash("berry::TextExpression"); TestExpression::TestExpression(IConfigurationElement::Pointer element) { std::string property; element->GetAttribute(ATT_PROPERTY, property); std::size_t pos = property.find_last_of(PROP_SEP); if (pos == std::string::npos) { throw CoreException("No namespace provided"); } fNamespace = property.substr(0, pos); fProperty = property.substr(pos + 1); Expressions::GetArguments(fArgs, element, ATT_ARGS); std::string arg = ""; bool result = element->GetAttribute(ATT_VALUE, arg); fExpectedValue = Expressions::ConvertArgument(arg, result); fForcePluginActivation = Expressions::GetOptionalBooleanAttribute(element, ATT_FORCE_PLUGIN_ACTIVATION); } TestExpression::TestExpression(Poco::XML::Element* element) { std::string property= element->getAttribute(ATT_PROPERTY); std::size_t pos = property.find_last_of(PROP_SEP); if (pos == std::string::npos) { throw CoreException("No namespace provided"); } fNamespace = property.substr(0, pos); fProperty = property.substr(pos + 1); Expressions::GetArguments(fArgs, element, ATT_ARGS); std::string value = element->getAttribute(ATT_VALUE); fExpectedValue = Expressions::ConvertArgument(value, value.size() > 0); fForcePluginActivation= Expressions::GetOptionalBooleanAttribute(element, ATT_FORCE_PLUGIN_ACTIVATION); } TestExpression::TestExpression(const std::string& namespaze, const std::string& property, std::vector<Object::Pointer>& args, Object::Pointer expectedValue) { TestExpression(namespaze, property, args, expectedValue, false); } TestExpression::TestExpression(const std::string& namespaze, const std::string& property, std::vector<Object::Pointer>& args, Object::Pointer expectedValue, bool forcePluginActivation) : fNamespace(namespaze), fProperty(property), fArgs(args), fExpectedValue(expectedValue), fForcePluginActivation(forcePluginActivation) { } EvaluationResult TestExpression::Evaluate(IEvaluationContext* context) { Object::Pointer element = context->GetDefaultVariable(); if (typeid(Platform) == typeid(element.GetPointer())) { std::string str = Platform::GetProperty(fProperty); if (str.size() == 0) { return EvaluationResult::FALSE_EVAL; } ObjectString::Pointer var = fArgs[0].Cast<ObjectString>(); if (var) return EvaluationResult::ValueOf(*var == str); return EvaluationResult::FALSE_EVAL; } Property::Pointer property= fgTypeExtensionManager.GetProperty(element, fNamespace, fProperty, context->GetAllowPluginActivation() && fForcePluginActivation); if (!property->IsInstantiated()) return EvaluationResult::NOT_LOADED; return EvaluationResult::ValueOf(property->Test(element, fArgs, fExpectedValue)); } void TestExpression::CollectExpressionInfo(ExpressionInfo* info) { info->MarkDefaultVariableAccessed(); info->AddAccessedPropertyName(fNamespace + PROP_SEP + fProperty); } bool TestExpression::operator==(Expression& object) { try { TestExpression& that = dynamic_cast<TestExpression&>(object); return this->fNamespace == that.fNamespace && this->fProperty == that.fProperty && this->fForcePluginActivation == that.fForcePluginActivation && this->Equals(this->fArgs, that.fArgs) && this->fExpectedValue == that.fExpectedValue; } catch (std::bad_cast) { return false; } } std::size_t TestExpression::ComputeHashCode() { return HASH_INITIAL * HASH_FACTOR + this->HashCode(fArgs) * HASH_FACTOR + fExpectedValue->HashCode() * HASH_FACTOR + Poco::hash(fNamespace) * HASH_FACTOR + Poco::hash(fProperty) * HASH_FACTOR + (fForcePluginActivation ? 1 : 0); } std::string TestExpression::ToString() { std::string args(""); for (unsigned int i= 0; i < fArgs.size(); i++) { Object::Pointer arg= fArgs[i]; ObjectString::Pointer strarg = arg.Cast<ObjectString>(); if (strarg) { args.append(1,'\''); args.append(*strarg); args.append(1,'\''); } else { args.append(arg->ToString()); } if (i < fArgs.size() - 1) args.append(", "); //$NON-NLS-1$ } return "<test property=\"" + fProperty + (fArgs.size() != 0 ? "\" args=\"" + args + "\"" : "\"") + (!fExpectedValue.IsNull() ? "\" value=\"" + fExpectedValue->ToString() + "\"" : "\"") + " plug-in activation: " + (fForcePluginActivation ? "eager" : "lazy") + "/>"; //$NON-NLS-1$ } //---- testing --------------------------------------------------- bool TestExpression::TestGetForcePluginActivation() { return fForcePluginActivation; } TypeExtensionManager& TestExpression::TestGetTypeExtensionManager() { return fgTypeExtensionManager; } }
30.190476
184
0.695233
46c7a76985f5d3f9668922bd594d87318ead7fe1
1,040
cpp
C++
AtCoder/abc161/E.cpp
noobie7/Codes
4d8265f4b7042bd7e8c0e0402d417c7e160ae6d4
[ "MIT" ]
2
2021-09-14T15:57:24.000Z
2022-03-18T14:11:04.000Z
AtCoder/abc161/E.cpp
noobie7/Codes
4d8265f4b7042bd7e8c0e0402d417c7e160ae6d4
[ "MIT" ]
null
null
null
AtCoder/abc161/E.cpp
noobie7/Codes
4d8265f4b7042bd7e8c0e0402d417c7e160ae6d4
[ "MIT" ]
null
null
null
/* "Do I really belong in this game I ponder, I just wanna play my part." - Guts over fear, Eminem */ #pragma GCC optimize ("O3") #pragma GCC target ("sse4") #include<bits/stdc++.h> using namespace std; typedef long long int ll; #define ff first #define Shazam ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); #define ss second #define all(c) c.begin(),c.end() #define endl "\n" #define test() int t; cin>>t; while(t--) #define fl(i,a,b) for(int i = a ; i <b ;i++) #define get(a) fl(i,0,a.size()) cin>>a[i]; #define pra(a) fl(i,0,a.size()) cout<<a[i]<<" "; cout<<endl; #define pr(a,n) fl(i,0,n) cout<<a[i]<<" "; cout<<endl; const ll INF = 2e18; const int inf = 2e9; const int mod1 = 1e9 + 7; int main(){ Shazam; int n,c,k; cin>>n>>k>>c; string s; cin>>s; vector<int> a,b; for(int i = 0 ; i < n ; i++) if(s[i]=='o'){a.push_back(i); i+=c;} for(int i = n-1; i >=0; i--) if(s[i]=='o'){b.push_back(i); i-=c;} for(int i = 0 ; i < k ; i++) {if(a[i]==b[k-1-i]) cout<<a[i]+1<<endl;} return 0; }
29.714286
81
0.575962
46ca9a317c482ebdc784219d9ead089b15fdd056
8,788
cpp
C++
test/src/tc/pm/gtest/cpp/src/helper/PMCppUtilityHelper.cpp
jonghenhan/iotivity
7dfc2bc6a5c0506cf88bc23e88e38fe1b795da31
[ "Apache-2.0" ]
301
2015-01-20T16:11:32.000Z
2021-11-25T04:29:36.000Z
test/src/tc/pm/gtest/cpp/src/helper/PMCppUtilityHelper.cpp
jonghenhan/iotivity
7dfc2bc6a5c0506cf88bc23e88e38fe1b795da31
[ "Apache-2.0" ]
13
2015-06-04T09:55:15.000Z
2020-09-23T00:38:07.000Z
test/src/tc/pm/gtest/cpp/src/helper/PMCppUtilityHelper.cpp
jonghenhan/iotivity
7dfc2bc6a5c0506cf88bc23e88e38fe1b795da31
[ "Apache-2.0" ]
233
2015-01-26T03:41:59.000Z
2022-03-18T23:54:04.000Z
/****************************************************************** * * Copyright 2016 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 * * LICENSE-2.0" target="_blank">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 "PMCppHelper.h" #include "PMCppUtilityHelper.h" bool PMCppUtilityHelper::readFile(const char *name, OCByteString *out) { FILE *file = NULL; int length = 0; uint8_t *buffer = NULL; bool result = false; size_t count, realCount; //Open file file = fopen(name, "rb"); if (!file) { OIC_LOG_V(ERROR, TAG, "Unable to open file %s", name); return result; } //Get file length if (fseek(file, 0, SEEK_END)) { OIC_LOG(ERROR, TAG, "Failed to SEEK_END"); goto exit; } length = ftell(file); if (length < 0) { OIC_LOG(ERROR, TAG, "Failed to ftell"); goto exit; } if (fseek(file, 0, SEEK_SET)) { OIC_LOG(ERROR, TAG, "Failed to SEEK_SET"); goto exit; } //Allocate memory buffer = (uint8_t *) malloc(length); if (!buffer) { OIC_LOG(ERROR, TAG, "Failed to allocate buffer"); goto exit; } //Read file contents into buffer count = 1; realCount = fread(buffer, length, count, file); if (realCount != count) { OIC_LOG_V(ERROR, TAG, "Read %d bytes %zu times instead of %zu", length, realCount, count); goto exit; } out->bytes = buffer; out->len = length; result = true; exit: fclose(file); return result; } void PMCppUtilityHelper::printDevices(DeviceList_t &list) { for (unsigned int i = 0; i < list.size(); i++) { std::cout << "Device " << i + 1 << " ID: "; std::cout << list[i]->getDeviceID() << " From IP: "; std::cout << list[i]->getDevAddr() << " Device Status(On/ Off) "; std::cout << list[i]->getDeviceStatus() << " Owned Status: "; std::cout << list[i]->getOwnedStatus() << std::endl; } } char* PMCppUtilityHelper::getOxmType(OicSecOxm_t oxmType) { char* resultString = NULL; switch (oxmType) { case OIC_JUST_WORKS: resultString = (char*) "OIC_JUST_WORKS"; break; case OIC_RANDOM_DEVICE_PIN: resultString = (char*) "OIC_RANDOM_DEVICE_PIN"; break; case OIC_MANUFACTURER_CERTIFICATE: resultString = (char*) "OIC_MANUFACTURER_CERTIFICATE"; break; case OIC_DECENTRALIZED_PUBLIC_KEY: resultString = (char*) "OIC_DECENTRALIZED_PUBLIC_KEY"; break; case OIC_OXM_COUNT: resultString = (char*) "OIC_OXM_COUNT"; break; case OIC_PRECONFIG_PIN: resultString = (char*) "OIC_PRECONFIG_PIN"; break; case OIC_MV_JUST_WORKS: resultString = (char*) "OC_STACK_RESOURCE_CREATED"; break; case OIC_CON_MFG_CERT: resultString = (char*) "OIC_CON_MFG_CERT"; break; default: resultString = (char*) "UNKNOWN_OXM_TYPE"; } return resultString; } void PMCppUtilityHelper::printUuid(OicUuid_t uuid) { for (int i = 0; i < UUID_LENGTH; i++) { std::cout << std::hex << uuid.id[i] << " "; } std::cout << std::endl; } void PMCppUtilityHelper::removeAllResFile() { CommonUtil::rmFile(JUSTWORKS_SERVER1_CBOR); CommonUtil::rmFile(JUSTWORKS_SERVER2_CBOR); CommonUtil::rmFile(RANDOMPIN_SERVER_CBOR); CommonUtil::rmFile(PRECONFIG_SERVER1_CBOR); CommonUtil::rmFile(PRECONFIG_SERVER2_CBOR); CommonUtil::rmFile(JUSTWORKS_SERVER7_CBOR); CommonUtil::rmFile(MV_JUSTWORKS_SERVER_CBOR); CommonUtil::rmFile(CLIENT_DATABASE); CommonUtil::rmFile(CLIENT_CBOR); CommonUtil::rmFile(MOT_CLIENT_DATABASE); CommonUtil::rmFile(MOT_CLIENT_CBOR); CommonUtil::rmFile(DEVICE_PROPERTIES); CommonUtil::rmFile(ROOT_CERT_FILE_TMP); } OCProvisionDev_t* PMCppUtilityHelper::getDevInst(OCProvisionDev_t* dev_lst, const int dev_num) { IOTIVITYTEST_LOG(DEBUG, "[PMHelper] getDevInst IN"); if (!dev_lst || 0 >= dev_num) { IOTIVITYTEST_LOG(ERROR, "[PMHelper] Device List is Empty"); return NULL; } OCProvisionDev_t* lst = (OCProvisionDev_t*) dev_lst; for (int i = 0; lst;) { if (dev_num == ++i) { IOTIVITYTEST_LOG(DEBUG, "[PMHelper] getDevInst OUT"); return lst; } lst = lst->next; } IOTIVITYTEST_LOG(DEBUG, "[PMHelper] getDevInst OUT"); return NULL; // in here |lst| is always |NULL| } int PMCppUtilityHelper::printDevList(OCProvisionDev_t* dev_lst) { IOTIVITYTEST_LOG(DEBUG, "[PMHelper] printDevList IN"); if (!dev_lst) { IOTIVITYTEST_LOG(INFO, "[PMHelper] Device List is Empty..."); return 0; } OCProvisionDev_t* lst = (OCProvisionDev_t*) dev_lst; int lst_cnt = 0; for (; lst;) { printf(" [%d] ", ++lst_cnt); printUuid((const OicUuid_t*) &lst->doxm->deviceID); printf("\n"); lst = lst->next; } printf("\n"); IOTIVITYTEST_LOG(DEBUG, "[PMHelper] printDevList OUT"); return lst_cnt; } size_t PMCppUtilityHelper::printUuidList(const OCUuidList_t* uid_lst) { IOTIVITYTEST_LOG(DEBUG, "[PMHelper] printUuidList IN"); if (!uid_lst) { IOTIVITYTEST_LOG(INFO, "[PMHelper] Device List is Empty..."); return 0; } OCUuidList_t* lst = (OCUuidList_t*) uid_lst; size_t lst_cnt = 0; for (; lst;) { printf(" [%zu] ", ++lst_cnt); printUuid((const OicUuid_t*) &lst->dev); printf("\n"); lst = lst->next; } printf("\n"); IOTIVITYTEST_LOG(DEBUG, "[PMHelper] printUuidList OUT"); return lst_cnt; } int PMCppUtilityHelper::printResultList(const OCProvisionResult_t* rslt_lst, const int rslt_cnt) { IOTIVITYTEST_LOG(DEBUG, "[PMHelper] printResultList IN"); if (!rslt_lst || 0 >= rslt_cnt) { IOTIVITYTEST_LOG(INFO, "[PMHelper] Device List is Empty..."); return 0; } int lst_cnt = 0; for (; rslt_cnt > lst_cnt; ++lst_cnt) { printf(" [%d] ", lst_cnt + 1); printUuid((const OicUuid_t*) &rslt_lst[lst_cnt].deviceId); printf(" - result: %s\n", CommonUtil::getOCStackResult(rslt_lst[lst_cnt].res)); } printf("\n"); IOTIVITYTEST_LOG(INFO, "[PMHelper] printResultList IN"); return lst_cnt; } void PMCppUtilityHelper::printUuid(const OicUuid_t* uid) { IOTIVITYTEST_LOG(DEBUG, "[PMHelper] printUuid IN"); for (int i = 0; i < UUID_LENGTH;) { printf("%02X", (*uid).id[i++]); if (i == 4 || i == 6 || i == 8 || i == 10) // canonical format for UUID has '8-4-4-4-12' { printf("%c", DASH); } } printf("\n"); IOTIVITYTEST_LOG(DEBUG, "[PMHelper] printUuid OUT"); } /** * Function to set failure message */ std::string PMCppUtilityHelper::setFailureMessage(OCStackResult expectedResult, OCStackResult actualResult) { std::string errorMessage("\033[1;31m[Error] Expected : "); errorMessage.append(CommonUtil::getOCStackResult(expectedResult)); errorMessage.append("\033[0m \033[1;31mActual : "); errorMessage.append(CommonUtil::getOCStackResult(actualResult)); errorMessage.append("\033[0m"); return errorMessage; } /** * Function to set failure message */ std::string PMCppUtilityHelper::setFailureMessage(OicSecOxm_t expectedResult, OicSecOxm_t actualResult) { std::string errorMessage("\033[1;31m[Error] Expected : "); errorMessage.append(PMCppUtilityHelper::getOxmType(expectedResult)); errorMessage.append("\033[0m \033[1;31mActual : "); errorMessage.append(PMCppUtilityHelper::getOxmType(actualResult)); errorMessage.append("\033[0m"); return errorMessage; } /** * Function to set failure message */ std::string PMCppUtilityHelper::setFailureMessage(std::string errorMessage) { std::string retErrorMessage("\033[1;31m[Error] Expected : "); retErrorMessage.append(errorMessage); retErrorMessage.append("\033[0m"); return retErrorMessage; }
27.20743
98
0.612995
46cdd8004bd7e3f2911eb9073495f88913ee36c7
2,051
cpp
C++
LeetCode/Hash/LongestSubstringWithoutRepeatingCharacters_f.cpp
a4org/Angorithm4
d2227d36608491bed270375bcea67fbde134209a
[ "MIT" ]
3
2021-07-26T15:58:45.000Z
2021-09-08T14:55:11.000Z
LeetCode/Hash/LongestSubstringWithoutRepeatingCharacters_f.cpp
a4org/Angorithm4
d2227d36608491bed270375bcea67fbde134209a
[ "MIT" ]
null
null
null
LeetCode/Hash/LongestSubstringWithoutRepeatingCharacters_f.cpp
a4org/Angorithm4
d2227d36608491bed270375bcea67fbde134209a
[ "MIT" ]
2
2021-05-31T11:27:59.000Z
2021-10-03T13:26:00.000Z
/* * LeetCode 3 Longest Substring Without Repeating Characters * Medium * Shuo Feng * 2021.9.15 */ /* * Solution 1: * Begin with a starting point and check characters after, update a set and record the maximum size. * When meet a repeating character, remove the previous point in set till there have not repeat, change starting point in " s ". * * a b c a b c b b Longest Substring: * Begin ↑(Find repeat) (abc) * a b c a b c b b * Begin ↑ (bca) * a b c a b c b b * Begin ↑ (cab) * a b c a b c b b * Begin ↑ (abc) * a b c a b c b b * Begin ↑ (bc) * a b c a b c b b * Begin ↑ (cb) * a b c a b c b b * Begin ↑ (b) * a b c a b c b b * Begin (b) */ #include<iostream> #include<string> #include<utility> #include<unordered_set> using namespace std; class Solution { public: int lengthOfLongestSubstring(string s) { int size = s.size(); if (size < 2) return size; int max_size = 0; int Begin = 0; // Begining place. unordered_set <char> search; for (int i = 0; i < size; ++i) { // Search in set. // Repetitive. while (search.find(s[i]) != search.end()) { search.erase(s[Begin]); Begin += 1; // Begin with next point. } // non_Repetitive. search.insert(s[i]); max_size = max(max_size, i - Begin + 1); } return max_size; } };
32.046875
130
0.387128
46cf676f19bb9b2850daf5c31dd6fa692a4b68ff
2,789
cpp
C++
sources/Page.cpp
khsabrina/notebook-b
5ab09040f7b3658314239148a54a45747a918b22
[ "MIT" ]
null
null
null
sources/Page.cpp
khsabrina/notebook-b
5ab09040f7b3658314239148a54a45747a918b22
[ "MIT" ]
null
null
null
sources/Page.cpp
khsabrina/notebook-b
5ab09040f7b3658314239148a54a45747a918b22
[ "MIT" ]
null
null
null
#include "Row.hpp" #include "Page.hpp" using namespace std; #include <iostream> #include <iterator> #include <map> const int LENGHT_ROW=100; Page::Page(){ } void Page::add(int col,int row,Direction dir, string str){ if(dir == Direction::Horizontal){ int size = str.size(); if (col + size > LENGHT_ROW){ throw invalid_argument{"You can't write here1"}; } if (!rows.contains(row)){ Row New; rows.insert({row, New}); rows[row].add(col,str); } else{ rows[row].check_horizontal(col, str.size()); //if(!check){return;} rows[row].add(col,str); } } if(dir == Direction::Vertical){ for(int i= 0; i<str.size();i++){ if(!rows.contains(row+i)){ Row New; rows.insert({row+i, New}); } else{ rows[row+i].check_vertical(col); //if(!check){return;} } } for(int i=0; i<str.size();i++){ string c(1, (char)str[(unsigned long)i]); rows[row+i].add(col,c); } } } string Page::read(int col,int row,Direction dir, int size){ string ans; if(dir == Direction::Horizontal){ if (col + size > LENGHT_ROW){ throw invalid_argument{"You can't write here"}; } if(!rows.contains(row)){ Row New; rows.insert({row, New}); } ans = rows[row].read(col,size); } else{ if (col > LENGHT_ROW){ throw invalid_argument{"You can't write here"}; } for(int i=0; i<size; i++){ if(!rows.contains(row+i)){ Row New; rows.insert({row+i, New}); } ans += rows[row+i].read(col,1); } } return ans; } void Page::erase(int col,int row, Direction dir , int size){ if(dir == Direction::Horizontal){ if (col + size > LENGHT_ROW){ cout << "here5"; throw invalid_argument{"You can't write here4"}; return; } if(!rows.contains(row)){ Row New; rows.insert({row, New}); } rows[row].erase(col,size); } else{ for(int i=0; i<size; i++){ if(!rows.contains(row+i)){ Row New; rows.insert({row+i, New}); } rows[row+i].erase(col,1); } } } void Page::show(){ map<int, Row>::iterator itr; for (itr = rows.begin(); itr != rows.end(); ++itr) { cout << itr->first << "."; itr->second.show(); cout << '\n'; } } // Page::~Page(){ // return; // }
24.901786
64
0.453926
46d4d4e5eb5f615fc8966b8330dc7b0a6e138afc
130
cpp
C++
src/CMake/Testftimeprototype.cpp
visit-dav/vis
c08bc6e538ecd7d30ddc6399ec3022b9e062127e
[ "BSD-3-Clause" ]
226
2018-12-29T01:13:49.000Z
2022-03-30T19:16:31.000Z
src/CMake/Testftimeprototype.cpp
visit-dav/vis
c08bc6e538ecd7d30ddc6399ec3022b9e062127e
[ "BSD-3-Clause" ]
5,100
2019-01-14T18:19:25.000Z
2022-03-31T23:08:36.000Z
src/CMake/Testftimeprototype.cpp
visit-dav/vis
c08bc6e538ecd7d30ddc6399ec3022b9e062127e
[ "BSD-3-Clause" ]
84
2019-01-24T17:41:50.000Z
2022-03-10T10:01:46.000Z
#include <sys/time.h> #include <sys/timeb.h> int main(int argc, char *argv[]) { struct timeb *tp; ftime(tp); return 0; }
13
32
0.615385
46d53436f721cfb55f85f51e483ddd0174db7856
3,866
cpp
C++
src/desktop/panes/fspane.cpp
KDE/kookbook
522ca12ebdf386cd3ca52d03fbf1b022c9e5e1b9
[ "MIT" ]
8
2018-12-18T20:49:56.000Z
2022-01-11T07:40:56.000Z
src/desktop/panes/fspane.cpp
KDE/kookbook
522ca12ebdf386cd3ca52d03fbf1b022c9e5e1b9
[ "MIT" ]
null
null
null
src/desktop/panes/fspane.cpp
KDE/kookbook
522ca12ebdf386cd3ca52d03fbf1b022c9e5e1b9
[ "MIT" ]
2
2019-02-18T17:08:49.000Z
2020-10-08T06:01:03.000Z
/* * Copyright (c) 2018 Sune Vuorela <sune@vuorela.dk> * * 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 "fspane.h" #include <memory> #include <QTreeView> #include <QFileSystemModel> #include <QVBoxLayout> #include <QIdentityProxyModel> #include <QDebug> class OneColumnProxy : public QIdentityProxyModel { public: OneColumnProxy(QObject* parent = nullptr) : QIdentityProxyModel(parent) {} int columnCount(const QModelIndex& ) const override { return 1; } }; class FileNameTitleMapper : public QIdentityProxyModel { public: FileNameTitleMapper(QObject* parent = nullptr) : QIdentityProxyModel(parent) {} void setFileNameTitleMap(QHash<QString,QString> map) { beginResetModel(); m_map = map; endResetModel(); } QHash<QString,QString> m_map; QVariant data(const QModelIndex& idx, int role) const override { if(role == Qt::DisplayRole) { QVariant d = QIdentityProxyModel::data(idx,QFileSystemModel::FilePathRole); QString str = d.toString(); auto it = m_map.constFind(str); if (it != m_map.constEnd()) { return it.value(); } } return QIdentityProxyModel::data(idx,role); } }; FsPane::FsPane(QWidget* parent) : QWidget(parent) { auto layout = std::make_unique<QVBoxLayout>(); auto tree = std::make_unique<QTreeView>(); m_dirModel = std::make_unique<QFileSystemModel>(); m_dirModel->setNameFilters(QStringList() << QStringLiteral("*.recipe.md")); m_dirModel->setNameFilterDisables(false); m_filenamemapper = std::make_unique<FileNameTitleMapper>(); m_filenamemapper->setSourceModel(m_dirModel.get()); m_proxy = std::make_unique<OneColumnProxy>(); m_proxy->setSourceModel(m_filenamemapper.get()); tree->setModel(m_proxy.get()); tree->setHeaderHidden(true); connect(tree.get(), &QTreeView::clicked, [this] (const QModelIndex& idx) { auto var = idx.data(QFileSystemModel::FilePathRole); emit this->fileSelected(var.toString()); }); m_tree = tree.get(); layout->addWidget(tree.release()); setLayout(layout.release()); } FsPane::~FsPane() { // for smart pointers } void FsPane::setRootPath(const QString& string) { auto path = m_dirModel->setRootPath(string); path = m_filenamemapper->mapFromSource(path); path = m_proxy->mapFromSource(path); if (path.isValid()) { m_tree->setModel(m_proxy.get()); m_tree->setRootIndex(path); m_rootPath = string; } else { m_tree->setModel(nullptr); m_rootPath = QString(); } } void FsPane::setFileNameTitleMap(QHash<QString, QString> titlemap) { m_filenamemapper->setFileNameTitleMap(titlemap); setRootPath(m_rootPath); }
31.430894
87
0.685722
46d9f66e3002849d353f2a3c08eb1ff530d8bd2a
334
hpp
C++
include/Btk/impl/mixer.hpp
BusyStudent/Btk
27b23aa77e4fbcc48bdfe566ce7cae46183c289c
[ "MIT" ]
2
2021-06-19T08:21:38.000Z
2021-08-15T21:37:30.000Z
include/Btk/impl/mixer.hpp
BusyStudent/Btk
27b23aa77e4fbcc48bdfe566ce7cae46183c289c
[ "MIT" ]
null
null
null
include/Btk/impl/mixer.hpp
BusyStudent/Btk
27b23aa77e4fbcc48bdfe566ce7cae46183c289c
[ "MIT" ]
1
2021-04-03T14:27:39.000Z
2021-04-03T14:27:39.000Z
#if !defined(_BTK_IMPL_MIXER) #define _BTK_IMPL_MIXER //Implment for mixer #include <SDL2/SDL_audio.h> #include <SDL2/SDL_error.h> #include <SDL2/SDL_rwops.h> #include "../mixer.hpp" #include "../rwops.hpp" #include "../function.hpp" #include "atomic.hpp" #include <vector> #include <mutex> #include <list> #endif // _BTK_IMPL_MIXER
20.875
29
0.730539
46da70a73467334640434461461fe89eaf2ba08b
5,631
cc
C++
apps/rwh/arguments.cc
OSADP/Pikalert-Vehicle-Data-Translator-
295da604408f6f13af0301b55476a81311459386
[ "Apache-2.0" ]
2
2020-06-03T15:59:50.000Z
2020-12-21T11:11:57.000Z
apps/rwh/arguments.cc
OSADP/Pikalert-Vehicle-Data-Translator-
295da604408f6f13af0301b55476a81311459386
[ "Apache-2.0" ]
null
null
null
apps/rwh/arguments.cc
OSADP/Pikalert-Vehicle-Data-Translator-
295da604408f6f13af0301b55476a81311459386
[ "Apache-2.0" ]
2
2019-10-02T06:47:23.000Z
2020-02-02T18:32:23.000Z
//============================================================================== // // (c) Copyright, 2013 University Corporation for Atmospheric Research (UCAR). // All rights reserved. // // File: $RCSfile: arguments.cc,v $ // Version: $Revision: 1.2 $ Dated: $Date: 2013/09/27 16:47:01 $ // //============================================================================== /** * * @file apps/probe_message_dataset_manager/arguments.cc * * Implementation for simple class that parses command line arguments. * */ // Include files #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <boost/format.hpp> #include "arguments.hh" using boost::format; // Constant and macros // Types, structures and classes // Global variables // Functions void get_command_string(int argc, char **argv, string &command_string) { for (int i=0; i<argc-1; i++) { command_string += string(argv[i]) + string(" "); } command_string += string(argv[argc-1]); } arguments::arguments(int argc, char **argv) { int c = 0; char *ptr = 0; int errflg = 0; begin_time = 0; begin_time_string = ""; end_time = 0; end_time_string = ""; error = ""; debug = 0; log_file = ""; road_wx_fcst_file = ""; road_cond_fcst_file = ""; vdt_seg_stats_file = ""; vdt_seg_assign_wx_file = ""; prev_rwh_conf_file = ""; test = false; // Parse command line options while ((c = getopt(argc, argv, "a:d:l:n:p:s:r:w:t")) != EOF) { switch (c) { case 'a': vdt_seg_assign_wx_file = optarg; break; case 'd': debug = (int)strtol(optarg, &ptr, 10); if (debug == 0 && ptr == optarg) { error = string("bad debug level"); return; } break; case 'l': log_file = optarg; break; case 's': vdt_seg_stats_file = optarg; break; case 'r': road_cond_fcst_file = optarg; break; case 'w': road_wx_fcst_file = optarg; break; case 'p': prev_rwh_conf_file = optarg; break; case 't': test = true; break; case '?': errflg = 1; break; } } if (errflg) { error = "bad command line option"; return; } ptr = strrchr(argv[0], '/'); if (ptr == NULL) ptr = argv[0]; else ptr++; program_name = string(ptr); if (test && (argc - optind) < 1) { fprintf(stderr, "Error: when specifying the -t option, you also need to specify a configuration file\n"); usage(argv[0]); exit(2); } else if (!test && (argc - optind) < 6) { usage(argv[0]); exit(2); } cfg_file = string(argv[optind++]); if (!test) { // Assign names to command line parameters begin_time_string = string(argv[optind++]); end_time_string = string(argv[optind++]); begin_time = datetime_2_utime((char *)(begin_time_string.c_str()) ); end_time = datetime_2_utime((char *)(end_time_string.c_str())); fcst_road_seg_site_list_file = string(argv[optind++]); vdt_road_seg_file = string(argv[optind++]); output_file = string(argv[optind++]); } get_command_string(argc, argv, command_string); } void arguments::usage(char *program_name) { fprintf(stderr, "usage: %s [-w road_wx_fcst_file] [-r road_cond_fcst_file] [-s vdt_seg_stats_file] [-a vdt_seg_assign_wx_file] [-p prev_rwh_conf_file] [-l log_file] [-d debug_level] [-t] config_file begin_time_string end_time_string fcst_road_seg_site_list_file vdt_road_seg_file rwh_output_file \n", program_name); fprintf(stderr, "config_file : configuration file for road weather hazzard application\n"); fprintf(stderr, "begin_time_string : begin time string in form yyyymmddhhmm of time window of interest\n"); fprintf(stderr, "end_time_string : end time string in form yyyymmddhhmm of time window of interest\n"); fprintf(stderr, "fcst_road_seg_site_list_file : ascii file with road segment site list entries for retrieving forecast data\n"); fprintf(stderr, "vdt_road_seg_file : netcdf file with road segments data\n"); fprintf(stderr, "output_file : output file with road weather hazard data\n"); fprintf(stderr, "-w road_wx_fcst_file : input file with road segment weather forecast data\n"); fprintf(stderr, "-r road_cond_fcst_file : input file with road segment conditions forecast data\n"); fprintf(stderr, "-s vdt_seg_stats_file : input file with VDT Stage II Segment Statistics data\n"); fprintf(stderr, "-a vdt_seg_assign_wx_file : input file with VDT Stage II Road-Weather Assignment data\n"); fprintf(stderr, "-p prev_rwh_conf_file : input file with a list of prevoius RWH files\n"); fprintf(stderr, "-l log_file: write log messages to log_file\n"); fprintf(stderr, "-d debug_level: set debug diagnostic level\n"); fprintf(stderr, "-t: run tests dictated by configuration file. Note if -t is specified, the configuration file is the only other command line parameter needed.\n"); } time_t arguments::datetime_2_utime(char *datetime) { struct tm time_tm; int ret = sscanf(datetime, "%4d%02d%02d%02d%02d", &time_tm.tm_year, &time_tm.tm_mon, &time_tm.tm_mday, &time_tm.tm_hour, &time_tm.tm_min); if(ret != 5) { fprintf(stderr, "Error: invalid date: %s, format must be YYYYMMDDHHMM\n", datetime); return -1; } time_tm.tm_year -= 1900; time_tm.tm_mon -= 1; time_tm.tm_sec = 0; time_t utime = timegm(&time_tm); return utime; }
28.439394
317
0.618007
46da8dd5beeb4b2abb3660c0727f7f527042298d
748
cpp
C++
src/MultiCamera.cpp
mario-nj/four-cam
8109d8f10bc967a728205d96f7f2d164016cd84b
[ "MIT" ]
null
null
null
src/MultiCamera.cpp
mario-nj/four-cam
8109d8f10bc967a728205d96f7f2d164016cd84b
[ "MIT" ]
null
null
null
src/MultiCamera.cpp
mario-nj/four-cam
8109d8f10bc967a728205d96f7f2d164016cd84b
[ "MIT" ]
null
null
null
#include "includes/CameraStreamer.hpp" #include "opencv2/highgui.hpp" using namespace cv; int main(int argc, char** argv) { // IP Câmera - urls /* vector<string> capture_source = { "", "" }; */ // USB Câmera - índices vector<int> capture_index = {0, 2, 4}; vector<string> label; for(int i = 0; i < capture_index.size(); i++){ string title = "CiMMov " + to_string(i); label.push_back(title); } CameraStreamer cam(capture_index); while (waitKey(20) != 27) { for (int i = 0; i < capture_index.size(); i++) { Mat frame; if (cam.frame_queue[i]->try_pop(frame)) { imshow(label[i], frame); } } } }
22
56
0.52139
46e75db4cb5af3abca61418168d8641ca99693c5
285
cpp
C++
chapter_2/section_x/io.cpp
martindes01/learncpp
50c500b0cf03c9520eab0a6bdeb4556da7d13bbf
[ "MIT" ]
4
2020-08-03T15:00:00.000Z
2022-01-08T20:22:55.000Z
chapter_2/section_x/io.cpp
martindes01/learncpp
50c500b0cf03c9520eab0a6bdeb4556da7d13bbf
[ "MIT" ]
null
null
null
chapter_2/section_x/io.cpp
martindes01/learncpp
50c500b0cf03c9520eab0a6bdeb4556da7d13bbf
[ "MIT" ]
null
null
null
// Include custom headers #include "io.h" // Include standard library headers #include <iostream> int readNumber() { std::cout << "Enter an integer: "; int x{ }; std::cin >> x; return x; } void writeAnswer(int answer) { std::cout << "The answer is " << answer << '\n'; }
14.25
50
0.614035
46ef9733080898aed1ced4a6f987e79f1a761388
3,766
cpp
C++
src/network/socket.cpp
leezhenghui/Mushroom
8aed2bdd80453d856145925d067bef5ed9d10ee0
[ "BSD-3-Clause" ]
351
2016-10-12T14:06:09.000Z
2022-03-24T14:53:54.000Z
src/network/socket.cpp
leezhenghui/Mushroom
8aed2bdd80453d856145925d067bef5ed9d10ee0
[ "BSD-3-Clause" ]
7
2017-03-07T01:49:16.000Z
2018-07-27T08:51:54.000Z
src/network/socket.cpp
UncP/Mushroom
8aed2bdd80453d856145925d067bef5ed9d10ee0
[ "BSD-3-Clause" ]
62
2016-10-31T12:46:45.000Z
2021-12-28T11:25:26.000Z
/** * > Author: UncP * > Github: www.github.com/UncP/Mushroom * > License: BSD-3 * > Time: 2017-04-23 10:23:53 **/ #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #include <fcntl.h> #include <cstring> #include <cassert> #include <cerrno> #include "socket.hpp" namespace Mushroom { Socket::Socket():fd_(-1) { } Socket::Socket(int fd):fd_(fd) { } Socket::~Socket() { } int Socket::fd() const { return fd_; } bool Socket::Valid() const { return fd_ != -1; } bool Socket::Create() { fd_ = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); return fd_ != -1; } bool Socket::Close() { bool flag = true; if (fd_ != -1) { flag = !close(fd_); fd_ = -1; } return flag; } bool Socket::Connect(const EndPoint &end_point) { struct sockaddr_in server; memset(&server, 0, sizeof(server)); server.sin_family = AF_INET; server.sin_port = htons(end_point.Port()); server.sin_addr.s_addr = end_point.Address(); return !connect(fd_, (const struct sockaddr *)&server, sizeof(server)); } bool Socket::Bind(uint16_t port) { struct sockaddr_in server; memset(&server, 0, sizeof(server)); server.sin_family = AF_INET; server.sin_port = htons(port); server.sin_addr.s_addr = htonl(INADDR_ANY); return !bind(fd_, (const struct sockaddr *)&server, sizeof(server)); } bool Socket::Listen() { return !listen(fd_, 32); } int Socket::Accept() { struct sockaddr_in client; memset(&client, 0, sizeof(client)); socklen_t len = sizeof(client); int fd = accept(fd_, (struct sockaddr *)&client, &len); return fd; } bool Socket::SetOption(int value, bool flag) { return !setsockopt(fd_, SOL_SOCKET, value, &flag, sizeof(flag)); } bool Socket::GetOption(int value, int *ret) { socklen_t len = sizeof(*ret); return !getsockopt(fd_, SOL_SOCKET, value, ret, &len); } bool Socket::SetResuseAddress() { int flag = 1; return !setsockopt(fd_, SOL_SOCKET, SO_REUSEADDR, &flag, sizeof(flag)); } bool Socket::GetPeerName(EndPoint *endpoint) { struct sockaddr_in addr; memset(&addr, 0, sizeof(addr)); socklen_t len = sizeof(addr); if (!getsockname(fd_, (struct sockaddr *)&addr, &len)) { *endpoint = EndPoint(ntohs(addr.sin_port), addr.sin_addr.s_addr); return true; } return false; } bool Socket::GetSockName(EndPoint *endpoint) { struct sockaddr_in addr; memset(&addr, 0, sizeof(addr)); socklen_t len = sizeof(addr); if (!getpeername(fd_, (struct sockaddr *)&addr, &len)) { *endpoint = EndPoint(ntohs(addr.sin_port), addr.sin_addr.s_addr); return true; } return false; } bool Socket::AddFlag(int flag) { int value = fcntl(fd_, F_GETFL, 0); assert(value != -1); return !fcntl(fd_, F_SETFL, value | flag); } bool Socket::SetNonBlock() { int value = fcntl(fd_, F_GETFL, 0); assert(value != -1); return !fcntl(fd_, F_SETFL, value | O_NONBLOCK); } uint32_t Socket::Write(const char *data, uint32_t len, bool *blocked) { uint32_t written = 0; for (; written < len;) { ssize_t r = write(fd_, data + written, len - written); if (r > 0) { written += r; continue; } else if (r == -1) { if (errno == EINTR) continue; if (errno == EAGAIN || errno == EWOULDBLOCK) { *blocked = true; break; } } printf("write error, %s :(\n", strerror(errno)); break; } return written; } uint32_t Socket::Read(char *data, uint32_t len, bool *blocked) { uint32_t has_read = 0; ssize_t r; for (; has_read < len && (r = read(fd_, data + has_read, len - has_read));) { if (r == -1) { if (errno == EINTR) continue; if (errno == EAGAIN || errno == EWOULDBLOCK) *blocked = true; else printf("read error, %s :(\n", strerror(errno)); break; } has_read += r; } return has_read; } } // namespace Mushroom
20.467391
78
0.648168
46f2bbfc9a51188edf94dd3a3ad3404ff9cdab9a
2,847
cpp
C++
source/main.cpp
Mstrodl/gm_win_toast
0255133b3d90f45bed5e8871f05d584d4985338b
[ "MIT" ]
1
2021-01-26T13:15:33.000Z
2021-01-26T13:15:33.000Z
source/main.cpp
Mstrodl/gm_win_toast
0255133b3d90f45bed5e8871f05d584d4985338b
[ "MIT" ]
null
null
null
source/main.cpp
Mstrodl/gm_win_toast
0255133b3d90f45bed5e8871f05d584d4985338b
[ "MIT" ]
null
null
null
#include <wintoastlib.h> #include <filesystem> #include <GarrysMod/Lua/Interface.h> //using namespace WinToastLib; const auto AUMI = WinToastLib::WinToast::configureAUMI(L"Facepunch", L"Garry's Mod"); bool is_usable = true; static const char* error_reasons[] = { "No error", "Not inialized", "OS is not supported", "Unable to create a shell link", "Invalid AUMI", "Initialization params are invalid", "Could not display toast", "Unknown" }; const std::string get_toast_error(int enum_value) { return std::string(error_reasons[enum_value]); } const std::wstring to_utf16(const char* utf8_str) { const std::string base_str(utf8_str); std::wstring utf16_str(base_str.size(), L' '); utf16_str.resize(std::mbstowcs(&utf16_str[0], base_str.c_str(), base_str.size())); return utf16_str; } class WinNotifsHandler : public WinToastLib::IWinToastHandler { public: void toastActivated() const {} void toastActivated(int action_index) const {} void toastDismissed(WinToastLib::IWinToastHandler::WinToastDismissalReason state) const {} void toastFailed() const {} }; LUA_FUNCTION(show_toast) { if (!is_usable) { LUA->PushBool(false); return 1; } const bool has_image_path = LUA->Top() >= 3; const char* title = LUA->CheckString(1); const char* content = LUA->CheckString(2); WinToastLib::WinToastTemplate templ(has_image_path ? WinToastLib::WinToastTemplate::ImageAndText02 : WinToastLib::WinToastTemplate::Text02 ); templ.setTextField(to_utf16(title), WinToastLib::WinToastTemplate::TextField::FirstLine); templ.setTextField(to_utf16(content), WinToastLib::WinToastTemplate::TextField::SecondLine); if (has_image_path) { const char* data_path = LUA->CheckString(3); const std::wstring gmod_path = std::filesystem::current_path().wstring(); const std::wstring full_path = gmod_path + L"/garrysmod/data/" + to_utf16(data_path); templ.setImagePath(full_path); } const bool success = WinToastLib::WinToast::instance()->showToast(templ, new WinNotifsHandler()) >= 0; LUA->PushBool(success); return 1; } GMOD_MODULE_OPEN() { if (!WinToastLib::WinToast::isCompatible()) { //LUA->ThrowError("[WinToasts] Your system is not supported!"); is_usable = false; return 0; } WinToastLib::WinToast::instance()->setAppName(L"Garry's Mod"); WinToastLib::WinToast::instance()->setAppUserModelId(AUMI); WinToastLib::WinToast::WinToastError err; if (!WinToastLib::WinToast::instance()->initialize(&err)) { //const std::string err_msg = "[WinToasts] Could not initialize: " + get_toast_error(err); //LUA->ThrowError(err_msg.c_str()); is_usable = false; return 0; } LUA->PushSpecial(GarrysMod::Lua::SPECIAL_GLOB); LUA->CreateTable(); LUA->PushCFunction(show_toast); LUA->SetField(-2, "Show"); LUA->SetField(-2, "WinToast"); LUA->Pop(); return 0; } GMOD_MODULE_CLOSE() { return 0; }
25.881818
103
0.727432
46f35ad0d1bfa320692ae6d13de0007a229878f3
130
cpp
C++
nano/src/nano/nano.cpp
lyLoveSharon/nano
aa768a241a4ea282f83ccd088561a5eefd59d342
[ "Apache-2.0" ]
null
null
null
nano/src/nano/nano.cpp
lyLoveSharon/nano
aa768a241a4ea282f83ccd088561a5eefd59d342
[ "Apache-2.0" ]
null
null
null
nano/src/nano/nano.cpp
lyLoveSharon/nano
aa768a241a4ea282f83ccd088561a5eefd59d342
[ "Apache-2.0" ]
null
null
null
#include "nano/nano.h" const char *nano_version() { return "0.0.1"; } const char *nano_module_name() { return "nano"; }
10.833333
30
0.623077
46f7ea9131f1e0f8f0ac7885da9e48173eabfb30
1,208
cpp
C++
ModeChoice/Household_List.cpp
kravitz/transims4
ea0848bf3dc71440d54724bb3ecba3947b982215
[ "NASA-1.3" ]
2
2018-04-27T11:07:02.000Z
2020-04-24T06:53:21.000Z
ModeChoice/Household_List.cpp
idkravitz/transims4
ea0848bf3dc71440d54724bb3ecba3947b982215
[ "NASA-1.3" ]
null
null
null
ModeChoice/Household_List.cpp
idkravitz/transims4
ea0848bf3dc71440d54724bb3ecba3947b982215
[ "NASA-1.3" ]
null
null
null
//********************************************************* // Household_List.cpp - read the household list file //********************************************************* #include "ModeChoice.hpp" #include "Utility.hpp" //--------------------------------------------------------- // Household_List //--------------------------------------------------------- void ModeChoice::Household_List (void) { int hhold, nfile; for (nfile=0; ; nfile++) { if (hhlist_file.Extend ()) { if (nfile > 0) { if (!hhlist_file.Open (nfile)) return; } Show_Message ("Reading %s %s -- Record", hhlist_file.File_Type (), hhlist_file.Extension ()); } else { if (nfile > 0) return; Show_Message ("Reading %s -- Record", hhlist_file.File_Type ()); } Set_Progress (); //---- store the household list ---- while (hhlist_file.Read ()) { Show_Progress (); Get_Integer (hhlist_file.Record (), &hhold); if (hhold <= 0) continue; if (!hhold_list.Add (hhold)) { Error ("Adding Household %d to the List", hhold); } } End_Progress (); } hhlist_file.Close (); Print (2, "Total Number of Household List Records = %d", hhold_list.Num_Records ()); hhold_list.Optimize (); }
24.16
96
0.508278
46fb1480e4ec109476ab56bb8b7429d68d7b3a9d
2,824
cpp
C++
examples/basin.cpp
danielelinaro/BAL
d735048d9962a0c424c29db93f774494c67b12a9
[ "MIT" ]
1
2020-02-02T22:30:37.000Z
2020-02-02T22:30:37.000Z
examples/basin.cpp
danielelinaro/BAL
d735048d9962a0c424c29db93f774494c67b12a9
[ "MIT" ]
null
null
null
examples/basin.cpp
danielelinaro/BAL
d735048d9962a0c424c29db93f774494c67b12a9
[ "MIT" ]
null
null
null
/*========================================================================= * * Program: Bifurcation Analysis Library * Module: basin.cpp * * Copyright (C) 2009 Daniele Linaro * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * *=========================================================================*/ #include <cstdio> #include <cstdlib> #include <nvector/nvector_serial.h> #include "balObject.h" #include "balDynamicalSystem.h" #include "balHindmarshRose.h" #include "balODESolver.h" #include "balBifurcationDiagram.h" #include "balParameters.h" using namespace bal; // TEST BifurcationDiagram int main(int argc, char *argv[]) { Parameters * par = Parameters::Create(); par->SetNumber(4); par->At(0) = 2.88; par->At(1) = 2.6; par->At(2) = 0.01; par->At(3) = 4.0; HindmarshRose * hr = HindmarshRose::Create(); hr->SetParameters(par); BifurcationDiagram * bifd = BifurcationDiagram::Create(); bifd->SetDynamicalSystem(hr); bifd->SetFilename("hr-basin.h5"); bifd->GetODESolver()->SetIntegrationMode(EVENTS); bifd->GetODESolver()->HaltAtEquilibrium(true); bifd->GetODESolver()->HaltAtCycle(true); bifd->GetODESolver()->SetTransientDuration(0e3); bifd->GetODESolver()->SetFinalTime(5e3); bifd->GetODESolver()->SetTimeStep(0.1); bifd->GetODESolver()->SetMaxNumberOfIntersections(300); bifd->SetNumberOfThreads(argc > 1 ? atoi(argv[1]) : 2); //double x0_chaos[] = {-0.882461371550183,-3.661932217696160,2.870154513826437}; int nX0 = 1000; double **X0 = new double*[nX0]; for(int i=0; i<nX0; i++) { X0[i] = new double[3]; /* X0[i][0] = 2.5*((double) random()/RAND_MAX); X0[i][1] = -10 + 12*((double) random()/RAND_MAX); X0[i][2] = 1.5; */ /* X0[i][0] = 2.5*((double) random()/RAND_MAX); X0[i][1] = -5; X0[i][2] = -1+3.0*((double) random()/RAND_MAX); */ X0[i][0] = 1.; X0[i][1] = -10 + 12*((double) random()/RAND_MAX); X0[i][2] = -1+3.0*((double) random()/RAND_MAX); } bifd->SetMode(IC); bifd->SetInitialConditions(nX0,X0); bifd->ComputeDiagram(); bifd->SaveSummaryData("hr-basin.classified"); bifd->Destroy(); hr->Destroy(); par->Destroy(); return 0; }
31.377778
82
0.621459
46fbdb4f601bffcca5874cf6df7c961fe59c9af8
1,342
cc
C++
packager/media/base/proto_json_util.cc
koln67/shaka-packager
5b9fd409a5de502e8af2e46ee12840bd2226874d
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1,288
2016-05-25T01:20:31.000Z
2022-03-02T23:56:56.000Z
packager/media/base/proto_json_util.cc
koln67/shaka-packager
5b9fd409a5de502e8af2e46ee12840bd2226874d
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
894
2016-05-17T00:39:30.000Z
2022-03-02T18:46:21.000Z
packager/media/base/proto_json_util.cc
koln67/shaka-packager
5b9fd409a5de502e8af2e46ee12840bd2226874d
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
400
2016-05-25T01:20:35.000Z
2022-03-03T02:12:00.000Z
// Copyright 2018 Google LLC. All rights reserved. // // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file or at // https://developers.google.com/open-source/licenses/bsd #include "packager/media/base/proto_json_util.h" #include <google/protobuf/util/json_util.h> #include "packager/base/logging.h" namespace shaka { namespace media { std::string MessageToJsonString(const google::protobuf::Message& message) { google::protobuf::util::JsonPrintOptions json_print_options; json_print_options.preserve_proto_field_names = true; std::string result; GOOGLE_CHECK_OK(google::protobuf::util::MessageToJsonString( message, &result, json_print_options)); return result; } bool JsonStringToMessage(const std::string& input, google::protobuf::Message* message) { google::protobuf::util::JsonParseOptions json_parse_options; json_parse_options.ignore_unknown_fields = true; auto status = google::protobuf::util::JsonStringToMessage(input, message, json_parse_options); if (!status.ok()) { LOG(ERROR) << "Failed to parse from JSON: " << input << " error: " << status.error_message(); return false; } return true; } } // namespace media } // namespace shaka
31.209302
80
0.68927
46fc87995f5fde8b171405aa8a3901dc788264c8
1,186
cpp
C++
SRC/2018ICPC/Web_XuZhou/H.cpp
YouDad/ACM
ac26e0b360267943af32692629d6c34e739ee70d
[ "MIT" ]
2
2018-07-27T08:09:48.000Z
2018-09-26T16:36:37.000Z
SRC/2018ICPC/Web_XuZhou/H.cpp
YouDad/ACM
ac26e0b360267943af32692629d6c34e739ee70d
[ "MIT" ]
null
null
null
SRC/2018ICPC/Web_XuZhou/H.cpp
YouDad/ACM
ac26e0b360267943af32692629d6c34e739ee70d
[ "MIT" ]
null
null
null
// https://nanti.jisuanke.com/t/31460 #include<stdio.h> #include<string.h> typedef long long ll; const int maxn=100005; ll arr[(1<<18)+2],iarr[(1<<18)+2],M; void update(ll*a,int x,ll val){ for(a[x+=M]=val,x/=2;x;x/=2) a[x]=a[2*x]+a[2*x+1]; } ll query(ll*a,int l,int r){ ll ans=0; for(l+=M-1,r+=M+1;l^r^1;l/=2,r/=2){ if(~l&1)ans+=a[l^1]; if( r&1)ans+=a[r^1]; } return ans; } int main(){ #ifdef LOCAL_DEBUG freopen("E:/ACM/SRC/1.txt","r",stdin); #endif for(int n,q;~scanf("%d%d",&n,&q);){ M=1;while(M-2<n)M*=2; for(int i=M+1;i<=M+n;i++) scanf("%lld",arr+i); for(int i=M+1;i<=M+n;i++) iarr[i]=arr[i]*(M+n+1-i); for(int i=M;i;i--) arr[i]=arr[i*2]+arr[i*2+1], iarr[i]=iarr[i*2]+iarr[i*2+1]; for(int op,l;q--;){ ll r; scanf("%d%d%lld",&op,&l,&r); if(op==1){ ll ret1=query(arr,l,r); ll ret2=query(iarr,l,r); printf("%lld\n",ret2-ret1*(n-r)); }else{ update(arr,l,r); update(iarr,l,(n+1-l)*r); } } } return 0; }
25.782609
49
0.436762
46fd94f34eb507d75cdb0864c86d48bb91ffe0fc
1,936
cc
C++
app/oxs/base/lock.cc
ViennaNovoFlop/ViennaNovoFlop-dev
f8c4d6c06590a0d9a3890d81e9b0b4dcb7ea9e00
[ "TCL", "SWL", "MIT", "X11", "BSD-3-Clause" ]
null
null
null
app/oxs/base/lock.cc
ViennaNovoFlop/ViennaNovoFlop-dev
f8c4d6c06590a0d9a3890d81e9b0b4dcb7ea9e00
[ "TCL", "SWL", "MIT", "X11", "BSD-3-Clause" ]
null
null
null
app/oxs/base/lock.cc
ViennaNovoFlop/ViennaNovoFlop-dev
f8c4d6c06590a0d9a3890d81e9b0b4dcb7ea9e00
[ "TCL", "SWL", "MIT", "X11", "BSD-3-Clause" ]
null
null
null
/* FILE: lock.cc -*-Mode: c++-*- * * Data structure locking class * */ #include "oc.h" #include "lock.h" #include "oxsexcept.h" OC_USE_STD_NAMESPACE; // Specify std namespace, if supported /* End includes */ OC_UINT4m Oxs_Lock::id_count=0; Oxs_Lock::~Oxs_Lock() { if(write_lock>0) OXS_THROW(Oxs_BadLock,"Delete with open write lock"); if(read_lock>0) OXS_THROW(Oxs_BadLock,"Delete with open read lock(s)"); if(dep_lock>0) OXS_THROW(Oxs_BadLock,"Delete with open dep lock(s)"); obj_id=0; } // Assignment operator does not copy lock counts, but // does check access restrictions. obj_id is copied // if there are no outstanding locks and obj_id>0. Oxs_Lock& Oxs_Lock::operator=(const Oxs_Lock& other) { if(read_lock>0) OXS_THROW(Oxs_BadLock,"Assignment attempt over open read lock(s)"); if(write_lock==0) { // This is the no-lock situation if(other.obj_id!=0) { obj_id = other.obj_id; } else { // Take the next valid id if((obj_id = ++id_count)==0) { obj_id = ++id_count; // Safety // Wrap around. For now make this fatal. OXS_THROW(Oxs_BadLock,"Lock count id overflow."); } } } // if write_lock>0, then presumably obj_id is already 0. return *this; } OC_BOOL Oxs_Lock::SetDepLock() { ++dep_lock; return 1; } OC_BOOL Oxs_Lock::ReleaseDepLock() { if(dep_lock<1) return 0; --dep_lock; return 1; } OC_BOOL Oxs_Lock::SetReadLock() { if(write_lock) return 0; ++read_lock; return 1; } OC_BOOL Oxs_Lock::ReleaseReadLock() { if(read_lock<1) return 0; --read_lock; return 1; } OC_BOOL Oxs_Lock::SetWriteLock() { if(read_lock>0 || write_lock>0) return 0; write_lock=1; obj_id=0; return 1; } OC_BOOL Oxs_Lock::ReleaseWriteLock() { if(write_lock!=1) return 0; if((obj_id = ++id_count)==0) { // Wrap around. Might want to issue a warning. obj_id = ++id_count; } write_lock=0; return 1; }
19.555556
71
0.658058
46fe7414e6a5c9bc077c601133632078f87b21aa
6,197
cc
C++
libsrc/pylith/faults/FaultCohesiveTract.cc
joegeisz/pylith
f74060b7b19d7e90abf8597bbe9250c96593c0ad
[ "MIT" ]
1
2021-01-20T17:18:28.000Z
2021-01-20T17:18:28.000Z
libsrc/pylith/faults/FaultCohesiveTract.cc
joegeisz/pylith
f74060b7b19d7e90abf8597bbe9250c96593c0ad
[ "MIT" ]
null
null
null
libsrc/pylith/faults/FaultCohesiveTract.cc
joegeisz/pylith
f74060b7b19d7e90abf8597bbe9250c96593c0ad
[ "MIT" ]
null
null
null
// -*- C++ -*- // // ---------------------------------------------------------------------- // // Brad T. Aagaard, U.S. Geological Survey // Charles A. Williams, GNS Science // Matthew G. Knepley, University of Chicago // // This code was developed as part of the Computational Infrastructure // for Geodynamics (http://geodynamics.org). // // Copyright (c) 2010-2017 University of California, Davis // // See COPYING for license information. // // ---------------------------------------------------------------------- // #include <portinfo> #include "FaultCohesiveTract.hh" // implementation of object methods #include "CohesiveTopology.hh" // USES CohesiveTopology #include "pylith/topology/Fields.hh" // USES Fields #include "pylith/topology/Field.hh" // USES Field #include "pylith/topology/Stratum.hh" // USES StratumIS #include "pylith/feassemble/Quadrature.hh" // USES Quadrature #include <cassert> // USES assert() #include <sstream> // USES std::ostringstream #include <stdexcept> // USES std::runtime_error // ---------------------------------------------------------------------- // Default constructor. pylith::faults::FaultCohesiveTract::FaultCohesiveTract(void) { // constructor _useLagrangeConstraints = false; } // constructor // ---------------------------------------------------------------------- // Destructor. pylith::faults::FaultCohesiveTract::~FaultCohesiveTract(void) { // destructor deallocate(); } // destructor // ---------------------------------------------------------------------- // Deallocate PETSc and local data structures. void pylith::faults::FaultCohesiveTract::deallocate(void) { // deallocate PYLITH_METHOD_BEGIN; FaultCohesive::deallocate(); PYLITH_METHOD_END; } // deallocate // ---------------------------------------------------------------------- // Initialize fault. Determine orientation and setup boundary void pylith::faults::FaultCohesiveTract::initialize(const topology::Mesh& mesh, const PylithScalar upDir[3]) { // initialize PYLITH_METHOD_BEGIN; assert(upDir); assert(_quadrature); delete _faultMesh; _faultMesh = new topology::Mesh(); CohesiveTopology::createFaultParallel(_faultMesh, mesh, id(), label(), useLagrangeConstraints()); // Reset fields. delete _fields; _fields = new topology::Fields(*_faultMesh);assert(_fields); // Initialize quadrature geometry. _quadrature->initializeGeometry(); PYLITH_METHOD_END; } // initialize // ---------------------------------------------------------------------- // Integrate contribution of cohesive cells to residual term. void pylith::faults::FaultCohesiveTract::integrateResidual(const topology::Field& residual, const PylithScalar t, topology::SolutionFields* const fields) { // integrateResidual throw std::logic_error("FaultCohesiveTract::integrateResidual() not implemented."); } // integrateResidual // ---------------------------------------------------------------------- // Compute Jacobian matrix (A) associated with operator. void pylith::faults::FaultCohesiveTract::integrateJacobian(topology::Jacobian* jacobian, const PylithScalar t, topology::SolutionFields* const fields) { // integrateJacobian throw std::logic_error("FaultCohesiveTract::integrateJacobian() not implemented."); _needNewJacobian = false; } // integrateJacobian // ---------------------------------------------------------------------- // Verify configuration is acceptable. void pylith::faults::FaultCohesiveTract::verifyConfiguration(const topology::Mesh& mesh) const { // verifyConfiguration PYLITH_METHOD_BEGIN; assert(_quadrature); const PetscDM dmMesh = mesh.dmMesh();assert(dmMesh); PetscBool hasLabel = PETSC_FALSE; PetscErrorCode err = DMHasLabel(dmMesh, label(), &hasLabel);PYLITH_CHECK_ERROR(err); if (!hasLabel) { std::ostringstream msg; msg << "Mesh missing group of vertices '" << label() << " for boundary condition."; throw std::runtime_error(msg.str()); } // if // check compatibility of mesh and quadrature scheme const int dimension = mesh.dimension()-1; if (_quadrature->cellDim() != dimension) { std::ostringstream msg; msg << "Dimension of reference cell in quadrature scheme (" << _quadrature->cellDim() << ") does not match dimension of cells in mesh (" << dimension << ") for fault '" << label() << "'."; throw std::runtime_error(msg.str()); } // if const int numCorners = _quadrature->refGeometry().numCorners(); const bool includeOnlyCells = true; topology::StratumIS cohesiveIS(dmMesh, "material-id", id(), includeOnlyCells); const PetscInt* cells = cohesiveIS.points(); const PetscInt ncells = cohesiveIS.size(); PetscInt coneSize = 0; for (PetscInt i=0; i < ncells; ++i) { err = DMPlexGetConeSize(dmMesh, cells[i], &coneSize);PYLITH_CHECK_ERROR(err); // TODO: Should be changed to Closure() if (2*numCorners != coneSize) { // No Lagrange vertices, just negative and positive sides of the // fault, so coneSize is 2*numCorners. std::ostringstream msg; msg << "Number of vertices in reference cell (" << numCorners << ") is not compatible with number of vertices (" << coneSize << ") in cohesive cell " << cells[i] << " for fault '" << label() << "'."; throw std::runtime_error(msg.str()); } // if } // for PYLITH_METHOD_END; } // verifyConfiguration // ---------------------------------------------------------------------- // Get vertex field associated with integrator. const pylith::topology::Field& pylith::faults::FaultCohesiveTract::vertexField(const char* name, const topology::SolutionFields* fields) { // vertexField throw std::logic_error("FaultCohesiveTract::vertexField() not implemented."); } // vertexField // ---------------------------------------------------------------------- // Get cell field associated with integrator. const pylith::topology::Field& pylith::faults::FaultCohesiveTract::cellField(const char* name, const topology::SolutionFields* fields) { // cellField throw std::logic_error("FaultCohesiveTract::cellField() not implemented."); } // cellField // End of file
34.237569
99
0.619977
46ffcc9c9c990a00d3ce0571090b9f9ef3d5f5e1
507
cpp
C++
p205/p205.cpp
suzyz/leetcode_practice
e22dc5a81e065dc962e5561b14ac84b9a2302e8a
[ "MIT" ]
1
2019-10-07T05:00:21.000Z
2019-10-07T05:00:21.000Z
p205/p205.cpp
suzyz/leetcode_practice
e22dc5a81e065dc962e5561b14ac84b9a2302e8a
[ "MIT" ]
null
null
null
p205/p205.cpp
suzyz/leetcode_practice
e22dc5a81e065dc962e5561b14ac84b9a2302e8a
[ "MIT" ]
null
null
null
class Solution { public: bool isIsomorphic(string s, string t) { if (s.length() != t.length()) return false; int n = s.length(); vector<char> from(260,'#'),to(260,'#'); for (int i = 0; i < n; ++i) { if (from[t[i]] == '#' && to[s[i]] == '#') { from[t[i]] = s[i]; to[s[i]] = t[i]; } else if (from[t[i]] != s[i] || to[s[i]] != t[i]) return false; } return true; } };
22.043478
52
0.368836
2000447c0fe485a0d3201f67bb26167f3660ef5a
1,036
cpp
C++
platform/android/src/geojson/point.cpp
mueschm/mapbox-gl-native
b07db0f8d01f855dcd336aa1baabde94c5c1740d
[ "BSL-1.0", "Apache-2.0" ]
316
2021-02-05T10:34:35.000Z
2022-03-23T21:58:39.000Z
platform/android/src/geojson/point.cpp
mueschm/mapbox-gl-native
b07db0f8d01f855dcd336aa1baabde94c5c1740d
[ "BSL-1.0", "Apache-2.0" ]
187
2021-02-11T10:39:30.000Z
2022-03-31T21:59:47.000Z
platform/android/src/geojson/point.cpp
mueschm/mapbox-gl-native
b07db0f8d01f855dcd336aa1baabde94c5c1740d
[ "BSL-1.0", "Apache-2.0" ]
93
2021-02-04T09:39:14.000Z
2022-03-31T04:03:56.000Z
#include "point.hpp" namespace mbgl { namespace android { namespace geojson { jni::Local<jni::Object<Point>> Point::New(jni::JNIEnv& env, const mbgl::Point<double>& point) { static auto& javaClass = jni::Class<Point>::Singleton(env); static auto method = javaClass.GetStaticMethod<jni::Object<Point> (jni::jdouble, jni::jdouble)>(env, "fromLngLat"); return javaClass.Call(env, method, point.x, point.y); } mbgl::Point<double> Point::convert(jni::JNIEnv &env, const jni::Object<Point>& jPoint) { static auto& javaClass = jni::Class<Point>::Singleton(env); static auto longitude = javaClass.GetMethod<jni::jdouble ()>(env, "longitude"); static auto latitude = javaClass.GetMethod<jni::jdouble ()>(env, "latitude"); if (!jPoint) { return {}; } return { jPoint.Call(env, longitude), jPoint.Call(env, latitude) }; } void Point::registerNative(jni::JNIEnv &env) { jni::Class<Point>::Singleton(env); } } // namespace geojson } // namespace android } // namespace mbgl
29.6
119
0.666023