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
109
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
listlengths 1
9
| max_stars_count
int64 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
int64 1
48.5k
⌀ | 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
int64 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
330k
| max_line_length
int64 6
990k
| alphanum_fraction
float64 0.01
0.99
| author_id
stringlengths 2
40
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
46f870a5ccfe3c9e560ab0b5a011273393cd1b42
| 492
|
cpp
|
C++
|
Camp_1-2563/Problems/Anyway.cpp
|
MasterIceZ/POSN_BUU
|
56e176fb843d7ddcee0cf4acf2bb141576c260cf
|
[
"MIT"
] | null | null | null |
Camp_1-2563/Problems/Anyway.cpp
|
MasterIceZ/POSN_BUU
|
56e176fb843d7ddcee0cf4acf2bb141576c260cf
|
[
"MIT"
] | null | null | null |
Camp_1-2563/Problems/Anyway.cpp
|
MasterIceZ/POSN_BUU
|
56e176fb843d7ddcee0cf4acf2bb141576c260cf
|
[
"MIT"
] | null | null | null |
#include<bits/stdc++.h>
using namespace std;
#define endl '\n'
int dp[1010][1010];
int main (){
ios::sync_with_stdio(0);
cin.tie(0);
int x, y, k;
cin >> x >> y >> k;
while(k--){
int a, b;
cin >> a >> b;
dp[a+1][b+1] = -1;
}
x++, y++;
dp[1][0] = 1;
for(int i=1; i<=x; ++i){
for(int j=1; j<=y; ++j){
if(dp[i][j] == -1){
dp[i][j] = 0;
}
else{
dp[i][j] = dp[i-1][j] + dp[i][j-1];
dp[i][j] %= 1000000;
}
}
}
cout << dp[x][y] << endl;
return 0;
}
| 14.057143
| 39
| 0.434959
|
MasterIceZ
|
46fc372a48840546fae2a5dc74795e817650969f
| 238
|
cpp
|
C++
|
In-Class Excercise/170319/Program 3/Program-3.cpp
|
skyclasher/Teknik-Pengaturcaraan-2
|
4895824d8c1a70654c312fd793c860cb8f05f12c
|
[
"Apache-2.0"
] | null | null | null |
In-Class Excercise/170319/Program 3/Program-3.cpp
|
skyclasher/Teknik-Pengaturcaraan-2
|
4895824d8c1a70654c312fd793c860cb8f05f12c
|
[
"Apache-2.0"
] | null | null | null |
In-Class Excercise/170319/Program 3/Program-3.cpp
|
skyclasher/Teknik-Pengaturcaraan-2
|
4895824d8c1a70654c312fd793c860cb8f05f12c
|
[
"Apache-2.0"
] | null | null | null |
#include <iostream>
using namespace std;
int main()
{
int numbers[] = {
10,20,30,40,50
};
int *valnumbers = numbers;
for(int i = 0; i < 5; i++){
cout << "Element-" << i << " : " << *(valnumbers+i) << endl;
}
return 0;
}
| 14
| 63
| 0.521008
|
skyclasher
|
2002de30a313f7d7db009663b8c1816227167e62
| 7,594
|
cpp
|
C++
|
Src/oDLNode.cpp
|
BastiaanOlij/omnis.xcomp.widget
|
629b203f4bd6d1e1e408f1b2ed3de4eaf45d0e1a
|
[
"MIT"
] | 1
|
2018-08-09T23:44:54.000Z
|
2018-08-09T23:44:54.000Z
|
Src/oDLNode.cpp
|
BastiaanOlij/omnis.xcomp.widget
|
629b203f4bd6d1e1e408f1b2ed3de4eaf45d0e1a
|
[
"MIT"
] | 2
|
2015-01-20T03:51:53.000Z
|
2020-03-27T04:45:38.000Z
|
Src/oDLNode.cpp
|
BastiaanOlij/omnis.xcomp.widget
|
629b203f4bd6d1e1e408f1b2ed3de4eaf45d0e1a
|
[
"MIT"
] | 1
|
2018-09-13T05:07:08.000Z
|
2018-09-13T05:07:08.000Z
|
/*
* omnis.xcomp.widget
* ===================
*
* oDLNode.cpp
* Implementation of our datalist node object
*
* Bastiaan Olij
*/
#include "oDLNode.h"
oDLNode::oDLNode(void) {
mTouched = true;
mExpanded = true;
mLineNo = 0;
mValue = QTEXT("");
mDescription = QTEXT("");
mTop = 0;
mBottom = 0;
mSortOrder = 0;
mListLineNo = -1;
};
oDLNode::oDLNode(const qstring & pValue, const qstring & pDescription, qlong pLineNo) {
mTouched = true;
mExpanded = true;
mLineNo = pLineNo;
mValue = pValue;
mDescription = pDescription;
mTop = 0;
mBottom = 0;
mSortOrder = 0;
mListLineNo = -1;
};
oDLNode::~oDLNode(void) {
clearChildNodes();
};
////////////////////////////////////////////////
// properties
////////////////////////////////////////////////
// touched?
bool oDLNode::touched(void) {
return mTouched;
};
// set value of touched
void oDLNode::setTouched(bool pTouched) {
mTouched = pTouched;
};
// expanded?
bool oDLNode::expanded(void) {
return mExpanded;
};
// set expanded
void oDLNode::setExpanded(bool pExpanded) {
mExpanded = pExpanded;
};
// related line number
qlong oDLNode::lineNo(void) {
return mLineNo;
};
// update the related line number
void oDLNode::setLineNo(qlong pLineNo) {
mLineNo = pLineNo;
};
// our sort order
qlong oDLNode::sortOrder(void) {
return mSortOrder;
};
// set our sort order
void oDLNode::setSortOrder(qlong pSortOrder) {
mSortOrder = pSortOrder;
};
////////////////////////////////////////////////
// for our drawing
////////////////////////////////////////////////
// drawn as visible line no
qlong oDLNode::listLineNo(void) {
return mListLineNo;
};
// set visible line no
void oDLNode::setListLineNo(qlong pLineNo) {
mListLineNo=pLineNo;
};
// top of our node
qdim oDLNode::top(void) {
return mTop;
};
// set the top of our node
void oDLNode::setTop(qdim pTop) {
mTop = pTop;
};
// bottom of our node
qdim oDLNode::bottom(void) {
return mBottom;
};
// set bottom of our node
void oDLNode::setBottom(qdim pBottom) {
mBottom = pBottom;
};
// our tree icon rectangle
qrect oDLNode::treeIconRect(void) {
return mTreeIconRect;
};
// set our tree icon rectangle
void oDLNode::setTreeIconRect(qrect pRect) {
mTreeIconRect = pRect;
};
////////////////////////////////////////////////
// read only info
////////////////////////////////////////////////
// value
const qstring & oDLNode::value(void) {
return mValue;
};
// description
const qstring & oDLNode::description(void) {
return mDescription;
};
// is this point within our tree icon?
bool oDLNode::aboveTreeIcon(qpoint pAt) {
if (mChildNodes.size()==0) {
return false;
} else {
return ((mTreeIconRect.left <= pAt.h) && (mTreeIconRect.right >= pAt.h) && (mTreeIconRect.top <= pAt.v) && (mTreeIconRect.bottom >= pAt.v));
};
};
////////////////////////////////////////////////
// methods
////////////////////////////////////////////////
// Clear all the child nodes
void oDLNode::clearChildNodes() {
// free all the children!
while (mChildNodes.size()>0) {
oDLNode *child = mChildNodes.back(); // get the last on our stack
mChildNodes.pop_back(); // and remove it from our stack
delete child;
};
};
// Add this node
void oDLNode::addNode(oDLNode * pNewNode) {
mChildNodes.push_back(pNewNode);
};
// Returns the number of child nodes
unsigned long oDLNode::childNodeCount() {
return mChildNodes.size();
};
// Find a child node by value
oDLNode * oDLNode::findChildByValue(const qstring & pValue) {
for (unsigned long index = 0; index < mChildNodes.size(); index++) {
oDLNode *child = mChildNodes[index];
if (pValue == child->value()) {
return child;
};
};
return NULL;
};
// Find a child node by description
oDLNode * oDLNode::findChildByDescription(const qstring & pDesc, bool pNoValue) {
for (unsigned long index = 0; index < mChildNodes.size(); index++) {
oDLNode *child = mChildNodes[index];
if ((pDesc == child->description()) && (!pNoValue || (child->value().length()==0))) {
return child;
};
};
return NULL;
};
// Find a child node by description
oDLNode * oDLNode::findChildByLineNo(qlong pLineNo, bool pNoValue) {
for (unsigned long index = 0; index < mChildNodes.size(); index++) {
oDLNode *child = mChildNodes[index];
if ((child->lineNo() == pLineNo) && (!pNoValue || (child->value().length()==0))) {
return child;
};
};
return NULL;
};
// Find a child node by screen location
oDLNode * oDLNode::findChildByPoint(qpoint pAt) {
for (unsigned long index = 0; index < mChildNodes.size(); index++) {
oDLNode *child = mChildNodes[index];
if ((child->mTop <= pAt.v) && (child->mBottom > pAt.v)) {
// Our point lies within this child, see if it lies within one of its children
oDLNode *subchild = child->findChildByPoint(pAt);
if (subchild != NULL) {
return subchild;
};
return child;
};
};
return NULL;
};
// Get child at specific index
oDLNode * oDLNode::getChildByIndex(unsigned long pIndex) {
if (pIndex < mChildNodes.size()) {
return mChildNodes[pIndex];
} else {
return NULL;
};
};
// Get our list line no for a line in our source list
qlong oDLNode::findListLineNo(qlong pLineNo) {
if (mLineNo == pLineNo) {
return mListLineNo;
};
if (mExpanded) {
// check our child nodes..
for (unsigned long index = 0; index < mChildNodes.size(); index++) {
oDLNode *child = mChildNodes[index];
qlong listLineNo = child->findListLineNo(pLineNo);
if (listLineNo>=0) {
// found it!
return listLineNo;
};
};
} else {
// not expanded? then we're not showing anything..
};
return -1;
};
// Find top position for specific line (will check child nodes if applicable)
qdim oDLNode::findTopForLine(qlong pLineNo) {
if (mLineNo == pLineNo) {
return mTop;
};
if (mExpanded) {
// check our child nodes..
for (unsigned long index = 0; index < mChildNodes.size(); index++) {
oDLNode *child = mChildNodes[index];
qdim top = child->findTopForLine(pLineNo);
if (top>=0) {
// found it!
return top;
};
};
} else {
// not expanded? then we're not showing anything..
};
return -1; // our positions start at the top..
};
// Static function that returns whether true if the sort order of A is smaller then B
bool oDLNode::order(oDLNode * pA, oDLNode * pB) {
if (pB == NULL) {
return false;
} else if (pA == NULL) {
return true;
};
return pA->mSortOrder < pB->mSortOrder;
};
// Sort our child nodes
void oDLNode::sortChildren(void) {
// sort our children
std::sort(mChildNodes.begin(), mChildNodes.end(), oDLNode::order);
// now tell our children to also sort
for (unsigned long index = 0; index < mChildNodes.size(); index++) {
oDLNode *child = mChildNodes[index];
child->sortChildren();
};
};
// Marks all children as untouched and remove any line nodes
void oDLNode::unTouchChildren(void) {
for (unsigned long index = 0; index < mChildNodes.size(); index++) {
oDLNode *child = mChildNodes[index];
child->setTouched(false);
child->unTouchChildren();
};
mListLineNo = -1; // reset this
// if this is a node created by our grouping, clear our related line and sort
if (mValue.length()!=0 || mDescription.length()!=0) {
mLineNo = 0;
mSortOrder = 0;
};
};
// Removes children that are untouched
void oDLNode::removeUntouched(void) {
unsigned long index = 0;
while (index < mChildNodes.size()) {
oDLNode * child = mChildNodes[index];
if (child->touched()) {
child->removeUntouched();
index++;
} else {
mChildNodes.erase(mChildNodes.begin() + index);
delete child;
};
};
};
| 22.204678
| 144
| 0.628523
|
BastiaanOlij
|
200785b3c06f7560ce9fe52f56e1ee08a28ef401
| 52
|
cpp
|
C++
|
Xlet.Wallet/lib/Xlet.Crypto.Base/src/ICrypto.cpp
|
MattPearce/xlet
|
e0f64f231e627d0cc52f3c032e66f59a63b2942f
|
[
"MIT"
] | 3
|
2020-11-29T03:14:36.000Z
|
2021-04-14T16:45:46.000Z
|
Xlet.Wallet/lib/Xlet.Crypto.Base/src/ICrypto.cpp
|
MattPearce/xlet
|
e0f64f231e627d0cc52f3c032e66f59a63b2942f
|
[
"MIT"
] | 2
|
2020-06-18T18:45:00.000Z
|
2020-06-26T08:04:43.000Z
|
Xlet.Wallet/lib/Xlet.Crypto.Base/src/ICrypto.cpp
|
MattPearce/xlet
|
e0f64f231e627d0cc52f3c032e66f59a63b2942f
|
[
"MIT"
] | 3
|
2020-11-30T21:04:50.000Z
|
2021-05-04T18:14:39.000Z
|
#include "ICrypto.h"
// Dummy file to trigger build
| 17.333333
| 30
| 0.730769
|
MattPearce
|
2007d5f8480343b29a44f164ffe86abf8f193587
| 18,302
|
cpp
|
C++
|
Algorithm/cloth/graph/Graph2Mesh.cpp
|
dolphin-li/ClothDesigner
|
82b186d6db320b645ac67a4d32d7746cc9bdd391
|
[
"MIT"
] | 32
|
2016-12-13T05:49:12.000Z
|
2022-02-04T06:15:47.000Z
|
Algorithm/cloth/graph/Graph2Mesh.cpp
|
dolphin-li/ClothDesigner
|
82b186d6db320b645ac67a4d32d7746cc9bdd391
|
[
"MIT"
] | 2
|
2019-07-30T02:01:16.000Z
|
2020-03-12T15:06:51.000Z
|
Algorithm/cloth/graph/Graph2Mesh.cpp
|
dolphin-li/ClothDesigner
|
82b186d6db320b645ac67a4d32d7746cc9bdd391
|
[
"MIT"
] | 18
|
2017-11-16T13:37:06.000Z
|
2022-03-11T08:13:46.000Z
|
#include "Graph2Mesh.h"
#include "ldpMat\ldp_basic_mat.h"
#include "cloth\clothPiece.h"
#include "cloth\graph\Graph.h"
#include "cloth\graph\GraphsSewing.h"
#include "cloth\graph\AbstractGraphCurve.h"
#include "cloth\graph\GraphLoop.h"
#include "cloth\TransformInfo.h"
#include "Renderable\ObjMesh.h"
#include "kdtree\PointTree.h"
extern "C"{
#include "triangle\triangle.h"
};
namespace ldp
{
inline float calcForwardBackwardConsistentStep(float step)
{
step = std::max(0.f, std::min(1.f, step));
int n = std::lroundf(1.f/step);
return 1.f / float(n);
}
static int findParamRange(float t, const std::vector<float>& ranges)
{
int bg = 0, ed = (int)ranges.size() - 1;
while (bg < ed)
{
float tb = ranges[bg];
float te = ranges[ed];
if (t <= te && t >= tb && ed - bg == 1)
return bg;
int mid = (bg + ed) / 2;
float tm = ranges[mid];
if (t <= tm && t >= tb)
ed = mid;
else if (t >= tm && t <= te)
bg = mid;
else
return -1;
}
return -1;
}
Graph2Mesh::Graph2Mesh()
{
m_in = new triangulateio;
m_out = new triangulateio;
m_vro = new triangulateio;
init_trianglulateio(m_in);
init_trianglulateio(m_out);
init_trianglulateio(m_vro);
}
Graph2Mesh::~Graph2Mesh()
{
reset_triangle_struct(m_in);
m_out->numberofholes = 0;
m_out->holelist = nullptr;
reset_triangle_struct(m_out);
reset_triangle_struct(m_vro);
delete m_in;
delete m_out;
delete m_vro;
}
void Graph2Mesh::triangulate(
std::vector<std::shared_ptr<ClothPiece>>& pieces,
std::vector<std::shared_ptr<GraphsSewing>>& sewings,
float pointMergeThre,
float triangleSize,
float pointOnLineThre
)
{
m_pieces = &pieces;
m_sewings = &sewings;
m_ptMergeThre = pointMergeThre;
m_ptOnLineThre = pointOnLineThre;
m_triSize = triangleSize;
precomputeSewing();
for (auto& piece : (*m_pieces))
{
piece->mesh2d().clear();
piece->mesh3d().clear();
piece->mesh3dInit().clear();
auto& panel = piece->graphPanel();
panel.makeGraphValid();
auto bloop = panel.getBoundingLoop();
if (bloop == nullptr)
continue;
prepareTriangulation();
// add bounding loop as the outer poly
addPolygon(*bloop);
// add other closed loops as the darts
for (auto loop_iter = panel.loop_begin(); loop_iter != panel.loop_end(); ++loop_iter)
{
if (loop_iter->isClosed() && loop_iter != bloop)
addDart(*loop_iter);
} // end for loop iter
// add inner lines
for (auto loop_iter = panel.loop_begin(); loop_iter != panel.loop_end(); ++loop_iter)
{
if (!loop_iter->isClosed())
addLine(*loop_iter); // ldp todo: add dart?
} // end for loop iter
finalizeTriangulation();
generateMesh(*piece.get());
} // end for piece
postComputeSewing();
removeIsolateVerts();
}
void Graph2Mesh::prepareTriangulation()
{
reset_triangle_struct(m_in);
m_out->numberofholes = 0;
m_out->holelist = nullptr;
reset_triangle_struct(m_out);
reset_triangle_struct(m_vro);
m_points.clear();
m_segments.clear();
m_holeCenters.clear();
m_triBuffer.clear();
m_triVertsBuffer.clear();
}
void Graph2Mesh::precomputeSewing()
{
const float step = m_triSize;
const float thre = m_ptMergeThre;
m_shapeSegs.clear();
m_segPairs.clear();
m_segStepMap.clear();
// 1. convert each shape to a segment, without considering the sewings
for (auto& piece : (*m_pieces))
{
const auto& panel = piece->graphPanel();
for (auto iter = panel.curve_begin(); iter != panel.curve_end(); ++iter)
{
createShapeSeg(iter, calcForwardBackwardConsistentStep(step / iter->getLength()));
m_shapePieceMap[iter] = piece.get();
}
} // end for piece
// 2. split a shape segment to multiple based on the M-N sew matching.
// after this step, the sewing must be 1-to-1 correspondence
// LDP NOTES: seems AB + AC sewing cannot be handled.
std::vector<float> fLens, sLens;
for (const auto& sew : *m_sewings)
{
if (sew->empty())
continue;
const auto& firsts = sew->firsts();
const auto& seconds = sew->seconds();
// update param
fLens.clear();
sLens.clear();
fLens.push_back(0);
sLens.push_back(0);
for (const auto& f : firsts)
fLens.push_back(fLens.back() + f.curve->getLength());
for (const auto& s : seconds)
sLens.push_back(sLens.back() + s.curve->getLength());
for (auto& f : fLens)
f /= fLens.back();
for (auto& s : sLens)
s /= sLens.back();
size_t fPos = 0, sPos = 0;
for (; fPos+1 < fLens.size() && sPos+1 < sLens.size();)
{
const float fStart = fLens[fPos], fEnd = fLens[fPos + 1];
const float sStart = sLens[sPos], sEnd = sLens[sPos + 1];
const float fLen = fEnd - fStart, sLen = sEnd - sStart;
const auto& fUnit = firsts[fPos];
const auto fShape = fUnit.curve;
auto& fSegs = m_shapeSegs[fShape];
const auto& sUnit = seconds[sPos];
const auto sShape = sUnit.curve;
auto& sSegs = m_shapeSegs[sShape];
size_t fPos_1 = fSegs->size() - 1;
size_t sPos_1 = sSegs->size() - 1;
if (fUnit.reverse)
fPos_1 = 0;
if (sUnit.reverse)
sPos_1 = 0;
if (fabs(fEnd - sEnd) < thre)
{
fPos++;
sPos++;
} // end if f, s too close
else if (fEnd > sEnd)
{
float local = (sEnd - fStart) / fLen;
if (fUnit.reverse)
local = 1.f - local;
fPos_1 = addSegToShape(*fSegs.get(), local) + fUnit.reverse;
sPos++;
} // end if f > s
else
{
float local = (fEnd - sStart) / sLen;
if (sUnit.reverse)
local = 1.f - local;
sPos_1 = addSegToShape(*sSegs.get(), local) + sUnit.reverse;
fPos++;
} // end else f < s
const float minStep = calcForwardBackwardConsistentStep(
std::min((*fSegs)[fPos_1]->step, (*sSegs)[sPos_1]->step));
updateSegStepMap((*fSegs)[fPos_1].get(), minStep);
updateSegStepMap((*sSegs)[sPos_1].get(), minStep);
m_segPairs.push_back(SegPair(fSegs->at(fPos_1).get(), fUnit.reverse,
sSegs->at(sPos_1).get(), sUnit.reverse, (size_t)sew->getSewingType(), sew->getAngleInDegree()));
} // end for fPos, sPos
} // end for sew
// 3. perform resampling, such that each sewing pair share the same sample points
for (auto& pair : m_segPairs)
{
for (int k = 0; k < 2; k++)
{
float step = m_segStepMap[pair.seg[k]];
resampleSeg(*pair.seg[k], step);
}
} // end for pair
}
void Graph2Mesh::SampleParamVec::reSample(float step)
{
this->step = step;
params.clear();
for (float s = 0.f; s < 1 + step - g_designParam.pointMergeDistThre; s += step)
params.push_back(Graph2Mesh::SampleParam(std::min(1.f, s), -1));
}
void Graph2Mesh::createShapeSeg(const AbstractGraphCurve* shape, float step)
{
auto iter = m_shapeSegs.find(shape);
if (iter == m_shapeSegs.end())
{
ShapeSegsPtr ptr(new ShapeSegs);
ptr->resize(1);
(*ptr)[0].reset(new SampleParamVec);
(*ptr)[0]->shape = shape;
(*ptr)[0]->start = 0;
(*ptr)[0]->end = 1;
(*ptr)[0]->reSample(step);
m_shapeSegs[shape] = ptr;
} // end if iter not found
else
throw std::exception("duplicated shape added!\n");
}
int Graph2Mesh::addSegToShape(ShapeSegs& segs, float tSegs)
{
for (size_t i = 0; i< segs.size(); i++)
{
const float segBegin = segs[i]->start;
const float segEnd = segs[i]->end;
if (tSegs > segBegin && tSegs < segEnd)
{
segs.insert(segs.begin() + i + 1, SampleParamVecPtr(new SampleParamVec()));
auto& oVec = segs[i];
auto& sVec = segs[i + 1];
const float oriStep = oVec->step;
oVec->step = calcForwardBackwardConsistentStep(oriStep * (segEnd - segBegin) / (tSegs - segBegin));
oVec->start = segBegin;
oVec->end = tSegs;
oVec->params.clear();
for (float s = 0.f; s < 1 + oVec->step - 1e-8; s += oVec->step)
oVec->params.push_back(SampleParam(std::min(1.f, s), -1));
sVec->shape = oVec->shape;
sVec->step = calcForwardBackwardConsistentStep(oriStep * (segEnd - segBegin) / (segEnd - tSegs));
sVec->start = tSegs;
sVec->end = segEnd;
sVec->reSample(sVec->step);
return i;
} // end if >, <
} // end for i
return -1;
}
void Graph2Mesh::updateSegStepMap(SampleParamVec* seg, float step)
{
auto iter = m_segStepMap.find(seg);
if (iter == m_segStepMap.end())
{
m_segStepMap.insert(std::make_pair(seg, step));
}
else
{
iter->second = std::min(step, iter->second);
}
}
void Graph2Mesh::resampleSeg(SampleParamVec& seg, float step)
{
if (fabs(seg.step - step) < std::numeric_limits<float>::epsilon())
return;
seg.reSample(step);
}
Float2 Graph2Mesh::addPolygon(const GraphLoop& poly)
{
// build a kdtree for existed points
typedef kdtree::PointTree<float, 2> Tree;
typedef Tree::Point Point;
std::vector<Point> treePoints;
for (int i = 0; i < m_points.size(); i++)
treePoints.push_back(Point(Float2(m_points[i]), i));
Tree tree;
tree.build(treePoints);
// begin
const float step = m_triSize;
const float thre = m_ptMergeThre;
int startIdx = (int)m_points.size();
// add points
std::vector<int> indices;
Float2 center = 0.f;
for (auto edge_iter = poly.edge_begin(); !edge_iter.isEnd(); ++edge_iter)
{
//TODO: reverse edge if needed
auto& shapeSegs = m_shapeSegs[&(*edge_iter)];
int segBegin = 0, segEnd = (int)shapeSegs->size(), segInc = 1;
if (edge_iter.shouldReverse())
{
segBegin = (int)shapeSegs->size() - 1;
segEnd = -1;
segInc = -1;
}
for (int iSeg = segBegin; iSeg != segEnd; iSeg+=segInc)
{
auto& seg = shapeSegs->at(iSeg);
int paramBegin = 0, paramEnd = (int)seg->params.size(), paramInc = 1;
if (edge_iter.shouldReverse())
{
paramBegin = (int)seg->params.size() - 1;
paramEnd = -1;
paramInc = -1;
}
for (int iParam = paramBegin; iParam != paramEnd; iParam += paramInc)
{
auto& sp = seg->params[iParam];
auto p = edge_iter->getPointByParam(sp.t * (seg->end - seg->start) + seg->start);
// if this shape is not used, we create points for it
// else we just use its idx
if (sp.idx == -1)
{
if (m_points.size() != startIdx)
{
if ((m_points.back() - p).length() < thre)
sp.idx = int(m_points.size()) - 1; // merged to the last point
else if ((m_points[startIdx] - p).length() < thre)
sp.idx = startIdx; // merged to the last point
}
if (sp.idx == -1)
{
// if there exists too close points, just use it.
float dist = 0;
auto np = tree.nearestPoint(p, dist);
if (dist < thre)
sp.idx = np.idx;
else
{
sp.idx = int(m_points.size());
m_points.push_back(p);
}
}
} // end if sp.idx == -1
indices.push_back(sp.idx);
center += m_points[sp.idx];
} // end for sp
} // end for p
} // end for edge_iter
// add segments
for (int i = 0; i < (int)indices.size() - 1; i++)
m_segments.push_back(Int2(indices[i], indices[i+1]));
if (indices.size() > 1 && poly.isClosed())
m_segments.push_back(Int2(indices.back(), indices.front()));
if (indices.size())
center /= indices.size();
return center;
}
void Graph2Mesh::addDart(const GraphLoop& poly)
{
Float2 center = addPolygon(poly);
m_holeCenters.push_back(center);
}
void Graph2Mesh::addLine(const GraphLoop& line)
{
addPolygon(line);
}
void Graph2Mesh::finalizeTriangulation()
{
if (m_points.size() < 3)
return;
// init points
m_in->numberofpoints = (int)m_points.size();
if (m_in->numberofpoints)
m_in->pointlist = (REAL *)malloc(m_in->numberofpoints * 2 * sizeof(REAL));
for (int i = 0; i<m_in->numberofpoints; i++)
{
m_in->pointlist[i * 2] = m_points[i][0];
m_in->pointlist[i * 2 + 1] = m_points[i][1];
}
// init segments, unique it before using it.
for (auto& s : m_segments)
{
if (s[0] > s[1])
std::swap(s[0], s[1]);
}
std::sort(m_segments.begin(), m_segments.end());
m_segments.resize(std::unique(m_segments.begin(), m_segments.end())-m_segments.begin());
m_in->numberofsegments = (int)m_segments.size();
if (m_in->numberofsegments)
m_in->segmentlist = (int *)malloc(m_in->numberofsegments * 2 * sizeof(int));
for (int i = 0; i<(int)m_segments.size(); i++)
{
m_in->segmentlist[i * 2] = m_segments[i][0];
m_in->segmentlist[i * 2 + 1] = m_segments[i][1];
}
// init holes
m_in->numberofholes = (int)m_holeCenters.size();
if (m_in->numberofholes)
m_in->holelist = (REAL*)malloc(m_in->numberofholes * 2 * sizeof(REAL));
for (int i = 0; i<m_in->numberofholes; i++)
{
m_in->holelist[i * 2] = m_holeCenters[i][0];
m_in->holelist[i * 2 + 1] = m_holeCenters[i][1];
}
// perform triangulation
const float triAreaWanted = 0.5 * m_triSize * m_triSize;
// Q: quiet
// p: polygon mode
// z: zero based indexing
// q%d: minimum angle %d
// D: delauney
// a%f: maximum triangle area %f
// YY: do not allow additional points inserted on segment
sprintf_s(m_cmds, "Qpzq%da%fYY", 30, triAreaWanted);
::triangulate(m_cmds, m_in, m_out, m_vro);
m_triBuffer.resize(m_out->numberoftriangles);
memcpy(m_triBuffer.data(), m_out->trianglelist, sizeof(int)*m_out->numberoftriangles * 3);
const ldp::Double2* vptr = (const ldp::Double2*)m_out->pointlist;
m_triVertsBuffer.resize(m_out->numberofpoints);
for (int i = 0; i < m_out->numberofpoints; i++)
m_triVertsBuffer[i] = vptr[i];
}
void Graph2Mesh::generateMesh(ClothPiece& piece)
{
auto& mesh2d = piece.mesh2d();
auto& mesh3d = piece.mesh3d();
auto& mesh3dInit = piece.mesh3dInit();
auto& transInfo = piece.transformInfo();
mesh2d.clear();
for (const auto& v : m_triVertsBuffer)
mesh2d.vertex_list.push_back(ldp::Float3(v[0], v[1], 0));
mesh2d.material_list.push_back(ObjMesh::obj_material());
for (const auto& t : m_triBuffer)
{
ObjMesh::obj_face f;
f.vertex_count = 3;
f.material_index = 0;
for (int k = 0; k < f.vertex_count; k++)
f.vertex_index[k] = t[k];
mesh2d.face_list.push_back(f);
}
mesh2d.updateNormals();
mesh2d.updateBoundingBox();
mesh3dInit.cloneFrom(&mesh2d);
transInfo.apply(mesh3dInit);
mesh3d.cloneFrom(&mesh3dInit);
}
void Graph2Mesh::postComputeSewing()
{
// 1. count the verts of each piece and accumulate
m_vertStart.clear();
int vertNum = 0;
for (const auto& piece : *m_pieces)
{
m_vertStart[piece.get()] = vertNum;
vertNum += (int)piece->mesh2d().vertex_list.size();
}
// 2. make stitching
m_stitches.clear();
for (const auto& pair : m_segPairs)
{
std::vector<SampleParam> param0 = pair.seg[0]->params;
std::vector<SampleParam> param1 = pair.seg[1]->params;
assert(param0.size() == param1.size());
if (pair.reverse[0])
std::reverse(param0.begin(), param0.end());
if (pair.reverse[1])
std::reverse(param1.begin(), param1.end());
const size_t n = std::min(param0.size(), param1.size());
for (size_t i = 0; i < n; i++)
{
auto piece0 = m_shapePieceMap[pair.seg[0]->shape];
auto piece1 = m_shapePieceMap[pair.seg[1]->shape];
int s0 = m_vertStart[piece0];
int s1 = m_vertStart[piece1];
int id0 = param0[i].idx + s0;
int id1 = param1[i].idx + s1;
if (id0 == id1)
continue;
m_stitches.push_back(StitchPointPair(id0, id1, pair.type, pair.angle));
}
} // end for pair
}
void Graph2Mesh::removeIsolateVerts()
{
int cntGlobal = 0;
std::vector<int> idxMapGlobal, vertUsed, idxMapLocal;
for (const auto& piece : *m_pieces)
{
auto& mesh = piece->mesh2d();
vertUsed.clear();
vertUsed.resize(mesh.vertex_list.size(), 0);
for (const auto& f : mesh.face_list)
for (int k = 0; k < f.vertex_count; k++)
vertUsed[f.vertex_index[k]] = 1;
auto tmp = mesh.vertex_list;
mesh.vertex_list.clear();
idxMapLocal.clear();
idxMapLocal.resize(tmp.size(), -1);
int cnt = 0;
for (size_t i = 0; i < vertUsed.size(); i++)
{
if (vertUsed[i])
{
idxMapGlobal.push_back(cntGlobal++);
idxMapLocal[i] = cnt++;
mesh.vertex_list.push_back(tmp[i]);
}
else
idxMapGlobal.push_back(-1);
}// end for i
for (auto& f : mesh.face_list)
for (int k = 0; k < f.vertex_count; k++)
f.vertex_index[k] = idxMapLocal[f.vertex_index[k]];
mesh.updateNormals();
mesh.updateBoundingBox();
piece->mesh3dInit().cloneFrom(&mesh);
piece->transformInfo().apply(piece->mesh3dInit());
piece->mesh3d().cloneFrom(&piece->mesh3dInit());
} // end for piece
auto tmp = m_stitches;
m_stitches.clear();
for (auto& st : tmp)
{
int f = idxMapGlobal[st.first];
int s = idxMapGlobal[st.second];
if (f < 0 || s < 0)
continue;
st.first = f;
st.second = s;
m_stitches.push_back(st);
}
}
void Graph2Mesh::reset_triangle_struct(triangulateio* io)const
{
if (io->pointlist) free(io->pointlist); /* In / out */
if (io->pointattributelist) free(io->pointattributelist); /* In / out */
if (io->pointmarkerlist) free(io->pointmarkerlist); /* In / out */
if (io->trianglelist) free(io->trianglelist); /* In / out */
if (io->triangleattributelist) free(io->triangleattributelist); /* In / out */
if (io->trianglearealist) free(io->trianglearealist); /* In only */
if (io->neighborlist) free(io->neighborlist); /* Out only */
if (io->segmentlist) free(io->segmentlist); /* In / out */
if (io->segmentmarkerlist) free(io->segmentmarkerlist); /* In / out */
if (io->holelist) free(io->holelist); /* In / pointer to array copied out */
if (io->regionlist) free(io->regionlist); /* In / pointer to array copied out */
if (io->edgelist) free(io->edgelist); /* Out only */
if (io->edgemarkerlist) free(io->edgemarkerlist); /* Not used with Voronoi diagram; out only */
if (io->normlist) free(io->normlist); /* Used only with Voronoi diagram; out only */
//all set to 0
init_trianglulateio(io);
}
}
| 29.75935
| 114
| 0.616217
|
dolphin-li
|
20114f1841275e0a483482039adcf422ed3b05df
| 4,990
|
cc
|
C++
|
bindings/name_parser/src/wrapper.cc
|
MannPE/KawAnime
|
1829b94752a3cf01773d7d360adb2c18e528fcc8
|
[
"MIT"
] | 611
|
2016-11-21T19:56:50.000Z
|
2022-03-29T11:17:41.000Z
|
bindings/name_parser/src/wrapper.cc
|
MannPE/KawAnime
|
1829b94752a3cf01773d7d360adb2c18e528fcc8
|
[
"MIT"
] | 83
|
2017-03-14T13:41:17.000Z
|
2021-12-31T00:35:24.000Z
|
bindings/name_parser/src/wrapper.cc
|
MannPE/KawAnime
|
1829b94752a3cf01773d7d360adb2c18e528fcc8
|
[
"MIT"
] | 88
|
2016-11-23T18:55:49.000Z
|
2022-03-20T21:52:53.000Z
|
/**
* Copyright (c) 2019 Kylart <kylart.dev@gmail.com>
*
* 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.
*/
#include "wrapper.h"
namespace Wrapper {
void Wrapper::SetInput(Napi::String value, Napi::Env env) {
this->input_ = ToWideString(value, env);
}
void Wrapper::Parse() {
this->anitomy_.Parse(this->input_);
this->parsed_ = this->anitomy_.elements();
}
anitomy::Elements Wrapper::Parsed() { return this->parsed_; }
Napi::Value Wrapper::ParsedResult(Napi::Env env) {
Napi::Object result = Napi::Object::New(env);
return BuildObject(this->parsed_, env);
}
// From https://stackoverflow.com/a/39018368/10611946
std::wstring Wrapper::ToWideString(Napi::String input, Napi::Env env) {
std::wstring result;
std::string _input = input.Utf8Value();
try {
std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
return converter.from_bytes(_input);
} catch(std::range_error& e) {
(void)e;
size_t length = _input.length();
std::wstring result;
result.reserve(length);
for (size_t i = 0; i < length; i++) {
result.push_back(_input[i] & 0xFF);
}
return result;
}
}
std::string Wrapper::ToStr(anitomy::string_t str) {
std::wstring ws_value(str.c_str());
return std::string(ws_value.begin(), ws_value.end());
}
void Wrapper::SetEntry(
Napi::Object object,
Napi::Env env,
const char *entry,
anitomy::Elements elements,
anitomy::ElementCategory pos
) {
Napi::String entry_name = Napi::String::New(env, entry);
switch (elements.count(pos)) {
case 0:
break;
case 1:
object.Set(entry_name.Utf8Value(), ToStr(elements.get(pos)).c_str());
break;
default:
object.Set(entry_name, CategoryArray(elements, pos, env));
}
}
Napi::Array Wrapper::CategoryArray(anitomy::Elements elements, anitomy::ElementCategory pos, Napi::Env env) {
std::vector<anitomy::string_t> category_elements = elements.get_all(pos);
Napi::Array output = Napi::Array::New(env);
unsigned int index = 0;
for (anitomy::string_t value : category_elements) {
output.Set(index, Napi::String::New(env, ToStr(value).c_str()));
index++;
}
return output;
}
Napi::Object Wrapper::BuildObject(anitomy::Elements elements, Napi::Env env) {
Napi::Object result = Napi::Object::New(env);
SetEntry(result, env, "anime_season", elements, anitomy::kElementAnimeSeason);
SetEntry(result, env, "season_prefix", elements, anitomy::kElementAnimeSeasonPrefix);
SetEntry(result, env, "anime_title", elements, anitomy::kElementAnimeTitle);
SetEntry(result, env, "anime_type", elements, anitomy::kElementAnimeType);
SetEntry(result, env, "anime_year", elements, anitomy::kElementAnimeYear);
SetEntry(result, env, "audio_term", elements, anitomy::kElementAudioTerm);
SetEntry(result, env, "device_compatibility", elements, anitomy::kElementDeviceCompatibility);
SetEntry(result, env, "episode_number", elements, anitomy::kElementEpisodeNumber);
SetEntry(result, env, "episode_number_alt", elements, anitomy::kElementEpisodeNumberAlt);
SetEntry(result, env, "episode_prefix", elements, anitomy::kElementEpisodePrefix);
SetEntry(result, env, "episode_title", elements, anitomy::kElementEpisodeTitle);
SetEntry(result, env, "file_checksum", elements, anitomy::kElementFileChecksum);
SetEntry(result, env, "file_extension", elements, anitomy::kElementFileExtension);
SetEntry(result, env, "file_name", elements, anitomy::kElementFileName);
SetEntry(result, env, "language", elements, anitomy::kElementLanguage);
SetEntry(result, env, "other", elements, anitomy::kElementOther);
SetEntry(result, env, "release_group", elements, anitomy::kElementReleaseGroup);
SetEntry(result, env, "release_information", elements, anitomy::kElementReleaseInformation);
SetEntry(result, env, "release_version", elements, anitomy::kElementReleaseVersion);
SetEntry(result, env, "source", elements, anitomy::kElementSource);
SetEntry(result, env, "subtitles", elements, anitomy::kElementSubtitles);
SetEntry(result, env, "video_resolution", elements, anitomy::kElementVideoResolution);
SetEntry(result, env, "video_term", elements, anitomy::kElementVideoTerm);
SetEntry(result, env, "volume_number", elements, anitomy::kElementVolumeNumber);
SetEntry(result, env, "volume_prefix", elements, anitomy::kElementVolumePrefix);
SetEntry(result, env, "unknown", elements, anitomy::kElementUnknown);
return result;
}
} // namespace Wrapper
| 38.091603
| 109
| 0.732465
|
MannPE
|
201365bb54c96707e73182e1b032f8ec7a0bf4ad
| 859
|
cpp
|
C++
|
GeneralLambda/main.cpp
|
colorhistory/cplusplus-general-programming
|
3ece924a2ab34711a55a45bc41e2b74384956204
|
[
"MIT"
] | 1
|
2019-09-28T09:40:08.000Z
|
2019-09-28T09:40:08.000Z
|
GeneralLambda/main.cpp
|
colorhistory/cplusplus-general-programming
|
3ece924a2ab34711a55a45bc41e2b74384956204
|
[
"MIT"
] | null | null | null |
GeneralLambda/main.cpp
|
colorhistory/cplusplus-general-programming
|
3ece924a2ab34711a55a45bc41e2b74384956204
|
[
"MIT"
] | null | null | null |
/****************************************************************************
**
** Copyright (C) 2019 Xiaohai <xiaohaidotpro@outlook.com>.
** Contact: http://xiaohai.pro
**
** This file is part of cplusplus-general-programming
**
**
****************************************************************************/
#include "bits/stdc++.h"
int main(int /* argc */, char** /* argv */) {
auto l = [](auto x, auto y) { return x < y; };
static std::default_random_engine engine(std::time(0));
static std::uniform_int_distribution<int> dis(0, 100);
std::vector<int> intVec1, intVec2;
for (int i = 0; i != 10; ++i) {
intVec1.push_back(dis(engine));
intVec2.push_back(dis(engine));
}
for (int i = 0; i != 10; ++i) {
std::cout << std::boolalpha << l(intVec1[i], intVec2[i]) << std::endl;
}
return 0;
}
| 26.84375
| 78
| 0.472643
|
colorhistory
|
20136fd33f8a6de8aa469ce2b8381ec120ea1036
| 1,873
|
cpp
|
C++
|
examples/src/jmespath_examples.cpp
|
stac47/jsoncons
|
b9e95d6a0bcb2dc8a821d33f98a530f10cfe1bc0
|
[
"BSL-1.0"
] | 507
|
2015-01-05T18:50:55.000Z
|
2022-03-30T16:50:10.000Z
|
examples/src/jmespath_examples.cpp
|
stac47/jsoncons
|
b9e95d6a0bcb2dc8a821d33f98a530f10cfe1bc0
|
[
"BSL-1.0"
] | 272
|
2015-01-20T13:09:19.000Z
|
2022-03-28T18:00:37.000Z
|
examples/src/jmespath_examples.cpp
|
stac47/jsoncons
|
b9e95d6a0bcb2dc8a821d33f98a530f10cfe1bc0
|
[
"BSL-1.0"
] | 140
|
2015-01-14T01:11:37.000Z
|
2022-03-29T08:35:35.000Z
|
// Copyright 2013 Daniel Parker
// Distributed under Boost license
#include <string>
#include <fstream>
#include <cassert>
#include <jsoncons/json.hpp>
#include <jsoncons_ext/jmespath/jmespath.hpp>
// for brevity
using jsoncons::json;
namespace jmespath = jsoncons::jmespath;
namespace {
void search_example()
{
std::string jtext = R"(
{
"locations": [
{"name": "Seattle", "state": "WA"},
{"name": "New York", "state": "NY"},
{"name": "Bellevue", "state": "WA"},
{"name": "Olympia", "state": "WA"}
]
}
)";
std::string expr = "locations[?state == 'WA'].name | sort(@) | {WashingtonCities: join(', ', @)}";
json doc = json::parse(jtext);
json result = jmespath::search(doc, expr);
std::cout << pretty_print(result) << "\n\n";
}
void jmespath_expression_example()
{
std::string jtext = R"(
{
"people": [
{
"age": 20,
"other": "foo",
"name": "Bob"
},
{
"age": 25,
"other": "bar",
"name": "Fred"
},
{
"age": 30,
"other": "baz",
"name": "George"
}
]
}
)";
auto expr = jmespath::jmespath_expression<json>::compile("people[?age > `20`].[name, age]");
json doc = json::parse(jtext);
json result = expr.evaluate(doc);
std::cout << pretty_print(result) << "\n\n";
}
} // namespace
void jmespath_examples()
{
std::cout << "\nJMESPath examples\n\n";
search_example();
jmespath_expression_example();
std::cout << "\n";
}
| 22.841463
| 106
| 0.444207
|
stac47
|
2015342d012b4d4225138d767087faaeb1a7e43f
| 5,813
|
cpp
|
C++
|
source/Game/GameStateMachine.cpp
|
GrimshawA/Nephilim
|
1e69df544078b55fdaf58a04db963e20094f27a9
|
[
"Zlib"
] | 19
|
2015-12-19T11:15:57.000Z
|
2022-03-09T11:22:11.000Z
|
source/Game/GameStateMachine.cpp
|
DevilWithin/Nephilim
|
1e69df544078b55fdaf58a04db963e20094f27a9
|
[
"Zlib"
] | 1
|
2017-05-17T09:31:10.000Z
|
2017-05-19T17:01:31.000Z
|
source/Game/GameStateMachine.cpp
|
GrimshawA/Nephilim
|
1e69df544078b55fdaf58a04db963e20094f27a9
|
[
"Zlib"
] | 3
|
2015-12-14T17:40:26.000Z
|
2021-02-25T00:42:42.000Z
|
#include <Nephilim/Game/GameStateMachine.h>
#include <Nephilim/Foundation/String.h>
#include <Nephilim/Animation/StateTransition.h>
#include <Nephilim/Game/GameState.h>
#include <Nephilim/Foundation/Time.h>
#include <Nephilim/Foundation/Logging.h>
#include <algorithm>
NEPHILIM_NS_BEGIN
GameStateMachine::GameStateMachine()
: mAnimation(NULL)
, batchPending(false)
{
}
GameStateMachine::~GameStateMachine()
{
}
/// Push a state batch down the stack
void GameStateMachine::triggerBatch(const GameStateBatch& batch)
{
nextBatch = batch;
batchPending = true;
}
/// Automaticaly change the state machine status
/// This uses a data-oriented FSM definition of the game screens
/// with well defined transitions and connections between nodes
/// for example, if all states in the FSM associate the BACK signal
/// with going to the previous state. its easy to go backwards without knowing what states to go to.
void GameStateMachine::triggerSignal(const String& sig)
{
}
void GameStateMachine::clear()
{
}
void GameStateMachine::drawCurrentList(GraphicsDevice* renderer)
{
int index = 0;
while(index < mCurrentList.size() && !mCurrentList.empty())
{
mCurrentList[index]->onRender(renderer);
//Log("Rendering state: %s", mCurrentList[index]->mName.c_str());
++index;
}
}
void GameStateMachine::drawList(std::vector<GameState*>& list, GraphicsDevice* renderer)
{
std::size_t index = 0;
while(index < list.size() && !list.empty())
{
list[index]->onRender(renderer);
// Log("Rendering state: %s", list[index]->mName.c_str());
++index;
}
}
/// Check if a given state is currently being executed
bool GameStateMachine::isActive(const String& name)
{
GameState* state = getBinding(name);
if(state)
{
return isActive(state);
}
else
{
return false; // state doesn't exist
}
}
/// Check if a given state is currently being executed
bool GameStateMachine::isActive(GameState* state)
{
// Check the currently active queue for the state
for (std::vector<GameState*>::iterator it = mCurrentList.begin(); it != mCurrentList.end(); ++it)
{
if((*it) == state)
{
return true; // the state is currently in the execution list
}
}
if(mAnimation)
{
for (std::vector<GameState*>::iterator it = mFutureList.begin(); it != mFutureList.end(); ++it)
{
if((*it) == state)
{
return true; // the state is currently in the list about to be used after transition
}
}
}
return false; // not found anywhere
}
/// Get a state or NULL
GameState* GameStateMachine::getBinding(const String& name)
{
std::map<String, GameState*>::iterator it = mBindingTable.find(name);
if(it != mBindingTable.end())
{
return it->second;
}
else return NULL;
};
/// Get the parent game, if any
GameCore* GameStateMachine::getParentGame()
{
return mGame;
}
/// Bind a new state to the list
bool GameStateMachine::bind(const String& name, GameState* state)
{
if(mBindingTable.find(name) != mBindingTable.end())
{
return false;
}
else
{
state->m_parent = this;
state->onAttach();
state->mGame = mGame;
mBindingTable[name] = state;
}
return true;
};
int GameStateMachine::getActiveStateCount()
{
return static_cast<int>(mCurrentList.size());
}
void GameStateMachine::pushEvent(const Event &event)
{
if(mAnimation)
{
return;
}
else
{
if(mCurrentList.size() == 0){
return;
}
int index = mCurrentList.size()-1;
bool stop = false;
while(index != -1 && stop == false){
mCurrentList[index]->PrimaryEventHandler(event);
stop = !mCurrentList[index]->m_letEventsThrough;
index--;
}
}
};
void GameStateMachine::drawStates(GraphicsDevice *renderer)
{
if(mAnimation)
{
mAnimation->draw(renderer);
return;
}
else
{
drawCurrentList(renderer);
return;
}
};
// Entry point of Updates
void GameStateMachine::update(Time &time)
{
// Handle the pending batch, by building a new list
if (batchPending)
{
GameStateList list;
for (auto i = 0; i < nextBatch.orderedGameStates.size(); ++i)
{
if (nextBatch.orderedGameStates[i].nameBased)
{
list.push_back(getBinding(nextBatch.orderedGameStates[i].name));
}
}
// Set our newly built list as the current one (needs work to support transitions)
if (nextBatch.animation)
{
// There is an animation, the batch is on future list waiting to be pushed into the current one
// mCurrentList stays the same and the animation is being processed now
mFutureList = list;
mAnimation = nextBatch.animation;
mAnimation->m_stack = this;
mAnimation->activate();
}
else
{
for (auto& gs : mCurrentList)
{
gs->onDeactivate();
}
mCurrentList = list;
for (auto& gs : mCurrentList)
{
if (!gs->_activated)
{
gs->onActivate();
gs->_activated = true;
}
}
}
batchPending = false;
}
// Wrap up the animation if it says it is finished
if(mAnimation && mAnimation->m_finished)
{
delete mAnimation;
Log("Passing future list with %d current %d", mCurrentList.size(), mFutureList.size());
mCurrentList = mFutureList;
mFutureList.clear();
for (auto& gs : mCurrentList)
{
gs->onActivate();
}
mAnimation = nullptr;
}
if(mAnimation)
{
mAnimation->m_stack = this;
mAnimation->update(time);
return;
}
else
{
if(mCurrentList.size() == 0){
return;
}
// older states draw first
int index = mCurrentList.size()-1;
bool stop = false;
while(index != -1 && stop == false){
/*stop = !*/mCurrentList[index]->onUpdate(time);
index--;
}
}
};
void GameStateMachine::updateList(GameStateList& list, const Time& time)
{
if(list.size() == 0)
{
return;
}
// older states draw first
int index = list.size()-1;
bool stop = false;
while(index != -1 && stop == false){
/*stop = !*/list[index]->onUpdate(time);
index--;
}
}
NEPHILIM_NS_END
| 19.705085
| 100
| 0.678995
|
GrimshawA
|
2016a7caab731eb69a5a9e8c8e4fe423ee941fd4
| 938
|
hpp
|
C++
|
src/cuda/api/miscellany.hpp
|
xandox/cuda-api-wrappers
|
6c9a02302c1cbd8c6832bf7ca342d83bd951e10e
|
[
"BSD-3-Clause"
] | 1
|
2020-09-16T10:28:06.000Z
|
2020-09-16T10:28:06.000Z
|
src/cuda/api/miscellany.hpp
|
xandox/cuda-api-wrappers
|
6c9a02302c1cbd8c6832bf7ca342d83bd951e10e
|
[
"BSD-3-Clause"
] | null | null | null |
src/cuda/api/miscellany.hpp
|
xandox/cuda-api-wrappers
|
6c9a02302c1cbd8c6832bf7ca342d83bd951e10e
|
[
"BSD-3-Clause"
] | 1
|
2020-11-17T19:49:06.000Z
|
2020-11-17T19:49:06.000Z
|
/**
* @file miscellany.hpp
*
* @brief Miscellaneous functionality which does not fit in another file
*
*/
#ifndef CUDA_API_WRAPPERS_MISCELLANY_HPP_
#define CUDA_API_WRAPPERS_MISCELLANY_HPP_
#include "error.hpp"
#include <cuda_runtime_api.h>
namespace cuda {
/**
* @brief Ensures the CUDA runtime has fully initialized
*
* @note The CUDA runtime uses lazy initialization, so that until you perform
* certain actions, the CUDA driver is not used to create a context, nothing
* is done on the device etc. This function forces this initialization to
* happen immediately, while not having any other effect.
*/
inline
void force_runtime_initialization()
{
// nVIDIA's Robin Thoni (https://www.rthoni.com/) guarantees
// the following code "does the trick"
auto status = cudaFree(nullptr);
throw_if_error(status, "Forcing CUDA runtime initialization");
}
} // namespace cuda
#endif /* CUDA_API_WRAPPERS_MISCELLANY_HPP_ */
| 26.055556
| 77
| 0.759062
|
xandox
|
20196c10e5889ab91bd757ec4b47ad4a794fd8a7
| 3,861
|
cpp
|
C++
|
data-structures/SkipList.cpp
|
Tumilok/algorithms-and-data-structures
|
c4d774ecb867a8cd130da8370ec4d782b698ecef
|
[
"MIT"
] | null | null | null |
data-structures/SkipList.cpp
|
Tumilok/algorithms-and-data-structures
|
c4d774ecb867a8cd130da8370ec4d782b698ecef
|
[
"MIT"
] | null | null | null |
data-structures/SkipList.cpp
|
Tumilok/algorithms-and-data-structures
|
c4d774ecb867a8cd130da8370ec4d782b698ecef
|
[
"MIT"
] | null | null | null |
//
// created by Uladzislau Tumilovich
//
#include "SkipList.h"
// Function checks whether skiplist is empty or not
bool is_SkipListEmpty(SkipList skiplist)
{
return skiplist.first == NULL || skiplist.first->next[0] == skiplist.last ? true : false;
}
// Function gives a random integer - 0 or 1
int randomiser()
{
return rand() % 2;
}
// Function gives level for new node
int getSkipListNodeLevel(int maxLevel)
{
int level = 1;
while (level <= maxLevel && randomiser() < 0.5) level++;
return level;
}
// Function creates new skiplist node
SkipListNode *createSkipListNode(int value, int level)
{
SkipListNode *newNode = new SkipListNode;
newNode->value = value;
newNode->next = new SkipListNode *[level];
return newNode;
}
// Function finds node of given value
SkipListNode *findSkipListNode(SkipList skiplist, int value)
{
SkipListNode *it = skiplist.first;
for (int i = skiplist.maxLevel - 1; i >= 0; i--)
{
while (it->next[i]->value < value) it = it->next[i];
if (it->next[i]->value == value) return it->next[i];
}
return NULL;
}
// Function inserts new node to a skiplist
void insertSkipListNode(SkipList skiplist, int value)
{
int level = getSkipListNodeLevel(skiplist.maxLevel);
SkipListNode *newNode = createSkipListNode(value, level);
SkipListNode *it = skiplist.first;
for (int i = skiplist.maxLevel - 1; i >= 0; i--)
{
while (it->next[i]->value < value) it = it->next[i];
if (i < level)
{
newNode->next[i] = it->next[i];
it->next[i] = newNode;
}
}
}
// Function removes node of given value from skiplist
bool removeSkipListNode(SkipList skiplist, int value)
{
SkipListNode *nodeToDelete = findSkipListNode(skiplist, value);
if (nodeToDelete == NULL) return false;
SkipListNode *previous[skiplist.maxLevel];
SkipListNode *it = skiplist.first;
for (int i = skiplist.maxLevel - 1; i >= 0; i--)
{
while (it->next[i]->value < nodeToDelete->value) it = it->next[i];
previous[i] = it;
}
for (int i = skiplist.maxLevel - 1; i >= 0; i--)
{
if (previous[i]->next[i]->value == nodeToDelete->value)
{
previous[i]->next[i] = previous[i]->next[i]->next[i];
nodeToDelete->next[i] = NULL;
}
}
delete [] nodeToDelete->next;
delete nodeToDelete;
return true;
}
// Function creates new skiplist
SkipList createSkipList(int maxLevel)
{
SkipListNode *firstNode = new SkipListNode;
firstNode->value = -INFINITY;
firstNode->next = new SkipListNode *[maxLevel];
SkipListNode *lastNode = new SkipListNode;
lastNode->value = INFINITY;
lastNode->next = new SkipListNode *[maxLevel];
for (int i = 0; i < maxLevel; i++)
{
firstNode->next[i] = lastNode;
lastNode->next[i] = NULL;
}
SkipList skiplist;
skiplist.maxLevel = maxLevel;
skiplist.first = firstNode;
skiplist.last = lastNode;
return skiplist;
}
// Function gives an amount of elements of a given level
int SkipListSize(SkipList skiplist)
{
if (is_SkipListEmpty(skiplist)) return 0;
int count = 0;
SkipListNode *it = skiplist.first->next[0];
while (it->value != INFINITY)
{
count++;
it = it->next[0];
}
return count;
}
// Function deletes skiplist
void deleteSkipList(SkipList &skiplist)
{
SkipListNode *p = skiplist.first->next[0];
SkipListNode *q = skiplist.first->next[0]->next[0];
while (p->value != INFINITY)
{
delete [] p->next;
delete p;
p = q;
q = q->next[0];
}
delete [] skiplist.first->next;
delete [] skiplist.last->next;
delete skiplist.first;
delete skiplist.last;
skiplist.first = NULL;
skiplist.last = NULL;
}
| 23.4
| 93
| 0.61927
|
Tumilok
|
201b1957cad8c7e2a53ced79a9f75ae004469b38
| 7,352
|
cpp
|
C++
|
Tools/ArcaneLab/Src/UI/AssetBrowserPanel.cpp
|
AustinLynes/Arcana-Tools
|
ce585d552e30174c4c629a9ea05e7f83947499a5
|
[
"Apache-2.0"
] | null | null | null |
Tools/ArcaneLab/Src/UI/AssetBrowserPanel.cpp
|
AustinLynes/Arcana-Tools
|
ce585d552e30174c4c629a9ea05e7f83947499a5
|
[
"Apache-2.0"
] | null | null | null |
Tools/ArcaneLab/Src/UI/AssetBrowserPanel.cpp
|
AustinLynes/Arcana-Tools
|
ce585d552e30174c4c629a9ea05e7f83947499a5
|
[
"Apache-2.0"
] | null | null | null |
#include "AssetBrowserPanel.h"
#include "../OutlineLayer.h"
namespace ArcanaTools {
void AssetBrowserPanel::OnAttach()
{
//m_path = s_AssetPath;
icons["back_arrow"] = reinterpret_cast<ImTextureID>(Texture2D::Create("resources/icons/back_arrow.png", false)->GetTextureID());
icons["forward_arrow"] = reinterpret_cast<ImTextureID>(Texture2D::Create("resources/icons/forward_arrow.png", false)->GetTextureID());
icons["up_arrow"] = reinterpret_cast<ImTextureID>(Texture2D::Create("resources/icons/up_arrow.png", false)->GetTextureID());
icons["import"] = reinterpret_cast<ImTextureID>(Texture2D::Create("resources/icons/import.png", false)->GetTextureID());
icons["folder"] = reinterpret_cast<ImTextureID>(Texture2D::Create("resources/icons/folder.png", false)->GetTextureID());
m_flags = ImGuiWindowFlags_NoCollapse;
m_search = "";
m_path = OutlineLayer::GetOutlineFilePath();
}
void AssetBrowserPanel::OnDetach()
{
}
void AssetBrowserPanel::OnUpdate()
{
}
void AssetBrowserPanel::MenuBar() {
// BACK ARROW
if (ImGui::ImageButton(icons["back_arrow"], { 16.0f, 16.0f })) {
if (m_path.has_parent_path() && m_path.relative_path().string() != OutlineLayer::GetOutlineFilePath()) {
m_forwardPath = m_path;
m_path = m_path.parent_path();
}
}
ImGui::SameLine();
if (ImGui::ImageButton(icons["forward_arrow"], { 16.0f, 16.0f })) {
if (m_forwardPath.relative_path() != "")
m_path = m_forwardPath;
m_forwardPath.relative_path() = "";
}
}
void AssetBrowserPanel::ContentBrowserLeft(ImVec2 size)
{
int clrCount = 0;
ImGui::PushStyleColor(ImGuiCol_ChildBg, IM_COL32(0x21, 0x21, 0x21, 0xFF)); clrCount++;
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, { 10.0f, 10.0f });
std::string filterBuffer;
if (ImGui::BeginChild("###AssetsLeft", size, true, ImGuiWindowFlags_AlwaysUseWindowPadding)) {
if (ImGui::InputTextWithHint("", "Assets", &filterBuffer)) {
}
ImVec2 childSize = ImGui::GetContentRegionAvail();
if (ImGui::BeginListBox("###ALLB", childSize)) {
for (auto& path : std::filesystem::directory_iterator(m_path))
{
/*const char* _path_ = reinterpret_cast<const char*>(path.path().c_str());*/
std::string _path_ = path.path().string();
std::string filename = path.path().filename().stem().string();
std::string extension = path.path().extension().string();
if (path.is_directory()) {
ImGui::Image(icons["folder"], { 16, 16 });
ImGui::SameLine();
ImGui::Text("%s", filename.c_str());
}
// determine extension
else if (path.path().extension() == ".png" || path.path().extension() == ".jpg") {
// LOAD THE TEXTURE... WRTIE THE TEXTURE
ImGui::Text("%s", filename.c_str());
}
}
ImGui::EndListBox();
}
ImGui::EndChild();
}
ImGui::PopStyleColor(clrCount);
ImGui::PopStyleVar();
}
void AssetBrowserPanel::ContentBrowserRight(ImVec2 size)
{
int clrCount = 0;
int varCount = 0;
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, { 0,0 }); varCount++;
ImGui::BeginGroup();
ImGui::BeginChild("###ARCB", size, true);
//-------------------------------------------------------------------------------------------------------
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, { 5.0f, 0.0f });
ImGui::PushStyleVar(ImGuiStyleVar_ChildBorderSize, 4);
ImGui::PushStyleColor(ImGuiCol_ChildBg, { 0,0,0,1 });
ImGui::PushStyleColor(ImGuiCol_Border, { 0.10,0.10,0.10,1 });
auto ns = ImGui::GetContentRegionAvail();
if (ImGui::BeginChild("###ARSC", { ns.x, 24}, true, ImGuiWindowFlags_AlwaysUseWindowPadding)) {
ImVec2 lastPos = ImGui::GetCursorPos();
ImGui::SetCursorPos({ lastPos.x, lastPos.y + 3 });
ImGui::Image(icons["folder"], { 16.0f, 16.0f });
ImGui::SameLine();
lastPos = ImGui::GetCursorPos();
ImGui::SetCursorPos({ lastPos.x + 5, lastPos.y + 2 });
curPath = m_path.relative_path().string().substr(
m_path.relative_path().string().find_first_of('/')+1,
m_path.relative_path().string().size()
);
ImGui::TextColored({ 1,1,1,1 }, "%s", curPath.c_str());
ImGui::EndChild();
}
ImGui::PopStyleVar(2);
ImGui::PopStyleColor(2);
//-------------------------------------------------------------------------------------------------- BROWSING SECTION
ImGui::PushStyleColor(ImGuiCol_FrameBg, IM_COL32(0x13, 0x13, 0x13, 0xFF)); clrCount++;
ImGui::PushStyleVar(ImGuiStyleVar_ChildRounding, 0); varCount++;
ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 0); varCount++;
auto childSize = ImGui::GetContentRegionAvail();
if (ImGui::BeginListBox("###AssetsRight", childSize)) {
for (auto& path : std::filesystem::directory_iterator(m_path))
{
/*const char* _path_ = reinterpret_cast<const char*>(path.path().c_str());*/
ImGui::BeginGroup();
ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, { 0,0 });
std::string _path_ = path.path().string();
std::string filename = path.path().filename().stem().string();
std::string extension = path.path().extension().string();
if (path.is_directory()) {
ImGui::ImageButton(icons["folder"], { 96, 96 });
if (ImGui::IsItemHovered() && ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Left)) {
directory_loaded_textures = false;
m_path /= path.path().filename();
ImGui::EndGroup();
ImGui::PopStyleVar();
didBreak = true;
break;
}
ImVec2 lastPos = ImGui::GetCursorPos();
ImGui::SetCursorPos({ lastPos.x + 96.0f, lastPos.y - 20.0f});
ImGui::Text("%s", filename.c_str());
}
// determine extension
else if (path.path().extension() == ".png" || path.path().extension() == ".jpg") {
// LOAD THE TEXTURE... WRTIE THE TEXTURE
if (!directory_loaded_textures) {
loaded_textures[filename] = Texture2D::Create(_path_, false);
}
ImGui::ImageButton((ImTextureID)loaded_textures[filename]->GetTextureID(), { 96, 96 });
ImVec2 lastPos = ImGui::GetCursorPos();
ImGui::SetCursorPos({ lastPos.x + 20, lastPos.y});
ImGui::Text("%s", filename.c_str());
}
ImGui::EndGroup();
//ImGui::NextColumn();
ImGui::PopStyleVar();
ImGui::SameLine();
}
if (!didBreak) {
directory_loaded_textures = true;
}
else {
didBreak = false;
}
ImGui::EndListBox();
}
ImGui::PopStyleColor(clrCount);
ImGui::PopStyleVar(varCount);
ImGui::EndChild();
ImGui::EndGroup();
}
void AssetBrowserPanel::OnRender()
{
int varCount = 0;
int clrCount = 0;
if (m_show) {
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, { 0,0 }); varCount++;
if (!Begin(m_tag.c_str())) {
ImGui::PopStyleVar(varCount);
return;
}
ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, { 0, 0 }); varCount++;
MenuBar();
//static float columnWidth = 300.0f;
//ImGui::Columns(2, "###Content_Panels");
//ImGui::SetColumnWidth(0, columnWidth);
// LEFT COLUMN
ImVec2 left_size = { ImGui::GetContentRegionAvail().x * 0.2f, ImGui::GetContentRegionAvail().y };
ContentBrowserLeft(left_size);
//ImGui::NextColumn();
ImGui::SameLine();
// RIGHT COLUMN
ImVec2 right_size = ImGui::GetContentRegionAvail();
ContentBrowserRight(right_size);
ImGui::PopStyleVar(varCount);
ImGui::PopStyleColor(clrCount);
End();
}
}
}
| 29.059289
| 136
| 0.637922
|
AustinLynes
|
2023ea5767968ee25084d5ac7a932ef63c47dd20
| 702
|
hpp
|
C++
|
include/memory/hadesmem/detail/last_error_preserver.hpp
|
CvX/hadesmem
|
d2c5164cc753dac37879ac8079f2ae23f2b8edb5
|
[
"MIT"
] | 24
|
2018-08-18T18:05:37.000Z
|
2021-09-28T00:26:35.000Z
|
include/memory/hadesmem/detail/last_error_preserver.hpp
|
CvX/hadesmem
|
d2c5164cc753dac37879ac8079f2ae23f2b8edb5
|
[
"MIT"
] | null | null | null |
include/memory/hadesmem/detail/last_error_preserver.hpp
|
CvX/hadesmem
|
d2c5164cc753dac37879ac8079f2ae23f2b8edb5
|
[
"MIT"
] | 9
|
2018-04-16T09:53:09.000Z
|
2021-02-26T05:04:49.000Z
|
// Copyright (C) 2010-2014 Joshua Boyce.
// See the file COPYING for copying permission.
#pragma once
#include <windows.h>
#include <hadesmem/config.hpp>
namespace hadesmem
{
namespace detail
{
class LastErrorPreserver
{
public:
LastErrorPreserver() HADESMEM_DETAIL_NOEXCEPT : last_error_(::GetLastError())
{
}
LastErrorPreserver(LastErrorPreserver const&) = delete;
LastErrorPreserver& operator=(LastErrorPreserver const&) = delete;
~LastErrorPreserver()
{
Revert();
}
void Update() HADESMEM_DETAIL_NOEXCEPT
{
last_error_ = ::GetLastError();
}
void Revert() HADESMEM_DETAIL_NOEXCEPT
{
SetLastError(last_error_);
}
private:
DWORD last_error_;
};
}
}
| 15.6
| 79
| 0.717949
|
CvX
|
20288356961c2e2b05b4297ee8b08cf3e2e71520
| 7,228
|
cpp
|
C++
|
source/DCHTTPConnection.cpp
|
HaikuArchives/BeDC
|
cf2f67fba574e934a06026c66b4f4298470716c8
|
[
"BSD-3-Clause"
] | null | null | null |
source/DCHTTPConnection.cpp
|
HaikuArchives/BeDC
|
cf2f67fba574e934a06026c66b4f4298470716c8
|
[
"BSD-3-Clause"
] | null | null | null |
source/DCHTTPConnection.cpp
|
HaikuArchives/BeDC
|
cf2f67fba574e934a06026c66b4f4298470716c8
|
[
"BSD-3-Clause"
] | null | null | null |
/*
----------------------
BeDC License
----------------------
Copyright 2002, The BeDC team.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions, and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions, and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the BeDC team nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "DCHTTPConnection.h"
#include "DCNetSetup.h"
#include "DCStrings.h"
#include "DCStringTokenizer.h"
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
const int DC_HTTP_RECV_BUFFER = 512;
enum
{
DC_HTTP_MSG_SEND = 'dHmS',
DC_HTTP_MSG_CONNECT = 'dHmC'
};
DCHTTPConnection::DCHTTPConnection(BMessenger target)
: BLooper("DCHTTPConnection", B_DISPLAY_PRIORITY)
{
fServer = "";
fFile = "";
fThreadID = -1;
fSocket = -1;
fTarget = target;
}
DCHTTPConnection::~DCHTTPConnection()
{
Disconnect();
EmptyHubList(&fHubs);
}
void
DCHTTPConnection::Disconnect()
{
if (fThreadID >= 0)
{
kill_thread(fThreadID);
fThreadID = -1;
}
if (fSocket >= 0)
{
#ifdef NETSERVER_BUILD
closesocket(fSocket);
#else
close(fSocket);
#endif
fSocket = -1;
}
}
void
DCHTTPConnection::Connect(const BString & optServer, const BString & optFile)
{
fServer = optServer;
fFile = optFile;
BMessage msg(DC_HTTP_MSG_CONNECT);
PostMessage(&msg);
}
void
DCHTTPConnection::InternalConnect()
{
sockaddr_in sockAddr;
memset(&sockAddr, 0, sizeof(sockAddr));
sockAddr.sin_family = AF_INET;
sockAddr.sin_port = htons(80);
// Get address
hostent * hostAddr = gethostbyname(fServer.String());
if (hostAddr)
{
sockAddr.sin_addr = *((in_addr *)(hostAddr->h_addr_list[0]));
fSocket = socket(AF_INET, SOCK_STREAM, 0);
if (fSocket >= 0)
{
if (connect(fSocket, (sockaddr *)&sockAddr, sizeof(sockAddr)) >= 0)
{
fThreadID = spawn_thread(ReceiveHandler, "http_receiver", B_DISPLAY_PRIORITY, this);
if (fThreadID >= 0)
{
resume_thread(fThreadID);
fTarget.SendMessage(DC_MSG_HTTP_CONNECTED);
return;
}
}
}
}
fTarget.SendMessage(DC_MSG_HTTP_CONNECT_ERROR);
Disconnect(); // failed... cleanup
return;
}
void
DCHTTPConnection::Send(const BString & text)
{
BMessage msg(DC_HTTP_MSG_SEND);
msg.AddString("text", text);
PostMessage(&msg);
}
int32
DCHTTPConnection::ReceiveHandler(void * data)
{
DCHTTPConnection * http = (DCHTTPConnection *)data; // Get our class :)
char recvBuffer[DC_HTTP_RECV_BUFFER + 1];
BString socketBuffer = "";
int amountRead = 0;
while (1)
{
memset(recvBuffer, 0, DC_HTTP_RECV_BUFFER + 1);
#ifdef NETSERVER_BUILD
if ((amountRead = recv(http->fSocket, recvBuffer, DC_HTTP_RECV_BUFFER, 0)) < 0)
{
if (amountRead != -1)
{
http->Disconnect(); // clean up.. we're done
return -1;
}
}
#else
if ((amountRead = recv(http->fSocket, recvBuffer, DC_HTTP_RECV_BUFFER, 0)) < 0)
{
http->Disconnect();
http->fTarget.SendMessage(DC_MSG_HTTP_RECV_ERROR);
return -1;
}
#endif
if (amountRead == 0) // that's it, our connection has been dropped by the server
{
// reset thread manually so it doesn't get killed
// since it will be free auto-magically by the OS
http->fThreadID = -1;
// Now cleanup the socket
http->Disconnect();
// Parse the lines into a hub list
http->ParseIntoHubList();
http->fLines.clear(); // empty the lines list to free memory
// Notify our target
http->fTarget.SendMessage(DC_MSG_HTTP_DISCONNECTED);
return 0; // success
}
recvBuffer[amountRead] = 0; // NULL-terminate
socketBuffer.Append(DCUTF8(recvBuffer));
int32 i;
while ((i = socketBuffer.FindFirst("\r\n")) != B_ERROR)
{
BString insert;
socketBuffer.MoveInto(insert, 0, i);
socketBuffer.RemoveFirst("\r\n");
http->fLines.push_back(insert);
}
}
}
void
DCHTTPConnection::MessageReceived(BMessage * msg)
{
switch (msg->what)
{
case DC_HTTP_MSG_SEND:
{
if (fSocket >= 0)
{
BString text;
if (msg->FindString("text", &text) == B_OK)
{
if (send(fSocket, text.String(), text.Length(), 0) <= 0)
fTarget.SendMessage(DC_MSG_HTTP_SEND_ERROR);
}
}
break;
}
case DC_HTTP_MSG_CONNECT:
{
InternalConnect();
break;
}
default:
BLooper::MessageReceived(msg);
break;
}
}
void
DCHTTPConnection::EmptyHubList(list<Hub *> * hubs)
{
while (hubs->begin() != hubs->end())
{
list<Hub *>::iterator i = hubs->begin();
delete (*i); // free the item
hubs->erase(i);
}
}
void
DCHTTPConnection::ParseIntoHubList()
{
list<BString>::iterator i;
BString name, server, desc;
uint32 users;
BString item;
EmptyHubList(&fHubs);
for (i = fLines.begin(); i != fLines.end(); i++)
{
BString tmpUsers;
item = (*i);
DCStringTokenizer tok(item, '|');
if (tok.GetListSize() < 4)
continue;
DCTokens::iterator iter = tok.GetTokenList().begin();
name = *iter++;
server = *iter++;
desc = *iter++;
tmpUsers = *iter++;
users = atoi(tmpUsers.String());
// Make sure we have a semi-valid server
if (server == "")
continue; // invalid
if (server.Length() <= 4) // i'd think it takes at least 5 characters for a domain name..
continue;
#define DCUTF8(X) X
// Insert into hub list
Hub * hub = new Hub(DCUTF8(name.String()), DCUTF8(server.String()), DCUTF8(desc.String()), users);
if (hub)
fHubs.push_back(hub);
}
}
list<DCHTTPConnection::Hub *> *
DCHTTPConnection::GetHubsCopy()
{
list<DCHTTPConnection::Hub *> * lst = new list<DCHTTPConnection::Hub *>;
list<DCHTTPConnection::Hub *>::iterator i;
for (i = fHubs.begin(); i != fHubs.end(); i++)
{
Hub * newHub = new Hub;
newHub->fName = (*i)->fName;
newHub->fServer = (*i)->fServer;
newHub->fDesc = (*i)->fDesc;
newHub->fUsers = (*i)->fUsers;
lst->push_back(newHub);
}
return lst;
}
void
DCHTTPConnection::SendListRequest()
{
// Format an HTTP request
BString http = "GET /";
http += GetFile();
http += " HTTP/1.1\r\nUser-Agent: BeDC/alpha\r\nHost: ";
http += GetServer();
http += "\r\n\r\n";
Send(http);
}
| 23.543974
| 100
| 0.68622
|
HaikuArchives
|
202a531ae2d065264efac61f259af74cec73ebaa
| 1,970
|
cpp
|
C++
|
src/SolarChargeSystem/lib/AsyncLTE/AsyncLTEResult.cpp
|
jack96013/Solar-Charge-System
|
e64c5fece5bff9b7a7f1c7d9b92235ed9e391812
|
[
"MIT"
] | null | null | null |
src/SolarChargeSystem/lib/AsyncLTE/AsyncLTEResult.cpp
|
jack96013/Solar-Charge-System
|
e64c5fece5bff9b7a7f1c7d9b92235ed9e391812
|
[
"MIT"
] | null | null | null |
src/SolarChargeSystem/lib/AsyncLTE/AsyncLTEResult.cpp
|
jack96013/Solar-Charge-System
|
e64c5fece5bff9b7a7f1c7d9b92235ed9e391812
|
[
"MIT"
] | null | null | null |
#include "AsyncLTEResult.h"
AsyncLTEResultBase::AsyncLTEResultBase()
{
}
void AsyncLTEResultBase::start()
{
status = WAIT;
}
void AsyncLTEResultBase::setOnReceived(Handler handler, void *arg)
{
this->handler = handler;
this->arg = arg;
}
bool AsyncLTEResultBase::isReceived()
{
return status == RECEIVED;
}
bool AsyncLTEResultBase::isCompleted()
{
return status == SUCCESSFUL || status == FAIL;
}
bool AsyncLTEResultBase::isFail()
{
return status == FAIL;
}
void AsyncLTEResultBase::onReceivedInvoke(String* string)
{
//status = RECEIVED;
if (handler != nullptr)
handler(this,string,arg);
}
void AsyncLTEResultBase::returnSuccessful()
{
status = SUCCESSFUL;
}
void AsyncLTEResultBase::returnFail()
{
status = FAIL;
}
void AsyncLTEResultBase::returnResult(int16_t val)
{
data.Int = val;
returnSuccessful();
}
void AsyncLTEResultBase::returnResult(int32_t val)
{
data.Long = val;
}
void AsyncLTEResultBase::returnResult(float val)
{
data.Float = val;
}
void AsyncLTEResultBase::returnResult(bool val)
{
data.Bool = val;
}
int16_t AsyncLTEResultBase::getInt()
{
return data.Int;
}
int32_t AsyncLTEResultBase::getLong()
{
return data.Long;
}
float AsyncLTEResultBase::getFloat()
{
return data.Float;
}
bool AsyncLTEResultBase::getBool()
{
return data.Bool;
}
void AsyncLTEResultBase::finish()
{
delete this;
}
void AsyncLTEResultBase::clear()
{
status = SUCCESSFUL;
handler = nullptr;
arg = nullptr;
data.Int = 0;
}
//===
// template<typename TResult>
// TResult* AsyncLTEResult<TResult>::getResult()
// {
// return result;
// }
// template<typename TResult>
// void AsyncLTEResult<TResult>::returnResult(TResult* result)
// {
// this->returnSuccessful();
// this->result = result;
// }
// template<typename TResult>
// void AsyncLTEResult<TResult>::finish()
// {
// delete result;
// delete this;
// }
| 15.634921
| 66
| 0.66802
|
jack96013
|
202bec087b184bc36d58987e5e2310aa1ef770d3
| 294
|
cpp
|
C++
|
src/solutions/28.cpp
|
bshankar/euler
|
c866a661a94d15d3744c74d85149534efac2ca23
|
[
"MIT"
] | null | null | null |
src/solutions/28.cpp
|
bshankar/euler
|
c866a661a94d15d3744c74d85149534efac2ca23
|
[
"MIT"
] | null | null | null |
src/solutions/28.cpp
|
bshankar/euler
|
c866a661a94d15d3744c74d85149534efac2ca23
|
[
"MIT"
] | null | null | null |
#include <iostream>
using namespace std;
int main() {
int inc = 2, sum = 1, k = 1;
int mod = 0;
while (k < 1001*1001) {
k += inc;
sum += k;
++mod;
if (mod == 4) {
mod = 0;
inc += 2;
}
}
cout << sum << endl;
}
| 16.333333
| 32
| 0.370748
|
bshankar
|
45c9e12fc1a33442d25ac7ea5b13844f0bedd487
| 2,222
|
hpp
|
C++
|
include/sql/fusion/create_table_stmt.hpp
|
cviebig/lib-sql
|
fed42f80b5866503c5f5710d791feec213c051a1
|
[
"MIT"
] | 4
|
2017-09-25T00:03:31.000Z
|
2020-04-02T07:06:24.000Z
|
include/sql/fusion/create_table_stmt.hpp
|
cviebig/lib-sql
|
fed42f80b5866503c5f5710d791feec213c051a1
|
[
"MIT"
] | 1
|
2018-05-16T20:00:42.000Z
|
2018-05-30T13:21:20.000Z
|
include/sql/fusion/create_table_stmt.hpp
|
cviebig/lib-sql
|
fed42f80b5866503c5f5710d791feec213c051a1
|
[
"MIT"
] | 1
|
2022-01-05T20:49:47.000Z
|
2022-01-05T20:49:47.000Z
|
#ifndef SQL_PARSER_FUSION_CREATE_TABLE_STMT_HPP
#define SQL_PARSER_FUSION_CREATE_TABLE_STMT_HPP
#include "sql/ast/create_table_stmt.hpp"
#include <boost/fusion/include/adapt_struct.hpp>
BOOST_FUSION_ADAPT_STRUCT(sql::ast::type_name,
(std::string, name)
(boost::optional<sql::ast::numeric_literal>, lower_bound)
(boost::optional<sql::ast::numeric_literal>, upper_bound)
)
BOOST_FUSION_ADAPT_STRUCT(sql::ast::column_def,
(sql::ast::identifier, name)
(sql::ast::type_name, type)
)
BOOST_FUSION_ADAPT_STRUCT(sql::ast::indexed_column,
(sql::ast::identifier, name)
(sql::ast::direction_type, direction)
)
BOOST_FUSION_ADAPT_STRUCT(sql::ast::table_constraint_primary_key,
(sql::ast::indexed_column_list, columns)
)
BOOST_FUSION_ADAPT_STRUCT(sql::ast::table_constraint_unique,
(sql::ast::indexed_column_list, columns)
)
BOOST_FUSION_ADAPT_STRUCT(sql::ast::table_constraint_foreign_key,
(sql::ast::identifier_list, columns)
(sql::ast::identifier, foreign_table)
(sql::ast::identifier_list, foreign_columns)
)
BOOST_FUSION_ADAPT_STRUCT(sql::ast::table_constraint,
(boost::optional<sql::ast::identifier>, name)
(sql::ast::table_constraint_type, type)
)
BOOST_FUSION_ADAPT_STRUCT(sql::ast::create_table_stmt_columns,
(sql::ast::column_def_list, columns)
(boost::optional<sql::ast::table_constraint_list>, constraints)
(bool, rowid)
)
BOOST_FUSION_ADAPT_STRUCT(sql::ast::create_table_stmt_select,
(sql::ast::select_stmt, statement)
)
BOOST_FUSION_ADAPT_STRUCT(sql::ast::create_table_stmt,
(bool, temporary)
(bool, if_not_exists)
(sql::ast::table_identifier, name)
(sql::ast::create_table_stmt_definition, definition)
)
#endif //SQL_PARSER_FUSION_CREATE_TABLE_STMT_HPP
| 36.42623
| 88
| 0.60171
|
cviebig
|
45ca2a05da87fca129e113e5729df71b6c3d126b
| 739
|
c++
|
C++
|
GeeksForGeeks/Array/Easy/WaveArray.c++
|
Chirag-Juneja/Algo
|
5006332e9ea1f77f941e3fa45962813dbe9399a6
|
[
"MIT"
] | 1
|
2021-08-13T21:54:40.000Z
|
2021-08-13T21:54:40.000Z
|
GeeksForGeeks/Array/Easy/WaveArray.c++
|
Chirag-Juneja/Algo
|
5006332e9ea1f77f941e3fa45962813dbe9399a6
|
[
"MIT"
] | null | null | null |
GeeksForGeeks/Array/Easy/WaveArray.c++
|
Chirag-Juneja/Algo
|
5006332e9ea1f77f941e3fa45962813dbe9399a6
|
[
"MIT"
] | null | null | null |
/*
Given a sorted array arr[] of distinct integers. Sort the array into a wave-like array and return it
In other words, arrange the elements into a sequence such that arr[1] >= arr[2] <= arr[3] >= arr[4] <= arr[5].....
Example 1:
Input:
n = 5
arr[] = {1,2,3,4,5}
Output: 2 1 4 3 5
Explanation: Array elements after
sorting it in wave form are
2 1 4 3 5.
*/
#include <bits/stdc++.h>
using namespace std;
class Solution{
public:
void convertToWave(vector<int>& arr, int n){
for(int i=0;i+1<n;i+=2){
swap(arr[i],arr[i+1]);
}
}
};
int main(){
vector<int> v = {1,2,3,4,5};
Solution sol = Solution();
sol.convertToWave(v,v.size());
for(auto a:v){
cout << a << endl;
}
}
| 20.527778
| 114
| 0.584574
|
Chirag-Juneja
|
45cb59a69e420a979aa3e13e0e3d031d70aea5e8
| 2,525
|
cpp
|
C++
|
AkameCore/Source Files/Rendering/System/BuiltInShaderPipelines/DeferredPipeline.cpp
|
SudharsanZen/Akame
|
376efe3929e4426e6dc01440ab9f6aa3e8dcb2bf
|
[
"Apache-2.0"
] | 2
|
2022-03-30T20:58:58.000Z
|
2022-03-31T02:06:17.000Z
|
AkameCore/Source Files/Rendering/System/BuiltInShaderPipelines/DeferredPipeline.cpp
|
SudharsanZen/Akame
|
376efe3929e4426e6dc01440ab9f6aa3e8dcb2bf
|
[
"Apache-2.0"
] | null | null | null |
AkameCore/Source Files/Rendering/System/BuiltInShaderPipelines/DeferredPipeline.cpp
|
SudharsanZen/Akame
|
376efe3929e4426e6dc01440ab9f6aa3e8dcb2bf
|
[
"Apache-2.0"
] | null | null | null |
#include<sstream>
#include "Rendering/System/DeferredPipeline.h"
#pragma warning(push, 0)
#include<glad/glad.h>
#include<GLFW/glfw3.h>
#pragma warning(pop)
DeferredPipeline::DeferredPipeline(int height, int width)
{
drfb.updateBufferSize(height, width);
}
void DeferredPipeline::WindowsResizeCallBacks(int height, int width)
{
drfb.updateBufferSize(height, width);
}
void DeferredPipeline::OnPreRender(std::shared_ptr<Shader> shader, RenderingSystem* rsys, Camera cam, unsigned int frameBuffer)
{
glDisable(GL_BLEND);
//deferred renderer-----------------------------------------------------------------------
glEnable(GL_DEPTH_TEST);
glDisable(GL_MULTISAMPLE);
drfb.bindFrameBuffer();
}
void DeferredPipeline::OnPostRender(std::shared_ptr<Shader> shader, RenderingSystem* rsys, Camera cam, unsigned int frameBuffer)
{
std::shared_ptr<LightSystem> lsys = rsys->lightsystem.lock();
int height = rsys->height, width = rsys->width;
drfb.unBindFrameBuffer(frameBuffer);
//render final to quad
glDisable(GL_DEPTH_TEST);//disable depth to remove quad from depth calulations
drfb.setUpShader(cam, lsys);
lsys->dir_sMap.useTextureArray(6);
drfb.set4x4Matrixfv("proj", cam.getProjectionMatrix());
drfb.set4x4Matrixfv("viewMat", cam.getViewMatrix());
drfb.setFloat("lambda",lsys->lambda);
drfb.setFloat("near",cam.getNear());
drfb.setFloat("far",lsys->shadowDistance);
drfb.setInt("shadowRes",(int)lsys->dir_sMap.GetResolution());
drfb.setVec3("viewDirection",cam.transform.forward());
lsys->dir_sMap.useTextureArray(6);
for (int i = 0; i < lsys->dirLightSpace.size(); i++)
{
drfb.set4x4MatrixfvArray("lightSpaceMat[0]",i,lsys->dirLightSpace[i]);
}
drfb.outPutToQaud();
//copy deferred rendering depth buffer to forward
glBindFramebuffer(GL_READ_FRAMEBUFFER, drfb.drfb.frameBuffer);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, frameBuffer); // write to default framebuffer
glBlitFramebuffer(
0, 0, width, height, 0, 0, width, height, GL_DEPTH_BUFFER_BIT, GL_NEAREST
);
glEnable(GL_BLEND);
glEnable(GL_DEPTH_TEST);
}
void RM_SKY_BOXPipeline::OnPreRender(std::shared_ptr<Shader> shader, RenderingSystem* rsys, Camera cam, unsigned int frameBuffer)
{
std::shared_ptr<LightSystem> lsys = rsys->lightsystem.lock();
shader->useShaderProgram();
if(lsys->drVector.size()>0)
shader->setUniformVec3("sunPose", -lsys->drVector[0].lightDir);
}
void RM_SKY_BOXPipeline::OnPostRender(std::shared_ptr<Shader> shader, RenderingSystem* rsys, Camera cam, unsigned int frameBuffer)
{
}
| 31.5625
| 131
| 0.739406
|
SudharsanZen
|
45d2f25b6dbcea645a1fe0cea3265b8589bf917e
| 6,922
|
c++
|
C++
|
map/hidimMapActor.c++
|
camilleg/vss
|
27f1c8f73f8d7ef2d4e5de077e4b2ed7e4f72803
|
[
"MIT"
] | null | null | null |
map/hidimMapActor.c++
|
camilleg/vss
|
27f1c8f73f8d7ef2d4e5de077e4b2ed7e4f72803
|
[
"MIT"
] | null | null | null |
map/hidimMapActor.c++
|
camilleg/vss
|
27f1c8f73f8d7ef2d4e5de077e4b2ed7e4f72803
|
[
"MIT"
] | null | null | null |
#include "mapActor.h"
HidimMapActor::HidimMapActor() :
dimLo(0),
dimHi(0),
cpt(0),
rgzLo(NULL),
rgzHi(NULL)
{
}
HidimMapActor::~HidimMapActor()
{
if (rgzLo)
delete [] rgzLo;
if (rgzHi)
delete [] rgzHi;
}
// LoadFile
//
// Read a map file with the following format:
// # of dimensions of low space
// # of dimensions of high space
// # of points
// floating-point coords of high space
// floating-point coords of low space
void HidimMapActor::loadFile(char* szFile)
{
FILE* pf = fopen(szFile, "rb");
int i;
if (!pf)
{
fprintf(stderr, "vss error: HidimMapActor LoadFile can't open file \"%s\"\n",
szFile);
return;
}
if (3 != fscanf(pf, "%d %d %d", &dimLo, &dimHi, &cpt))
{
fprintf(stderr, "vss error: HidimMapActor LoadFile syntax error in file \"%s\"\n",
szFile);
goto LAbort;
}
// Validity check
if (!setDims(dimLo, dimHi) || !setNumPoints(cpt) || !FValid())
return;
// Read in the data points.
if (rgzHi)
delete [] rgzHi;
rgzHi = new float[cpt * dimHi];
for (i=0; i < cpt * dimHi; i++)
if (1 != fscanf(pf, "%f ", &rgzHi[i]))
{
fprintf(stderr, "vss error: HidimMapActor LoadFile syntax error in file \"%s\"\n",
szFile);
goto LAbort;
}
if (rgzLo)
delete [] rgzLo;
rgzLo = new float[cpt * dimLo];
for (i=0; i < cpt * dimLo; i++)
if (1 != fscanf(pf, "%f ", &rgzLo[i]))
{
fprintf(stderr, "vss error: HidimMapActor LoadFile syntax error in file \"%s\"\n",
szFile);
goto LAbort;
}
fclose(pf);
mymap.Init(cpt, dimLo, dimHi, rgzLo, rgzHi);
return;
LAbort:
if (rgzLo)
{
delete [] rgzLo;
rgzLo = NULL;
}
if (rgzHi)
{
delete [] rgzHi;
rgzHi = NULL;
}
dimLo = dimHi = cpt = 0;
fclose(pf);
}
int HidimMapActor::FValid(void)
{
if (cpt < dimLo + 1)
{
fprintf(stderr, "vss error: # of points (%d) < low dimension (%d) + 1\n",
cpt, dimLo);
return 0;
}
return 1;
}
int HidimMapActor::setDims(int loDim, int hiDim)
{
if (loDim >= hiDim)
{
fprintf(stderr, "vss error: HidimMapActor SetDims loDim not < hiDim\n");
return 0;
}
if (loDim <= 0 || hiDim <= 0)
{
fprintf(stderr, "vss error: HidimMapActor SetDims dimension nonpositive\n");
return 0;
}
dimLo = loDim;
dimHi = hiDim;
return 1;
}
int HidimMapActor::setNumPoints(int num)
{
if (num <= 0)
{
fprintf(stderr, "vss error: HidimMapActor SetNumPoints nonpositive\n");
return 0;
}
cpt = num;
return 1;
}
void HidimMapActor::computeLowPoints(void)
{
if (isDebug())
printf("HidimMapActor::computeLowPoints()\n");
if (rgzLo)
delete [] rgzLo;
rgzLo = NULL;
if (!FValid())
return;
const int cz = cpt * dimLo;
rgzLo = new float[cz];
if (rgzHi && rgzLo)
{
mymap.GA();
for (int ipt = 0; ipt < cpt; ipt++)
for (int idim = 0; idim < dimLo; idim++)
rgzLo[ipt*dimLo + idim] = mymap.PzQ(ipt)[idim];
if (isDebug())
printf("HidimMapActor::computeLowPoints calls mymap.Init(%d %d %d)\n",
cpt, dimLo, dimHi);
mymap.Init(cpt, dimLo, dimHi, rgzLo, rgzHi);
}
}
void HidimMapActor::setLowPoints(int cz, float* rgz)
{
if (isDebug())
printf("HidimMapActor::setLowPoints(%d)\n", cz);
if (rgzLo)
delete [] rgzLo;
rgzLo = NULL;
if (!FValid())
return;
if (cz != cpt * dimLo)
{
fprintf(stderr, "vss error: HidimMapActor SetLowPoints array: %d entries, should be %d\n", cz, cpt * dimLo);
return;
}
rgzLo = new float[cz];
// Instead of a straight FloatCopy, throw a little randomness in here
// to avoid degeneracies when 4 points lie on a circle.
// FloatCopy(rgzLo, rgz, cz);
for (int i=0; i<cz; i++)
rgzLo[i] = rgz[i] + (drand48() - .5) * .00008;
if (rgzHi && rgzLo)
{
if (isDebug())
printf("HidimMapActor::setLowPoints calls mymap.Init(%d %d %d)\n",
cpt, dimLo, dimHi);
mymap.Init(cpt, dimLo, dimHi, rgzLo, rgzHi);
}
}
void HidimMapActor::setHighPoints(int cz, float* rgz)
{
if (isDebug())
printf("HidimMapActor::setHighPoints(%d)\n", cz);
if (rgzHi)
delete [] rgzHi;
rgzHi = NULL;
if (!FValid())
return;
if (cz != cpt * dimHi)
{
fprintf(stderr, "vss error: HidimMapActor SetHighPoints array: %d entries, should be %d\n", cz, cpt * dimHi);
return;
}
rgzHi = new float[cz];
FloatCopy(rgzHi, rgz, cz);
if (rgzHi && rgzLo)
{
if (isDebug())
printf("HidimMapActor::setHighPoints calls mymap.Init(%d %d %d)\n",
cpt, dimLo, dimHi);
mymap.Init(cpt, dimLo, dimHi, rgzLo, rgzHi);
}
}
// Send the data to mymap, and stuff the result in place.
// return a string to be stuffed into the string mapAndSend is building?
int HidimMapActor::mapArray(float * dataArray, int size)
{
if (!rgzLo || !rgzHi || cpt == 0)
// no error message, that happened already probably.
return 0;
if (size < dimLo)
{
fprintf(stderr, "vss error: HidimMapActor mapArray too short (%d, should be %d).\n", size, dimLo);
return 0;
}
// if (isDebug())
// printf("HidimMapActor::mapArray checkpoint 0\n");
// Copy any extra args happening to come along for the ride
// to the end of the array.
// This is useful if there are some args we want to pass to a
// message group which are NOT to be mapped.
int i;
for (i=dimLo; i<size; i++)
dataArray[dimHi+i-dimLo] = dataArray[i];
MCPoint pt(iMaxMCPoint);
// if (isDebug())
// printf("HidimMapActor::mapArray checkpoint 1, dimLo=%d\n", dimLo);
// Map dataArray to pt, then copy back into dataArray.
switch(dimLo)
{
default:
fprintf(stderr, "vss error: HidimMapActor dimLo should be 2 or 3, not %d\n",
dimLo);
return 0;
case 2:
mymap.MCPointFromXY(pt, dataArray[0], dataArray[1]);
break;
case 3:
mymap.MCPointFromXYZ(pt, dataArray[0], dataArray[1], dataArray[2]);
break;
}
// if (isDebug())
// printf("HidimMapActor::mapArray checkpoint 2\n");
for (i=0; i<dimHi; i++)
dataArray[i] = pt[i];
// if (isDebug())
// printf("HidimMapActor::mapArray checkpoint 3\n");
return dimHi + (size - dimLo);
}
float HidimMapActor::map(float)
{
fprintf(stderr, "vss error: HidimMapActor::map() should never be called.\n");
// Though I suppose it could be called if dimLo == 1.
return 0.0f;
}
int HidimMapActor::receiveMessage(const char* Message)
{
CommandFromMessage(Message);
if (CommandIs("LoadFile"))
{
ifS( szFile, loadFile(szFile) );
return Uncatch();
}
if (CommandIs("SetDims"))
{
ifDD( loDim, hiDim, setDims(loDim, hiDim) );
return Uncatch();
}
if (CommandIs("SetNumPoints"))
{
ifD( num, setNumPoints(num) );
return Uncatch();
}
if (CommandIs("SetLowPoints"))
{
ifFloatArray( rgz, cz, setLowPoints(cz, rgz) );
return Uncatch();
}
if (CommandIs("SetHighPoints"))
{
ifFloatArray( rgz, cz, setHighPoints(cz, rgz) );
return Uncatch();
}
if (CommandIs("UseGeneticAlgorithm"))
{
ifNil( mymap.SetSammon(0) );
}
if (CommandIs("UseSammonsMapping"))
{
ifNil( mymap.SetSammon(1) );
}
if (CommandIs("ComputeLowPoints"))
{
ifNil( computeLowPoints() );
}
return MapActor::receiveMessage(Message);
}
| 21.039514
| 111
| 0.636232
|
camilleg
|
45da991d2633875e338bf2442d9dc452935ddf79
| 1,298
|
cpp
|
C++
|
codeforces/G1 - Playlist for Polycarp (easy version)/Accepted.cpp
|
kzvd4729/Problem-Solving
|
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
|
[
"MIT"
] | 1
|
2022-02-11T16:55:36.000Z
|
2022-02-11T16:55:36.000Z
|
codeforces/G1 - Playlist for Polycarp (easy version)/Accepted.cpp
|
kzvd4729/Problem-Solving
|
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
|
[
"MIT"
] | null | null | null |
codeforces/G1 - Playlist for Polycarp (easy version)/Accepted.cpp
|
kzvd4729/Problem-Solving
|
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
|
[
"MIT"
] | null | null | null |
/****************************************************************************************
* @author: kzvd4729 created: Jul/08/2019 02:16
* solution_verdict: Accepted language: GNU C++14
* run_time: 77 ms memory_used: 94800 KB
* problem: https://codeforces.com/contest/1185/problem/G1
****************************************************************************************/
#include<bits/stdc++.h>
#define long long long
using namespace std;
const int N=1e6;
const long mod=1e9+7;
int aa[N+2],bb[N+2],n,dp[(1<<15)+2][3][226];
long dfs(int msk,int gn,int rm)
{
if(rm<0)return 0;if(rm==0)return 1;
if(dp[msk][gn][rm]!=-1)return dp[msk][gn][rm];
long now=0;
for(int i=0;i<n;i++)
{
if(bb[i]==gn)continue;
if((msk&(1<<i)))continue;
now=(now+dfs(msk|(1<<i),bb[i],rm-aa[i]))%mod;
}
return dp[msk][gn][rm]=now;
}
int main()
{
ios_base::sync_with_stdio(0);cin.tie(0);
int t;cin>>n>>t;
for(int i=0;i<n;i++)cin>>aa[i]>>bb[i],bb[i]--;
long ans=0;
memset(dp,-1,sizeof(dp));
for(int i=0;i<n;i++)
ans=(ans+dfs((1<<i),bb[i],t-aa[i]))%mod;
cout<<ans<<endl;
return 0;
}
| 35.081081
| 111
| 0.430663
|
kzvd4729
|
45dc021ef9732c9f79d722e9acd25ff0a3bf6ddc
| 1,643
|
cpp
|
C++
|
src/model/opengl/VertexArray.cpp
|
XantNero/Courseproject-Modelling-road-traffic-
|
f0aae780935d4ac9ed30d8b50b965813b6a60632
|
[
"MIT"
] | null | null | null |
src/model/opengl/VertexArray.cpp
|
XantNero/Courseproject-Modelling-road-traffic-
|
f0aae780935d4ac9ed30d8b50b965813b6a60632
|
[
"MIT"
] | null | null | null |
src/model/opengl/VertexArray.cpp
|
XantNero/Courseproject-Modelling-road-traffic-
|
f0aae780935d4ac9ed30d8b50b965813b6a60632
|
[
"MIT"
] | null | null | null |
#include "VertexArray.h"
#include <GL/glew.h>
#include "debug.h"
VertexArray::VertexArray()
{
GLCall(glGenVertexArrays(1, &m_RendererID));
}
VertexArray::~VertexArray()
{
GLCall(glDeleteVertexArrays(1, &m_RendererID));
}
void VertexArray::bind() const
{
GLCall(glBindVertexArray(m_RendererID));
}
void VertexArray::unbind() const
{
GLCall(glBindVertexArray(0));
//glBindBuffer(GL_ARRAY_BUFFER, 0);
}
void VertexArray::setIndexBuffer(const std::shared_ptr<IndexBuffer> ib)
{
m_IndexBuffer = ib;
}
const std::shared_ptr<IndexBuffer>& VertexArray::getIndexBuffer() const
{
return m_IndexBuffer;
}
const std::vector<std::shared_ptr<VertexBuffer>>& VertexArray::getVertexBufferArray() const
{
return m_VertexBuffers;
}
void VertexArray::addVertexBuffer(const std::shared_ptr<VertexBuffer> vb, const VertexBufferLayout& layout)
{
vb->bind();
const auto& elements = layout.getElementArray();
unsigned int offset = 0;
for (unsigned int i = 0; i < elements.size(); ++i) {
const auto& element = elements[i];
GLCall(glEnableVertexArrayAttrib(m_RendererID, i));
//std::cout << i << ' ' << element.count << ' ' << element.type << " " << element.normalized << ' ' << layout.getStride() << ' ' << offset << '\n';
GLCall(glVertexAttribPointer(i, element.count, element.type,
element.normalized ? GL_TRUE : GL_FALSE, layout.getStride(), (void*)offset));
offset += element.size;
}
// GLCall(glEnableVertexAttribArray(0));
// GLCall(glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float), 0));
m_VertexBuffers.push_back(vb);
}
| 29.339286
| 155
| 0.678028
|
XantNero
|
45dc1acf36d067e88b1ba7f3e4afde9bc478d1f4
| 732
|
cpp
|
C++
|
lib/Frontend/CXTextDiagnosticPrinter.cpp
|
Gnimuc/libclangex
|
3d519fba37210d06578b10ea9bdb1d496be0e9d0
|
[
"Apache-2.0",
"MIT-0",
"MIT"
] | 1
|
2022-01-11T00:49:42.000Z
|
2022-01-11T00:49:42.000Z
|
lib/Frontend/CXTextDiagnosticPrinter.cpp
|
Gnimuc/libclangex
|
3d519fba37210d06578b10ea9bdb1d496be0e9d0
|
[
"Apache-2.0",
"MIT-0",
"MIT"
] | 4
|
2021-08-01T06:07:06.000Z
|
2022-02-04T14:14:15.000Z
|
lib/Frontend/CXTextDiagnosticPrinter.cpp
|
Gnimuc/libclangex
|
3d519fba37210d06578b10ea9bdb1d496be0e9d0
|
[
"Apache-2.0",
"MIT-0",
"MIT"
] | null | null | null |
#include "clang-ex/Frontend/CXTextDiagnosticPrinter.h"
#include "clang/Frontend/TextDiagnosticPrinter.h"
#include "llvm/Support/raw_ostream.h"
CXDiagnosticConsumer clang_TextDiagnosticPrinter_create(CXDiagnosticOptions Opts,
CXInit_Error *ErrorCode) {
CXInit_Error Err = CXInit_NoError;
std::unique_ptr<clang::DiagnosticConsumer> ptr =
std::make_unique<clang::TextDiagnosticPrinter>(
llvm::errs(), static_cast<clang::DiagnosticOptions *>(Opts));
if (!ptr) {
fprintf(stderr, "LIBCLANGEX ERROR: failed to create `clang::TextDiagnosticPrinter`\n");
Err = CXInit_CanNotCreate;
}
if (ErrorCode)
*ErrorCode = Err;
return ptr.release();
}
| 33.272727
| 91
| 0.688525
|
Gnimuc
|
45dee87dcf3529cb2500058cb997d8ffef5b655a
| 403
|
cpp
|
C++
|
Network_dll/src/Network.cpp
|
BenjaminViranin/Network-Library
|
0c5c05d8d8f050facf4a6a34bfdc9882477fb8ee
|
[
"MIT"
] | null | null | null |
Network_dll/src/Network.cpp
|
BenjaminViranin/Network-Library
|
0c5c05d8d8f050facf4a6a34bfdc9882477fb8ee
|
[
"MIT"
] | null | null | null |
Network_dll/src/Network.cpp
|
BenjaminViranin/Network-Library
|
0c5c05d8d8f050facf4a6a34bfdc9882477fb8ee
|
[
"MIT"
] | null | null | null |
#include "../include/Network.h"
Network::Network()
{
Init();
}
Network::~Network()
{
Destroy();
}
int Network::Init()
{
int err = WSAStartup(MAKEWORD(2, 2), &m_wsa);
if (err < 0)
{
std::cout << "WSAStartup failed !" << std::endl;
std::cin.get();
return EXIT_FAILURE;
}
std::cout << ":: Init Network :: ";
}
void Network::Destroy()
{
std::cout << "Destroy Network :: ";
WSACleanup();
}
| 13.896552
| 50
| 0.585608
|
BenjaminViranin
|
45df42aaf2c4e4af4f61d0f63a52dd70de033cb8
| 3,179
|
hpp
|
C++
|
include/ripple/arch/topology.hpp
|
robclu/ripple
|
734dfa77e100a86b3c60589d41ca627e41d4a783
|
[
"MIT"
] | 4
|
2021-04-25T16:38:12.000Z
|
2021-12-23T08:32:15.000Z
|
include/ripple/arch/topology.hpp
|
robclu/ripple
|
734dfa77e100a86b3c60589d41ca627e41d4a783
|
[
"MIT"
] | null | null | null |
include/ripple/arch/topology.hpp
|
robclu/ripple
|
734dfa77e100a86b3c60589d41ca627e41d4a783
|
[
"MIT"
] | null | null | null |
/**==--- ripple/arch/topology.hpp -------------------------- -*- C++ -*- ---==**
*
* Ripple
*
* Copyright (c) 2019 - 2021 Rob Clucas.
*
* This file is distributed under the MIT License. See LICENSE for details.
*
*==------------------------------------------------------------------------==**
* \file topology.hpp
* \brief This file defines a struct to store the topology of the system.
*
*==------------------------------------------------------------------------==*/
#ifndef RIPPLE_ARCH_TOPOLOGY_HPP
#define RIPPLE_ARCH_TOPOLOGY_HPP
#include "cpu_info.hpp"
#include "gpu_info.hpp"
#include <map>
namespace ripple {
/**
* Defines a map type to map gpu indices to stream indices.
*/
using StreamMap = std::map<ripple::GpuInfo::Index, ripple::GpuInfo::Id>;
/**
* The Topology struct stores information about the topology of the system. It
* holds information about the caches, processors, processor mapping, gpu
* devies, etc, which can be used to optimally partiion parallel algorithms.
*/
struct Topology {
private:
/** Conversion factor for bytes to gb. */
static constexpr float bytes_to_gb = 1.0f / 1073741824.0f;
public:
/** Constructor to create the topology. */
Topology() noexcept {
gpus = GpuInfo::create_for_all_devices();
}
/**
* Gets the number of gpus in the system.
* \return The total number of gpus in the system.
*/
auto num_gpus() const noexcept -> size_t {
return gpus.size();
}
/**
* Gets the number of cpu cores for the system.
* \return The number of independent cpu cores in the system.
*/
auto num_cores() const noexcept -> size_t {
return cpu_info.available_cores();
}
/**
* Calculates the total number of bytes of memory available from all gpus.
* \return The total number of bytes of gpu memory in the system.
*/
auto combined_gpu_memory() const noexcept -> uint64_t {
uint64_t total_mem = 0;
for (const auto& gpu : gpus) {
total_mem += gpu.mem_size;
}
return total_mem;
}
/**
* Calculates the total number of gigabytes of memory available from all gpus.
* \return The total number of gigabytes of gpu memory in the system.
*/
auto combined_gpu_memory_gb() const noexcept -> float {
return static_cast<float>(combined_gpu_memory()) * bytes_to_gb;
}
/**
* Determines if peer to peer access is possible between two gpus.
* \param size_t gpu_id1 The index of the first gpu.
* \param size_t gpu_id2 The index of the second gpu.
* \return true if peer to peer is possible between the gpus.
*/
auto device_to_device_available(size_t gpu_id1, size_t gpu_id2) const noexcept
-> bool {
return gpu_id1 == gpu_id2 || gpus[gpu_id1].peer_to_peer_available(gpu_id2);
}
std::vector<GpuInfo> gpus; //!< Gpus for the system.
CpuInfo cpu_info; //!< Cpu info for the system.
};
/**
* Gets a reference to the system topology.
* \return A reference to the system topology.
*/
static inline auto topology() noexcept -> Topology& {
static Topology topo;
return topo;
}
} // namespace ripple
#endif // RIPPLE_ARCH_TOPOLOGY_HPP
| 29.435185
| 80
| 0.634476
|
robclu
|
45dfacd03bb18689548bf9e7b3e6473738583a7c
| 1,233
|
cpp
|
C++
|
src/ui/page.cpp
|
demisardonic/battletested
|
89f502a721f4d7056a74acd22af9d79c8e3f0dba
|
[
"MIT"
] | null | null | null |
src/ui/page.cpp
|
demisardonic/battletested
|
89f502a721f4d7056a74acd22af9d79c8e3f0dba
|
[
"MIT"
] | null | null | null |
src/ui/page.cpp
|
demisardonic/battletested
|
89f502a721f4d7056a74acd22af9d79c8e3f0dba
|
[
"MIT"
] | null | null | null |
#include <ncurses.h>
#include "ui/page.h"
#include "ui/page_game.h"
#include "ui/ui.h"
Page::Page(UI *ui){
this->parent = ui;
}
AnyKeyPage::AnyKeyPage(UI *ui, Page *next):Page(ui){
nextPage = next;
}
void AnyKeyPage::input(){
getch();
this->parent->change_page(nextPage);
}
void AnyKeyPage::exit(){
delete this;
}
void AnyKeyPage::update(){
}
TitlePage::TitlePage(UI *ui):AnyKeyPage(ui, new GamePage(ui)){
}
void TitlePage::draw(){
mvprintw(17,9," _ _ _ _ _____ _ _ ");
mvprintw(18,9,"| | | | | | | | |_ _| | | | |");
mvprintw(19,9,"| |__ __ _ | |_ | |_ | | ___ | | ___ ___ | |_ ___ __| |");
mvprintw(20,9,"| '_ \\ / _` || __|| __|| | / _ \\ | | / _ \\/ __|| __| / _ \\ / _` |");
mvprintw(21,9,"| |_) || (_| || |_ | |_ | || __/ | | | __/\\__ \\| |_ | __/| (_| |");
mvprintw(22,9,"|_.__/ \\__,_| \\__| \\__||_| \\___| \\_/ \\___||___/ \\__| \\___| \\__,_|");
}
void TitlePage::enter(){
}
BlankPage::BlankPage(UI *ui):Page(ui){
}
void BlankPage::draw(){
clear();
}
void BlankPage::input(){
getch();
}
void BlankPage::update(){
}
| 20.898305
| 98
| 0.459854
|
demisardonic
|
45e2c9896ed64d297bec34ed7d9c90ed3471c5db
| 26,183
|
cc
|
C++
|
FELICITY/Static_Codes/AHF/src_code/Mesh.cc
|
brianchowlab/BcLOV4-FEM
|
f54bd8efa0e0f2c7ca2de4a6688ef1a403376285
|
[
"MIT"
] | null | null | null |
FELICITY/Static_Codes/AHF/src_code/Mesh.cc
|
brianchowlab/BcLOV4-FEM
|
f54bd8efa0e0f2c7ca2de4a6688ef1a403376285
|
[
"MIT"
] | null | null | null |
FELICITY/Static_Codes/AHF/src_code/Mesh.cc
|
brianchowlab/BcLOV4-FEM
|
f54bd8efa0e0f2c7ca2de4a6688ef1a403376285
|
[
"MIT"
] | null | null | null |
/*
============================================================================================
Class for array based half-facet (AHF) data structure. This is a sub-class of BaseMesh
which stores a *pointer* to a BasePtCoord object. This way, many different meshes,
of varying topological dimension, can share the same vertex (point) coordinates. This
also means that we can implement various methods in a more general way.
Note: Everything is indexed starting at 0!
Also note: using a vector of structs is 2 x faster than using a vector of integers.
Copyright (c) 05-23-2020, Shawn W. Walker
============================================================================================
*/
#define _MESH_CC
#ifndef _BASICMATH_H
#include "BasicMath.h" // simple math operations
#endif
#ifndef _BASEMESH_CC
#include "BaseMesh.cc" // base class for all mesh topology stuff
#endif
#ifndef _BASEPTCOORD_CC
#include "BasePtCoord.cc" // base class for all vertex coordinates
#endif
/* C++ class definition */
#define MMC Mesh
// template the topological and geometric dimension
template <SmallIndType CELL_DIM, SmallIndType GEO_DIM>
class MMC: public BaseMesh<CELL_DIM>
{
public:
MMC();
MMC(BasePtCoord<GEO_DIM>*);
~MMC();
// open Mesh for modification
inline void Open()
{
BaseMesh<CELL_DIM>::Open();
Vtx->Open();
};
// close Mesh; modification is no longer allowed
inline void Close()
{
BaseMesh<CELL_DIM>::Close();
Vtx->Close();
};
// clear all data
void Clear()
{
BaseMesh<CELL_DIM>::Clear();
Vtx->Clear();
};
// set pointer to vertex coordinates
void Set_Vertex_Data(BasePtCoord<GEO_DIM>*);
// coordinate conversion
void Reference_To_Cartesian(const CellIndType&, const CellIndType*, const PointType*, PointType*);
void Cartesian_To_Reference(const CellIndType&, const CellIndType*, const PointType*, PointType*);
void Barycentric_To_Reference(const CellIndType&, const PointType*, PointType*);
void Reference_To_Barycentric(const CellIndType&, const PointType*, PointType*);
void Barycentric_To_Cartesian(const CellIndType&, const CellIndType*, const PointType*, PointType*);
void Cartesian_To_Barycentric(const CellIndType&, const CellIndType*, const PointType*, PointType*);
// cell quantities
void Diameter(const CellIndType&, const CellIndType*, RealType*);
void Bounding_Box(const CellIndType&, const CellIndType*, PointType*, PointType*);
void Bounding_Box(PointType*, PointType*);
void Volume(const CellIndType&, const CellIndType*, RealType*);
// Angles!!!!
// simplex centers
void Barycenter(const CellIndType&, const CellIndType*, PointType*);
void Circumcenter(const CellIndType&, const CellIndType*, PointType*, RealType*);
void Incenter(const CellIndType&, const CellIndType*, PointType*, RealType*);
// others
void Shape_Regularity(const CellIndType&, const CellIndType*, RealType*);
private:
/* keep a pointer to the set of global vertex coordinates */
BasePtCoord<GEO_DIM>* Vtx;
// basic internal method
void init();
};
/***************************************************************************************/
/* constructor */
template <SmallIndType CELL_DIM, SmallIndType GEO_DIM>
MMC<CELL_DIM, GEO_DIM>::MMC() : BaseMesh<CELL_DIM>()
{
init(); // basic initialization
}
/***************************************************************************************/
/* constructor */
template <SmallIndType CELL_DIM, SmallIndType GEO_DIM>
MMC<CELL_DIM, GEO_DIM>::MMC(BasePtCoord<GEO_DIM>* Input_Vtx) : BaseMesh<CELL_DIM>()
{
init(); // basic initialization
Set_Vertex_Data(Input_Vtx);
Open(); // init to open
}
/***************************************************************************************/
/* set pointer for the vertex coordinate data */
template <SmallIndType CELL_DIM, SmallIndType GEO_DIM>
void MMC<CELL_DIM, GEO_DIM>::init()
{
// initialize pointer to vertex coordinates
Vtx = (BasePtCoord<GEO_DIM>*) NULL;
// what else to do or check?
if (GEO_DIM < CELL_DIM)
{
std::cout << "Desired topological dimension of a cell is " << CELL_DIM << "." << std::endl;
std::cout << "Desired geometric dimension is " << GEO_DIM << "." << std::endl;
std::cout << "Geometric dimension must be >= topological dimension!" << std::endl;
std::exit(1);
}
//std::cout << "Mesh constructor..." << std::endl;
}
/***************************************************************************************/
/* DE-structor */
template <SmallIndType CELL_DIM, SmallIndType GEO_DIM>
MMC<CELL_DIM, GEO_DIM>::~MMC()
{
Clear();
//std::cout << "Mesh destructor..." << std::endl;
}
/***************************************************************************************/
/* set pointer for the vertex coordinate data */
template <SmallIndType CELL_DIM, SmallIndType GEO_DIM>
void MMC<CELL_DIM, GEO_DIM>::Set_Vertex_Data(BasePtCoord<GEO_DIM>* Input_Vtx)
{
// set pointer to vertex coordinates
Vtx = Input_Vtx;
}
/***************************************************************************************/
/* convert reference element coordinates to cartesian coordinates, where the reference
element is the "standard" reference simplex.
Inputs: number of cells, and the cell indices (an array),
reference coordinates (an array of consecutive groups of length CELL_DIM
Outputs: cartesian coordinates (an array of consecutive groups of length GEO_DIM
NOTE: the number of groups equals the number of cells. */
template <SmallIndType CELL_DIM, SmallIndType GEO_DIM>
void MMC<CELL_DIM, GEO_DIM>::Reference_To_Cartesian(
const CellIndType& Num_Cell, const CellIndType* CI,
const PointType* PR,
PointType* PC)
{
MMC const& this_mesh = *this; // for const
const BasePtCoord<GEO_DIM>* const& c_Vtx = Vtx; // for const
// loop through the given cells
for (CellIndType ii=0; ii < Num_Cell; ++ii)
{
// get the vertex indices of the current cell
const VtxIndType* VI = this_mesh.Get_Cell_vtx(CI[ii]);
// get the relevant ref-coord for the current cell
const PointType* PR_ii = PR + ii*CELL_DIM;
// get relevant output for current cell
PointType* PC_local = PC + ii*GEO_DIM;
Simplex_Reference_To_Cartesian<CELL_DIM, GEO_DIM>(c_Vtx, VI, PR_ii, PC_local);
}
}
/***************************************************************************************/
/* convert cartesian coordinates to reference element coordinates, where the reference
element is the "standard" reference simplex.
Inputs: number of cells, and the cell indices (an array),
cartesian coordinates (an array of consecutive groups of length GEO_DIM
Outputs: reference coordinates (an array of consecutive groups of length CELL_DIM
NOTE: the number of groups equals the number of cells. */
template <SmallIndType CELL_DIM, SmallIndType GEO_DIM>
void MMC<CELL_DIM, GEO_DIM>::Cartesian_To_Reference(
const CellIndType& Num_Cell, const CellIndType* CI,
const PointType* PC,
PointType* PR)
{
MMC const& this_mesh = *this; // for const
const BasePtCoord<GEO_DIM>* const& c_Vtx = Vtx; // for const
// loop through the given cells
for (CellIndType ii=0; ii < Num_Cell; ++ii)
{
// get the vertex indices of the current cell
const VtxIndType* VI = this_mesh.Get_Cell_vtx(CI[ii]);
// get relevant cart-coord for current cell
const PointType* PC_local = PC + ii*GEO_DIM;
// get the relevant output for the current cell
PointType* PR_ii = PR + ii*CELL_DIM;
Simplex_Cartesian_To_Reference<CELL_DIM, GEO_DIM>(c_Vtx, VI, PC_local, PR_ii);
}
}
/***************************************************************************************/
/* convert barycentric coordinates to reference element coordinates.
Inputs: number of cells,
barycentric coordinates (an array of consecutive groups of length (CELL_DIM+1)
Outputs: reference coordinates (an array of consecutive groups of length CELL_DIM
NOTE: the number of groups equals the number of cells. */
template <SmallIndType CELL_DIM, SmallIndType GEO_DIM>
void MMC<CELL_DIM, GEO_DIM>::Barycentric_To_Reference(
const CellIndType& Num_Cell, const PointType* PB,
PointType* PR)
{
// just copy over the 1st thru CELL_DIM barycentric coordinates
for (CellIndType ii=0; ii < Num_Cell; ++ii)
{
// get relevant bary-coord for current cell
const PointType* PB_local = PB + ii*(CELL_DIM+1);
// get the relevant output for the current cell
PointType* PR_ii = PR + ii*CELL_DIM;
Simplex_Barycentric_To_Reference<CELL_DIM>(PB_local, PR_ii);
}
}
/***************************************************************************************/
/* convert reference element coordinates to barycentric coordinates.
Inputs: number of cells,
reference coordinates (an array of consecutive groups of length CELL_DIM
Outputs: barycentric coordinates (an array of consecutive groups of length (CELL_DIM+1)
NOTE: the number of groups equals the number of cells. */
template <SmallIndType CELL_DIM, SmallIndType GEO_DIM>
void MMC<CELL_DIM, GEO_DIM>::Reference_To_Barycentric(
const CellIndType& Num_Cell, const PointType* PR,
PointType* PB)
{
// just copy over the 1st thru (CELL_DIM) barycentric coordinates
for (CellIndType ii=0; ii < Num_Cell; ++ii)
{
// get relevant ref-coord for current cell
const PointType* PR_local = PR + ii*CELL_DIM;
// get the relevant output for the current cell
PointType* PB_ii = PB + ii*(CELL_DIM+1);
Simplex_Reference_To_Barycentric<CELL_DIM>(PR_local, PB_ii);
}
}
/***************************************************************************************/
/* convert barycentric coordinates to cartesian coordinates.
Inputs: number of cells, and the cell indices (an array),
barycentric coordinates (an array of consecutive groups of length (CELL_DIM+1)
Outputs: cartesian coordinates (an array of consecutive groups of length GEO_DIM
NOTE: the number of groups equals the number of cells. */
template <SmallIndType CELL_DIM, SmallIndType GEO_DIM>
void MMC<CELL_DIM, GEO_DIM>::Barycentric_To_Cartesian(
const CellIndType& Num_Cell, const CellIndType* CI,
const PointType* PB,
PointType* PC)
{
MMC const& this_mesh = *this; // for const
const BasePtCoord<GEO_DIM>* const& c_Vtx = Vtx; // for const
// loop through the given cells
for (CellIndType ii=0; ii < Num_Cell; ++ii)
{
// get the vertex indices of the current cell
const VtxIndType* VI = this_mesh.Get_Cell_vtx(CI[ii]);
// get the relevant bary-coord for the current cell
const PointType* PB_local = PB + ii*(CELL_DIM+1);
// get relevant output for current cell
PointType* PC_ii = PC + ii*GEO_DIM;
Simplex_Barycentric_To_Cartesian<CELL_DIM, GEO_DIM>(c_Vtx, VI, PB_local, PC_ii);
}
}
/***************************************************************************************/
/* convert cartesian coordinates to barycentric coordinates.
Inputs: number of cells, and the cell indices (an array),
cartesian coordinates (an array of consecutive groups of length GEO_DIM
Outputs: barycentric coordinates (an array of consecutive groups of length (CELL_DIM+1)
NOTE: the number of groups equals the number of cells. */
template <SmallIndType CELL_DIM, SmallIndType GEO_DIM>
void MMC<CELL_DIM, GEO_DIM>::Cartesian_To_Barycentric(
const CellIndType& Num_Cell, const CellIndType* CI,
const PointType* PC,
PointType* PB)
{
// first, convert from cartesian to reference domain coordinates
PointType* PR = new PointType[Num_Cell*CELL_DIM];
Cartesian_To_Reference(Num_Cell, CI, PC, PR);
Reference_To_Barycentric(Num_Cell, PR, PB);
delete(PR);
}
/***************************************************************************************/
/* compute the diameter of (simplex) cells in the mesh.
Inputs: number of cells, and the cell indices (an array)
Outputs: diameter of each simplex (an array), defined to be the maximum edge length
NOTE: the length of the arrays equals the number of cells. */
template <SmallIndType CELL_DIM, SmallIndType GEO_DIM>
void MMC<CELL_DIM, GEO_DIM>::Diameter(
const CellIndType& Num_Cell, const CellIndType* CI,
RealType* Diam)
{
MMC const& this_mesh = *this; // for const
const BasePtCoord<GEO_DIM>* const& c_Vtx = Vtx; // for const
if (CELL_DIM==0) // diameters are zero!
{
// loop through the given cells
for (CellIndType ii=0; ii < Num_Cell; ++ii)
{
Diam[ii] = 0.0;
}
}
else
{
// loop through the given cells
for (CellIndType ii=0; ii < Num_Cell; ++ii)
{
// get the vertex indices of the current cell
const VtxIndType* VI = this_mesh.Get_Cell_vtx(CI[ii]);
Diam[ii] = Simplex_Diameter<CELL_DIM, GEO_DIM>(c_Vtx, VI);
}
}
}
/***************************************************************************************/
/* return the bounding (cartesian) box of the given cells in the mesh.
Inputs: number of cells, and the cell indices (an array)
Output: min and max limits of the coordinates (component-wise).
example: if GEO_DIM==3, then
BB_min[] = {X_min, Y_min, Z_min},
BB_max[] = {X_max, Y_max, Z_max}. */
template <SmallIndType CELL_DIM, SmallIndType GEO_DIM>
void MMC<CELL_DIM, GEO_DIM>::Bounding_Box(
const CellIndType& Num_Cell, const CellIndType* CI,
PointType* BB_min, PointType* BB_max)
{
MMC const& this_mesh = *this; // for const
const BasePtCoord<GEO_DIM>* const& c_Vtx = Vtx; // for const
std::vector<VtxIndType> mesh_vertices;
mesh_vertices.reserve(Num_Cell*(CELL_DIM+1));
// loop through the given cells
for (CellIndType ii=0; ii < Num_Cell; ++ii)
{
// get the vertex indices of the current cell
const VtxIndType* VI = this_mesh.Get_Cell_vtx(CI[ii]);
for (SmallIndType tt=0; tt < (CELL_DIM+1); ++tt)
{
mesh_vertices.push_back(VI[tt]);
}
}
// make the vertex list unique
std::sort( mesh_vertices.begin(), mesh_vertices.end() );
std::vector<VtxIndType>::iterator it;
it = std::unique (mesh_vertices.begin(), mesh_vertices.end());
mesh_vertices.resize( std::distance(mesh_vertices.begin(), it) );
const VtxIndType Num_Vtx = (VtxIndType) mesh_vertices.size();
const VtxIndType* VI = mesh_vertices.data();
c_Vtx->Bounding_Box(Num_Vtx, VI, BB_min, BB_max);
}
/* return the bounding (cartesian) box of the *entire* mesh. */
template <SmallIndType CELL_DIM, SmallIndType GEO_DIM>
void MMC<CELL_DIM, GEO_DIM>::Bounding_Box(PointType* BB_min, PointType* BB_max)
{
MMC const& this_mesh = *this; // for const
const BasePtCoord<GEO_DIM>* const& c_Vtx = Vtx; // for const
std::vector<VtxIndType> mesh_vertices;
this_mesh.Get_Unique_Vertices(mesh_vertices);
const VtxIndType Num_Vtx = (VtxIndType) mesh_vertices.size();
const VtxIndType* VI = mesh_vertices.data();
c_Vtx->Bounding_Box(Num_Vtx, VI, BB_min, BB_max);
}
/***************************************************************************************/
/* compute the volume of (simplex) cells in the mesh.
Inputs: number of cells, and the cell indices (an array)
Outputs: volume of each simplex (an array)
NOTE: the length of the arrays equals the number of cells. */
template <SmallIndType CELL_DIM, SmallIndType GEO_DIM>
void MMC<CELL_DIM, GEO_DIM>::Volume(
const CellIndType& Num_Cell, const CellIndType* CI,
RealType* Vol)
{
MMC const& this_mesh = *this; // for const
const BasePtCoord<GEO_DIM>* const& c_Vtx = Vtx; // for const
// loop through the given cells
for (CellIndType ii=0; ii < Num_Cell; ++ii)
{
// get the vertex indices of the current cell
const VtxIndType* VI = this_mesh.Get_Cell_vtx(CI[ii]);
Vol[ii] = Simplex_Volume<CELL_DIM, GEO_DIM>(c_Vtx, VI);
}
}
/***************************************************************************************/
/* compute the barycenter of (simplex) cells in the mesh.
Inputs: number of cells, and the cell indices (an array)
Outputs: cartesian coordinates of center (an array of consecutive groups of length GEO_DIM)
NOTE: the number of groups equals the number of cells. */
template <SmallIndType CELL_DIM, SmallIndType GEO_DIM>
void MMC<CELL_DIM, GEO_DIM>::Barycenter(
const CellIndType& Num_Cell, const CellIndType* CI,
PointType* CC)
{
MMC const& this_mesh = *this; // for const
const BasePtCoord<GEO_DIM>* const& c_Vtx = Vtx; // for const
// loop through the given cells
for (CellIndType ii=0; ii < Num_Cell; ++ii)
{
// get the vertex indices of the current cell
const VtxIndType* VI = this_mesh.Get_Cell_vtx(CI[ii]);
// get relevant output for current cell
PointType* PC_local = PC + ii*GEO_DIM;
Simplex_Barycenter<CELL_DIM, GEO_DIM>(c_Vtx, VI, PC_local);
}
}
/***************************************************************************************/
/* compute the circumcenter and circumradius of (simplex) cells in the mesh.
see: https://westy31.home.xs4all.nl/Circumsphere/ncircumsphere.htm#Coxeter
Inputs: number of cells, and the cell indices (an array)
Outputs: barycentric coordinates of center (an array of consecutive groups of length (CELL_DIM+1))
circumradius (an array with same length as number of cells)
NOTE: the number of groups equals the number of cells. */
template <SmallIndType CELL_DIM, SmallIndType GEO_DIM>
void MMC<CELL_DIM, GEO_DIM>::Circumcenter(
const CellIndType& Num_Cell, const CellIndType* CI,
PointType* CB, RealType* CR)
{
MMC const& this_mesh = *this; // for const
const BasePtCoord<GEO_DIM>* const& c_Vtx = Vtx; // for const
// loop through the given cells
for (CellIndType ii=0; ii < Num_Cell; ++ii)
{
// get the vertex indices of the current cell
const VtxIndType* VI = this_mesh.Get_Cell_vtx(CI[ii]);
// get relevant output for current cell
PointType* CB_ii = CB + ii*(CELL_DIM+1);
CR[ii] = Simplex_Circumcenter<CELL_DIM, GEO_DIM>(c_Vtx, VI, CB_ii);
}
}
/***************************************************************************************/
/* compute the incenter and inradius of (simplex) cells in the mesh.
see: "Coincidences of simplex centers and related facial structures" by Edmonds, et al.
Inputs: number of cells, and the cell indices (an array)
Outputs: barycentric coordinates of center (an array of consecutive groups of length (CELL_DIM+1))
inradius (an array with same length as number of cells)
NOTE: the number of groups equals the number of cells. */
template <SmallIndType CELL_DIM, SmallIndType GEO_DIM>
void MMC<CELL_DIM, GEO_DIM>::Incenter(
const CellIndType& Num_Cell, const CellIndType* CI,
PointType* CB, RealType* CR)
{
MMC const& this_mesh = *this; // for const
const BasePtCoord<GEO_DIM>* const& c_Vtx = Vtx; // for const
// loop through the given cells
for (CellIndType ii=0; ii < Num_Cell; ++ii)
{
// get the vertex indices of the current cell
const VtxIndType* VI = this_mesh.Get_Cell_vtx(CI[ii]);
// get relevant output for current cell
PointType* CB_ii = CB + ii*(CELL_DIM+1);
CR[ii] = Simplex_Incenter<CELL_DIM, GEO_DIM>(c_Vtx, VI, CB_ii);
}
}
/***************************************************************************************/
/* compute the "shape regularity" of (simplex) cells in the mesh.
Inputs: number of cells, and the cell indices (an array)
Outputs: the "shape regularity" ratio (an array with same length as number of cells)
*/
template <SmallIndType CELL_DIM, SmallIndType GEO_DIM>
void MMC<CELL_DIM, GEO_DIM>::Shape_Regularity(
const CellIndType& Num_Cell, const CellIndType* CI,
RealType* SR)
{
MMC const& this_mesh = *this; // for const
const BasePtCoord<GEO_DIM>* const& c_Vtx = Vtx; // for const
// loop through the given cells
for (CellIndType ii=0; ii < Num_Cell; ++ii)
{
// get the vertex indices of the current cell
const VtxIndType* VI = this_mesh.Get_Cell_vtx(CI[ii]);
SR[ii] = Simplex_Shape_Regularity<CELL_DIM, GEO_DIM>(c_Vtx, VI);
}
}
// SWW: the only methods that go here are the ones that require BOTH cell connectivity
// *and* vertex coordinates.
// add these methods:
// is it better to have a generic method that calls the other stuff???
/* easy:
Angles (hard if you want to be general...)
(need a local-to-global mapping sub-routine...)
Remove_Unused_Vertices
*/
/*
function [Global_to_Local_Indexing, Local_to_Global_Indexing] =...
Create_Global_Local_Index_Mapping(Ordered_Indices,Max_Global_Index)
%Create_Global_Local_Index_Mapping
%
% This routine creates two vectors of data that act as mappings between 'local' and
% 'global' indexing.
%
% [Global_to_Local_Indexing, Local_to_Global_Indexing] =
% Create_Global_Local_Index_Mapping(Ordered_Indices,Max_Global_Index)
%
% OUTPUTS
% -------
% Global_to_Local_Indexing:
% A (Max_Global_Index x 1) array that maps from global indices to local
% indices. In other words, to get the local index corresponding to global
% index 'j', just look at Global_to_Local_Indexing(j). Note: some of the riws
%
% Local_to_Global_Indexing:
% An Nx1 array that maps from local indices to global indices. In other words,
% to get the global index corresponding to local index 'i', just look at
% Local_to_Global_Indexing(i).
% Note: 'Local_to_Global_Indexing' = 'Ordered_Indices'.
%
% Examples:
%
% Global_to_Local_Indexing:
%
% (Global Indexing) (Col) (Local Indexing)
% Node #1 (Row #1): 6 <-- Local Node #6
% Node #2 (Row #2): 3 <-- Local Node #3
% Node #3 (Row #3): 0 <-- NOT a Local Node
% Node #4 (Row #4): 0 <-- NOT a Local Node
% Node #5 (Row #5): 2 <-- Local Node #2
% Node #6 (Row #6): 1 <-- Local Node #1
% Node #7 (Row #7): 0 <-- NOT a Local Node
% Node #8 (Row #8): 7 <-- Local Node #7
% ...
%
% Local_to_Global_Indexing:
%
% (Local Indexing) (Col) (Global Indexing)
% Node #1 (Row #1): 6 <-- Global Node #6
% Node #2 (Row #2): 5 <-- Global Node #5
% Node #3 (Row #3): 2 <-- Global Node #2
% Node #4 (Row #4): 10 <-- Global Node #10
% Node #5 (Row #5): 14 <-- Global Node #14
% Node #6 (Row #6): 1 <-- Global Node #1
% Node #7 (Row #7): 8 <-- Global Node #8
% Node #8 (Row #8): 17 <-- Global Node #17
% ...
%
% INPUTS
% ------
% Ordered_Indices:
% An Nx1 array of numbers considered to be indices into a global data
% structure. However, row i of 'Ordered_Indices' corresponds to index 'i' in
% the local data structure.
%
% Max_Global_Index:
% Largest index value in the global data structure (must be greater than N).
% Copyright (c) 06-05-2007, Shawn W. Walker
Local_to_Global_Indexing = Ordered_Indices;
Local_Index_Vec = (1:1:length(Ordered_Indices))';
Global_to_Local_Indexing = zeros(Max_Global_Index,1);
Global_to_Local_Indexing(Local_to_Global_Indexing,1) = Local_Index_Vec;
end
*/
// make simple Python interface BEFORE doing mesh refinement...
// make uniform refinement a separate thing
// need adaptive refinement
// don't worry about modifying the cell data structure yet, b/c this is connected to refinement
// need topological/connectivity changes!!!! for this, in 3-D, can think of an edge as the intersection of two half-facets?
/* easy:
faceNormal (simplex normal/normal space)
featureEdges (complicated for general dimension)
vertexNormal (averaged normal space when normal space is 1-D)
tetrahedron:
Order_Cell_Vertices_For_Hcurl (special case for tetrahedra, CELL_DIM==3)
faces?
facetNormal?
Get_Facet_Info?
interval:
edgeTangent (simplex tangent/tangent space)
featurePoints
Get_Arclength
vertexTangent (averaged tangent space when tangent space is 1-D)
*/
/* harder:
Get_Adjacency_Matrix
Reorder
Get_Facet_Info?
Get_Laplacian_Smoothing_Matrix
**Refine
*/
/* move to multi-mesh
nearestNeighbor: Vertex closest to a specified point
pointLocation: simplex containing specified point
*/
// For my mesh generator, need to evaluate cut edges. can do this by first finding all intersected tetrahedra. then make an edge mesh from that?
// Or just store all the unique edges of the mesh? think of the edge mesh as a graph! Store each edge as a pair of vertices (with smallest global index first) and the cell that the edge belongs to.
#undef MMC
/***/
| 38.847181
| 199
| 0.612917
|
brianchowlab
|
45e61a32ceeb77e71341412ab0708f3a04aa3abd
| 1,341
|
cpp
|
C++
|
CppSTL/Chapter1/operators/op_une.cpp
|
SebastianTirado/Cpp-Learning-Archive
|
fb83379d0cc3f9b2390cef00119464ec946753f4
|
[
"MIT"
] | 19
|
2019-09-15T12:23:51.000Z
|
2020-06-18T08:31:26.000Z
|
CppSTL/Chapter1/operators/op_une.cpp
|
SebastianTirado/Cpp-Learning-Archive
|
fb83379d0cc3f9b2390cef00119464ec946753f4
|
[
"MIT"
] | 15
|
2021-12-07T06:46:03.000Z
|
2022-01-31T07:55:32.000Z
|
CppSTL/Chapter1/operators/op_une.cpp
|
SebastianTirado/Cpp-Learning-Archive
|
fb83379d0cc3f9b2390cef00119464ec946753f4
|
[
"MIT"
] | 13
|
2019-06-29T02:58:27.000Z
|
2020-05-07T08:52:22.000Z
|
#include <iostream>
#include <vector>
using std::vector;
using std::endl;
using std::ostream;
template<class T1, class T2>
class A {
template<class t1, class t2>
friend ostream& operator<<( ostream& , const A<t1, t2>& );
public:
explicit A() : a(2.0), b(2.0) {};
A(T1 aa, T2 bb) : a(aa), b(bb) {};
A<T1, T2> operator+( const A<T1, T2>& );
/* Overloading the unary operator ! */
A<T1, T2> operator!() {
return A<T1, T2>(-a, -b);
}
/* Overloading the operator '*' to return a multiplied x10 and b multiplied x20 */
A<T1, T2> operator*() {
return A<T1, T2>(a*10, b*20);
}
private:
T1 a;
T2 b;
};
template<class T1, class T2>
A<T1, T2> A<T1, T2>::operator+( const A<T1, T2>& a1)
{
return A<T1, T2>(this->a+a1.a, this->b+a1.b);
}
template<class T1, class T2>
ostream& operator<<( ostream& out, const A<T1, T2>& a1)
{
out << "a= " << a1.a << " | b= " << a1.b << endl;
return out;
}
int main(int argc, char* argv[]) {
A<int, double> a1, a2(4, 3.0), a3(0,0);
A<int, double> *ptr;
a1 = a2;
ptr = &a2;
/* a3 = a1+a2; | Same as below */
a3 = a1.operator+(a2);
/* Print a few tests */
std::cout << "a1: " << a1 << "\na2: " << a2 << "\na3: " << a3;
std::cout << "!a1: " << !a1;
std::cout << "*a2: " << *a2;
return 0;
}
| 22.728814
| 86
| 0.51827
|
SebastianTirado
|
45ea6a214560d1758947730f90e7327200ebd181
| 1,691
|
hpp
|
C++
|
meta/symboltable.hpp
|
tamim-asif/lgraph-private
|
733bbcd9e14a9850580b51c011e33785ab758b9d
|
[
"BSD-3-Clause"
] | null | null | null |
meta/symboltable.hpp
|
tamim-asif/lgraph-private
|
733bbcd9e14a9850580b51c011e33785ab758b9d
|
[
"BSD-3-Clause"
] | null | null | null |
meta/symboltable.hpp
|
tamim-asif/lgraph-private
|
733bbcd9e14a9850580b51c011e33785ab758b9d
|
[
"BSD-3-Clause"
] | null | null | null |
#ifndef LGRAPH_SYMBOL_TABLE_H_
#define LGRAPH_SYMBOL_TABLE_H_
#include "lgraphbase.hpp"
#include "integer.hpp"
#include "pyrope_type.hpp"
#include <sparsehash/dense_hash_map>
#include <string>
using Symbol_Mapping = Char_Array<Index_ID>; // maps Index_ID (of node) => Char_Array_ID (of variable cast from Index_ID),
// and Char_Array_ID => variable name
using Type_Mapping = Dense<Pyrope_Type>; // Char_Array_ID (of variable name) => Pyrope_Type
const std::string LGRAPH_SYMBOL_TABLE_SYM_FLAG = "_symb";
const std::string LGRAPH_SYMBOL_TABLE_TYP_FLAG = "_varb";
class LGraph_Symbol_Table : virtual public LGraph_Base {
public:
LGraph_Symbol_Table() = delete;
explicit LGraph_Symbol_Table(const std::string &path, const std::string &name) noexcept;
virtual ~LGraph_Symbol_Table();
void set_node_variable_type(Index_ID node, const std::string &variable, const Pyrope_Type &t);
const char *get_node_variable(Index_ID node) const;
const Pyrope_Type &get_node_variable_type(Index_ID id) const;
void merge(Index_ID n1, Index_ID n2);
void merge(Index_ID n, const Pyrope_Type &t);
Char_Array_ID save_integer(const Integer &);
Integer load_integer(Char_Array_ID) const;
virtual void clear();
virtual void reload();
virtual void sync();
virtual void emplace_back();
private:
Char_Array_ID str2id(const std::string &s) { return (symbols.include(s)) ? symbols.get_id(s) : symbols.create_id(s); }
Char_Array_ID node2id(Index_ID node) const { return symbols.get_field(std::to_string(node)); }
Symbol_Mapping symbols;
Type_Mapping types;
};
#endif
| 35.229167
| 127
| 0.717918
|
tamim-asif
|
45eb26741075e63e772f9d51273ccd651456f72b
| 608
|
hpp
|
C++
|
sprout/rational/values.hpp
|
osyo-manga/Sprout
|
8885b115f739ef255530f772067475d3bc0dcef7
|
[
"BSL-1.0"
] | 1
|
2020-02-04T05:16:01.000Z
|
2020-02-04T05:16:01.000Z
|
sprout/rational/values.hpp
|
osyo-manga/Sprout
|
8885b115f739ef255530f772067475d3bc0dcef7
|
[
"BSL-1.0"
] | null | null | null |
sprout/rational/values.hpp
|
osyo-manga/Sprout
|
8885b115f739ef255530f772067475d3bc0dcef7
|
[
"BSL-1.0"
] | null | null | null |
#ifndef SPROUT_RATIONAL_VALUES_HPP
#define SPROUT_RATIONAL_VALUES_HPP
#include <sprout/config.hpp>
#include <sprout/rational/rational.hpp>
#include <sprout/cstdlib/abs.hpp>
namespace sprout {
//
// abs
//
template<typename IntType>
inline SPROUT_CONSTEXPR sprout::rational<IntType>
abs(sprout::rational<IntType> const& x) {
return x.numerator() >= IntType(0) ? x
: sprout::detail::make_rational<IntType>(
-x.numerator(), x.denominator(),
sprout::detail::rational_private_constructor_tag()
)
;
}
} // namespace sprout
#endif // SPROUT_RATIONAL_VALUES_HPP
| 24.32
| 55
| 0.702303
|
osyo-manga
|
45eb6a7e47c044c70b8c05a3e2f78a3735462eab
| 515
|
hpp
|
C++
|
webserv/Abstract&Interfaces/AServer.hpp
|
sfcdota/mini-web-server
|
69be414a8824570a8f0b85d3eb567614ed54892b
|
[
"BSD-3-Clause"
] | null | null | null |
webserv/Abstract&Interfaces/AServer.hpp
|
sfcdota/mini-web-server
|
69be414a8824570a8f0b85d3eb567614ed54892b
|
[
"BSD-3-Clause"
] | null | null | null |
webserv/Abstract&Interfaces/AServer.hpp
|
sfcdota/mini-web-server
|
69be414a8824570a8f0b85d3eb567614ed54892b
|
[
"BSD-3-Clause"
] | null | null | null |
//
// Created by sfcdo on 20.07.2021.
//
#ifndef WEBSERV_ASERVER_HPP_
#define WEBSERV_ASERVER_HPP_
#include <vector>
#include "parser.hpp"
#include "../BufferReader.hpp"
class AServer {
protected:
AServer(const std::vector<ServerConfig>& config, const ssize_t & INPUT_BUFFER_SIZE);
virtual ~AServer();
fd_set master_read_, working_read_,
master_write_, working_write_;
timeval timeout_;
const std::vector<ServerConfig>& config_;
BufferReader buffer_reader_;
};
#endif //WEBSERV_ASERVER_HPP_
| 23.409091
| 86
| 0.751456
|
sfcdota
|
45eb89d594e84151bd1dd181295def7229f4f633
| 2,110
|
cpp
|
C++
|
tests/test-graph.cpp
|
inetic/club
|
1fa777beaf8ddf9cf6817dea08dbca579113a989
|
[
"Apache-2.0"
] | 122
|
2016-06-23T12:27:24.000Z
|
2016-08-01T06:11:55.000Z
|
tests/test-graph.cpp
|
inetic/libclub
|
1fa777beaf8ddf9cf6817dea08dbca579113a989
|
[
"Apache-2.0"
] | 2
|
2019-09-03T17:44:48.000Z
|
2019-09-03T17:48:27.000Z
|
tests/test-graph.cpp
|
inetic/libclub
|
1fa777beaf8ddf9cf6817dea08dbca579113a989
|
[
"Apache-2.0"
] | 15
|
2016-11-03T10:10:56.000Z
|
2021-03-19T06:05:03.000Z
|
// Copyright 2016 Peter Jankuliak
//
// 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.
#define BOOST_TEST_DYN_LINK
#include <boost/test/unit_test.hpp>
#include <iostream>
#include "club/graph.h"
#include <club/debug/string_tools.h>
// -------------------------------------------------------------------
BOOST_AUTO_TEST_CASE(graph) {
using ID = unsigned int;
using G = club::Graph<ID>;
using IDs = std::set<ID>;
{
G g;
g.nodes.insert(0);
g.nodes.insert(1);
auto removed = g.remove_unreachable_nodes(0);
BOOST_CHECK(removed == IDs({1}));
BOOST_CHECK(g.nodes == IDs({0}));
}
{
G g;
g.nodes.insert(0);
g.nodes.insert(1);
g.add_edge(0, 1);
auto removed = g.remove_unreachable_nodes(0);
BOOST_CHECK(removed == IDs({}));
BOOST_CHECK(g.nodes == IDs({0, 1}));
}
{
// 1 4
// |\ /|
// | 0--3 |
// |/ \|
// 2 5
G g;
g.nodes.insert(0);
g.nodes.insert(1);
g.nodes.insert(2);
g.nodes.insert(3);
g.nodes.insert(4);
g.nodes.insert(5);
g.add_edge(0, 1);
g.add_edge(1, 2);
g.add_edge(2, 0);
g.add_edge(3, 4);
g.add_edge(4, 5);
g.add_edge(5, 3);
g.add_edge(1, 3);
{
auto removed = g.remove_unreachable_nodes(1);
BOOST_CHECK(removed == IDs({}));
BOOST_CHECK(g.nodes == IDs({0, 1, 2, 3, 4, 5}));
}
g.remove_edge(1, 3);
{
auto removed = g.remove_unreachable_nodes(1);
BOOST_CHECK(removed == IDs({3, 4, 5}));
BOOST_CHECK(g.nodes == IDs({0, 1, 2}));
}
}
}
| 21.752577
| 75
| 0.57109
|
inetic
|
45efa2f82f1804d2c6d7370eb03e236cdc081c4c
| 8,883
|
cpp
|
C++
|
Src/Client/ClientControl.cpp
|
StavrosBizelis/NetworkDistributedDeferredShading
|
07c03ce9b13bb5adb164cd4321b2bba284e49b4d
|
[
"MIT"
] | null | null | null |
Src/Client/ClientControl.cpp
|
StavrosBizelis/NetworkDistributedDeferredShading
|
07c03ce9b13bb5adb164cd4321b2bba284e49b4d
|
[
"MIT"
] | null | null | null |
Src/Client/ClientControl.cpp
|
StavrosBizelis/NetworkDistributedDeferredShading
|
07c03ce9b13bb5adb164cd4321b2bba284e49b4d
|
[
"MIT"
] | null | null | null |
/***********************************************************************
* AUTHOR: <Stavros Bizelis>
* FILE: ClientControl.cpp
* DATE: Wed Jun 20 20:04:02 2018
* DESCR:
***********************************************************************/
#include "Client/ClientControl.h"
#include "Common/Core/MyUtilities.h"
namespace Network
{
/***********************************************************************
* Method: ClientControl::ClientControl
* Params: const std::string &a_hostName, const unsigned int &a_hostPort
* Effects:
***********************************************************************/
ClientControl::ClientControl(const std::string &a_hostName, const unsigned int &a_hostPort)
: m_hostName(a_hostName), m_hostPort(a_hostPort), m_resolver{m_io}, m_connected(false), m_communicatesWithServer(false)
{
m_sizeMsgOut = std::make_shared<NetworkMsg>();
m_sizeMsgOut->CreateSizeMsg(0);
m_sizeMsgIn = std::make_shared<NetworkMsg>();
m_sizeMsgIn->CreateSizeMsg(0);
}
/***********************************************************************
* Method: ClientControl::~ClientControl
* Params:
* Effects:
***********************************************************************/
ClientControl::~ClientControl()
{
}
/***********************************************************************
* Method: ClientControl::Connect
* Params:
* Returns: void
* Effects:
***********************************************************************/
void ClientControl::Connect()
{
asio::ip::tcp::resolver::query l_query(m_hostName, std::to_string(m_hostPort) );
asio::ip::tcp::resolver::results_type l_endpoints = m_resolver.resolve(l_query);
m_io.run();
std::cout << "connnecting to:" << m_hostName << "/" << std::to_string(m_hostPort) << std::endl;
m_socket = std::make_shared<asio::ip::tcp::socket>(m_io);
asio::connect(*m_socket, l_endpoints);
m_connected = true;
std::cout << "Connected to " << m_hostName << "/" << std::to_string(m_hostPort) << std::endl << std::endl;
m_socket->set_option( asio::ip::tcp::no_delay(true) );
}
/***********************************************************************
* Method: ClientControl::StartCommunication
* Params:
* Returns: bool
* Effects:
***********************************************************************/
bool
ClientControl::StartCommunication()
{
if( !m_connected )
return false;
m_communicatesWithServer = true;
std::cout << "Start Communication" << std::endl << std::endl;
return true;
}
/***********************************************************************
* Method: ClientControl::RegisterMessage
* Params: const std::list< NetworkMsgPtr >::iterator& a_message
* Returns: void
* Effects:
***********************************************************************/
void
ClientControl::RegisterMessage( const std::list< NetworkMsgPtr >::iterator& a_message, const std::size_t& a_size )
{
// allow the socket to poll again
SocketState& l_state = m_socketState;
l_state.m_isPolling = false;
// check if it is size message
if( (*a_message)->GetType() == MsgType::MSG_SIZE )
{
// IFDBG( std::cout << "Input Msg Message" << (**a_message) << std::endl );
// if it is a size message - then we should expect another message after it with the given size
uint32_t l_size;
(*a_message)->DeserializeSizeMsg( l_size );
NetworkMsgPtr l_msg = std::make_shared<NetworkMsg>();
l_msg->SetSize(l_size);
std::lock_guard<std::mutex> guard(m_expectingMessageMut);
l_state.m_expectingMessage.first = true;
l_state.m_expectingMessage.second = l_msg;
l_state.m_expectedMessageCompleteness.first = 0; // zero completeness for the next message
l_state.m_expectedMessageCompleteness.second = l_size; // this is the goal
}
else
{
// IFDBG( std::cout << "Input Message" << (**a_message) << std::endl );
// add the message to m_inputMsgs
l_state.m_expectedMessageCompleteness.first += a_size;
if(l_state.m_expectedMessageCompleteness.first == l_state.m_expectedMessageCompleteness.second)
{
std::lock_guard<std::mutex> guard(m_inMsgMut);
l_state.m_inputMsgs.push_back( *a_message );
m_socketState.m_expectingMessage.first = false;
l_state.m_expectedMessageCompleteness.first = 0;
}
}
// remove message from pre input messages
std::lock_guard<std::mutex> guard(m_preInMsgMut);
m_preInputMsgs.erase(a_message);
}
/***********************************************************************
* Method: ClientControl::PushMsg
* Params: const NetworkMsgPtr &a_msg
* Returns: void
* Effects:
***********************************************************************/
void
ClientControl::PushMsg(const NetworkMsgPtr &a_msg)
{
Network::NetworkMsgPtr l_sizeMsg = std::make_shared<Network::NetworkMsg>();
l_sizeMsg->CreateSizeMsg( (uint32_t)a_msg->GetSize() );
std::lock_guard<std::mutex> guard(m_outMsgMut);
m_socketState.m_outputMsgs.push_back(l_sizeMsg);
m_socketState.m_outputMsgs.push_back(a_msg);
// IFDBG( std::cout << "Push message" << *a_msg << std::endl );
}
/***********************************************************************
* Method: ClientControl::PushMsg
* Params: const NetworkMsgPtr &a_msg
* Returns: void
* Effects:
***********************************************************************/
std::vector<NetworkMsgPtr>
ClientControl::GetMsgs()
{
std::lock_guard<std::mutex> guard(m_inMsgMut);
std::vector<NetworkMsgPtr> l_toReturn;
m_socketState.m_inputMsgs.swap(l_toReturn);
return l_toReturn;
}
/***********************************************************************
* Method: ClientControl::Update
* Params:
* Returns: void
* Effects:
***********************************************************************/
void
ClientControl::Update()
{
ClientControl* l_me = this;
if( m_communicatesWithServer && m_connected)
{
// send messages
m_outMsgMut.lock();
// block until the previous frame is sent
while( m_socketState.m_pendingOutMsgs.size() > 0 ){m_io.run();}
m_socketState.m_pendingOutMsgs.insert( m_socketState.m_outputMsgs.begin(), m_socketState.m_outputMsgs.end() );
for( std::vector<NetworkMsgPtr>::iterator l_message = m_socketState.m_outputMsgs.begin(); l_message != m_socketState.m_outputMsgs.end(); ++l_message )
{
NetworkMsgPtr l_actMsg = *l_message;
SocketState* l_statePtr = &m_socketState;
m_socket->async_send(
asio::buffer(l_actMsg->GetData(), l_actMsg->GetSize() ),
[l_statePtr, l_actMsg](const std::error_code& a_error, std::size_t bytes_transferred)
{
l_statePtr->m_pendingOutMsgs.erase( l_statePtr->m_pendingOutMsgs.find( l_actMsg ) );
}
);
}
m_socketState.m_outputMsgs.clear();
m_outMsgMut.unlock();
// receive message
if( !m_socketState.m_isPolling )
{
m_socketState.m_isPolling = true;
if( !m_socketState.m_expectingMessage.first ) // if there is no expected message - create a size message to expect
{
m_preInMsgMut.lock();
m_preInputMsgs.push_front(m_sizeMsgIn);
m_preInMsgMut.unlock();
}
else // if there is an expected message - copy it to the preInputMessages
{
std::lock_guard<std::mutex> guard(m_expectingMessageMut);
m_preInMsgMut.lock();
m_preInputMsgs.push_front( m_socketState.m_expectingMessage.second );
m_preInMsgMut.unlock();
}
m_preInMsgMut.lock();
std::list< NetworkMsgPtr >::iterator l_preInputMessage = m_preInputMsgs.begin();
m_preInMsgMut.unlock();
m_socket->async_receive( asio::buffer((*l_preInputMessage)->GetData()+m_socketState.m_expectedMessageCompleteness.first, (*l_preInputMessage)->GetSize()-m_socketState.m_expectedMessageCompleteness.first ),
[ l_me, l_preInputMessage](const std::error_code& a_error, std::size_t length )
{
if (!a_error)
{
// IFDBG( std::cout << "ACTUALLY RECEIVED LENGTH " << length << std::endl<< std::endl; );
l_me->RegisterMessage(l_preInputMessage, length);
}
}
);
}
}
m_io.run();
}
}
| 38.288793
| 213
| 0.535405
|
StavrosBizelis
|
45f2e999d15501fadaa45ef9c0ace330a70e9c92
| 1,582
|
cpp
|
C++
|
src/leader_local.cpp
|
logpicker/prototype
|
0a25fccc24a8e298dee9bae240fcd73a4e5d185e
|
[
"MIT"
] | null | null | null |
src/leader_local.cpp
|
logpicker/prototype
|
0a25fccc24a8e298dee9bae240fcd73a4e5d185e
|
[
"MIT"
] | null | null | null |
src/leader_local.cpp
|
logpicker/prototype
|
0a25fccc24a8e298dee9bae240fcd73a4e5d185e
|
[
"MIT"
] | null | null | null |
#include "leader.h"
#include "log.hpp"
#include "logpicker_leader.h"
#include <rpc/client.h>
#include "rpc/server.h"
#include "error_out.hpp"
#include "utils.hpp"
#include "cert.hpp"
#include <thread>
int main(int argc, char **argv) {
std::string arg = argv[1];
int cnt = std::stoi(arg);
std::string config_filename = argv[2];
std::string cert_filename = argv[3];
cert_t cert = read_cert_from_disk(cert_filename);
//cert.resize(32);
log_pool_t lp;
for(int i = 0; i < cnt; i++) {
//auto log = Log::read_log(config_filename, i);
lp.emplace_back(i);
}
boost::asio::io_context ios;
Log l = Log::read_leader(config_filename);
log_map_t pool = read_log_pool(config_filename);
leader_t leader(ios, l, pool);
auto port = rpc::constants::DEFAULT_PORT - 1;
lpp::printfn("Starting leader instance {} on port: {}\n", l.get_id(), port);
rpc::server srv("0.0.0.0", port);
srv.bind("start_run", [&leader](const logpicker_request_t& req){ leader.start_run(req); return true;});
lpp::printfn("Starting leader \n");
srv.suppress_exceptions(false);
srv.async_run(64);
std::thread submitter([&ios, &lp, &cert, &leader]() {
std::this_thread::sleep_for(std::chrono::seconds(1));
for(int i = 0; i < 100; i++) {
session_id_t sid(hash_certificate(cert), current_timestamp_sid());
logpicker_request_t lp_request{cert, lp, sid};
leader.start_run(lp_request);
}
});
leader.run(32);
ios.run();
std::cin.ignore();
return 0;
}
| 30.423077
| 107
| 0.62579
|
logpicker
|
45f5ba962b9812851ddf2324319d84be97b07978
| 2,455
|
cc
|
C++
|
wasp_exec/src/executors/inairtest.cc
|
tuloski/wasp_exec
|
00ac1e3d00e974c380a9d498a346b50996bee2e7
|
[
"MIT"
] | null | null | null |
wasp_exec/src/executors/inairtest.cc
|
tuloski/wasp_exec
|
00ac1e3d00e974c380a9d498a346b50996bee2e7
|
[
"MIT"
] | null | null | null |
wasp_exec/src/executors/inairtest.cc
|
tuloski/wasp_exec
|
00ac1e3d00e974c380a9d498a346b50996bee2e7
|
[
"MIT"
] | null | null | null |
#include "inairtest.h"
#include "executil.h"
#include "tstutil.h"
#include <iostream>
#include <boost/lexical_cast.hpp>
extern ros::NodeHandle * global_nh;
using namespace std;
Exec::InAirTest::InAirTest (std::string ns, int id) : Executor (ns, id),
received_mms_state(false) {
lrs_msgs_tst::TSTExecInfo einfo;
einfo.can_be_aborted = false;
einfo.can_be_enoughed = false;
einfo.can_be_paused = false;
set_exec_info(ns, id, einfo);
update_from_exec_info (einfo);
}
void Exec::InAirTest::callbackState(const mms_msgs::MMS_status::ConstPtr& msg){
_mms_status = *msg;
received_mms_state = true;
}
bool Exec::InAirTest::prepare () {
bool res = true;
received_mms_state = false;
counter_wait_mms_state = 0;
ROS_INFO ("Exec::InAirTest::prepare");
if (res) {
set_active_flag (node_ns, node_id, true);
}
return res;
}
void Exec::InAirTest::start () {
ROS_INFO ("Exec::InAirTest::start: %s - %d", node_ns.c_str(), node_id);
if (!do_before_work()) {
ROS_ERROR("Exec InAirTest: do_before_work failed");
return;
}
ROS_INFO ("TREE NS: %s", tni.ns.c_str());
ROS_INFO ("THIS ID: %d", tni.id);
ROS_INFO ("PARENT ID: %d", tni.parent_id);
// sleep (5);
string answer = "unknown";
ros::Subscriber state_sub; //subscriber to qos_sensors topic
state_sub = global_nh->subscribe("mms_status", 10, &Exec::InAirTest::callbackState,this);
while (!received_mms_state){
ros::spinOnce(); //when called from delegation there is no ROS so we need to run the spin to read the topics
usleep(200000);
counter_wait_mms_state++;
if (counter_wait_mms_state > 15){ //Waited mms_state for 3 seconds...something failed
fail ("Exec InAirTest: Failed to receive mms state");
return;
}
}
//TODO use enum instead of values
if (_mms_status.mms_state == 10 || _mms_status.mms_state == 20 || _mms_status.mms_state == 30
|| _mms_status.mms_state == 40 || _mms_status.mms_state == 45 || _mms_status.mms_state == 71
|| _mms_status.mms_state == 711 || _mms_status.mms_state == 712){
answer = "false";
} else {
answer = "true";
}
ROS_ERROR("Exec InAirTest: answer: %s", answer.c_str());
if (set_parameter_string (tni.ns, tni.parent_id, "answer", answer)) {
ROS_INFO ("answer set in parent");
} else {
fail ("Exec InAirTest: Failed to set answer parameter in parent");
return;
}
ROS_INFO ("Exec::InAirTest: finished");
wait_for_postwork_conditions ();
}
| 25.842105
| 112
| 0.684318
|
tuloski
|
45f90d0193d17bcca649a0fd0f6369bc5dece996
| 3,692
|
hpp
|
C++
|
include/robot_faces/entities/proxy-entity.hpp
|
AndrewMurtagh/robot_faces
|
54408875584cb84beb70f090a2de3d26b781de03
|
[
"MIT"
] | 1
|
2021-08-17T15:15:33.000Z
|
2021-08-17T15:15:33.000Z
|
include/robot_faces/entities/proxy-entity.hpp
|
AndrewMurtagh/robot_faces
|
54408875584cb84beb70f090a2de3d26b781de03
|
[
"MIT"
] | null | null | null |
include/robot_faces/entities/proxy-entity.hpp
|
AndrewMurtagh/robot_faces
|
54408875584cb84beb70f090a2de3d26b781de03
|
[
"MIT"
] | 1
|
2020-08-27T02:23:18.000Z
|
2020-08-27T02:23:18.000Z
|
#ifndef PROXY_ENTITY_H
#define PROXY_ENTITY_H
#include <SFML/Graphics.hpp>
#include <robot_faces/entities/ientity.hpp>
#include <robot_faces/entities/entity.hpp>
#include <robot_faces/consts.hpp>
#include <robot_faces/utils.hpp>
template <typename T>
class ProxyEntity : public IEntity
{
protected:
// defined above public so it is defined in constructor
typedef typename std::multimap<T, std::shared_ptr<Entity>> EntityMap;
typedef typename std::multimap<T, std::shared_ptr<Entity>>::iterator EntityMapItr;
typedef typename std::pair<T, std::shared_ptr<Entity>> EntityMapPair;
T shape_;
bool show_;
EntityMap entity_map_;
sf::Transform curr_transformation_;
sf::Transform target_transformation_;
public:
ProxyEntity(T, EntityMap);
void setShape(T);
void show(const bool);
/*
IEntity
*/
void setTransformation(const sf::Transform transform) override;
void setColour(const sf::Color colour) override;
void setExpression(const Expression expression) override;
void draw(sf::RenderWindow &renderWindow, const float frame_delta_time) override;
};
template<typename T>
ProxyEntity<T>::ProxyEntity(T shape, EntityMap entity_map) : shape_(shape),
entity_map_(entity_map),
show_(true)
{
}
template<typename T>
void ProxyEntity<T>::setShape(T shape)
{
shape_ = shape;
}
template<typename T>
void ProxyEntity<T>::show(const bool show)
{
show_ = show;
}
/*
IEntity
*/
template<typename T>
void ProxyEntity<T>::setTransformation(const sf::Transform transform)
{
target_transformation_ = transform;
}
template<typename T>
void ProxyEntity<T>::setColour(const sf::Color colour)
{
for (EntityMapPair entity : entity_map_)
{
entity.second->setColour(colour);
}
}
template<typename T>
void ProxyEntity<T>::setExpression(const Expression expression)
{
for (EntityMapPair entity : entity_map_)
{
entity.second->setExpression(expression);
}
}
template<typename T>
void ProxyEntity<T>::draw(sf::RenderWindow &renderWindow, const float frame_delta_time)
{
if (!show_)
return;
const float *curr_trans_matrix = curr_transformation_.getMatrix();
const float *target_trans_matrix = target_transformation_.getMatrix();
sf::Transform new_curr_transformation(
curr_trans_matrix[0] + frame_delta_time * SPEED * (target_trans_matrix[0] - curr_trans_matrix[0]),
curr_trans_matrix[4] + frame_delta_time * SPEED * (target_trans_matrix[4] - curr_trans_matrix[1]),
curr_trans_matrix[12] + frame_delta_time * SPEED * (target_trans_matrix[12] - curr_trans_matrix[12]),
curr_trans_matrix[1] + frame_delta_time * SPEED * (target_trans_matrix[1] - curr_trans_matrix[1]),
curr_trans_matrix[5] + frame_delta_time * SPEED * (target_trans_matrix[5] - curr_trans_matrix[5]),
curr_trans_matrix[13] + frame_delta_time * SPEED * (target_trans_matrix[13] - curr_trans_matrix[13]),
curr_trans_matrix[3] + frame_delta_time * SPEED * (target_trans_matrix[3] - curr_trans_matrix[3]),
curr_trans_matrix[7] + frame_delta_time * SPEED * (target_trans_matrix[7] - curr_trans_matrix[7]),
curr_trans_matrix[15] + frame_delta_time * SPEED * (target_trans_matrix[15] - curr_trans_matrix[15]));
curr_transformation_ = new_curr_transformation;
for (EntityMapPair entity : entity_map_)
{
entity.second->setTransformation(curr_transformation_);
if (entity.first == shape_)
{
entity.second->draw(renderWindow, frame_delta_time);
}
}
}
#endif // PROXY_ENTITY_H
| 29.774194
| 110
| 0.702059
|
AndrewMurtagh
|
45fe1c05afcd93c26bf3e3290dd73880379ddb9d
| 6,565
|
cpp
|
C++
|
src/plugins/win32/drawdeviceIrrlicht/irrlicht/source/Irrlicht/os.cpp
|
miahmie/krkrz
|
e4948f61393ca4a2acac0301a975165dd4efc643
|
[
"Unlicense",
"Apache-2.0",
"Libpng",
"FTL",
"IJG"
] | 2
|
2020-02-25T15:18:53.000Z
|
2020-08-24T13:30:34.000Z
|
src/plugins/win32/drawdeviceIrrlicht/irrlicht/source/Irrlicht/os.cpp
|
miahmie/krkrz
|
e4948f61393ca4a2acac0301a975165dd4efc643
|
[
"Unlicense",
"Apache-2.0",
"Libpng",
"FTL",
"IJG"
] | null | null | null |
src/plugins/win32/drawdeviceIrrlicht/irrlicht/source/Irrlicht/os.cpp
|
miahmie/krkrz
|
e4948f61393ca4a2acac0301a975165dd4efc643
|
[
"Unlicense",
"Apache-2.0",
"Libpng",
"FTL",
"IJG"
] | 1
|
2019-11-25T05:29:30.000Z
|
2019-11-25T05:29:30.000Z
|
// Copyright (C) 2002-2008 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#include "os.h"
#include "irrString.h"
#include "IrrCompileConfig.h"
#include "irrMath.h"
#if defined(_IRR_USE_SDL_DEVICE_)
#include <SDL/SDL_endian.h>
#define bswap_16(X) SDL_Swap16(X)
#define bswap_32(X) SDL_Swap32(X)
#elif defined(_IRR_WINDOWS_API_)
#if (defined(_MSC_VER) && (_MSC_VER > 1298))
#include <stdlib.h>
#define bswap_16(X) _byteswap_ushort(X)
#define bswap_32(X) _byteswap_ulong(X)
#else
#define bswap_16(X) ((((X)&0xFF) << 8) | (((X)&=0xFF00) >> 8))
#define bswap_32(X) ( (((X)&0x000000FF)<<24) | (((X)&0xFF000000) >> 24) | (((X)&0x0000FF00) << 8) | (((X) &0x00FF0000) >> 8))
#endif
#else
#if defined(_IRR_OSX_PLATFORM_)
#include <libkern/OSByteOrder.h>
#define bswap_16(X) OSReadSwapInt16(&X,0)
#define bswap_32(X) OSReadSwapInt32(&X,0)
#elif defined(__FreeBSD__)
#include <sys/endian.h>
#define bswap_16(X) bswap16(X)
#define bswap_32(X) bswap32(X)
#elif !defined(_IRR_SOLARIS_PLATFORM_) && !defined(__PPC__)
#include <byteswap.h>
#else
#define bswap_16(X) ((((X)&0xFF) << 8) | (((X)&=0xFF00) >> 8))
#define bswap_32(X) ( (((X)&0x000000FF)<<24) | (((X)&0xFF000000) >> 24) | (((X)&0x0000FF00) << 8) | (((X) &0x00FF0000) >> 8))
#endif
#endif
namespace irr
{
namespace os
{
u16 Byteswap::byteswap(u16 num) {return bswap_16(num);}
s16 Byteswap::byteswap(s16 num) {return bswap_16(num);}
u32 Byteswap::byteswap(u32 num) {return bswap_32(num);}
s32 Byteswap::byteswap(s32 num) {return bswap_32(num);}
f32 Byteswap::byteswap(f32 num) {u32 tmp=bswap_32(*((u32*)&num)); return *((f32*)&tmp);}
}
}
#if defined(_IRR_WINDOWS_API_)
// ----------------------------------------------------------------
// Windows specific functions
// ----------------------------------------------------------------
#ifdef _IRR_XBOX_PLATFORM_
#include <xtl.h>
#else
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#endif
namespace irr
{
namespace os
{
//! prints a debuginfo string
void Printer::print(const c8* message)
{
c8* tmp = new c8[strlen(message) + 2];
sprintf(tmp, "%s\n", message);
OutputDebugString(tmp);
printf(tmp);
delete [] tmp;
}
LARGE_INTEGER HighPerformanceFreq;
BOOL HighPerformanceTimerSupport = FALSE;
void Timer::initTimer()
{
// disable hires timer on multiple core systems, bios bugs result in bad hires timers.
SYSTEM_INFO sysinfo;
DWORD affinity, sysaffinity;
GetSystemInfo(&sysinfo);
s32 affinityCount = 0;
// count the processors that can be used by this process
if (GetProcessAffinityMask( GetCurrentProcess(), &affinity, &sysaffinity ))
{
for (u32 i=0; i<32; ++i)
{
if ((1<<i) & affinity)
affinityCount++;
}
}
if (sysinfo.dwNumberOfProcessors == 1 || affinityCount == 1)
{
HighPerformanceTimerSupport = QueryPerformanceFrequency(&HighPerformanceFreq);
}
else
{
HighPerformanceTimerSupport = false;
}
initVirtualTimer();
}
u32 Timer::getRealTime()
{
if (HighPerformanceTimerSupport)
{
LARGE_INTEGER nTime;
QueryPerformanceCounter(&nTime);
return u32((nTime.QuadPart) * 1000 / HighPerformanceFreq.QuadPart);
}
return GetTickCount();
}
} // end namespace os
#else
// ----------------------------------------------------------------
// linux/ansi version
// ----------------------------------------------------------------
#include <stdio.h>
#include <time.h>
#include <sys/time.h>
namespace irr
{
namespace os
{
//! prints a debuginfo string
void Printer::print(const c8* message)
{
printf("%s\n", message);
}
void Timer::initTimer()
{
initVirtualTimer();
}
u32 Timer::getRealTime()
{
timeval tv;
gettimeofday(&tv, 0);
return (u32)(tv.tv_sec * 1000) + (tv.tv_usec / 1000);
}
} // end namespace os
#endif // end linux / windows
namespace os
{
// The platform independent implementation of the printer
ILogger* Printer::Logger = 0;
void Printer::log(const c8* message, ELOG_LEVEL ll)
{
if (Logger)
Logger->log(message, ll);
}
void Printer::log(const c8* message, const c8* hint, ELOG_LEVEL ll)
{
if (!Logger)
return;
Logger->log(message, hint, ll);
}
void Printer::log(const wchar_t* message, ELOG_LEVEL ll)
{
if (Logger)
Logger->log(message, ll);
}
// our Randomizer is not really os specific, so we
// code one for all, which should work on every platform the same,
// which is desireable.
s32 Randomizer::seed = 0x0f0f0f0f;
//! generates a pseudo random number
s32 Randomizer::rand()
{
const s32 m = 2147483399; // a non-Mersenne prime
const s32 a = 40692; // another spectral success story
const s32 q = m/a;
const s32 r = m%a; // again less than q
seed = a * (seed%q) - r* (seed/q);
if (seed<0) seed += m;
return seed;
}
//! resets the randomizer
void Randomizer::reset()
{
seed = 0x0f0f0f0f;
}
// ------------------------------------------------------
// virtual timer implementation
f32 Timer::VirtualTimerSpeed = 1.0f;
s32 Timer::VirtualTimerStopCounter = 0;
u32 Timer::LastVirtualTime = 0;
u32 Timer::StartRealTime = 0;
u32 Timer::StaticTime = 0;
//! returns current virtual time
u32 Timer::getTime()
{
if (isStopped())
return LastVirtualTime;
return LastVirtualTime + (u32)((StaticTime - StartRealTime) * VirtualTimerSpeed);
}
//! ticks, advances the virtual timer
void Timer::tick()
{
StaticTime = getRealTime();
}
//! sets the current virtual time
void Timer::setTime(u32 time)
{
StaticTime = getRealTime();
LastVirtualTime = time;
StartRealTime = StaticTime;
}
//! stops the virtual timer
void Timer::stopTimer()
{
if (!isStopped())
{
// stop the virtual timer
LastVirtualTime = getTime();
}
--VirtualTimerStopCounter;
}
//! starts the virtual timer
void Timer::startTimer()
{
++VirtualTimerStopCounter;
if (!isStopped())
{
// restart virtual timer
setTime(LastVirtualTime);
}
}
//! sets the speed of the virtual timer
void Timer::setSpeed(f32 speed)
{
setTime(getTime());
VirtualTimerSpeed = speed;
if (VirtualTimerSpeed < 0.0f)
VirtualTimerSpeed = 0.0f;
}
//! gets the speed of the virtual timer
f32 Timer::getSpeed()
{
return VirtualTimerSpeed;
}
//! returns if the timer currently is stopped
bool Timer::isStopped()
{
return VirtualTimerStopCounter != 0;
}
void Timer::initVirtualTimer()
{
StaticTime = getRealTime();
StartRealTime = StaticTime;
}
} // end namespace os
} // end namespace irr
| 21.810631
| 127
| 0.642346
|
miahmie
|
45ff9ab1ff61f3bf9dac7f4918c28f7ef0628764
| 2,214
|
cpp
|
C++
|
2019/cpp/1906.cpp
|
Chrinkus/advent-of-code
|
b2ae137dc7a1d6fc9e20f29549e891404591c47f
|
[
"MIT"
] | 1
|
2021-12-04T20:55:02.000Z
|
2021-12-04T20:55:02.000Z
|
2019/cpp/1906.cpp
|
Chrinkus/advent-of-code
|
b2ae137dc7a1d6fc9e20f29549e891404591c47f
|
[
"MIT"
] | null | null | null |
2019/cpp/1906.cpp
|
Chrinkus/advent-of-code
|
b2ae137dc7a1d6fc9e20f29549e891404591c47f
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <vector>
#include <string>
#include <unordered_map>
#include <algorithm>
#include "utils.hpp"
using Object_map = std::unordered_map<std::string,std::string>;
const std::string SENTINEL = "COM";
const std::string START = "YOU";
const std::string GOAL = "SAN";
int count_orbits(const Object_map& om)
{
int count = 0;
for (const auto& o : om)
for (auto s = o.first; s != SENTINEL; s = om.at(s))
++count;
return count;
}
int count_orbits_from_to(const Object_map& om, const std::string& from,
const std::string& to)
{
int count = 0;
for (auto s = om.at(from); s != to; s = om.at(s))
++count;
return count;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
std::vector<std::string>
trace_route(const Object_map& om, const std::string& obj)
{
std::vector<std::string> route;
for (auto s = om.at(obj); s != SENTINEL; s = om.at(s))
route.push_back(s);
return route;
}
int count_transfers(const Object_map& om)
{
std::vector<std::string> you_map = trace_route(om, START);
std::vector<std::string> san_map = trace_route(om, GOAL);
auto res = std::find_first_of(std::begin(you_map), std::end(you_map),
std::begin(san_map), std::end(san_map));
if (res == std::end(you_map))
return -1;
return count_orbits_from_to(om, START, *res) +
count_orbits_from_to(om, GOAL, *res);
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
int main()
{
std::cout << "Advent of Code 2019 - Day 6\n"
<< "Universal Orbit Map\n";
std::vector<std::string> vs;
for (std::string orbit; std::cin >> orbit; )
vs.push_back(orbit);
std::cout << "Input size: " << vs.size() << '\n'
<< " * first: " << vs.front() << '\n'
<< " * last : " << vs.back() << '\n';
Object_map obj_map;
for (const auto& s : vs) {
auto v = split(s, ')');
obj_map[v[1]] = v[0];
}
int part1 = count_orbits(obj_map);
int part2 = count_transfers(obj_map);
std::cout << "Part 1: " << part1 << '\n';
std::cout << "Part 2: " << part2 << '\n';
}
| 26.674699
| 79
| 0.531165
|
Chrinkus
|
45ffcf253ed25fd6793fc8a13fa5c2dabab6d305
| 2,827
|
cpp
|
C++
|
internal/files/configs/theme_config/theme_config.cpp
|
YarikRevich/SyE
|
3f73350f7e8fd9975e747c9c49667bbee278b594
|
[
"MIT"
] | null | null | null |
internal/files/configs/theme_config/theme_config.cpp
|
YarikRevich/SyE
|
3f73350f7e8fd9975e747c9c49667bbee278b594
|
[
"MIT"
] | null | null | null |
internal/files/configs/theme_config/theme_config.cpp
|
YarikRevich/SyE
|
3f73350f7e8fd9975e747c9c49667bbee278b594
|
[
"MIT"
] | null | null | null |
#include <tuple>
#include <cstring>
#include <string>
#include <yaml-cpp/yaml.h>
#include "theme_config.hpp"
#include "./../helper/helper.hpp"
#include "./../../../files/exec/exec.hpp"
#ifdef __APPLE__
#include <filesystem>
namespace fs = std::filesystem;
#elif defined(__linux__)
#include <experimental/filesystem>
namespace fs = std::experimental::filesystem;
#endif
template <typename T>
void ThemeConfig<T>::open()
{
auto config_path = PathsManagment::get_path_for_config_directory("theme");
for (const auto &file : fs::directory_iterator(config_path))
{
auto split_file_path = PathsManagment::get_split_file_path(file.path().c_str());
auto file_extension = PathsManagment::get_file_extension(split_file_path[split_file_path.size() - 1]);
if (std::strcmp(file_extension.c_str(), "yaml") == 0)
{
this->files.push_back(file.path());
}
}
};
template <typename T>
void ThemeConfig<T>::read()
{
std::string file_name = _EXEC_FILE->getFileName();
auto file_extension = PathsManagment::get_file_extension(file_name);
for (auto const file : this->files)
{
YAML::Node config = YAML::LoadFile(file);
if (!config["insert"].IsDefined())
{
// MessageWriter({RedPrinter({file, "does not contain insert"})});
}
if (!config["effects"].IsDefined())
{
// MessageWriter({RedPrinter({file, "does not contain effects"})});
};
if (!config["command"].IsDefined())
{
// MessageWriter({RedPrinter({file, "does not contain command"})});
};
if (!config["effects"].IsScalar())
{
continue;
}
ThemeConfigData data;
data.name = file;
auto insert = config["insert"].as<std::vector<std::string>>();
if (insert.empty() || insert.size() > 2 || insert.size() < 2)
{
continue;
};
data.insert = {
ParseManagement::transform_string_to_lower(insert[0]),
ParseManagement::transform_string_to_lower(insert[1])};
auto command = config["command"].as<std::vector<std::string>>();
if (insert.empty() || insert.size() > 2 || insert.size() < 2)
{
continue;
};
data.command = {
ParseManagement::transform_string_to_lower(command[0]),
ParseManagement::transform_string_to_lower(command[1])};
data.effects = config["effects"].as<std::string>();
this->data = data;
};
};
template <typename T>
void ThemeConfig<T>::open_and_read()
{
this->open();
this->read();
};
template <typename T>
T ThemeConfig<T>::get()
{
return this->data;
};
template class ThemeConfig<ThemeConfigData>;
ThemeConfig<ThemeConfigData> _THEME_CONFIG;
| 26.92381
| 110
| 0.605235
|
YarikRevich
|
45ffd20b3fa0b8e9830ce722a5f7b7fde5f78c82
| 1,725
|
hpp
|
C++
|
src/gameworld/gameworld/other/discountbuy/discountbuyconfig.hpp
|
mage-game/metagame-xm-server
|
193b67389262803fe0eae742800b1e878b5b3087
|
[
"MIT"
] | 3
|
2021-12-16T13:57:28.000Z
|
2022-03-26T07:50:08.000Z
|
src/gameworld/gameworld/other/discountbuy/discountbuyconfig.hpp
|
mage-game/metagame-xm-server
|
193b67389262803fe0eae742800b1e878b5b3087
|
[
"MIT"
] | null | null | null |
src/gameworld/gameworld/other/discountbuy/discountbuyconfig.hpp
|
mage-game/metagame-xm-server
|
193b67389262803fe0eae742800b1e878b5b3087
|
[
"MIT"
] | 1
|
2022-03-26T07:50:11.000Z
|
2022-03-26T07:50:11.000Z
|
#ifndef __DISCOUNT_BUY_CONFIG_HPP__
#define __DISCOUNT_BUY_CONFIG_HPP__
#include "servercommon/struct/discountbuyparam.hpp"
#include "servercommon/struct/itemlistparam.h"
#include "servercommon/configbase.h"
#include "servercommon/pugixml/pugixml_adapter.hpp"
struct DiscountBuyPhaseConfig
{
struct ConfigItem
{
ConfigItem() : phase(0), active_level(0), last_time_s(0), begin_open_day(0),end_open_day(0){}
int phase;
int active_level;
long long last_time_s;
int begin_open_day;
int end_open_day;
ItemConfigData notice_mail_item;
};
DiscountBuyPhaseConfig() : cfg_count(0) {}
int cfg_count;
ConfigItem cfg_list[DISCOUNT_BUY_PHASE_MAX_COUNT];
};
struct DiscountBuyItemConfig
{
const static int CONFIG_ITEM_MAX_COUNT = 5000;
UNSTD_STATIC_CHECK(CONFIG_ITEM_MAX_COUNT >= DISCOUNT_BUY_PHASE_MAX_COUNT * DISCOUNT_BUY_ITEM_PER_PHASE);
struct ConfigItem
{
ConfigItem() : seq(0), phase(0), item_seq(0), price(0), buy_limit_count(0) {}
int seq;
int phase;
int item_seq;
int price;
int buy_limit_count;
ItemConfigData item;
};
DiscountBuyItemConfig() : cfg_count(0) {}
int cfg_count;
ConfigItem cfg_list[CONFIG_ITEM_MAX_COUNT];
};
class DiscountBuyConfig : public ConfigBase
{
public:
DiscountBuyConfig();
~DiscountBuyConfig();
bool Init(std::string path, std::string *err);
int GetPhaseCfgCount() { return m_pahse_cfg.cfg_count; }
const DiscountBuyPhaseConfig::ConfigItem * GetPhaseCfg(int phase);
const DiscountBuyItemConfig::ConfigItem * GetItemCfg(int seq);
private:
int InitPhaseCfg(PugiXmlNode RootElement);
int InitItemCfg(PugiXmlNode RootElement);
DiscountBuyPhaseConfig m_pahse_cfg;
DiscountBuyItemConfig m_item_cfg;
};
#endif // __DISCOUNT_BUY_CONFIG_HPP__
| 23.310811
| 105
| 0.781449
|
mage-game
|
45ffef52338f5f0df00c4e1e5bbc05d9793727cb
| 723
|
hpp
|
C++
|
tests/fonts_for_tests/include/fonts_for_tests/freetype.hpp
|
cpp-niel/mfl
|
d22d698b112b95d102150d5f3a5f35d8eb7fb0f3
|
[
"MIT"
] | 4
|
2021-04-02T02:52:05.000Z
|
2021-12-11T00:42:35.000Z
|
tests/fonts_for_tests/include/fonts_for_tests/freetype.hpp
|
cpp-niel/mfl
|
d22d698b112b95d102150d5f3a5f35d8eb7fb0f3
|
[
"MIT"
] | null | null | null |
tests/fonts_for_tests/include/fonts_for_tests/freetype.hpp
|
cpp-niel/mfl
|
d22d698b112b95d102150d5f3a5f35d8eb7fb0f3
|
[
"MIT"
] | null | null | null |
#pragma once
#include "mfl/font_family.hpp"
#include "mfl/units.hpp"
#include <ft2build.h>
#include FT_FREETYPE_H
#include <memory>
namespace mfl::fft
{
class freetype
{
public:
freetype();
[[nodiscard]] FT_Face face(const font_family family) const;
private:
using library_ptr = std::unique_ptr<std::remove_pointer_t<FT_Library>, decltype(&FT_Done_FreeType)>;
using face_ptr = std::unique_ptr<std::remove_pointer_t<FT_Face>, decltype(&FT_Done_Face)>;
library_ptr ft_library_;
face_ptr italic_face_;
face_ptr normal_face_;
face_ptr bold_face_;
face_ptr mono_face_;
};
void ft_set_size(FT_Face face, const points size);
}
| 22.59375
| 108
| 0.677732
|
cpp-niel
|
34051de0e6bbe0dbf72bc4e053b0304e33c17cd8
| 598
|
cpp
|
C++
|
Game/Formula.cpp
|
Thendplayer/MagicIdle
|
e1da124eeab95cf7e3010ee2773cef9e8d80b097
|
[
"MIT"
] | 1
|
2021-02-06T04:28:39.000Z
|
2021-02-06T04:28:39.000Z
|
Game/Formula.cpp
|
Thendplayer/MagicIdle
|
e1da124eeab95cf7e3010ee2773cef9e8d80b097
|
[
"MIT"
] | null | null | null |
Game/Formula.cpp
|
Thendplayer/MagicIdle
|
e1da124eeab95cf7e3010ee2773cef9e8d80b097
|
[
"MIT"
] | null | null | null |
#include "Formula.h"
namespace MagicIdle
{
Formula::Formula()
: _initialValue(0),
_multiplier(0),
_exponent(0)
{
}
Formula::Formula(
KmbNumber initialValue,
KmbNumber multiplier,
float exponent
) : _initialValue(initialValue),
_multiplier(multiplier),
_exponent(exponent)
{
}
KmbNumber Formula::Calculate(int x)
{
KmbNumber result = _initialValue + _multiplier * std::pow(x, _exponent);
return result;
}
void Formula::operator=(Formula& other)
{
_initialValue = other._initialValue;
_multiplier = other._multiplier;
_exponent = other._exponent;
}
}
| 17.085714
| 74
| 0.704013
|
Thendplayer
|
34064a4ebd4cb298e968579d87a0931e52b9643d
| 1,104
|
cpp
|
C++
|
Examples/FavorPolicy.cpp
|
krzysztof-jusiak/qfsm
|
b339f8bdb7f4d2c65dc943cc84e0e0038552190c
|
[
"BSL-1.0"
] | 1
|
2020-12-18T20:43:20.000Z
|
2020-12-18T20:43:20.000Z
|
Examples/FavorPolicy.cpp
|
krzysztof-jusiak/qfsm
|
b339f8bdb7f4d2c65dc943cc84e0e0038552190c
|
[
"BSL-1.0"
] | null | null | null |
Examples/FavorPolicy.cpp
|
krzysztof-jusiak/qfsm
|
b339f8bdb7f4d2c65dc943cc84e0e0038552190c
|
[
"BSL-1.0"
] | null | null | null |
//
// Copyright (c) 2011-2012 Krzysztof Jusiak (krzysztof at jusiak dot net)
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#include <QFsm/QFsm.hpp>
#include "Utility.hpp"
class FavorPolicy : public QFsm::Fsm
{
struct S1 { };
struct S2 { };
public:
typedef QFsm::TransitionTable
<
Transition < S1, e1, S2 >,
Transition < S2, e2, S1 >
>
TransitionTable;
};
int main()
{
{
QFsm::Front::Fsm<FavorPolicy, QFsm::Back::FavorExecutionSpeed> fsm;
fsm.processEvent(e1());
fsm.visitCurrentStates(ShowCurrentStateVisitor());
fsm.processEvent(e2());
fsm.visitCurrentStates(ShowCurrentStateVisitor());
}
{
QFsm::Front::Fsm<FavorPolicy, QFsm::Back::FavorCompilationTime> fsm;
fsm.processEvent(e1());
fsm.visitCurrentStates(ShowCurrentStateVisitor());
fsm.processEvent(e2());
fsm.visitCurrentStates(ShowCurrentStateVisitor());
}
return 0;
}
| 22.530612
| 90
| 0.632246
|
krzysztof-jusiak
|
340abf84ca72dc3116a404e8148196dc045aaefb
| 4,361
|
hpp
|
C++
|
ros_stairsdetection/src/step.hpp
|
ne0h/hmmwv_stairsdetection
|
f07a0ac1b0063df0057d806a95cc02a7dad5cb04
|
[
"MIT"
] | null | null | null |
ros_stairsdetection/src/step.hpp
|
ne0h/hmmwv_stairsdetection
|
f07a0ac1b0063df0057d806a95cc02a7dad5cb04
|
[
"MIT"
] | null | null | null |
ros_stairsdetection/src/step.hpp
|
ne0h/hmmwv_stairsdetection
|
f07a0ac1b0063df0057d806a95cc02a7dad5cb04
|
[
"MIT"
] | null | null | null |
#pragma once
#include <sstream>
#include <cmath>
#include <geometry_msgs/Point.h>
#define PI 3.14159265
/**
* \brief Represents a single Step.
* \author Maximilian Hess <mail@ne0h.de>
*/
class Step {
public:
/**
* Default constructor that generates a Step with empty coordinates.
*/
Step() {
m_min.x = m_min.y = m_min.z = 0.0;
m_max.x = m_max.y = m_max.z = 0.0;
}
/**
* Creates a Step out of two points.
* @param min bottom left point
* @param max top right point
*/
Step(geometry_msgs::Point min, geometry_msgs::Point max) : m_min(min), m_max(max) {}
/**
* Creates a new Step out of the bottom center point, the dimensions and its position within the stairway
* @param bottomCenter the point in the bottom center
* @param width the width of the Step
* @param height the height of the Step
* @param depth the depth of the Step
* @param i the position within the stairway, starting from the bottom
*/
Step(geometry_msgs::Point bottomCenter, const double width, const double height, const double depth, const int i) {
m_min.x = bottomCenter.x + (i * depth);
m_min.y = bottomCenter.y - (width / 2);
m_min.z = bottomCenter.z + (i * height);
m_max.x = bottomCenter.x + (i * depth);
m_max.y = bottomCenter.y + (width / 2);
m_max.z = bottomCenter.z + ((i+1) * height);
}
/**
* Default destructor.
*/
~Step() {}
/**
* Returns the bottom left point.
* @return the bottom left point
*/
geometry_msgs::Point getMin() {
return m_min;
}
/**
* Returns the top right point.
* @return the top right point
*/
geometry_msgs::Point getMax() {
return m_max;
}
/**
* Resets the bottom left point.
* @param min the new point
*/
void setMin(geometry_msgs::Point min) {
m_min = min;
}
/**
* Resets the top right point.
* @param may the new point
*/
void setMax(geometry_msgs::Point max) {
m_max = max;
}
/**
* Resets both points.
* @param min the new bottom left point
* @param max the new top right point
*/
void setMinMax(geometry_msgs::Point min, geometry_msgs::Point max) {
m_min = min;
m_max = max;
}
/**
* Returns the width of the Step.
* @return the width of the Step
*/
double getWidth() {
return fabs(m_max.y - m_min.y);
}
/**
* Returns the height of the Step.
* @return the height of the Step.
*/
double getHeight() {
return fabs(m_max.z - m_min.z);
}
/**
* Returns a new point that is in the middle of top edge.
* @return a new point that is in the middle of top edge
*/
geometry_msgs::Point getCenterTop() {
geometry_msgs::Point p;
p.x = (m_max.x + m_min.x) / 2;
p.y = (m_max.y + m_min.y) / 2;
p.z = (m_max.z > m_min.z) ? m_max.z : m_min.z;
return p;
}
/**
* Returns a new point that is in the middle of the bottom edge.
* @return a new point that is in the middle of the bottom edge
*/
geometry_msgs::Point getCenterBottom() {
geometry_msgs::Point p;
p.x = (m_max.x + m_min.x) / 2;
p.y = (m_max.y + m_min.y) / 2;
p.z = m_min.z;
return p;
}
/**
* Returns the height above ground level.
* @return the height above ground level
*/
double getHeightAboveGround() {
// Not deterministic if m_min or m_max is heigher...
return (m_min.z < m_max.z) ? m_min.z : m_max.z;
}
/**
* Returns the inclination of the Step, expressed in degrees
* @return the inclination of the Step, expressed in degrees
*/
double getInclination() {
return atan(fabs(m_min.x - m_max.x) / fabs(m_min.z - m_max.z)) * 180 / PI;
}
/**
* Returns a brief, human-readable description of the Step
* @return a brief, human-readable description of the Step
*/
std::string toString() {
std::stringstream ss;
ss << std::fixed << std::setprecision(3);
ss << "Width: " << getWidth() << ", height: " << getHeight();
ss << ", distance: " << m_min.x;
//ss << ", inclination: " << getInclination();
ss << ", height above ground: " << getHeightAboveGround();
return ss.str();
}
/**
* Validates if this Step is equal to another Step
* @param other the other Step
*/
bool equals(Step &other) {
return (m_min.x == other.getMin().x && m_min.y == other.getMin().y && m_min.z == other.getMin().z
&& m_max.x == other.getMax().x && m_max.y == other.getMax().y && m_max.z == other.getMax().z);
}
private:
geometry_msgs::Point m_min;
geometry_msgs::Point m_max;
};
| 23.446237
| 116
| 0.63701
|
ne0h
|
340c93500132b2edb63a775261fe8e41be61a8a4
| 3,027
|
cpp
|
C++
|
src/uploader_util.cpp
|
turutosiya/mod_uploader24
|
7c95ee7ae7e10465cbb26ae3025036b917c5fd38
|
[
"Zlib"
] | null | null | null |
src/uploader_util.cpp
|
turutosiya/mod_uploader24
|
7c95ee7ae7e10465cbb26ae3025036b917c5fd38
|
[
"Zlib"
] | null | null | null |
src/uploader_util.cpp
|
turutosiya/mod_uploader24
|
7c95ee7ae7e10465cbb26ae3025036b917c5fd38
|
[
"Zlib"
] | null | null | null |
/******************************************************************************
* Copyright (C) 2007 Tetsuya Kimata <kimata@acapulco.dyndns.org>
*
* All rights reserved.
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any
* damages arising from the use of this software.
*
* Permission is granted to anyone to use this software for any
* purpose, including commercial applications, and to alter it and
* redistribute it freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must
* not claim that you wrote the original software. If you use this
* software in a product, an acknowledgment in the product
* documentation would be appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must
* not be misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*
* $Id: uploader_util.cpp 2756 2007-12-11 10:57:59Z svn $
*****************************************************************************/
#include "Environment.h"
#include "apr_strings.h"
#include "apr_network_io.h"
#include "uploader_util.h"
#include "UploaderConfig.h"
#include "UploadItemIO.h"
#include "PostFlowController.h"
#include "DownloadFlowController.h"
#include "CharCodeConverter.h"
#include "Auxiliary.h"
#include "SourceInfo.h"
SOURCE_INFO_ADD("$Id: uploader_util.cpp 2756 2007-12-11 10:57:59Z svn $");
const char *get_word(apr_pool_t *pool, const char **input,
const char delimiter)
{
const char *start;
const char *end;
start = end = *input;
while ((*end != '\0') && (*end != delimiter)) {
end++;
}
if (*end == '\0') {
*input = end;
} else {
*input = end + 1;
}
if (end != start) {
return apr_pstrmemdup(pool, start, end - start);
} else {
return "";
}
}
void get_page_count(apr_size_t item_count, apr_size_t per_page_item_number,
apr_size_t *page_count)
{
*page_count = (item_count == 0)
? 1
: (item_count-1)/per_page_item_number + 1;
}
void get_page(apr_pool_t *pool, const char *arg, apr_size_t page_count,
apr_size_t *page_no)
{
*page_no = atosize(get_word(pool, &arg, ARG_SEPARATE_STR[0]));
if (*page_no == 0) {
*page_no = 1;
} else if (*page_no > page_count) {
*page_no = page_count;
}
}
bool can_post(UploaderConfig *config, apr_sockaddr_t *ip_address)
{
if (config->is_debug_mode) {
return true;
}
return config->get_post_flow_controller()->can_post(ip_address);
}
void regist_post(UploaderConfig *config, apr_sockaddr_t *ip_address)
{
if (config->is_debug_mode) {
return;
}
config->get_post_flow_controller()->regist_post(ip_address);
}
// Local Variables:
// mode: c++
// coding: utf-8-dos
// End:
| 27.026786
| 79
| 0.626693
|
turutosiya
|
34165f86f52d2a5977b46abfb185dad1443d3835
| 365
|
cpp
|
C++
|
Codeforces Online Judge Solve/Tanya-and-stairways.cpp
|
Remonhasan/programming-solve
|
5a4ac8c738dd361e1c974162e0eaebbaae72fd80
|
[
"Apache-2.0"
] | null | null | null |
Codeforces Online Judge Solve/Tanya-and-stairways.cpp
|
Remonhasan/programming-solve
|
5a4ac8c738dd361e1c974162e0eaebbaae72fd80
|
[
"Apache-2.0"
] | null | null | null |
Codeforces Online Judge Solve/Tanya-and-stairways.cpp
|
Remonhasan/programming-solve
|
5a4ac8c738dd361e1c974162e0eaebbaae72fd80
|
[
"Apache-2.0"
] | null | null | null |
#include<bits/stdc++.h>
using namespace std;
#define pb push_back
int main ()
{
int n;
cin>>n;
vector<int>a;
int p=-1;
for(int i=0;i<n;i++){
int x;
cin>>x;
if(x==1 && p!= -1)
a.pb(p);
p=x;
}
a.pb(p);
cout << a.size()<< endl;
for (int i: a)
cout << i << " ";
}
| 16.590909
| 29
| 0.386301
|
Remonhasan
|
341dd7bd451c1855ebe391af323a9ba22b7e3d9d
| 4,915
|
cpp
|
C++
|
GlobalIllumination/SceneMaterialManager.cpp
|
wzchua/graphic
|
71d154b56a268cce6a1b06e275083210e205aa60
|
[
"Apache-2.0"
] | null | null | null |
GlobalIllumination/SceneMaterialManager.cpp
|
wzchua/graphic
|
71d154b56a268cce6a1b06e275083210e205aa60
|
[
"Apache-2.0"
] | null | null | null |
GlobalIllumination/SceneMaterialManager.cpp
|
wzchua/graphic
|
71d154b56a268cce6a1b06e275083210e205aa60
|
[
"Apache-2.0"
] | null | null | null |
#include "SceneMaterialManager.h"
void SceneMaterialManager::addMaterialShapeGroup(const tinyobj::shape_t & shape, const tinyobj::attrib_t & attrib, const tinyobj::material_t & material, const GLuint64 textureIds[4])
{
auto const & result = mMatGroupMap.find(material.name);
GLuint index = -1;
if (result == mMatGroupMap.end()) {
index = mGroupList.size();
mGroupList.emplace_back();
mMat.emplace_back();
mMatGroupMap[material.name] = index;
Mat & mat = mMat[index];
mat.texAmbient = textureIds[0];
mat.texDiffuse = textureIds[1];
mat.texAlpha = textureIds[2];
mat.texHeight = textureIds[3];
mat.ambient = { material.ambient[0], material.ambient[1], material.ambient[2], 1.0f };
mat.diffuse = { material.diffuse[0], material.diffuse[1], material.diffuse[2], 1.0f };
mat.specular = { material.specular[0], material.specular[1], material.specular[2], 1.0f };
mat.shininess = material.shininess;
mat.useBumpMap = (material.bump_texname.length() > 0) ? 1 : 0;
}
else {
index = result->second;
}
ShapeGroup& group = mGroupList[index];
group.addShape(shape, attrib, textureIds, material);
}
void SceneMaterialManager::generateGPUBuffers()
{
auto matSize = sizeof(Mat);
//Mat UBO
for (auto & m : mMat) {
GLuint buffer;
glGenBuffers(1, &buffer);
glBindBuffer(GL_UNIFORM_BUFFER, buffer);
glBufferData(GL_UNIFORM_BUFFER, matSize, &m, GL_STATIC_DRAW);
glBindBuffer(GL_UNIFORM_BUFFER, 0);
mMatBufferList.push_back(buffer);
}
//VBO, EBO, VAO
for (auto & g : mGroupList) {
g.generateGPUBuffers();
}
}
void SceneMaterialManager::render(GLuint programId)
{
for (int i = 0; i < mGroupList.size(); i++) {
glBindBufferBase(GL_UNIFORM_BUFFER, GlobalShaderComponents::MATERIAL_UBO_BINDING, mMatBufferList[i]);
mGroupList[i].render();
}
}
void SceneMaterialManager::makeAllTextureResident()
{
for (auto const & t : textureMap) {
auto handle = glGetTextureHandleARB(t.second);
glMakeTextureHandleResidentARB(handle);
mTextureResident.insert(std::make_pair(t.first, handle));
}
}
void SceneMaterialManager::resetTextureMap()
{
std::vector<unsigned int> textureIds;
for (auto const& iter : textureMap) {
textureIds.push_back(iter.second);
}
glDeleteTextures((GLsizei)textureIds.size(), textureIds.data());
textureMap.clear();
}
void SceneMaterialManager::getTextureHandles(const tinyobj::material_t & material, GLuint64 & texAmbient, GLuint64 & texDiffuse, GLuint64 & texAlpha, GLuint64 & texHeight)
{
auto textureResult = textureMap.find(material.ambient_texname);
GLuint64 nullHandle = glGetTextureHandleARB(nullTextureId);
//ambient
if (textureResult == textureMap.end()) {
texAmbient = nullHandle;
}
else {
GLuint textureId = textureResult->second;
texAmbient = glGetTextureHandleARB(textureId);
}
textureResult = textureMap.find(material.diffuse_texname);
if (textureResult == textureMap.end()) {
texDiffuse = nullHandle;
}
else {
GLuint textureId = textureResult->second;
texDiffuse = glGetTextureHandleARB(textureId);
}
textureResult = textureMap.find(material.alpha_texname);
if (textureResult == textureMap.end()) {
texAlpha = nullHandle;
}
else {
GLuint textureId = textureResult->second;
texAlpha = glGetTextureHandleARB(textureId);
}
textureResult = textureMap.find(material.bump_texname);
if (textureResult == textureMap.end()) {
texHeight = nullHandle;
}
else {
GLuint textureId = textureResult->second;
texHeight = glGetTextureHandleARB(textureId);
}
}
std::pair<glm::vec3, glm::vec3> SceneMaterialManager::getSceneMinMaxCoords() const
{
std::pair<glm::vec3, glm::vec3> minmax = mGroupList[0].getMinMaxCoords();
for (auto & g : mGroupList) {
auto newMinMax = g.getMinMaxCoords();
minmax.first = glm::min(minmax.first, newMinMax.first);
minmax.second = glm::max(minmax.second, newMinMax.second);
}
return minmax;
}
SceneMaterialManager::SceneMaterialManager()
{
int w = 1, h = 1;
unsigned char image[4] = { 255, 255, 255, 255 };
glGenTextures(1, &nullTextureId);
glBindTexture(GL_TEXTURE_2D, nullTextureId);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, &image);
glBindTexture(GL_TEXTURE_2D, 0);
auto handle = glGetTextureHandleARB(nullTextureId);
glMakeTextureHandleResidentARB(handle);
}
SceneMaterialManager::~SceneMaterialManager()
{
glDeleteTextures(1, &nullTextureId);
resetTextureMap();
for (int i = 0; i < mGroupList.size(); i++) {
mGroupList[i].destroyData();
}
}
| 31.915584
| 182
| 0.663886
|
wzchua
|
341e6e488261d8872d6bf3e6a693542d944ece71
| 20,079
|
hpp
|
C++
|
include/scran/quality_control/PerCellQCFilters.hpp
|
LTLA/libscran
|
12faf62c42c388f26db3b03d322c5f430e2c5080
|
[
"MIT"
] | 4
|
2021-06-16T10:08:04.000Z
|
2022-02-23T14:03:41.000Z
|
include/scran/quality_control/PerCellQCFilters.hpp
|
LTLA/libscran
|
12faf62c42c388f26db3b03d322c5f430e2c5080
|
[
"MIT"
] | 3
|
2021-10-16T23:14:47.000Z
|
2021-12-23T07:51:54.000Z
|
include/scran/quality_control/PerCellQCFilters.hpp
|
LTLA/libscran
|
12faf62c42c388f26db3b03d322c5f430e2c5080
|
[
"MIT"
] | null | null | null |
#ifndef SCRAN_PER_CELL_QC_FILTERS_H
#define SCRAN_PER_CELL_QC_FILTERS_H
#include <vector>
#include <cstdint>
#include "../utils/vector_to_pointers.hpp"
#include "PerCellQCMetrics.hpp"
#include "IsOutlier.hpp"
/**
* @file PerCellQCFilters.hpp
*
* @brief Create filters to identify low-quality cells.
*/
namespace scran {
/**
* @brief Create filters to identify low-quality cells.
*
* Use an outlier-based approach on common QC metrics (see the `PerCellQCMetrics` class) to identify low-quality cells.
* Specifically, low-quality cells are defined as those with:
*
* - Low total counts, indicating that library preparation or sequencing depth was suboptimal.
* - Low numbers of detected features, a slightly different flavor of the above reasoning.
* - High proportions of counts in the mitochondrial (or spike-in) subsets, representing cell damage.
*
* Outliers are defined on each metric by counting the number of MADs from the median value across all cells.
* This assumes that most cells in the experiment are of high (or at least acceptable) quality;
* any anomalies are indicative of low-quality cells that should be filtered out.
* See the `IsOutlier` class for implementation details.
*
* For the total counts and number of detected features, the outliers are defined after log-transformation of the metrics.
* This improves resolution at low values and ensures that the defined threshold is not negative.
*/
class PerCellQCFilters {
public:
/**
* Set the number of MADs from the median to define the threshold for outliers.
*
* @param n Number of MADs.
*
* @return A reference to this `PerCellQCFilters` object.
*/
PerCellQCFilters& set_nmads(double n = 3) {
outliers.set_nmads(n);
return *this;
}
public:
/**
* @brief Thresholds to define outliers on each metric.
*/
struct Thresholds {
/**
* Lower thresholds to define small outliers on the total counts.
* Each entry contains the threshold used for the corresponding block.
* For unblocked analyses, this will be of length 1 as all cells are assumed to belong to the same block.
*
* Note that, despite the fact that the outliers are defined on the log-scale,
* these thresholds are reported on the original scale - see the `IsOutlier` class for details.
*/
std::vector<double> sums;
/**
* Lower thresholds to define small outliers on the number of detected features.
* Each entry contains the threshold used for the corresponding block.
* For unblocked analyses, this will be of length 1 as all cells are assumed to belong to the same block.
*
* Note that, despite the fact that the outliers are defined on the log-scale,
* these thresholds are reported on the original scale - see the `IsOutlier` class for details.
*/
std::vector<double> detected;
/**
* Upper thresholds to define large outliers on the subset proportions.
* Each vector corresponds to a feature subset while each entry of the inner vector corresponds to a block of cells.
* For unblocked analyses, all cells are assumed to belong to a single block, i.e., all inner vectors have length 1.
*/
std::vector<std::vector<double> > subset_proportions;
};
public:
/**
* Identify low-quality cells as those that have outlier values for QC metrics.
* This uses QC metrics that are typically computed by the `PerCellQCMetrics` class.
*
* @tparam S Floating point type, used for the sum.
* @tparam D Integer type, used for the number of detected features.
* @tparam PPTR Pointer to a floating point type, for the subset proportions.
* @tparam X Boolean type to indicate whether a cell should be discarded.
*
* @param ncells Number of cells.
* @param[in] sums Pointer to an array of length equal to `ncells`, containing the per-cell sums.
* @param[in] detected Pointer to an array of length equal to `ncells`, containing the number of detected features for each cell.
* @param[in] subset_proportions Vector of pointers of length equal to the number of feature subsets.
* Each pointer corresponds to a feature subset and should point to an array of length equal to `ncells`, containing the proportion of counts in that subset for each cell.
* @param[out] filter_by_sums Pointer to an output array of length equal to `ncells`,
* indicating whether a cell should be filtered out due to low count sums.
* @param[out] filter_by_detected Pointer to an output array of length equal to `ncells`,
* indicating whether a cell should be filtered out due to a low number of detected features.
* @param[out] filter_by_subset_proportions Vector of pointers of length equal to the number of feature subsets.
* Each pointer corresponds to a feature subset and should point to an array of length equal to `ncells`,
* indicating whether a cell should be filtered out due to a high proportion of counts for that subset.
* @param[out] overall_filter Pointer to an output array of length equal to `ncells`,
* indicating whether a cell should be filtered out for any reason.
*
* @return A `Thresholds` object defining the thresholds for each QC metric.
*/
template<typename S, typename D, typename PPTR, typename X>
Thresholds run(size_t ncells, const S* sums, const D* detected, std::vector<PPTR> subset_proportions,
X* filter_by_sums, X* filter_by_detected, std::vector<X*> filter_by_subset_proportions, X* overall_filter)
{
auto fun = [&](size_t n, auto metric, auto output) -> auto {
return outliers.run(n, metric, output);
};
return run_internal(fun,
ncells,
sums,
detected,
std::move(subset_proportions),
filter_by_sums,
filter_by_detected,
std::move(filter_by_subset_proportions),
overall_filter);
}
/**
* Identify low-quality cells from QC metrics, with blocking during outlier identification.
* Specifically, outliers are only computed within each block, which is useful when cells in different blocks have different distributions for the QC metrics, e.g., because they were sequenced at different depth.
* By blocking, we avoid confounding the outlier detection with systematic differences between blocks.
*
* @tparam B Pointer to an integer type, to hold the block IDs.
* @tparam S Floating point type, used for the sum.
* @tparam D Integer type, used for the number of detected features.
* @tparam PPTR Pointer to a floating point type, for the subset proportions.
* @tparam X Boolean type to indicate whether a cell should be discarded.
*
* @param ncells Number of cells.
* @param[in] block Pointer to an array of block identifiers.
* If provided, the array should be of length equal to `ncells`.
* Values should be integer IDs in \f$[0, N)\f$ where \f$N\f$ is the number of blocks.
* This can also be `NULL`, in which case all cells are assumed to belong to the same block.
* @param[in] sums Pointer to an array of length equal to `ncells`, containing the per-cell sums.
* @param[in] detected Pointer to an array of length equal to `ncells`, containing the number of detected features for each cell.
* @param[in] subset_proportions Vector of pointers of length equal to the number of feature subsets.
* Each pointer corresponds to a feature subset and should point to an array of length equal to `ncells`, containing the proportion of counts in that subset for each cell.
* @param[out] filter_by_sums Pointer to an output array of length equal to `ncells`,
* indicating whether a cell should be filtered out due to low count sums.
* @param[out] filter_by_detected Pointer to an output array of length equal to `ncells`,
* indicating whether a cell should be filtered out due to a low number of detected features.
* @param[out] filter_by_subset_proportions Vector of pointers of length equal to the number of feature subsets.
* Each pointer corresponds to a feature subset and should point to an array of length equal to `ncells`,
* indicating whether a cell should be filtered out due to a high proportion of counts for that subset.
* @param[out] overall_filter Pointer to an output array of length equal to `ncells`,
* indicating whether a cell should be filtered out for any reason.
*
* @return A `Thresholds` object defining the thresholds for each QC metric in each block.
*/
template<typename B, typename S, typename D, typename PPTR, typename X>
Thresholds run_blocked(size_t ncells, const B* block, const S* sums, const D* detected, std::vector<PPTR> subset_proportions,
X* filter_by_sums, X* filter_by_detected, std::vector<X*> filter_by_subset_proportions, X* overall_filter)
{
if (!block) {
return run(ncells,
sums,
detected,
std::move(subset_proportions),
filter_by_sums,
filter_by_detected,
std::move(filter_by_subset_proportions),
overall_filter);
} else {
auto by_block = block_indices(ncells, block);
auto fun = [&](size_t n, auto metric, auto output) -> auto {
return outliers.run_blocked(n, by_block, metric, output);
};
return run_internal(fun,
ncells,
sums,
detected,
std::move(subset_proportions),
filter_by_sums,
filter_by_detected,
std::move(filter_by_subset_proportions),
overall_filter);
}
}
private:
template<class FUNCTION, typename S, typename D, typename PPTR, typename X>
Thresholds run_internal(FUNCTION&& fun, size_t ncells, const S* sums, const D* detected, std::vector<PPTR> subset_proportions,
X* filter_by_sums, X* filter_by_detected, std::vector<X*> filter_by_subset_proportions, X* overall_filter)
{
Thresholds output;
outliers.set_lower(true).set_upper(false).set_log(true);
// Filtering to remove outliers on the log-sum.
{
#ifdef SCRAN_LOGGER
SCRAN_LOGGER("scran::PerCellQCFilters", "Filtering on the total count per cell");
#endif
auto res = fun(ncells, sums, filter_by_sums);
output.sums = res.lower;
std::copy(filter_by_sums, filter_by_sums + ncells, overall_filter);
}
// Filtering to remove outliers on the log-detected number.
{
#ifdef SCRAN_LOGGER
SCRAN_LOGGER("scran::PerCellQCFilters", "Filtering on the number of detected genes");
#endif
auto res = fun(ncells, detected, filter_by_detected);
output.detected = res.lower;
for (size_t i = 0; i < ncells; ++i) {
overall_filter[i] |= filter_by_detected[i];
}
}
// Filtering to remove outliers on the subset proportions.
#ifdef SCRAN_LOGGER
SCRAN_LOGGER("scran::PerCellQCFilters", "Filtering on the proportions in control subsets");
#endif
size_t nsubsets = subset_proportions.size();
if (filter_by_subset_proportions.size() != nsubsets) {
throw std::runtime_error("mismatching number of input/outputs for subset proportion filters");
}
outliers.set_upper(true).set_lower(false).set_log(false);
output.subset_proportions.resize(nsubsets);
for (size_t s = 0; s < subset_proportions.size(); ++s) {
auto dump = filter_by_subset_proportions[s];
auto res = fun(ncells, subset_proportions[s], dump);
output.subset_proportions[s] = res.upper;
for (size_t i = 0; i < ncells; ++i) {
overall_filter[i] |= dump[i];
}
}
return output;
}
public:
/**
* @brief Results of the QC filtering.
*
* @tparam X Boolean type to indicate whether a cell should be discarded.
*/
template<typename X = uint8_t>
struct Results {
/**
* @param ncells Number of cells.
* @param nsubsets Number of feature subsets.
*/
Results(size_t ncells, int nsubsets) : filter_by_sums(ncells), filter_by_detected(ncells),
filter_by_subset_proportions(nsubsets, std::vector<X>(ncells)),
overall_filter(ncells) {}
/**
* Vector of length equal to the number of cells.
* Entries are set to 1 if the total count in the corresponding cell is a small outlier (indicating that the cell should be considered as low-quality).
*/
std::vector<X> filter_by_sums;
/**
* Vector of length equal to the number of cells.
* Entries are set to 1 if the number of detected features in the corresponding cell is a small outlier (indicating that the cell should be considered as low-quality).
*/
std::vector<X> filter_by_detected;
/**
* Vector of length equal to the number of feature subsets.
* Each inner vector corresponds to a feature subset and is of length equal to the number of cells.
* Entries are set to 1 if the subset proportion in the corresponding cell is a small outlier (indicating that the cell should be considered as low-quality).
*/
std::vector<std::vector<X> > filter_by_subset_proportions;
/**
* Vector of length equal to the number of cells.
* Entries are set to 1 if the cell is to be considered as low-quality from any of the reasons listed in the previous vectors.
*/
std::vector<X> overall_filter;
/**
* The thresholds used to define outliers for each of the filtering criteria.
*/
Thresholds thresholds;
};
public:
/**
* Identify low-quality cells from QC metrics, see `run()`.
*
* @tparam X Boolean type to indicate whether a cell should be discarded.
* @tparam S Type of the sum.
* @tparam D Type of the number of detected features.
* @tparam PPTR Type of the pointer to the subset proportions.
*
* @param ncells Number of cells.
* @param[in] sums Pointer to an array of length equal to `ncells`, containing the per-cell sums.
* @param[in] detected Pointer to an array of length equal to `ncells`, containing the number of detected features for each cell.
* @param[in] subset_proportions Vector of pointers of length equal to the number of feature subsets.
* Each pointer corresponds to a feature subset and should point to an array of length equal to `ncells`, containing the proportion of counts in that subset for each cell.
*
* @return A `Results` object indicating whether a cell should be filtered out for each reason.
*/
template<typename X = uint8_t, typename S, typename D, typename PPTR>
Results<X> run(size_t ncells, const S* sums, const D* detected, std::vector<PPTR> subset_proportions) {
Results<X> output(ncells, subset_proportions.size());
output.thresholds = run(ncells,
sums,
detected,
std::move(subset_proportions),
output.filter_by_sums.data(),
output.filter_by_detected.data(),
vector_to_pointers(output.filter_by_subset_proportions),
output.overall_filter.data());
return output;
}
/**
* Identify low-quality cells from QC metrics with blocking, see `run_blocked()`.
*
* @tparam X Boolean type to indicate whether a cell should be discarded.
* @tparam B Pointer to an integer type, to hold the block IDs.
* @tparam S Type of the sum.
* @tparam D Type of the number of detected features.
* @tparam PPTR Type of the pointer to the subset proportions.
*
* @param ncells Number of cells.
* @param[in] block Optional pointer to an array of block identifiers, see `run_blocked()` for details.
* @param[in] sums Pointer to an array of length equal to `ncells`, containing the per-cell sums.
* @param[in] detected Pointer to an array of length equal to `ncells`, containing the number of detected features for each cell.
* @param[in] subset_proportions Vector of pointers of length equal to the number of feature subsets.
* Each pointer corresponds to a feature subset and should point to an array of length equal to `ncells`, containing the proportion of counts in that subset for each cell.
*
* @return A `Results` object indicating whether a cell should be filtered out for each reason.
*/
template<typename X = uint8_t, typename B, typename S, typename D, typename PPTR>
Results<X> run_blocked(size_t ncells, const B* block, const S* sums, const D* detected, std::vector<PPTR> subset_proportions) {
Results<X> output(ncells, subset_proportions.size());
output.thresholds = run_blocked(ncells,
block,
sums,
detected,
std::move(subset_proportions),
output.filter_by_sums.data(),
output.filter_by_detected.data(),
vector_to_pointers(output.filter_by_subset_proportions),
output.overall_filter.data());
return output;
}
public:
/**
* Identify low-quality cells from QC metrics, see `run()` for details.
*
* @tparam X Boolean type to indicate whether a cell should be discarded.
* @tparam R Class that holds the QC metrics, typically a `PerCellQCMetrics::Results`.
*
* @param metrics Precomputed QC metrics, typically generated by `PerCellQCMetrics::run`.
*
* @return A `Results` object indicating whether a cell should be filtered out for each reason.
*/
template<typename X=uint8_t, class R>
Results<X> run(const R& metrics) {
return run(metrics.sums.size(), metrics.sums.data(), metrics.detected.data(), vector_to_pointers(metrics.subset_proportions));
}
/**
* Identify low-quality cells from QC metrics with blocking, see `run_blocked()` for details.
*
* @tparam X Boolean type to indicate whether a cell should be discarded.
* @tparam R Class that holds the QC metrics, typically a `PerCellQCMetrics::Results`.
* @tparam B Integer type, to hold the block IDs.
*
* @param metrics Precomputed QC metrics, typically generated by `PerCellQCMetrics::run`.
* @param[in] block Optional pointer to an array of block identifiers, see `run_blocked()` for details.
*
* @return A `Results` object indicating whether a cell should be filtered out for each reason.
*/
template<typename X=uint8_t, class R, typename B>
Results<X> run_blocked(const R& metrics, const B* block) {
return run_blocked(metrics.sums.size(), block, metrics.sums.data(), metrics.detected.data(), vector_to_pointers(metrics.subset_proportions));
}
private:
IsOutlier outliers;
};
}
#endif
| 50.072319
| 216
| 0.644554
|
LTLA
|
34218751873b8b49f12bcc12e66aee4cc7835ce1
| 255
|
cpp
|
C++
|
Raven.CppClient/SecurityException.cpp
|
mlawsonca/ravendb-cpp-client
|
c3a3d4960c8b810156547f62fa7aeb14a121bf74
|
[
"MIT"
] | 3
|
2019-04-24T02:34:53.000Z
|
2019-08-01T08:22:26.000Z
|
Raven.CppClient/SecurityException.cpp
|
mlawsonca/ravendb-cpp-client
|
c3a3d4960c8b810156547f62fa7aeb14a121bf74
|
[
"MIT"
] | 2
|
2019-03-21T09:00:02.000Z
|
2021-02-28T23:49:26.000Z
|
Raven.CppClient/SecurityException.cpp
|
mlawsonca/ravendb-cpp-client
|
c3a3d4960c8b810156547f62fa7aeb14a121bf74
|
[
"MIT"
] | 3
|
2019-03-04T11:58:54.000Z
|
2021-03-01T00:25:49.000Z
|
#include "stdafx.h"
#include "SecurityException.h"
namespace ravendb::client::exceptions::security
{
SecurityException::SecurityException() = default;
SecurityException::SecurityException(const std::string& message)
: RavenException(message)
{}
}
| 21.25
| 65
| 0.768627
|
mlawsonca
|
342530a70e80e04bf75b6ab21cfe0dcf5b929481
| 492
|
cpp
|
C++
|
codeforces/edu/ITMO Academy: pilot course/Disjoint Sets Union/step 2/b.cpp
|
tysm/cpsols
|
262212646203e516d1706edf962290de93762611
|
[
"MIT"
] | 4
|
2020-10-05T19:24:10.000Z
|
2021-07-15T00:45:43.000Z
|
codeforces/edu/ITMO Academy: pilot course/Disjoint Sets Union/step 2/b.cpp
|
tysm/cpsols
|
262212646203e516d1706edf962290de93762611
|
[
"MIT"
] | null | null | null |
codeforces/edu/ITMO Academy: pilot course/Disjoint Sets Union/step 2/b.cpp
|
tysm/cpsols
|
262212646203e516d1706edf962290de93762611
|
[
"MIT"
] | null | null | null |
#include <cpplib/stdinc.hpp>
#include <cpplib/adt/dsu.hpp>
int32_t main(){
desync();
int n;
cin >> n;
vi ans(n);
iota(all(ans), 0);
DSU dsu(n+1);
vi out;
for(int i=0; i<n; ++i){
int pos;
cin >> pos;
pos--;
int res = ans[dsu.find(pos)];
out.eb(res+1);
int res_r = ans[dsu.find((res+1)%n)];
dsu.merge(res, (res+1)%n);
ans[dsu.find(res)] = res_r;
}
cout << out << endl;
return 0;
}
| 16.965517
| 45
| 0.463415
|
tysm
|
3429e4a18e9e9f0a9121f79e7cd3cc139464cf9b
| 1,840
|
cpp
|
C++
|
src/test/compacttxfinder_tests.cpp
|
WestonReed/bitcoinxt
|
ac5b611797cb83226b7abce53cc50d48cb2a0c16
|
[
"MIT"
] | 515
|
2015-01-03T03:44:52.000Z
|
2022-02-11T18:37:43.000Z
|
src/test/compacttxfinder_tests.cpp
|
WestonReed/bitcoinxt
|
ac5b611797cb83226b7abce53cc50d48cb2a0c16
|
[
"MIT"
] | 427
|
2015-01-20T15:15:26.000Z
|
2020-08-31T10:48:30.000Z
|
src/test/compacttxfinder_tests.cpp
|
WestonReed/bitcoinxt
|
ac5b611797cb83226b7abce53cc50d48cb2a0c16
|
[
"MIT"
] | 192
|
2015-02-15T01:23:16.000Z
|
2021-11-04T16:42:20.000Z
|
// Copyright (c) 2016 The Bitcoin XT developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <boost/test/unit_test_suite.hpp>
#include <boost/test/test_tools.hpp>
#include "blockencodings.h"
#include "compactprefiller.h"
#include "compactthin.h"
#include "compacttxfinder.h"
#include "sync.h"
#include "test/test_bitcoin.h"
#include "test/thinblockutil.h"
#include "txmempool.h"
BOOST_AUTO_TEST_SUITE(comapacttxfinder_tests)
BOOST_AUTO_TEST_CASE(compacttxfinder_test) {
CTxMemPool mpool(CFeeRate(0));
TestMemPoolEntryHelper entry;
CBlock block = TestBlock1();
mpool.addUnchecked(block.vtx[1].GetHash(), entry.FromTx(block.vtx[1]));
mpool.addUnchecked(block.vtx[2].GetHash(), entry.FromTx(block.vtx[2]));
mpool.addUnchecked(block.vtx[3].GetHash(), entry.FromTx(block.vtx[3]));
CompactBlock cmpct(block, CoinbaseOnlyPrefiller());
CompactStub stub(cmpct);
std::vector<ThinTx> all = stub.allTransactions();
CompactTxFinder finder(mpool, cmpct.shorttxidk0, cmpct.shorttxidk1);
// Should find the txs in mpool
BOOST_CHECK_EQUAL(
block.vtx[1].GetHash().ToString(),
finder(all[1]).GetHash().ToString());
BOOST_CHECK_EQUAL(
block.vtx[2].GetHash().ToString(),
finder(all[2]).GetHash().ToString());
BOOST_CHECK_EQUAL(
block.vtx[3].GetHash().ToString(),
finder(all[3]).GetHash().ToString());
// Should not find txs not in mempool
BOOST_CHECK(finder(all[4]).IsNull());
// If tx is erased from mempool, it should not be found
LOCK(mpool.cs);
auto i = mpool.mapTx.find(block.vtx[1].GetHash());
mpool.mapTx.erase(i);
BOOST_CHECK(finder(all[1]).IsNull());
}
BOOST_AUTO_TEST_SUITE_END()
| 32.280702
| 75
| 0.694022
|
WestonReed
|
342fb1fb962582e097bc3884a3c5631796c62b79
| 3,146
|
cpp
|
C++
|
src/io/file_parser.cpp
|
kaiyuhou/nprint-wlan
|
d8ded24a1f08087b8484f652215354f0202227f3
|
[
"Apache-2.0"
] | null | null | null |
src/io/file_parser.cpp
|
kaiyuhou/nprint-wlan
|
d8ded24a1f08087b8484f652215354f0202227f3
|
[
"Apache-2.0"
] | null | null | null |
src/io/file_parser.cpp
|
kaiyuhou/nprint-wlan
|
d8ded24a1f08087b8484f652215354f0202227f3
|
[
"Apache-2.0"
] | null | null | null |
/*
* Copyright 2020 nPrint
* 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 https://www.apache.org/licenses/LICENSE-2.0
*/
#include "file_parser.hpp"
#define CUSTOM_OUTPUT_RESERVE_SIZE 50
#define BITSTRING_RESERVE_SIZE 10000
#define FIELDS_RESERVE_SIZE 300
void FileParser::set_conf(Config c)
{
packets_processed = 0;
this->config = c;
/* Write header when we set the config */
format_and_write_header();
/* Reserve vectors and use them the entire time */
custom_output.reserve(CUSTOM_OUTPUT_RESERVE_SIZE);
bitstring_vec.reserve(BITSTRING_RESERVE_SIZE);
fields_vec.reserve(FIELDS_RESERVE_SIZE);
if(config.ip_file != NULL)
{
printf("ip map loaded\n");
load_ip_map(config.ip_file);
has_ip_map = true;
}
else
{
has_ip_map = false;
}
}
void FileParser::set_filewriter(FileWriter *fw)
{
this->fw = fw;
}
#define IP_FILE_IP_LOC 0
void FileParser::load_ip_map(std::string ip_file)
{
std::string line;
std::vector<std::string> tokens;
std::ifstream infile(ip_file);
while(getline(infile, line))
{
tokenize_line(line, tokens);
m.insert(make_pair(tokens[IP_FILE_IP_LOC], 0));
}
}
void FileParser::tokenize_line(std::string line, std::vector<std::string> &to_fill, char delimiter)
{
std::string token;
std::stringstream ss;
to_fill.clear();
ss.str(line);
while(getline(ss, token, delimiter)) to_fill.push_back(token);
}
SuperPacket *FileParser::process_packet(void *pkt)
{
bool wtf;
SuperPacket *sp;
std::string src_ip;
std::vector<std::string> to_fill;
std::map<std::string, std::uint32_t>::iterator mit;
to_fill.clear();
sp = new SuperPacket(pkt, config.payload, &config); // kaiyu
if(!sp->check_parseable())
{
delete sp;
return NULL;
}
if(config.verbose) sp->print_packet();
src_ip = sp->get_ip_address();
/* determine if we should output the packet */
wtf = true;
/* Not writing per host, keep track of num processed */
if(!has_ip_map)
{
/* Exit when done */
if(config.num_packets != 0 && packets_processed >= config.num_packets) exit(0);
packets_processed++;
}
/* Writing per host */
else
{
mit = m.find(src_ip);
/* IP not been seen yet */
if(mit == m.end())
{
wtf = false;
}
/* IP in map, check if we've surpassed total packets to process for IP */
else
{
if((mit->second >= config.num_packets) && config.num_packets != 0) wtf = false;
mit->second++;
}
}
if(wtf)
{
return sp;
}
else
{
delete sp;
return NULL;
}
}
void FileParser::write_output(SuperPacket *sp)
{
sp->get_bitstring(&config, bitstring_vec);
fw->write_bitstring_line(custom_output, bitstring_vec);
bitstring_vec.clear();
custom_output.clear();
delete sp;
}
| 23.654135
| 99
| 0.618245
|
kaiyuhou
|
34329bdaac7e37881e159a5b85cdd2241e8b0cf0
| 2,011
|
cpp
|
C++
|
sourceCode/application/ui/project/dialog_selectoneoflayers.cpp
|
lp-rep/stackprof-1
|
62d9cb96ad7dcdaa26b6383559f542cadc1c7af2
|
[
"CECILL-B"
] | 2
|
2022-02-27T20:08:04.000Z
|
2022-03-03T13:45:40.000Z
|
sourceCode/application/ui/project/dialog_selectoneoflayers.cpp
|
lp-rep/stackprof-1
|
62d9cb96ad7dcdaa26b6383559f542cadc1c7af2
|
[
"CECILL-B"
] | 1
|
2021-06-07T17:09:04.000Z
|
2021-06-11T11:48:23.000Z
|
sourceCode/application/ui/project/dialog_selectoneoflayers.cpp
|
lp-rep/stackprof-1
|
62d9cb96ad7dcdaa26b6383559f542cadc1c7af2
|
[
"CECILL-B"
] | 1
|
2021-06-03T21:06:55.000Z
|
2021-06-03T21:06:55.000Z
|
#include <QVector>
#include <QDebug>
#include "dialog_selectoneoflayers.h"
#include "ui_dialog_selectoneoflayers.h"
Dialog_selectOneOfLayers::Dialog_selectOneOfLayers(QWidget *parent) :
QDialog(parent),
ui(new Ui::Dialog_selectOneOfLayers), _tRadioButtonPtr {nullptr, nullptr, nullptr},
_selected_iLayer(-1) {
ui->setupUi(this);
_tRadioButtonPtr[0] = ui->radioButton_L1;
_tRadioButtonPtr[1] = ui->radioButton_L2;
_tRadioButtonPtr[2] = ui->radioButton_L3;
for (int i = 0; i < 3; i++) {
_tRadioButtonPtr[i]->setProperty("iLayer", i);
connect(_tRadioButtonPtr[i], &QRadioButton::clicked, this, &Dialog_selectOneOfLayers::slot_radioButtonClicked);
}
}
void Dialog_selectOneOfLayers::slot_radioButtonClicked() {
QObject *ptrSender = sender();
QVariant qvariant_iLayer = ptrSender->property("iLayer");
bool bOk = false;
int iLayer = qvariant_iLayer.toInt(&bOk);
if (!bOk) {
qDebug() << __FUNCTION__ << " error: fail in qvariant_iLayer.toInt()";
return;
}
_selected_iLayer = iLayer;
}
void Dialog_selectOneOfLayers::setLayersName(const QVector<QString> qVectStr) {
if (qVectStr.size() != 3) {
return;
}
for (int i = 0; i < 3; i++) {
_tRadioButtonPtr[i]->setText(qVectStr[i]);
}
}
void Dialog_selectOneOfLayers::setAvailableLayers(const QVector<bool>& qvectBAvailableLayers) {
if (qvectBAvailableLayers.size() != 3) {
return;
}
for (int i = 0; i < 3; i++) {
_tRadioButtonPtr[i]->setVisible(false);
}
for (int i = 0; i < 3; i++) {
_tRadioButtonPtr[i]->setVisible(qvectBAvailableLayers[i]);
}
_selected_iLayer = qvectBAvailableLayers.indexOf(true); //@LP if none, will be -1
if (_selected_iLayer >= 0) {
_tRadioButtonPtr[_selected_iLayer]->setChecked(true);
}
}
int Dialog_selectOneOfLayers::getSelected() {
return(_selected_iLayer);
}
Dialog_selectOneOfLayers::~Dialog_selectOneOfLayers() {
delete ui;
}
| 28.728571
| 119
| 0.669816
|
lp-rep
|
3434c95eca8494631784e41d96583fabc8c23f07
| 809
|
hpp
|
C++
|
src/procman/exec_string_utils.hpp
|
ashuang/procman
|
0ba4409878117c727b3c59ab4fac800bdc9ee1b1
|
[
"BSD-3-Clause"
] | 9
|
2019-01-04T09:52:06.000Z
|
2022-01-13T09:20:57.000Z
|
include/procman/exec_string_utils.hpp
|
ori-drs/procman_ros
|
769354bd45fab0653c2537c857431553a08b0a5e
|
[
"BSD-3-Clause"
] | 32
|
2020-05-11T13:32:30.000Z
|
2022-02-22T09:39:28.000Z
|
src/procman/exec_string_utils.hpp
|
ashuang/procman
|
0ba4409878117c727b3c59ab4fac800bdc9ee1b1
|
[
"BSD-3-Clause"
] | 12
|
2016-11-19T18:15:56.000Z
|
2021-09-27T00:04:49.000Z
|
#ifndef PROCMAN_EXEC_STRING_UTILS_HPP__
#define PROCMAN_EXEC_STRING_UTILS_HPP__
#include <map>
#include <string>
#include <vector>
#include "procman.hpp"
namespace procman {
/**
* Do variable expansion on a command argument. This searches the argument for
* text of the form $VARNAME and ${VARNAME}. For each discovered variable, it
* then expands the variable using the environment. If a variable expansion
* fails, then the corresponding text is left unchanged.
*/
std::string ExpandVariables(const std::string& input);
std::vector<std::string> SeparateArgs(const std::string& input);
std::vector<std::string> Split(const std::string& input,
const std::string& delimeters,
int max_items);
void Strfreev(char** vec);
} // namespace procman
#endif // PROCMAN_EXEC_STRING_UTILS_HPP__
| 26.096774
| 79
| 0.752781
|
ashuang
|
3439607697e5e8c1e6579a95521eb6dbbd337fef
| 1,757
|
cpp
|
C++
|
Faciles/ASCII Art.cpp
|
informaticienzero/CodinGame
|
c6aac236b1929be0a0c254c7bf92adf7c5ead5cd
|
[
"MIT"
] | 2
|
2019-08-22T07:12:24.000Z
|
2019-12-03T21:12:09.000Z
|
Faciles/ASCII Art.cpp
|
informaticienzero/CodinGame
|
c6aac236b1929be0a0c254c7bf92adf7c5ead5cd
|
[
"MIT"
] | null | null | null |
Faciles/ASCII Art.cpp
|
informaticienzero/CodinGame
|
c6aac236b1929be0a0c254c7bf92adf7c5ead5cd
|
[
"MIT"
] | 7
|
2019-03-18T00:47:14.000Z
|
2021-07-12T08:41:42.000Z
|
#include <array>
#include <cctype>
#include <iostream>
#include <string>
#include <vector>
struct Letter
{
char associated_char;
std::vector<std::string> parts;
};
int main()
{
int L;
std::cin >> L; std::cin.ignore();
int H;
std::cin >> H; std::cin.ignore();
std::string T;
std::getline(std::cin, T);
// First preparing the line to print.
for (char & c : T)
{
if (isalpha(c))
{
c = toupper(c);
}
else
{
c = '?';
}
}
std::vector<std::string> rows;
for (int i = 0; i < H; i++)
{
std::string ROW;
std::getline(std::cin, ROW);
rows.push_back(ROW);
}
constexpr std::size_t char_number = 27;
std::array<Letter, char_number> letters;
for (std::size_t i = 0; i < char_number; ++i)
{
// Get the rows one by one, from 0 to H.
// To divise them, we advance each turn by L.
for (std::size_t j = 0; j < H; ++j)
{
letters[i].parts.push_back(rows[j].substr(i * L, L));
}
letters[i].associated_char = 'A' + i;
}
std::vector<Letter> to_print;
for (char c : T)
{
// We know that '?' is the last one of the letters array.
if (c == '?')
{
to_print.push_back(letters[char_number - 1]);
}
else
{
to_print.push_back(letters[c - 'A']);
}
}
const std::size_t size = to_print.size();
for (std::size_t line = 0; line < H; ++line)
{
for (std::size_t i = 0; i < size; ++i)
{
std::cout << to_print[i].parts[line];
}
std::cout << std::endl;
}
}
| 21.168675
| 65
| 0.467843
|
informaticienzero
|
3439f2921d7cdb9e032ed289151e9ee4e823baaf
| 273
|
cpp
|
C++
|
Upsolving/Codeforces/1107B.cpp
|
rodrigoAMF7/Notebook---Maratonas
|
06b38197a042bfbd27b20f707493e0a19fda7234
|
[
"MIT"
] | 4
|
2019-01-25T21:22:55.000Z
|
2019-03-20T18:04:01.000Z
|
Upsolving/Codeforces/1107B.cpp
|
rodrigoAMF/competitive-programming-notebook
|
06b38197a042bfbd27b20f707493e0a19fda7234
|
[
"MIT"
] | null | null | null |
Upsolving/Codeforces/1107B.cpp
|
rodrigoAMF/competitive-programming-notebook
|
06b38197a042bfbd27b20f707493e0a19fda7234
|
[
"MIT"
] | null | null | null |
#include <bits/stdc++.h>
using namespace std;
#define ll long long
int main(){
/*
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
*/
ll n, k, x;
cin >> n;
while(n--){
cin >> k >> x;
cout << ((k - 1)*9) + x << "\n";
}
return 0;
}
| 10.92
| 36
| 0.498168
|
rodrigoAMF7
|
343bddfdcce0329ae08d2b1d34f6169deb8253ff
| 320
|
cpp
|
C++
|
source/chapter_05/listings/listing_05_01_forloop.cpp
|
ShinyGreenRobot/CPP-Primer-Plus-Sixth-Edition
|
ce2c8fca379508929dfd24dce10eff2c09117999
|
[
"MIT"
] | null | null | null |
source/chapter_05/listings/listing_05_01_forloop.cpp
|
ShinyGreenRobot/CPP-Primer-Plus-Sixth-Edition
|
ce2c8fca379508929dfd24dce10eff2c09117999
|
[
"MIT"
] | null | null | null |
source/chapter_05/listings/listing_05_01_forloop.cpp
|
ShinyGreenRobot/CPP-Primer-Plus-Sixth-Edition
|
ce2c8fca379508929dfd24dce10eff2c09117999
|
[
"MIT"
] | null | null | null |
/**
* \file
* listing_05_01_forloop.cpp
*
* \brief
* Introducing the for loop.
*/
#include <iostream>
int main()
{
using namespace std;
int i; // create a counter
// initialize; test ; update
for (i = 0; i < 5; i++)
{
cout << "C++ knows loops.\n";
}
cout << "C++ knows when to stop.\n";
return 0;
}
| 12.307692
| 37
| 0.571875
|
ShinyGreenRobot
|
34409e545ddc67c337a3a2684c66f9182c837c27
| 3,803
|
cpp
|
C++
|
src/socket.cpp
|
unitedtimur/POP3Client
|
d1aacb67dd31f0042a3f7a1c7ef71a276c6db262
|
[
"MIT"
] | 1
|
2021-10-17T12:46:05.000Z
|
2021-10-17T12:46:05.000Z
|
src/socket.cpp
|
unitedtimur/POP3Client
|
d1aacb67dd31f0042a3f7a1c7ef71a276c6db262
|
[
"MIT"
] | null | null | null |
src/socket.cpp
|
unitedtimur/POP3Client
|
d1aacb67dd31f0042a3f7a1c7ef71a276c6db262
|
[
"MIT"
] | null | null | null |
#include "../include/socket.h"
#include "../include/configuration.h"
#include "../include/functionality.h"
#include "WS2tcpip.h"
Socket::Socket(const std::wstring& host, const std::wstring& port) :
host(host),
port(port),
clientSocket(-1),
addr(nullptr)
{
}
Socket::~Socket()
{
// Закрываем сокет
closesocket(this->clientSocket);
// Очищаем информацию и WSACleanup
freeaddrinfo(addr);
WSACleanup();
}
bool Socket::start()
{
// Инициализация WSADATA
WSADATA wsaData;
WORD version = MAKEWORD(2, 2);
// Производим инициализацию
if (WSAStartup(version, &wsaData) != 0)
{
Functionality::notify(configuration::error::WSASTARTUP);
return false;
}
addrinfo hints;
// Производим инициализацию подключения
ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
hints.ai_flags = AI_PASSIVE;
// Производим инициализацию по полученному хосту и порту
if (getaddrinfo(Functionality::ws2s(host).c_str(), Functionality::ws2s(port).c_str(), &hints, &addr) != 0)
{
Functionality::notify(configuration::error::GETADDRINFO);
return false;
}
// Создаём сокет по полученным данным
if ((this->clientSocket = socket(addr->ai_family, addr->ai_socktype, addr->ai_protocol)) == INVALID_SOCKET)
{
Functionality::notify(configuration::error::SOCKET);
return false;
}
// Данная функция преобразует строку символов addr->ai_addr->sa_data в структуру сетевого адреса сетевого семейства адресов
if (inet_pton(addr->ai_family, addr->ai_addr->sa_data, (PVOID)(addr->ai_addrlen)) == SOCKET_ERROR)
{
Functionality::notify(configuration::error::HOST);
return false;
}
// Производим подключение к сокету сервера
if (connect(this->clientSocket, addr->ai_addr, int(addr->ai_addrlen)) == SOCKET_ERROR)
{
Functionality::notify(configuration::error::CONNECT);
return false;
}
return true;
}
std::wstring Socket::get_port() const
{
// Возвращаем port
return port;
}
std::wstring Socket::get_host() const
{
// Возвращаем hostname
return host;
}
bool Socket::isReadyRead()
{
fd_set recieveFd;
struct timeval timeout;
int selectReturnValue;
// Инициализируем нулём ответ сокета сервера
FD_ZERO(&recieveFd);
// Выставляем значение для ответа
FD_SET(this->clientSocket, &recieveFd);
// Устанавливаем таймаут ответа сервера в виде 10 секунд
timeout.tv_sec = 10;
timeout.tv_usec = 0;
// Получаем общее количество дескрипторов сокетов
selectReturnValue = select(this->clientSocket, &recieveFd, 0, 0, &timeout);
// Если всё ок
if (selectReturnValue > 0)
{
return true;
}
return false;
}
bool Socket::sendAll(const std::wstring& message)
{
// Преобразуем в std::string
std::string msg = Functionality::ws2s(message);
msg += '\r\n';
char* ptr = (char*)(msg.c_str());
int length = static_cast<int>(msg.length());
// Отправляем всё до последнего байта
while (length > 0)
{
int i = send(this->clientSocket, ptr, length, 0);
if (i == SOCKET_ERROR)
return false;
ptr += i;
length -= i;
}
return true;
}
bool Socket::recvAll(std::wstring& message)
{
const int max_buffer_size = configuration::default::BUFFER_SIZE;
char buffer[max_buffer_size];
int size_recv;
// Получаем все отправленные нам байты
while (true)
{
memset(buffer, 0, max_buffer_size);
if ((size_recv = recv(this->clientSocket, buffer, max_buffer_size, 0) == SOCKET_ERROR))
{
return false;
}
else
{
if (Functionality::ws2s(message)[message.size()] == '\0')
{
message += Functionality::s2ws(std::string(buffer));
return true;
}
}
}
return true;
}
void Socket::operator<<(const std::wstring& message)
{
// Отправляем сообщение
this->sendAll(message);
}
void Socket::operator>>(std::wstring& message)
{
// Получаем ответ
this->recvAll(message);
}
| 21.01105
| 124
| 0.707073
|
unitedtimur
|
3440c72dfd3fbd205073743ce429e0b03a8b2785
| 7,699
|
hpp
|
C++
|
src/elona/config/config.hpp
|
Vorlent/ElonaFoobar
|
8e544af1f82377c9add6961589ddc99e22c5ed4c
|
[
"MIT"
] | null | null | null |
src/elona/config/config.hpp
|
Vorlent/ElonaFoobar
|
8e544af1f82377c9add6961589ddc99e22c5ed4c
|
[
"MIT"
] | null | null | null |
src/elona/config/config.hpp
|
Vorlent/ElonaFoobar
|
8e544af1f82377c9add6961589ddc99e22c5ed4c
|
[
"MIT"
] | null | null | null |
#pragma once
#include <iostream>
#include <string>
#include <unordered_set>
#include "../../snail/window.hpp"
#include "../../thirdparty/ordered_map/ordered_map.h"
#include "../../util/noncopyable.hpp"
#include "../elona.hpp"
#include "../filesystem.hpp"
#include "../log.hpp"
#include "config_def.hpp"
namespace elona
{
class ConfigDef;
class Config
{
public:
static Config& instance();
Config()
{
}
~Config() = default;
void load_def(std::istream& is, const std::string& mod_id);
void load_def(const fs::path& config_def_path, const std::string& mod_id);
void load(std::istream&, const std::string&, bool);
void save();
void clear()
{
def.clear();
storage_.clear();
getters_.clear();
setters_.clear();
}
// If your are vimmer, ex command ":sort /\w\+;/ r" can sort the list well.
int alert_wait;
bool allow_enhanced_skill;
bool always_center;
int animation_wait;
bool attack_animation;
bool attack_neutral_npcs;
int attack_wait;
std::string auto_turn_speed;
bool autodisable_numlock;
bool autopick;
bool autosave;
bool damage_popup;
std::string display_mode;
int enhanced_skill_lowerbound;
int enhanced_skill_upperbound;
bool extra_class;
bool extra_help;
bool extra_race;
std::string font_filename;
std::string fullscreen;
int general_wait;
bool heartbeat;
bool hide_autoidentify;
bool hide_shop_updates;
bool high_quality_shadow;
std::string hp_bar_position;
int initial_key_repeat_wait;
bool joypad;
int key_repeat_wait;
int key_wait;
std::string language;
bool leash_icon;
int max_damage_popup;
bool message_add_timestamps;
int message_transparency;
bool music;
bool net;
bool object_shadow;
std::string pcc_graphic_scale;
int restock_interval;
int run_wait;
int screen_refresh_wait;
bool scroll;
bool scroll_when_run;
int select_fast_start_wait;
int select_fast_wait;
int select_wait;
bool skip_confirm_at_shop;
bool skip_overcasting_warning;
bool skip_random_event_popups;
bool sound;
int start_run_wait;
std::string startup_script;
bool story;
bool title_effect;
int walk_wait;
bool weather_effect;
bool window_animation;
bool wizard;
bool is_test = false; // testing use only
const std::unordered_set<std::string>& get_mod_ids()
{
return mod_ids_;
}
bool is_visible(const std::string& key) const
{
return def.get_metadata(key).is_visible();
}
void bind_getter(
const std::string& key,
std::function<hcl::Value(void)> getter)
{
if (!def.exists(key))
{
throw std::runtime_error("No such config value " + key);
}
getters_[key] = getter;
}
template <typename T>
void bind_setter(
const std::string& key,
std::function<void(const T&)> setter)
{
if (!def.exists(key))
{
throw std::runtime_error("No such config value " + key);
}
setters_[key] = [setter](const hcl::Value& value) {
setter(value.as<T>());
};
}
void inject_enum(
const std::string& key,
std::vector<std::string> variants,
std::string default_variant)
{
def.inject_enum(key, variants, default_variant);
auto EnumDef = def.get<spec::EnumDef>(key);
if (storage_.find(key) != storage_.end())
{
// Check if this enum has an invalid value. If so, set it to the
// default.
std::string current = get<std::string>(key);
if (!EnumDef.get_index_of(current))
{
ELONA_WARN("config")
<< "Config key "s << key << " had invalid variant "s
<< current << ". "s
<< "("s << def.type_to_string(key) << ")"s
<< "Setting to "s << EnumDef.get_default() << "."s;
set(key, EnumDef.get_default());
}
}
else
{
set(key,
EnumDef.get_default()); // Set the enum to its default value.
}
}
template <typename T>
T get(const std::string& key) const
{
if (storage_.find(key) == storage_.end())
{
// TODO fallback to default specified in config definition instead
throw std::runtime_error("No such config value " + key);
}
if (!storage_.at(key).is<T>())
{
throw std::runtime_error(
"Expected type \"" + def.type_to_string(key) + "\" for key " +
key);
}
try
{
if (getters_.find(key) != getters_.end())
{
return getters_.at(key)().as<T>();
}
else
{
return storage_.at(key).as<T>();
}
}
catch (std::exception& e)
{
throw std::runtime_error(
"Error on getting config value " + key + ": " + e.what());
}
}
void set(const std::string& key, const hcl::Value value)
{
ELONA_LOG("config") << "Set: " << key << " to " << value;
if (!def.exists(key))
{
throw std::runtime_error("No such config key " + key);
}
if (verify_types(value, key))
{
if (value.is<int>())
{
int temp = value.as<int>();
temp = clamp(temp, def.get_min(key), def.get_max(key));
storage_[key] = temp;
}
else
{
storage_[key] = std::move(value);
}
if (setters_.find(key) != setters_.end())
{
setters_[key](storage_.at(key));
}
}
else
{
std::stringstream ss;
ss << "Wrong config item type for key " << key << ": ";
ss << def.type_to_string(key) << " expected, got ";
ss << value;
throw std::runtime_error(ss.str());
}
}
void run_setter(const std::string& key)
{
if (storage_.find(key) == storage_.end())
{
return;
}
if (setters_.find(key) != setters_.end())
{
setters_[key](storage_.at(key));
}
}
const ConfigDef& get_def() const
{
return def;
}
private:
void load_defaults(bool);
void visit(const hcl::Value&, const std::string&, const std::string&, bool);
void visit_object(
const hcl::Object&,
const std::string&,
const std::string&,
bool);
bool verify_types(const hcl::Value&, const std::string&);
ConfigDef def;
tsl::ordered_map<std::string, hcl::Value> storage_;
tsl::ordered_map<std::string, std::function<hcl::Value(void)>> getters_;
tsl::ordered_map<std::string, std::function<void(const hcl::Value&)>>
setters_;
std::unordered_set<std::string> mod_ids_;
};
/***
* Loads config options that are marked to be loaded before the application
* instance is initialized, like screen size. The config file is loaded from the
* current profile.
*/
void initialize_config_preload();
void load_config();
void set_config(const std::string& key, int value);
void set_config(const std::string& key, const std::string& value);
void set_config(const std::string& key, const std::string& value1, int value2);
snail::Window::FullscreenMode config_get_fullscreen_mode();
} // namespace elona
| 26.010135
| 80
| 0.560462
|
Vorlent
|
3442ce0c70f7feca295b033a0bd04a1bce324835
| 2,190
|
hpp
|
C++
|
include/DAL/instruction.hpp
|
NzZs79/DevAutomator
|
81e7b41945452ce8dad6f48fd8b3d958b6ebbef7
|
[
"MIT"
] | null | null | null |
include/DAL/instruction.hpp
|
NzZs79/DevAutomator
|
81e7b41945452ce8dad6f48fd8b3d958b6ebbef7
|
[
"MIT"
] | null | null | null |
include/DAL/instruction.hpp
|
NzZs79/DevAutomator
|
81e7b41945452ce8dad6f48fd8b3d958b6ebbef7
|
[
"MIT"
] | null | null | null |
#include "general.hpp"
#include <vector>
#include <iterator>
#include <memory>
#include "DAL/environment.hpp"
#include <string>
#ifndef INSTRUCTION_H
#define INSTRUCTION_H
typedef enum {
JMP_INST = 0,
JMP_TRUE_INST,
JMP_FALSE_INST,
DEF_INST,
EQUAL_INST,
OPER_INST,
VAR_INST,
LITERAL_INST,
TRUE_INST,
FALSE_INST,
} InstCode;
class Instruction {
public:
Instruction() = default;
Instruction(InstCode iCode_) : iCode(iCode_) {}
virtual ~Instruction() {};
int code() const {
return iCode;
}
virtual void eval(DAL_Environment &){};
protected:
// Instruction Code it's identifer of
// Instructions.
InstCode iCode;
};
using InstPtr = std::shared_ptr<Instruction>;
class InstructionSet {
public:
auto begin() {
return insts.begin();
}
auto end() {
return insts.end();
}
void append(InstPtr inst) {
insts.push_back(inst);
}
size_t size() {
return insts.size();
}
void eval(DAL_Environment &env);
private:
std::vector<InstPtr> insts;
};
class CONDInst : public Instruction {
public:
CONDInst(InstCode iCode_) : Instruction(iCode_) {}
};
class OPERInst: public Instruction {
public:
OPERInst(InstCode iCode_) : Instruction(iCode_) {}
};
class VARInst: public Instruction {
public:
VARInst(InstCode iCode_) : Instruction(iCode_) {}
};
class TERM: public Instruction {
public:
TERM(InstCode iCode_) : Instruction(iCode_) {}
};
class VAR : public TERM {
public:
VAR(std::string ident_) : TERM(VAR_INST), ident(ident_) {}
~VAR() {}
void eval(DAL_Environment &env);
private:
std::string ident;
};
class Literal : public TERM {
public:
Literal(std::string value_) :
TERM(LITERAL_INST), value(value_) {}
~Literal() {}
void eval(DAL_Environment &env);
private:
std::string value;
};
class TRUE_ : public TERM {
public:
TRUE_() : TERM(TRUE_INST) {}
~TRUE_() {}
void eval(DAL_Environment &env);
};
class FALSE_ : public TERM {
public:
FALSE_() : TERM(FALSE_INST) {}
~FALSE_() {}
void eval(DAL_Environment &env);
};
#endif /* INSTRUCTION_H */
| 16.846154
| 62
| 0.6379
|
NzZs79
|
344829ca2f450746fc90478eb07930f0b1dd47e2
| 4,444
|
cpp
|
C++
|
Real-Time Corruptor/BizHawk_RTC/waterbox/libsnes/bsnes/snes/chip/armdsp/armdsp.cpp
|
redscientistlabs/Bizhawk50X-Vanguard
|
96e0f5f87671a1230784c8faf935fe70baadfe48
|
[
"MIT"
] | 1,414
|
2015-06-28T09:57:51.000Z
|
2021-10-14T03:51:10.000Z
|
Real-Time Corruptor/BizHawk_RTC/waterbox/libsnes/bsnes/snes/chip/armdsp/armdsp.cpp
|
redscientistlabs/Bizhawk50X-Vanguard
|
96e0f5f87671a1230784c8faf935fe70baadfe48
|
[
"MIT"
] | 2,369
|
2015-06-25T01:45:44.000Z
|
2021-10-16T08:44:18.000Z
|
Real-Time Corruptor/BizHawk_RTC/waterbox/libsnes/bsnes/snes/chip/armdsp/armdsp.cpp
|
redscientistlabs/Bizhawk50X-Vanguard
|
96e0f5f87671a1230784c8faf935fe70baadfe48
|
[
"MIT"
] | 430
|
2015-06-29T04:28:58.000Z
|
2021-10-05T18:24:17.000Z
|
#include <snes/snes.hpp>
#define ARMDSP_CPP
namespace SNES {
//zero 01-sep-2014 - dont clobber these when reconstructing!
uint8 *ArmDSP::firmware;
uint8 *ArmDSP::programROM;
uint8 *ArmDSP::dataROM;
static bool trace = 0;
#include "opcodes.cpp"
#include "memory.cpp"
#include "disassembler.cpp"
ArmDSP armdsp;
void ArmDSP::Enter() { armdsp.enter(); }
void ArmDSP::enter() {
//reset hold delay
while(bridge.reset) {
tick();
continue;
}
//reset sequence delay
if(bridge.ready == false) {
tick(65536);
bridge.ready = true;
}
while(true) {
if(scheduler.sync == Scheduler::SynchronizeMode::All) {
scheduler.exit(Scheduler::ExitReason::SynchronizeEvent);
}
if(exception) {
print("* ARM unknown instruction\n");
print("\n", disassemble_registers());
print("\n", disassemble_opcode(pipeline.instruction.address), "\n");
while(true) tick(frequency);
}
if(pipeline.reload) {
pipeline.reload = false;
pipeline.prefetch.address = r[15];
pipeline.prefetch.opcode = bus_readword(r[15]);
r[15].step();
}
pipeline.instruction = pipeline.prefetch;
pipeline.prefetch.address = r[15];
pipeline.prefetch.opcode = bus_readword(r[15]);
r[15].step();
//todo: bus_readword() calls tick(); so we need to prefetch this as well
//pipeline.mdr.address = r[15];
//pipeline.mdr.opcode = bus_readword(r[15]);
//if(pipeline.instruction.address == 0x00000208) trace = 1;
if(trace) {
print("\n", disassemble_registers(), "\n");
print(disassemble_opcode(pipeline.instruction.address), "\n");
usleep(200000);
}
//trace = 0;
instruction = pipeline.instruction.opcode;
if(!condition()) continue;
if((instruction & 0x0fc000f0) == 0x00000090) { op_multiply(); continue; }
if((instruction & 0x0fb000f0) == 0x01000000) { op_move_to_register_from_status_register(); continue; }
if((instruction & 0x0fb000f0) == 0x01200000) { op_move_to_status_register_from_register(); continue; }
if((instruction & 0x0e000010) == 0x00000000) { op_data_immediate_shift(); continue; }
if((instruction & 0x0e000090) == 0x00000010) { op_data_register_shift(); continue; }
if((instruction & 0x0e000000) == 0x02000000) { op_data_immediate(); continue; }
if((instruction & 0x0e000000) == 0x04000000) { op_move_immediate_offset(); continue; }
if((instruction & 0x0e000010) == 0x06000000) { op_move_register_offset(); continue; }
if((instruction & 0x0e000000) == 0x08000000) { op_move_multiple(); continue; }
if((instruction & 0x0e000000) == 0x0a000000) { op_branch(); continue; }
exception = true;
}
}
void ArmDSP::tick(unsigned clocks) {
if(bridge.timer && --bridge.timer == 0) bridge.busy = false;
step(clocks);
synchronize_cpu();
}
//MMIO: $00-3f|80-bf:3800-38ff
//3800-3807 mirrored throughout
//a0 ignored
uint8 ArmDSP::mmio_read(unsigned addr) {
cpu.synchronize_coprocessors();
uint8 data = 0x00;
addr &= 0xff06;
if(addr == 0x3800) {
if(bridge.armtocpu.ready) {
bridge.armtocpu.ready = false;
data = bridge.armtocpu.data;
}
}
if(addr == 0x3802) {
bridge.timer = 0;
bridge.busy = false;
}
if(addr == 0x3804) {
data = bridge.status();
}
return data;
}
void ArmDSP::mmio_write(unsigned addr, uint8 data) {
cpu.synchronize_coprocessors();
addr &= 0xff06;
if(addr == 0x3802) {
bridge.cputoarm.ready = true;
bridge.cputoarm.data = data;
}
if(addr == 0x3804) {
data &= 1;
if(!bridge.reset && data) arm_reset();
bridge.reset = data;
}
}
void ArmDSP::init() {
}
void ArmDSP::load() {
}
void ArmDSP::unload() {
}
void ArmDSP::power() {
for(unsigned n = 0; n < 16 * 1024; n++) programRAM[n] = random(0x00);
}
void ArmDSP::reset() {
bridge.reset = false;
arm_reset();
}
void ArmDSP::arm_reset() {
create(ArmDSP::Enter, 21477272, 8192);
bridge.ready = false;
bridge.timer = 0;
bridge.timerlatch = 0;
bridge.busy = false;
bridge.cputoarm.ready = false;
bridge.armtocpu.ready = false;
for(auto &rd : r) rd = 0;
shiftercarry = 0;
exception = 0;
pipeline.reload = true;
r[15].write = [&] { pipeline.reload = true; };
}
ArmDSP::ArmDSP() {
firmware = new uint8[160 * 1024]();
programRAM = new uint8[16 * 1024]();
programROM = &firmware[0];
dataROM = &firmware[128 * 1024];
}
ArmDSP::~ArmDSP() {
delete[] firmware;
delete[] programRAM;
}
}
| 23.638298
| 106
| 0.64784
|
redscientistlabs
|
451a992b1a7e398756373bd0ff13111d3c428557
| 3,530
|
cpp
|
C++
|
source/material/Dielectric.cpp
|
xzrunner/raytracing
|
c130691a92fab2cc9605f04534f42ca9b99e6fde
|
[
"MIT"
] | null | null | null |
source/material/Dielectric.cpp
|
xzrunner/raytracing
|
c130691a92fab2cc9605f04534f42ca9b99e6fde
|
[
"MIT"
] | null | null | null |
source/material/Dielectric.cpp
|
xzrunner/raytracing
|
c130691a92fab2cc9605f04534f42ca9b99e6fde
|
[
"MIT"
] | null | null | null |
#include "raytracing/material/Dielectric.h"
#include "raytracing/bxdf/FresnelReflector.h"
#include "raytracing/bxdf/FresnelTransmitter.h"
#include "raytracing/bxdf/Lambertian.h"
#include "raytracing/bxdf/GlossySpecular.h"
#include "raytracing/world/World.h"
#include "raytracing/tracer/Tracer.h"
#include "raytracing/light/Light.h"
#include "raytracing/utilities/ShadeRec.h"
namespace rt
{
Dielectric::Dielectric()
{
fresnel_brdf = std::make_unique<FresnelReflector>();
fresnel_btdf = std::make_unique<FresnelTransmitter>();
}
RGBColor Dielectric::Shade(const ShadeRec& sr) const
{
RGBColor L(Phong::Shade(sr));
Vector3D wi;
Vector3D wo(-sr.ray.dir);
RGBColor fr = fresnel_brdf->sample_f(sr, wo, wi); // computes wi
Ray reflected_ray(sr.hit_point, wi);
double t;
RGBColor Lr, Lt;
float ndotwi = static_cast<float>(sr.normal * wi);
//const double S = 0.0001;
const double S = 1;
// total internal reflection
if (fresnel_btdf->Tir(sr))
{
if (ndotwi < 0.0) {
// reflected ray is inside
Lr = sr.w.GetTracer()->TraceRay(reflected_ray, t, sr.depth + 1);
L += cf_in.Powc(static_cast<float>(t * S)) * Lr; // inside filter color
}
else {
// reflected ray is outside
Lr = sr.w.GetTracer()->TraceRay(reflected_ray, t, sr.depth + 1); // kr = 1
L += cf_out.Powc(static_cast<float>(t * S)) * Lr; // outside filter color
}
}
else { // no total internal reflection
Vector3D wt;
RGBColor ft = fresnel_btdf->sample_f(sr, wo, wt); // computes wt
Ray transmitted_ray(sr.hit_point, wt);
float ndotwt = static_cast<float>(sr.normal * wt);
if (ndotwi < 0.0) {
// reflected ray is inside
Lr = fr * sr.w.GetTracer()->TraceRay(reflected_ray, t, sr.depth + 1) * fabs(ndotwi);
L += cf_in.Powc(static_cast<float>(t * S)) * Lr; // inside filter color
// transmitted ray is outside
Lt = ft * sr.w.GetTracer()->TraceRay(transmitted_ray, t, sr.depth + 1) * fabs(ndotwt);
L += cf_out.Powc(static_cast<float>(t * S)) * Lt; // outside filter color
}
else {
// reflected ray is outside
Lr = fr * sr.w.GetTracer()->TraceRay(reflected_ray, t, sr.depth + 1) * fabs(ndotwi);
L += cf_out.Powc(static_cast<float>(t * S)) * Lr; // outside filter color
// transmitted ray is inside
Lt = ft * sr.w.GetTracer()->TraceRay(transmitted_ray, t, sr.depth + 1) * fabs(ndotwt);
L += cf_in.Powc(static_cast<float>(t * S)) * Lt; // inside filter color
}
}
return (L);
}
RGBColor Dielectric::AreaLightShade(const ShadeRec& sr) const
{
Vector3D wo = -sr.ray.dir;
RGBColor L = m_ambient_brdf->rho(sr, wo) * sr.w.GetAmbient()->L(sr);
int num_lights = sr.w.GetLights().size();
for (int j = 0; j < num_lights; j++) {
Vector3D wi = sr.w.GetLights()[j]->GetDirection(sr);
float ndotwi = static_cast<float>(sr.normal * wi);
if (ndotwi > 0.0) {
bool in_shadow = false;
if (sr.w.GetLights()[j]->CastsShadows()) {
Ray shadowRay(sr.hit_point, wi);
in_shadow = sr.w.GetLights()[j]->InShadow(shadowRay, sr);
}
if (!in_shadow)
L += ( m_diffuse_brdf->f(sr, wo, wi)
+ m_specular_brdf->f(sr, wo, wi)) * sr.w.GetLights()[j]->L(sr) * ndotwi * sr.w.GetLights()[j]->G(sr) / sr.w.GetLights()[j]->Pdf(sr);
}
}
return (L);
}
void Dielectric::SetEtaIn(float in)
{
fresnel_brdf->SetEtaIn(in);
fresnel_btdf->SetEtaIn(in);
}
void Dielectric::SetEtaOut(float out)
{
fresnel_brdf->SetEtaOut(out);
fresnel_btdf->SetEtaOut(out);
}
}
| 28.934426
| 140
| 0.64221
|
xzrunner
|
451bae514611aa2a7281c9cd903890a56cddaa97
| 1,280
|
cpp
|
C++
|
progress/mountains.cpp
|
birdhumming/usaco
|
f011e7bd4b71de22736a61004e501af2b273b246
|
[
"OLDAP-2.2.1"
] | null | null | null |
progress/mountains.cpp
|
birdhumming/usaco
|
f011e7bd4b71de22736a61004e501af2b273b246
|
[
"OLDAP-2.2.1"
] | null | null | null |
progress/mountains.cpp
|
birdhumming/usaco
|
f011e7bd4b71de22736a61004e501af2b273b246
|
[
"OLDAP-2.2.1"
] | null | null | null |
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
vector<pair<int, int> > peaks;
bool is_in(int x1, int y1, int x2, int y2) { //is the peak (x1, y1) within the mountain (x2, y2)
if (x1==-1 || x2==-1) return false;
if (x2-y2 >= x1-y1 && x2+y2 >= x1+y1) return true;
return false;
}
int main() {
ifstream fin ("mountains.in");
ofstream fout ("mountains.out");
int N, x, y; fin>>N;
int count=0, ans=0;
for (int i=0; i<N; i++) {
//cout<<"i = "<<i<<'\n';
fin>>x>>y;
for (int j=0; j<peaks.size(); j++) {
if (is_in(x, y, peaks[j].first, peaks[j].second)) { //(x, y) is inside/on peaks[j].first;
count=-1;
break;
}
else if (is_in(peaks[j].first, peaks[j].second, x, y)) { //current peaks is in (x, y)
peaks[j].first=-1;
count++;
}
//cout<<"j = "<<j<<", count = "<<count<<'\n';
}
if (count!=-1) {
pair<int, int> temp;
temp.first=x, temp.second=y;
peaks.push_back(temp);
}
if (count==0) ans++;
if (count>0) {
ans-=count;
ans++;
}
count=0;
}
fout<<ans;
}
| 26.666667
| 101
| 0.450781
|
birdhumming
|
45281c21fe8ac4584f35fdb69d7bec6b5e72f1a2
| 1,599
|
hpp
|
C++
|
platforms/linux/src/Application/Packets/Commands/Read/Peripheral/ReadRequest.hpp
|
iotile/baBLE-linux
|
faedca2c70b7fe91ea8ae0c3d8aff6bf843bd9db
|
[
"MIT"
] | 13
|
2018-07-04T16:35:37.000Z
|
2021-03-03T10:41:07.000Z
|
platforms/linux/src/Application/Packets/Commands/Read/Peripheral/ReadRequest.hpp
|
iotile/baBLE
|
faedca2c70b7fe91ea8ae0c3d8aff6bf843bd9db
|
[
"MIT"
] | 11
|
2018-06-01T20:32:32.000Z
|
2019-01-21T17:03:47.000Z
|
platforms/linux/src/Application/Packets/Commands/Read/Peripheral/ReadRequest.hpp
|
iotile/baBLE-linux
|
faedca2c70b7fe91ea8ae0c3d8aff6bf843bd9db
|
[
"MIT"
] | null | null | null |
#ifndef BABLE_PERIPHERAL_READREQUEST_HPP
#define BABLE_PERIPHERAL_READREQUEST_HPP
#include "Application/Packets/Base/ControllerToHostPacket.hpp"
namespace Packet {
namespace Commands {
namespace Peripheral {
class ReadRequest : public ControllerToHostPacket {
public:
static const Packet::Type initial_type() {
return Packet::Type::HCI;
};
static const uint16_t initial_packet_code() {
return Format::HCI::AttributeCode::ReadRequest;
};
static const uint16_t final_packet_code() {
return static_cast<uint16_t>(BaBLE::Payload::ReadPeripheral);
};
explicit ReadRequest(uint16_t attribute_handle = 0);
void unserialize(HCIFormatExtractor& extractor) override;
std::vector<uint8_t> serialize(HCIFormatBuilder& builder) const override;
std::vector<uint8_t> serialize(FlatbuffersFormatBuilder& builder) const override;
void prepare(const std::shared_ptr<PacketRouter>& router) override;
void set_socket(AbstractSocket* socket) override;
const std::string stringify() const override;
private:
enum ReadType {
None,
Service,
Characteristic,
CharacteristicValue,
CharacteristicConfiguration
};
uint16_t m_attribute_handle;
ReadType m_type;
Format::HCI::Service m_service;
Format::HCI::Characteristic m_characteristic;
Format::HCI::AttributeErrorCode m_error;
};
}
}
}
#endif //BABLE_PERIPHERAL_READREQUEST_HPP
| 24.6
| 89
| 0.668543
|
iotile
|
4534790320eba5e4c94fa12b4ecac6b8cdac97e4
| 1,002
|
hpp
|
C++
|
src/Board.hpp
|
syanush/rhotetris
|
4f85da828e966a2679e8160c5f810cde6b19419c
|
[
"MIT"
] | null | null | null |
src/Board.hpp
|
syanush/rhotetris
|
4f85da828e966a2679e8160c5f810cde6b19419c
|
[
"MIT"
] | null | null | null |
src/Board.hpp
|
syanush/rhotetris
|
4f85da828e966a2679e8160c5f810cde6b19419c
|
[
"MIT"
] | null | null | null |
#pragma once
#include <array>
#include "GameOverEvent.hpp"
#include "Piece.hpp"
namespace RhoTetris {
enum class Colors { Default, Magenta };
class Board : public GameOverEvent {
public:
static const int kBoardWidth = 10;
static const int kBoardHeight = 22;
void clear();
void update();
void makeNewPiece();
void movePieceLeft();
void movePieceRight();
void rotatePiece();
void hardDrop();
Colors getCell(int col, int row) const { return m_gameBoard[row][col]; }
int getRow() const { return m_row; }
int getCol() const { return m_col; }
const Piece& getPiece() const { return *m_piece; }
private:
std::array<std::array<Colors, kBoardWidth>, kBoardHeight> m_gameBoard;
const Piece* m_piece;
// piece position on the board
int m_row;
int m_col;
bool collidesAt(int col, int row);
void lockPiece();
bool isCompleteLine(int row) const;
void clearCompleteLine(int aRow);
void clearCompleteLines();
void touchDown();
};
} // namespace RhoTetris
| 20.875
| 74
| 0.699601
|
syanush
|
4534f00e10e2659637c3dea74e5dea14b8bab46b
| 7,336
|
cpp
|
C++
|
vendor/mysql-connector-c++-1.1.3/test/framework/test_timer.cpp
|
caiqingfeng/libmrock
|
bb7c94482a105e92b6d3e8640b13f9ff3ae49a83
|
[
"Apache-2.0"
] | 1
|
2015-12-01T04:16:54.000Z
|
2015-12-01T04:16:54.000Z
|
vendor/mysql-connector-c++-1.1.3/test/framework/test_timer.cpp
|
caiqingfeng/libmrock
|
bb7c94482a105e92b6d3e8640b13f9ff3ae49a83
|
[
"Apache-2.0"
] | null | null | null |
vendor/mysql-connector-c++-1.1.3/test/framework/test_timer.cpp
|
caiqingfeng/libmrock
|
bb7c94482a105e92b6d3e8640b13f9ff3ae49a83
|
[
"Apache-2.0"
] | null | null | null |
/*
Copyright (c) 2009, 2011, Oracle and/or its affiliates. All rights reserved.
The MySQL Connector/C++ is licensed under the terms of the GPLv2
<http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most
MySQL Connectors. There are special exceptions to the terms and
conditions of the GPLv2 as it is applied to this software, see the
FLOSS License Exception
<http://www.mysql.com/about/legal/licensing/foss-exception.html>.
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; version 2 of the License.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "test_timer.h"
namespace testsuite
{
Timer::Timer()
{
}
clock_t Timer::startTest(const String & test)
{
std::map<String, test_timer>::const_iterator cit=theInstance().timeRecorder.find(test);
if (cit == theInstance().timeRecorder.end())
{
theInstance().currentTest=test;
test_timer t=test_timer();
theInstance().timeRecorder[test]=t;
return theInstance().timeRecorder[test].cpu;
}
return static_cast<clock_t> (-1);
}
clock_t Timer::stopTest(const String & test)
{
std::map<String, test_timer>::const_iterator cit=theInstance().timeRecorder.find(test);
if (cit != theInstance().timeRecorder.end())
{
clock_t now=clock();
theInstance().timeRecorder[test].cpu=now - theInstance().timeRecorder[test].cpu;
return theInstance().timeRecorder[test].cpu;
}
return static_cast<clock_t> (-1);
}
clock_t Timer::startTimer(const String & name, const String & file, const unsigned int line)
{
// HACK
return startTimer(theInstance().currentTest, name, file, line);
}
clock_t Timer::startTimer(const String & test, const String & name, const String & file, const unsigned int line)
{
std::map<String, test_timer>::const_iterator cit=theInstance().timeRecorder.find(test);
if (cit == theInstance().timeRecorder.end())
// unknown test - must not happen
return static_cast<clock_t> (-1);
std::map<String, timer>::const_iterator it=theInstance().timeRecorder[test].timers.find(name);
clock_t now=clock();
if (it == theInstance().timeRecorder[test].timers.end())
{
timer t=timer(now, file, line);
theInstance().timeRecorder[test].timers[name]=t;
}
else
{
/* TODO: API semantics are somewhat unclear - not sure what is best */
theInstance().timeRecorder[test].timers[name].start=now;
theInstance().timeRecorder[name].timers[name].stopped=false;
}
return theInstance().timeRecorder[name].timers[name].start;
}
clock_t Timer::stopTimer(const String & name)
{
// hack
return stopTimer(theInstance().currentTest, name);
}
clock_t Timer::stopTimer(const String & test, const String & name)
{
std::map<String, test_timer>::const_iterator cit=theInstance().timeRecorder.find(test);
if (cit == theInstance().timeRecorder.end())
// unknown test - must not happen
return static_cast<clock_t> (-1);
std::map<String, timer>::const_iterator it=theInstance().timeRecorder[test].timers.find(name);
if (it == theInstance().timeRecorder[test].timers.end())
// unknown timer
return static_cast<clock_t> (-1);
if (theInstance().timeRecorder[test].timers[name].stopped)
// has been stopped before
return static_cast<clock_t> (-1);
clock_t runtime=clock() - theInstance().timeRecorder[test].timers[name].start;
theInstance().timeRecorder[test].timers[name].stopped=true;
theInstance().timeRecorder[test].timers[name].total_cpu+=runtime;
theInstance().timeRecorder[test].timers[name].start=static_cast<clock_t> (0);
return runtime;
}
clock_t Timer::getTime(const String &name)
{
return getTime(theInstance().currentTest, name);
}
clock_t Timer::getTime(const String & test, const String & name)
{
std::map<String, test_timer>::const_iterator cit=theInstance().timeRecorder.find(test);
if (cit == theInstance().timeRecorder.end())
// unknown test - must not happen
return static_cast<clock_t> (-1);
std::map<String, timer>::const_iterator it=theInstance().timeRecorder[test].timers.find(name);
if (it == theInstance().timeRecorder[test].timers.end())
// unknown timer
return static_cast<clock_t> (-1);
return theInstance().timeRecorder[test].timers[name].total_cpu;
}
float Timer::getSeconds(const String & name)
{
return translate2seconds(getTime(name));
}
float Timer::translate2seconds(clock_t inWallClocks)
{
#ifdef CLOCKS_PER_SEC
/* it looks like CLOCKS_PER_SEC should be defined on all platforms... just to feel safe.
Maybe use sysconf(_SC_CLK_TCK) */
return static_cast<float> (inWallClocks) / CLOCKS_PER_SEC;
#else
return static_cast<float> (inWallClocks);
#endif
}
unsigned int Timer::getLine(const String &name)
{
return getLine(theInstance().currentTest, name);
}
unsigned int Timer::getLine(const String & test, const String & name)
{
std::map<String, test_timer>::const_iterator cit=theInstance().timeRecorder.find(test);
if (cit == theInstance().timeRecorder.end())
// unknown test - must not happen
return 0;
std::map<String, timer>::const_iterator it=theInstance().timeRecorder[test].timers.find(name);
if (it == theInstance().timeRecorder[test].timers.end())
// unknown timer
return 0;
return theInstance().timeRecorder[test].timers[name].line;
}
const String Timer::getFile(const String &name)
{
return getFile(theInstance().currentTest, name);
}
const String Timer::getFile(const String & test, const String & name)
{
std::map<String, test_timer>::const_iterator cit=theInstance().timeRecorder.find(test);
if (cit == theInstance().timeRecorder.end())
// unknown test - must not happen
return 0;
std::map<String, timer>::const_iterator it=theInstance().timeRecorder[test].timers.find(name);
if (it == theInstance().timeRecorder[test].timers.end())
// unknown timer
return 0;
return theInstance().timeRecorder[test].timers[name].file;
}
const List & Timer::getNames()
{
static List names;
std::map<String, test_timer>::const_iterator cit=theInstance().timeRecorder.find("perf_statement::anonymousSelect");
std::map<String, timer>::const_iterator it;
for (; cit != theInstance().timeRecorder.end(); ++cit)
{
for (it=theInstance().timeRecorder[cit->first].timers.begin(); it != theInstance().timeRecorder[cit->first].timers.end(); ++it)
{
names.push_back(it->first);
}
}
return names;
}
const List & Timer::getNames(const String & test)
{
static List names;
std::map<String, test_timer>::const_iterator cit=theInstance().timeRecorder.find(test);
if (cit == theInstance().timeRecorder.end())
{
return names;
}
std::map<String, timer>::const_iterator it;
for (it=theInstance().timeRecorder[cit->first].timers.begin(); it != theInstance().timeRecorder[cit->first].timers.end(); ++it)
{
names.push_back(it->first);
}
return names;
}
}
| 29.461847
| 131
| 0.717694
|
caiqingfeng
|
453a00edfc34b51d44704592d3f8bbd5c3e57a32
| 11,951
|
cpp
|
C++
|
Shader Labb 2/Instance.cpp
|
Cousken/3DEngine
|
dd8a58f1cc08f17b1286c136215913123f234eb4
|
[
"MIT"
] | 1
|
2015-04-11T14:41:38.000Z
|
2015-04-11T14:41:38.000Z
|
Shader Labb 2/Instance.cpp
|
Cousken/3DEngine
|
dd8a58f1cc08f17b1286c136215913123f234eb4
|
[
"MIT"
] | null | null | null |
Shader Labb 2/Instance.cpp
|
Cousken/3DEngine
|
dd8a58f1cc08f17b1286c136215913123f234eb4
|
[
"MIT"
] | null | null | null |
#include "Instance.h"
#include "Engine.h"
#include "Light.h"
#include "EffectTechnique.h"
Instance::~Instance(void)
{
}
bool Instance::Init( )
{
myOrientation = Matrix44f::Identity();
BuildHierachy(myHierarchy, &myModel);
myBoneInstances.Init( myModel.myBones.Count(), 1 );
if( myModel.GetAnimation() != NULL )
{
myAnimation = new BoneInstanceHierarchy( myModel.GetAnimation() );
for( int i = 0; i < myModel.myBones.Count(); i++ )
{
BoneInstance* temp = new BoneInstance;
temp->SetBone( &myModel.myBones[i] );
temp->SetBoneAnimationInstance( myAnimation->GetTransformationAnimations()[i] );
myBoneInstances.Add( temp );
}
}
return true;
}
Instance::Instance( Model& aModel )
: myModel(aModel)
{
myEffectFile = "";
ClearLights();
myAnimation = NULL;
}
void Instance::Render( Camera& aCamera, EffectTechniques::TechniqueType aTechinqueType )
{
UpdateLights();
CommonUtilities::StaticArray< Matrix44f, 255 > boneMatrices;
for( int i = 0; i < myBoneInstances.Count(); i++ )
{
boneMatrices[i] = myBoneInstances[i]->GetTransformed();
//boneMatrices[i] = Matrix44f::Identity();
}
myOrientation.SetPosition(myPosition);
RenderModel(&myModel, myOrientation, aTechinqueType, myHierarchy, boneMatrices);
}
void Instance::RenderUsingEffect(Camera& aCamera, EffectTechniques::TechniqueType aTechinqueType, Effect *anEffect)
{
myOrientation.SetPosition(myPosition);
RenderModelUsingEffect(&myModel, myOrientation, aTechinqueType, myHierarchy, anEffect);
}
void Instance::RenderFromLight( EffectTechniques::TechniqueType aTechinqueType )
{
CommonUtilities::StaticArray< Matrix44f, 255 > boneMatrices;
for( int i = 0; i < myBoneInstances.Count(); i++ )
{
boneMatrices[i] = myBoneInstances[i]->GetTransformed();
//boneMatrices[i] = Matrix44f::Identity();
}
myOrientation.SetPosition(myPosition);
RenderModel(&myModel, myOrientation, aTechinqueType, myHierarchy, boneMatrices);
}
void Instance::RenderToTarget( Camera& myCamera, EffectTechniques::TechniqueType aTechnique, RenderProcessTarget& aRenderTarget )
{
CommonUtilities::StaticArray< Matrix44f, 255 > boneMatrices;
for( int i = 0; i < myBoneInstances.Count(); i++ )
{
boneMatrices[i] = myBoneInstances[i]->GetTransformed();
}
myOrientation.SetPosition(myPosition);
RenderModelToTarget(&myModel, myOrientation, aTechnique, myHierarchy, boneMatrices, aRenderTarget);
}
void Instance::RenderModel( Model* aModel, const Matrix44f aParentSpace, EffectTechniques::TechniqueType aTechniqueType, TransformationNodeInstance& aHierarchy, CommonUtilities::StaticArray< Matrix44f, 255 >& aBoneMatrixArray )
{
aModel->Render(aParentSpace, aBoneMatrixArray, aTechniqueType);
for(int i=0;i<aModel->myChilds.Count();i++)
{
assert(aHierarchy.GetChilds()[i]->GetTransformationNode()!=NULL);
Matrix44f worldMatrix=aHierarchy.GetChilds()[i]->GetTransformation();
worldMatrix*=aParentSpace;
//myModel.Render(worldMatrix, aTechniqueType);
RenderModel(aModel->myChilds[i], worldMatrix, aTechniqueType, (*aHierarchy.GetChilds()[i]), aBoneMatrixArray );
}
}
void Instance::RenderModelUsingEffect( Model* aModel, const Matrix44f aParentSpace, EffectTechniques::TechniqueType aTechniqueType, TransformationNodeInstance& aHierarchy, Effect *anEffect )
{
aModel->RenderUsingEffect(aParentSpace, aTechniqueType, anEffect);
for(int i=0;i<aModel->myChilds.Count();i++)
{
assert(aHierarchy.GetChilds()[i]->GetTransformationNode()!=NULL);
Matrix44f worldMatrix=aHierarchy.GetChilds()[i]->GetTransformation();
worldMatrix*=aParentSpace;
//myModel.Render(worldMatrix, aTechniqueType);
RenderModelUsingEffect(aModel->myChilds[i], worldMatrix, aTechniqueType, (*aHierarchy.GetChilds()[i]), anEffect );
}
}
void Instance::RenderModelToTarget( Model* aModel, const Matrix44f aParentSpace, EffectTechniques::TechniqueType aTechniqueType, TransformationNodeInstance& aHierarchy, CommonUtilities::StaticArray< Matrix44f, 255 >& aBoneMatrixArray, RenderProcessTarget& aRenderTarget )
{
aModel->RenderToTarget(aParentSpace, aBoneMatrixArray, aRenderTarget, aTechniqueType);
for(int i=0;i<aModel->myChilds.Count();i++)
{
assert(aHierarchy.GetChilds()[i]->GetTransformationNode()!=NULL);
Matrix44f worldMatrix=aHierarchy.GetChilds()[i]->GetTransformation();
worldMatrix*=aParentSpace;
//myModel.Render(worldMatrix, aTechniqueType);
RenderModelToTarget(aModel->myChilds[i], worldMatrix, aTechniqueType, (*aHierarchy.GetChilds()[i]), aBoneMatrixArray, aRenderTarget );
}
}
void Instance::SetOrientation( Matrix44f& aOrientation )
{
myOrientation = aOrientation;
myPosition = myOrientation.GetPosition();
}
Matrix44f& Instance::GetOrientation()
{
myOrientation.SetPosition(myPosition);
return myOrientation;
}
void Instance::SetPosition( Vector3f& aPosition )
{
myPosition = aPosition;
}
void Instance::GetPosition( Vector3f& aPosition )
{
aPosition = myPosition;
}
void Instance::PerformRotation( Matrix33f& aOrientation )
{
myOrientation = myOrientation * aOrientation;
}
void Instance::PerformTransformation( Matrix44f& aOrientation )
{
myOrientation.SetPosition(myPosition);
myOrientation *= aOrientation;
myPosition = myOrientation.GetPosition();
}
Model& Instance::GetModel()
{
return myModel;
}
void Instance::TryAddLight( float aLightsStrength, Light* aLight )
{
if (aLight != 0 )
{
if (aLight->GetType() == Light::DIRECTIONAL_LIGHT_TYPE)
{
TryAddDirectionalLight(aLight, aLightsStrength);
}
else if (aLight->GetType() == Light::POINT_LIGHT_TYPE)
{
TryAddPointLight(aLight, aLightsStrength);
}
else if (aLight->GetType() == Light::SPOT_LIGHT_TYPE)
{
TryAddSpotLight(aLight, aLightsStrength);
}
}
}
void Instance::ClearLights()
{
myDirectionalLights[0] = 0;
myDirectionalLights[1] = 0;
myDirectionalLights[2] = 0;
myDirectionalLights[3] = 0;
myPointLights[0] = 0;
myPointLights[1] = 0;
myPointLights[2] = 0;
myPointLights[3] = 0;
mySpotLights[0] = 0;
mySpotLights[1] = 0;
mySpotLights[2] = 0;
mySpotLights[3] = 0;
}
void Instance::UpdateLights()
{
UpdateDirectionalLights();
UpdatePointLights();
UpdateSpotLights();
}
void Instance::TryAddDirectionalLight( Light* aLight, float aLightsStrength )
{
const int nbrOfLights = 4;
for (int lightChecked = 0; lightChecked < nbrOfLights; lightChecked++)
{
if (myDirectionalLights[lightChecked] == 0)
{
LightWithStrength* newStruct = new LightWithStrength(aLight, aLightsStrength);
myDirectionalLights.Insert(lightChecked, newStruct);
break;
}
else
{
if ( myDirectionalLights[lightChecked]->myStrength < aLightsStrength )
{
LightWithStrength* newStruct = new LightWithStrength(aLight, aLightsStrength);
myDirectionalLights.Insert(lightChecked, newStruct);
break;
}
}
}
}
void Instance::TryAddPointLight( Light* aLight, float aLightsStrength )
{
const int nbrOfLights = 4;
for (int lightChecked = 0; lightChecked < nbrOfLights; lightChecked++)
{
if (myPointLights[lightChecked] == 0)
{
LightWithStrength* newStruct = new LightWithStrength(aLight, aLightsStrength);
myPointLights.Insert(lightChecked, newStruct);
break;
}
else
{
if ( myPointLights[lightChecked]->myStrength < aLightsStrength )
{
LightWithStrength* newStruct = new LightWithStrength(aLight, aLightsStrength);
myPointLights.Insert(lightChecked, newStruct);
break;
}
}
}
}
void Instance::TryAddSpotLight( Light* aLight, float aLightsStrength )
{
const int nbrOfLights = 4;
for (int lightChecked = 0; lightChecked < nbrOfLights; lightChecked++)
{
if (mySpotLights[lightChecked] == 0)
{
LightWithStrength* newStruct = new LightWithStrength(aLight, aLightsStrength);
mySpotLights.Insert(lightChecked, newStruct);
break;
}
else
{
if ( mySpotLights[lightChecked]->myStrength < aLightsStrength )
{
LightWithStrength* newStruct = new LightWithStrength(aLight, aLightsStrength);
mySpotLights.Insert(lightChecked, newStruct);
break;
}
}
}
}
void Instance::UpdateDirectionalLights()
{
//CommonUtilities::StaticArray<Vector4f,9> lightVectors;
//CommonUtilities::StaticArray<Vector4f,9> lightColours;
//int nbrOfLights = 0;
//for (int lightUpdated = 0; lightUpdated < 4; lightUpdated++)
//{
// if (myDirectionalLights[lightUpdated] != 0)
// {
// lightVectors[lightUpdated] = myDirectionalLights[lightUpdated]->myLight->GetCurrentLightDir();
// lightColours[lightUpdated] = myDirectionalLights[lightUpdated]->myLight->GetLightColor();
// nbrOfLights++;
// }
//}
//Engine::GetInstance()->GetEffectInput().UpdateDirectionalLights(lightVectors, lightColours, nbrOfLights);
}
void Instance::UpdatePointLights()
{
//CommonUtilities::StaticArray<Vector4f,9> lightColours;
//CommonUtilities::StaticArray<Vector3f, 9> lightPositions;
//CommonUtilities::StaticArray<float, 9> lightMaxDistnaces;
//int nbrOfLights = 0;
//for (int lightUpdated = 0; lightUpdated < 4; lightUpdated++)
//{
// if (myPointLights[lightUpdated] != 0)
// {
// lightColours[lightUpdated] = myPointLights[lightUpdated]->myLight->GetLightColor();
// lightPositions[lightUpdated] = myPointLights[lightUpdated]->myLight->GetPosition();
// lightMaxDistnaces[lightUpdated] = myPointLights[lightUpdated]->myLight->GetMaxDistance();
// nbrOfLights++;
// }
//}
//Engine::GetInstance()->GetEffectInput().UpdatePointLights(lightPositions, lightColours, lightMaxDistnaces, nbrOfLights);
}
void Instance::UpdateSpotLights()
{
//CommonUtilities::StaticArray<Vector4f,9> lightVectors;
//CommonUtilities::StaticArray<Vector4f,9> lightColours;
//CommonUtilities::StaticArray<Vector3f, 9> lightPositions;
//CommonUtilities::StaticArray<float, 9> lightMaxDistnaces;
//CommonUtilities::StaticArray<float, 9> lightInnerFallofs;
//CommonUtilities::StaticArray<float, 9> lightsOuterFallofs;
//int nbrOfLights = 0;
//for (int lightUpdated = 0; lightUpdated < 4; lightUpdated++)
//{
// if (mySpotLights[lightUpdated] != 0)
// {
// lightVectors[lightUpdated] = mySpotLights[lightUpdated]->myLight->GetCurrentLightDir();
// lightColours[lightUpdated] = mySpotLights[lightUpdated]->myLight->GetLightColor();
// lightPositions[lightUpdated] = mySpotLights[lightUpdated]->myLight->GetPosition();
// lightMaxDistnaces[lightUpdated] = mySpotLights[lightUpdated]->myLight->GetMaxDistance();
// lightInnerFallofs[lightUpdated] = mySpotLights[lightUpdated]->myLight->GetInnerFallofAngle();
// lightsOuterFallofs[lightUpdated] = mySpotLights[lightUpdated]->myLight->GetOuterFallofAngle();
// nbrOfLights++;
// }
//}
//Engine::GetInstance()->GetEffectInput().UpdateSpotLights(lightPositions, lightColours, lightMaxDistnaces
// , lightVectors, lightInnerFallofs, lightsOuterFallofs, nbrOfLights);
}
void Instance::BuildHierachy( TransformationNodeInstance& aHierarchy, Model* aModel )
{
const int nbrOfChildren = aModel->myChildsTransformations.Count();
for ( int copyCreated = 0; copyCreated < nbrOfChildren; copyCreated++)
{
TransformationNodeInstance* newChildNode = new TransformationNodeInstance();
newChildNode->SetTransformationNode(aModel->myChildsTransformations[copyCreated]);
BuildHierachy( (*newChildNode) , myModel.myChilds[copyCreated]);
aHierarchy.AddChildNode(newChildNode);
}
}
void Instance::Update( float aElapsedTime )
{
myHierarchy.Update(aElapsedTime);
if(myAnimation!=NULL)
{
myAnimation->Update(aElapsedTime);
}
if(myBoneInstances.Count()>0)
{
Matrix44f identity= Matrix44f::Identity();
TransformFrame(0,identity);
for( int i = 0; i < myBoneInstances.Count(); i++ )
{
myBoneInstances[i]->ApplyBindPose();
}
};
}
void Instance::TransformFrame( int aBoneId, const Matrix44f& aParentWorld )
{
myBoneInstances[aBoneId]->Transform(aParentWorld);
for(int i=0; i < myModel.myBones[aBoneId].GetChildren().Count(); i++)
{
TransformFrame( myModel.myBones[aBoneId].GetChildren()[i], myBoneInstances[aBoneId]->GetTransformed());
}
}
| 29.728856
| 271
| 0.745628
|
Cousken
|
4555bde2b27d87d8b07b7f9c16f95820e5c33892
| 769
|
cpp
|
C++
|
CppStudio/Easy/09.cpp
|
vvhappyguy/Access-to-IT
|
1452c64f8c03addf6836a846af63123f65a9f620
|
[
"Apache-2.0"
] | null | null | null |
CppStudio/Easy/09.cpp
|
vvhappyguy/Access-to-IT
|
1452c64f8c03addf6836a846af63123f65a9f620
|
[
"Apache-2.0"
] | null | null | null |
CppStudio/Easy/09.cpp
|
vvhappyguy/Access-to-IT
|
1452c64f8c03addf6836a846af63123f65a9f620
|
[
"Apache-2.0"
] | null | null | null |
//compiled with clang (10.0.1)
//9. Дан одномерный массив, длину массива задаёт пользователь.
//Вычислить сумму квадратов тех чисел, модуль которых превышает значение 2,5.
//Input: int n , (float) * n
//Output: float
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int n;
float sum;
cout << "Введите количество элементов в массиве: ";
cin >> n;
float *massNumber = new float[n];
cout << "Введите сами элменты: " << endl;
for (int i = 0; i < n; i++)
{
cout << i + 1 << " элемент: ";
cin >> massNumber[i];
if(fabs(massNumber[i] > 2.5))
{
sum += massNumber[i];
}
}
cout << "Сумма чисел равна " << sum << endl;
delete [] massNumber;
return 0;
}
| 24.03125
| 77
| 0.56567
|
vvhappyguy
|
45583baf13cef610e42413db24e8011758a6d15c
| 4,012
|
hh
|
C++
|
cc/pch.Darwin.hh
|
acorg/acmacs-base
|
a1a6e5b346ea3746f3fc1750ed4b7f29c7c0d049
|
[
"MIT"
] | null | null | null |
cc/pch.Darwin.hh
|
acorg/acmacs-base
|
a1a6e5b346ea3746f3fc1750ed4b7f29c7c0d049
|
[
"MIT"
] | null | null | null |
cc/pch.Darwin.hh
|
acorg/acmacs-base
|
a1a6e5b346ea3746f3fc1750ed4b7f29c7c0d049
|
[
"MIT"
] | null | null | null |
#include <algorithm>
#include <array>
#include <atomic>
#include <bzlib.h>
#include <cassert>
#include <cctype>
#include <cerrno>
#include <chrono>
#include <cinttypes>
#include <cmath>
#include <condition_variable>
#include <csignal>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <deque>
#include <exception>
#include <fcntl.h>
#include <fstream>
#include <functional>
#include <getopt.h>
#include <initializer_list>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <limits>
#include <locale>
#include <map>
#include <memory>
#include <mutex>
#include <numeric>
#include <optional>
#include <queue>
#include <random>
#include <regex>
#include <set>
#include <shared_mutex>
#include <sstream>
#include <stack>
#include <stdexcept>
#include <string>
#include <string_view>
#include <sys/mman.h>
#include <sys/types.h>
#include <thread>
#include <tuple>
#include <type_traits>
#include <typeinfo>
#include <unistd.h>
#include <utility>
#include <variant>
#include <vector>
// ----------------------------------------------------------------------
#if __has_include(<filesystem>)
#include <filesystem>
#elif __has_include(<experimental/filesystem>)
#include <experimental/filesystem>
#endif
#if __has_include(<experimental/iterator>)
#include <experimental/iterator>
#endif
// ----------------------------------------------------------------------
#pragma GCC diagnostic push
#ifdef __clang__
#pragma GCC diagnostic ignored "-Wdeprecated-dynamic-exception-spec"
#pragma GCC diagnostic ignored "-Wdocumentation"
#endif
#include <lzma.h>
#pragma GCC diagnostic pop
#include <curl/curl.h>
// #include <openssl/md5.h>
// ----------------------------------------------------------------------
// #pragma GCC diagnostic push
// #ifdef __clang__
// #pragma GCC diagnostic ignored "-Wclass-varargs"
// #pragma GCC diagnostic ignored "-Wcovered-switch-default"
// #pragma GCC diagnostic ignored "-Wdeprecated"
// #pragma GCC diagnostic ignored "-Wdocumentation"
// #pragma GCC diagnostic ignored "-Wdocumentation-unknown-command"
// #pragma GCC diagnostic ignored "-Wexit-time-destructors"
// // #pragma GCC diagnostic ignored "-Wextra-semi"
// #pragma GCC diagnostic ignored "-Wfloat-equal"
// // #pragma GCC diagnostic ignored "-Wmissing-noreturn"
// #pragma GCC diagnostic ignored "-Wnested-anon-types"
// #pragma GCC diagnostic ignored "-Wold-style-cast"
// #pragma GCC diagnostic ignored "-Wrange-loop-analysis"
// #pragma GCC diagnostic ignored "-Wreserved-id-macro" // in Python.h
// #pragma GCC diagnostic ignored "-Wshadow"
// #pragma GCC diagnostic ignored "-Wshadow-field"
// // #pragma GCC diagnostic ignored "-Wsign-conversion"
// #pragma GCC diagnostic ignored "-Wundef"
// #pragma GCC diagnostic ignored "-Wundefined-reinterpret-cast"
// #pragma GCC diagnostic ignored "-Wzero-as-null-pointer-constant"
// #endif
// #include <Python.h>
// #include <pybind11/pybind11.h>
// #include <pybind11/stl.h>
// #include <pybind11/stl_bind.h>
// #pragma GCC diagnostic pop
// ----------------------------------------------------------------------
// #include <cairo-pdf.h>
// ----------------------------------------------------------------------
// #include <uWS/uWS.h>
// ----------------------------------------------------------------------
// #include <bsoncxx/builder/basic/array.hpp>
// #include <bsoncxx/builder/basic/document.hpp>
// #include <bsoncxx/builder/stream/document.hpp>
// #include <bsoncxx/json.hpp>
// #include <bsoncxx/types.hpp>
// #include <bsoncxx/types/value.hpp>
// #include <mongocxx/client.hpp>
// #include <mongocxx/database.hpp>
// #include <mongocxx/exception/query_exception.hpp>
// #include <mongocxx/instance.hpp>
// #include <mongocxx/pool.hpp>
// #include <websocketpp/config/asio.hpp>
// #include <websocketpp/server.hpp>
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
| 28.253521
| 73
| 0.639831
|
acorg
|
45599a45271ba21da38aa923f238479bb649e50f
| 2,304
|
cpp
|
C++
|
src/Externals/cleaver/lib/backup/PaddedField.cpp
|
Haydelj/SCIRun
|
f7ee04d85349b946224dbff183438663e54b9413
|
[
"MIT"
] | null | null | null |
src/Externals/cleaver/lib/backup/PaddedField.cpp
|
Haydelj/SCIRun
|
f7ee04d85349b946224dbff183438663e54b9413
|
[
"MIT"
] | null | null | null |
src/Externals/cleaver/lib/backup/PaddedField.cpp
|
Haydelj/SCIRun
|
f7ee04d85349b946224dbff183438663e54b9413
|
[
"MIT"
] | null | null | null |
/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2020 Scientific Computing and Imaging Institute,
University of Utah.
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 "PaddedField.h"
namespace Cleaver
{
const float PaddedField::DefaultThickness = 2;
const float PaddedField::DefaultHighValue = +10000;
const float PaddedField::DefaultLowValue = -10000;
PaddedField::PaddedField(const Cleaver::ScalarField *field, float thickness, float high, float low)
: m_origi_field(field), m_thickness(thickness), m_highValue(high), m_lowValue(low)
{
computeBounds();
}
void PaddedField::setField(const Cleaver::ScalarField *field)
{
m_origi_field = field;
computeBounds();
}
void PaddedField::setThickness(float thickness)
{
m_thickness = thickness;
computeBounds();
}
void PaddedField::setHighValue(float value)
{
m_highValue = value;
}
void PaddedField::setLowValue(float value)
{
m_lowValue = value;
}
void PaddedField::computeBounds()
{
vec3 origin = m_origi_field->bounds().origin - vec3(m_thickness,m_thickness,m_thickness);
vec3 size = m_origi_field->bounds().size + vec3(2*m_thickness,2*m_thickness,2*m_thickness);
m_bounds = BoundingBox(origin, size);
}
}
| 30.315789
| 99
| 0.751736
|
Haydelj
|
455dff9f0174aadc5711be32e0a8f2ec8998be26
| 7,055
|
hpp
|
C++
|
include/utils4cpp/str/UString.hpp
|
shaoguangwu/utils4cpp
|
6cc2093220e7be293761432cde88dff275c8f678
|
[
"BSD-3-Clause"
] | 1
|
2019-10-17T01:34:56.000Z
|
2019-10-17T01:34:56.000Z
|
include/utils4cpp/str/UString.hpp
|
shaoguangwu/utils4cpp
|
6cc2093220e7be293761432cde88dff275c8f678
|
[
"BSD-3-Clause"
] | null | null | null |
include/utils4cpp/str/UString.hpp
|
shaoguangwu/utils4cpp
|
6cc2093220e7be293761432cde88dff275c8f678
|
[
"BSD-3-Clause"
] | 3
|
2019-10-17T01:33:37.000Z
|
2019-12-02T02:13:45.000Z
|
/************************************************************************************
**
** BSD 3-Clause License
**
** Copyright (c) 2019, shaoguang. All rights reserved.
**
** Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are met:
**
** 1. Redistributions of source code must retain the above copyright notice, this
** list of conditions and the following disclaimer.
**
** 2. Redistributions in binary form must reproduce the above copyright notice,
** this list of conditions and the following disclaimer in the documentation
** and/or other materials provided with the distribution.
**
** 3. Neither the name of the copyright holder nor the names of its
** contributors may be used to endorse or promote products derived from
** this software without specific prior written permission.
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
** AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
** IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
** FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
** DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
** CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
** OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
************************************************************************************/
#ifndef UTILS4CPP_STR_USTRING_HPP
#define UTILS4CPP_STR_USTRING_HPP
#include <type_traits>
#include "utils4cpp/str/UStringUtils.hpp"
namespace utils4cpp {
namespace str {
template<class StringT>
class UString
{
StringT m_data;
public:
using value_type = typename StringT::value_type;
using input_string_type = StringT;
using size_type = typename StringT::size_type;
using reference = typename StringT::reference;
using const_reference = typename StringT::const_reference;
public:
UString() noexcept(std::is_nothrow_default_constructible_v<StringT>) = default;
~UString() = default;
UString(value_type ch)
: m_data(1, ch) {}
UString(size_type count, value_type ch)
: m_data(count, ch) {}
UString(const StringT& str, size_type pos)
: m_data(str, pos) {}
UString(const StringT& str, size_type pos, size_type count)
: m_data(str, pos, count){}
UString(const value_type* s, size_type count)
: m_data(s, count) {}
UString(const value_type* s)
: m_data(s) {}
template<class InputIterator>
UString(InputIterator first, InputIterator last)
: m_data(first, last) {}
UString(const StringT& str) noexcept(std::is_nothrow_copy_constructible_v<StringT>)
: m_data(str)
{}
UString(StringT&& str) noexcept(std::is_nothrow_move_constructible_v<StringT>)
: m_data(std::move(str))
{}
UString(const UString& other) noexcept(std::is_nothrow_copy_constructible_v<StringT>)
: m_data(other.m_data)
{}
UString(UString&& other) noexcept(std::is_nothrow_move_constructible_v<StringT>)
: m_data(std::move(other.m_data))
{}
UString(std::initializer_list<value_type> list)
: m_data(list) {}
#ifdef UTILS4CPP_HAS_CPP17
// string_view支持
template<class T>
explicit UString(const T& t)
: m_data(t) {}
template<class T>
UString(const T& t, size_type pos, size_type n)
: m_data(t, n) {}
#endif // UTILS4CPP_HAS_CPP17
UString& operator=(value_type ch) noexcept
{
m_data.assign(1, ch);
}
UString& operator=(const StringT& str)
{
m_data = str;
return *this;
}
UString& operator=(StringT&& str) noexcept
{
m_data = std::move(str);
return *this;
}
UString& operator=(const UString& other)
{
if (this != &other) {
m_data = other.m_data;
}
return *this;
}
UString& operator=(UString&& other) noexcept
{
if (this != &other) {
m_data = std::move(other.m_data);
}
return *this;
}
size_type size() const noexcept
{
return m_data.size();
}
size_type count() const noexcept
{
return m_data.size();
}
size_type length() const noexcept
{
return m_data.length();
}
bool empty() const noexcept
{
return m_data.empty();
}
StringT& data() noexcept
{
return m_data;
}
const StringT& data() const noexcept
{
return m_data;
}
const StringT& constData() const noexcept
{
return m_data;
}
StringT toInputString()
{
return m_data;
}
StringT moveToInputString() noexcept
{
return std::move(m_data);
}
reference operator[](size_type pos)
{
return m_data[pos];
}
const_reference operator[](size_type pos) const
{
return m_data[pos];
}
const value_type* c_str() const noexcept
{
return m_data.c_str();
}
UString substr(size_type pos = 0, size_type count = StringT::npos) const
{
return m_data.substr(pos, count);
}
bool startsWith(value_type c, UCaseSensitivity cs = UCaseSensitive, const std::locale& loc = std::locale) const
{
return endsWith(c, cs, loc);
}
bool startsWith(const StringT& s, UCaseSensitivity cs = UCaseSensitive) const
{
}
bool startsWith(const UString& s, UCaseSensitivity cs = UCaseSensitive)
{
}
bool startsWith(UBasicStringView<value_type> str, UCaseSensitivity cs = UCaseSensitive) const noexcept
{
}
bool endsWith();
UString& fill(value_type ch) noexcept
{
std::fill(m_data.begin(), m_data.end(), ch);
return *this;
}
void clear() noexcept
{
return m_data.clear();
}
void swap(UString& other) noexcept(
std::allocator_traits<StringT::Allocator>::propagate_on_container_swap::value ||
std::allocator_traits<StringT::Allocator>::is_always_equal::value)
{
m_data.swap(other.m_data);
}
void swap(StringT& str) noexcept(
std::allocator_traits<StringT::Allocator>::propagate_on_container_swap::value ||
std::allocator_traits<StringT::Allocator>::is_always_equal::value)
{
m_data.swap(str);
}
UString& reverse()
{
reverseStringSelf(m_data);
return *this;
}
UString reversed() const
{
return UString(reverseString(m_data));
}
UString& remove(size_type pos, size_type count)
{
}
};
} // namespace str
} // namespace utils4cpp
#endif // UTILS4CPP_STR_USTRING_HPP
| 26.927481
| 115
| 0.635152
|
shaoguangwu
|
456112f948858b44c30eb8253bd794580c9571a1
| 1,767
|
cpp
|
C++
|
Libs/Core/Testing/Cpp/ctkBackTraceTest.cpp
|
kraehlit/CTK
|
6557c5779d20b78f501f1fd6ce1063d0f219cca6
|
[
"Apache-2.0"
] | 515
|
2015-01-13T05:42:10.000Z
|
2022-03-29T03:10:01.000Z
|
Libs/Core/Testing/Cpp/ctkBackTraceTest.cpp
|
kraehlit/CTK
|
6557c5779d20b78f501f1fd6ce1063d0f219cca6
|
[
"Apache-2.0"
] | 425
|
2015-01-06T05:28:38.000Z
|
2022-03-08T19:42:18.000Z
|
Libs/Core/Testing/Cpp/ctkBackTraceTest.cpp
|
kraehlit/CTK
|
6557c5779d20b78f501f1fd6ce1063d0f219cca6
|
[
"Apache-2.0"
] | 341
|
2015-01-08T06:18:17.000Z
|
2022-03-29T21:47:49.000Z
|
/*=========================================================================
Library: CTK
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0.txt
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=========================================================================*/
#include <ctkBackTrace.h>
#include <QDebug>
//-----------------------------------------------------------------------------
void Q_DECL_EXPORT bt_func1()
{
ctkBackTrace bt;
qDebug() << bt.stackTrace();
if (!bt.stackFrame(1).contains("ctkBackTrace"))
{
qCritical() << "Stack frame for ctkBackTrace::ctkBackTrace(...) missing";
exit(EXIT_FAILURE);
}
if (!bt.stackFrame(2).contains("bt_func1"))
{
qCritical() << "Stack frame for bt_func1() missing";
exit(EXIT_FAILURE);
}
if (!bt.stackFrame(3).contains("bt_func2"))
{
qCritical() << "Stack frame for bt_func2() missing";
exit(EXIT_FAILURE);
}
}
//-----------------------------------------------------------------------------
void Q_DECL_EXPORT bt_func2()
{
bt_func1();
}
//-----------------------------------------------------------------------------
int ctkBackTraceTest(int /*argc*/, char* /*argv*/[])
{
bt_func2();
return EXIT_SUCCESS;
}
| 27.184615
| 79
| 0.54386
|
kraehlit
|
4565bbae89b433154fe632e8c47a6c49b131cfe0
| 1,367
|
cc
|
C++
|
test/test_saved_options.cc
|
halfflat/tinyopt
|
12e4a7be36fb692a4b9b814ddef13dbb0c00a40c
|
[
"BSD-3-Clause"
] | 3
|
2019-03-07T14:45:06.000Z
|
2019-04-27T12:57:15.000Z
|
test/test_saved_options.cc
|
halfflat/tinyopt
|
12e4a7be36fb692a4b9b814ddef13dbb0c00a40c
|
[
"BSD-3-Clause"
] | 4
|
2021-04-02T19:07:38.000Z
|
2021-06-03T12:39:29.000Z
|
test/test_saved_options.cc
|
halfflat/tinyopt
|
12e4a7be36fb692a4b9b814ddef13dbb0c00a40c
|
[
"BSD-3-Clause"
] | null | null | null |
#include <sstream>
#include <string>
#include <vector>
#include <gtest/gtest.h>
#include <tinyopt/tinyopt.h>
using svector = std::vector<std::string>;
TEST(saved_options, add) {
to::saved_options so1;
for (auto x: {"tasty", "fish", "cake"}) so1.add(x);
EXPECT_EQ((svector{"tasty", "fish", "cake"}), svector(so1.begin(), so1.end()));
to::saved_options so2;
so2.add("penguin");
so2.add("puffin");
so2 += so1;
EXPECT_EQ((svector{"penguin", "puffin", "tasty", "fish", "cake"}), svector(so2.begin(), so2.end()));
}
TEST(saved_options, arglist) {
to::saved_options so;
for (auto x: {"tasty", "fish", "cake"}) so.add(x);
auto A = so.as_arglist();
EXPECT_EQ(3, A.argc);
EXPECT_EQ("tasty", std::string(A.argv[0]));
EXPECT_EQ("fish", std::string(A.argv[1]));
EXPECT_EQ("cake", std::string(A.argv[2]));
EXPECT_EQ(nullptr, A.argv[3]);
}
TEST(saved_options, serialize) {
to::saved_options so;
so.add("a b c\t");
so.add("\n");
so.add("xyz");
so.add("x'y'z");
so.add("");
std::stringstream s;
s << so;
EXPECT_EQ("'a b c\t' '\n' xyz 'x'\\''y'\\''z' ''", s.str());
}
TEST(saved_options, deserialize) {
std::stringstream s("a '' '\t' b' c 'd");
to::saved_options so;
s >> so;
EXPECT_EQ((svector{"a", "", "\t", "b c d"}), svector(so.begin(), so.end()));
}
| 24.410714
| 104
| 0.567666
|
halfflat
|
457390d9b1775239b1af41a158d8669c3dfa6286
| 1,347
|
hpp
|
C++
|
SOLVER/src/core/output/element-wise/io/ElementIO_ParNetCDF.hpp
|
nicklinyi/AxiSEM-3D
|
cd11299605cd6b92eb867d4109d2e6a8f15e6b4d
|
[
"MIT"
] | 8
|
2020-06-05T01:13:20.000Z
|
2022-02-24T05:11:50.000Z
|
SOLVER/src/core/output/element-wise/io/ElementIO_ParNetCDF.hpp
|
nicklinyi/AxiSEM-3D
|
cd11299605cd6b92eb867d4109d2e6a8f15e6b4d
|
[
"MIT"
] | 24
|
2020-10-21T19:03:38.000Z
|
2021-11-17T21:32:02.000Z
|
SOLVER/src/core/output/element-wise/io/ElementIO_ParNetCDF.hpp
|
nicklinyi/AxiSEM-3D
|
cd11299605cd6b92eb867d4109d2e6a8f15e6b4d
|
[
"MIT"
] | 5
|
2020-06-21T11:54:22.000Z
|
2021-06-23T01:02:39.000Z
|
//
// ElementIO_ParNetCDF.hpp
// AxiSEM3D
//
// Created by Kuangdai Leng on 7/29/20.
// Copyright © 2020 Kuangdai Leng. All rights reserved.
//
// parallel NetCDF IO for element output
#ifndef ElementIO_ParNetCDF_hpp
#define ElementIO_ParNetCDF_hpp
#include "ElementIO.hpp"
#include "NetCDF_Writer.hpp"
class ElementIO_ParNetCDF: public ElementIO {
public:
// initialize
void initialize(const std::string &groupName,
int numRecordSteps,
const std::vector<std::string> &channels,
int npnts, const std::vector<int> &naGrid,
const eigen::IMatX4_RM &elemNaInfo,
const eigen::DMatXX_RM &elemCoords);
// finalize
void finalize();
// dump to file
void dumpToFile(const eigen::DColX &bufferTime,
const std::vector<eigen::RTensor5> &bufferFields,
int bufferLine);
private:
//////////////////// const ////////////////////
// file
std::unique_ptr<NetCDF_Writer> mNcFile = nullptr;
// variable id
int mVarID_Time = -1;
std::vector<int> mVarID_Data;
// current line in time dimension
int mFileLineTime = 0;
// first element index on na-grid
std::vector<int> mFirstElemNaGrid;
};
#endif /* ElementIO_ParNetCDF_hpp */
| 25.903846
| 69
| 0.601336
|
nicklinyi
|
4577cf4f5bb9c2e1bfdc6005f9901f4f5d59964b
| 11,589
|
hpp
|
C++
|
fmt11.hpp
|
r-lyeh-archived/fmt11
|
1820e9e6e8cdaccc216151013882f456cfbf657c
|
[
"Unlicense"
] | 5
|
2018-01-18T14:51:10.000Z
|
2021-04-10T00:57:03.000Z
|
fmt11.hpp
|
r-lyeh-archived/fmt11
|
1820e9e6e8cdaccc216151013882f456cfbf657c
|
[
"Unlicense"
] | null | null | null |
fmt11.hpp
|
r-lyeh-archived/fmt11
|
1820e9e6e8cdaccc216151013882f456cfbf657c
|
[
"Unlicense"
] | 4
|
2018-01-18T14:51:14.000Z
|
2020-10-27T12:55:06.000Z
|
// Tiny format/mustache templating library (C++11)
// - rlyeh, public domain
// Inspired by the better, safer and more featured library [fmtlib](https://github.com/fmtlib/fmt)
// PS: I ripped the examples and a few tests as well O:)
// ## Features
// [x] Basic python formatting: "{} {0} {1} {2:#x} {4:8.2} {:<20}"
// [x] Basic mustache templating "{{key}}"
// [x] Tiny, cross-platform, macro-less, header-only.
// [x] Public domain.
// ## Cons
// [ ] Probably slow. No recursive code, but some allocations remain still.
// [ ] Probably unsafe. No exhaustive bound checking is performed at all.
// [ ] Probably not full featured enough.
// ## Alternatives
// - https://github.com/apfeltee/cpp11-sprintf
// - https://github.com/c42f/tinyformat
// - https://github.com/d-led/fakeformat
// - https://github.com/dbralir/print
// - https://github.com/fmtlib/fmt
// - https://github.com/kainjow/Mustache
// - https://github.com/no1msd/mstch/
// - https://github.com/rnlf/flossy
// - https://github.com/seanmiddleditch/formatxx
#ifndef FMT11_VERSION
#define FMT11_VERSION "1.0.2" /* (2016/06/01): Parse valid identifiers only
#define FMT11_VERSION "1.0.1" // (2016/05/31): Extra boundary checks
#define FMT11_VERSION "1.0.0" // (2016/05/29): Initial version */
#include <iomanip>
#include <map>
#include <sstream>
#include <string>
#include <tuple>
template<unsigned trail_args, typename Map, typename... Args>
inline std::string fmt11hlp( const Map *ctx, const char *format, Args... args) {
std::stringstream out;
if( format ) {
auto tpl = std::tuple_cat( std::tuple<Args...>{ args... }, std::make_tuple( 0,0,0,0,0,0,0,0,0,0) );
char raw[64], tag[32], fmt[32];
unsigned fix, dig, counter = 0;
while( *format ) {
if( *format++ != '{' ) {
out << format[-1];
} else {
auto parse = []( char raw[64], char tag[32], char fmt[32], unsigned &fix, unsigned &dig, const char *in ) -> int {
int lv = 0; // parses [{] { [tag][:][fmt] } [}] expressions; returns num of bytes parsed or 0 if error
char *o = raw, *m = tag, *g = 0;
while( *in && *in == '{' ) {
*o++ = *in++, ++lv;
if( (o - raw) >= 63 ) return 0;
}
while( *in && lv > 0 ) {
/**/ if( *in < 32 ) return 0;
else if( *in < '0' && !g ) return 0;
else if( *in == '}' ) --lv, *o++ = *in++;
else if( *in == ':' ) g = fmt, *o++ = *in++;
else *( g ? g : m)++ = *o++ = *in++;
if( ((o - raw) >= 63) || ((m - tag) >= 31) || ( g && (g - fmt) >= 31 )) return 0;
}
*o = *m = *(g ? g : fmt) = 0;
if( 0 != lv ) {
return 0;
}
fix = dig = 0;
for( char *f = fmt; *f != 0; ++f ) {
char *input = f;
if( *input >= '0' && *input <= '9' ) {
double dbl = atof(input);
fix = int(dbl), dig = int(dbl * 1000 - fix * 1000);
while( dig && !(dig % 10) ) dig /= 10;
//printf("%s <> %d %d\n", input, fix, dig );
break;
}
}
return o - raw;
};
int read_bytes = parse( raw, tag, fmt, fix, dig, &format[-1] );
if( !read_bytes ) {
out << format[-1];
} else {
// style
format += read_bytes - 1;
for( char *f = fmt; *f; ++f ) switch( *f ) {
default:
if( f[0] >= '0' && f[0] <= '9' ) {
while( (f[0] >= '0' && f[0] <= '9') || f[0] == '.' ) ++f; --f;
out << std::setw( fix );
out << std::fixed;
out << std::setprecision( dig );
} else {
out.fill( f[0] );
}
break; case '#': out << std::showbase;
break; case 'b': out << std::boolalpha;
break; case 'D': out << std::dec << std::uppercase;
break; case 'd': out << std::dec;
break; case 'O': out << std::oct << std::uppercase;
break; case 'o': out << std::oct;
break; case 'X': out << std::hex << std::uppercase;
break; case 'x': out << std::hex;
break; case 'f': out << std::fixed;
break; case '<': out << std::left;
break; case '>': out << std::right;
}
// value
char arg = tag[0];
if( !arg ) {
if( counter < (sizeof...(Args) - trail_args) ) {
arg = '0' + counter++;
} else {
arg = '\0';
}
//printf("arg %d/%d\n", int(counter), (sizeof...(Args) - trail_args));
}
switch( arg ) {
default:
if( ctx ) {
auto find = ctx->find(tag);
if( find == ctx->end() ) out << raw;
else out << find->second;
} else {
out << raw;
}
break; case 0: out << raw;
break; case '0': out << std::get<0>(tpl);
break; case '1': out << std::get<1>(tpl);
break; case '2': out << std::get<2>(tpl);
break; case '3': out << std::get<3>(tpl);
break; case '4': out << std::get<4>(tpl);
break; case '5': out << std::get<5>(tpl);
break; case '6': out << std::get<6>(tpl);
break; case '7': out << std::get<7>(tpl);
break; case '8': out << std::get<8>(tpl);
break; case '9': out << std::get<9>(tpl);
}
}
}
}
}
return out.str();
}
inline std::string fmt11( const char *format ) {
return fmt11hlp<1, std::map<std::string, std::string>>( nullptr, format, 0 );
}
template<typename... Args>
inline std::string fmt11( const char *format, Args... args ) {
return fmt11hlp<0, std::map<std::string, std::string>>( nullptr, format, args... );
}
template<typename Map>
inline std::string fmt11map( const Map &ctx, const char *format ) {
return fmt11hlp<1>( &ctx, format, 0 );
}
template<typename Map, typename... Args>
inline std::string fmt11map( const Map &ctx, const char *format, Args... args) {
return fmt11hlp<0>( &ctx, format, args... );
}
#ifdef FMT11_BUILD_DEMO
#include <stdio.h>
int main() {
# define TEST(a,b) printf("[%s] L%d: %s\n", !!((a) == (b)) ? " OK ":"FAIL", __LINE__, (a).c_str())
// basics
TEST( fmt11("Hello"), "Hello" );
TEST( fmt11("Hello {} {}", 123, "456"), "Hello 123 456" ); // equivalent to {0} {1}
TEST( fmt11("Hello {0} {1}", 123, "456"), "Hello 123 456" );
TEST( fmt11("Hello {1} {0}", 123, "456"), "Hello 456 123" );
// indices and reordering
TEST( fmt11("Hello {1} {0}", 123, "world" ), "Hello world 123");
TEST( fmt11("Hello {0} {1}", 123, "world" ), "Hello 123 world");
TEST( fmt11("{0}{1}{0}", "abra", "cad" ), "abracadabra");
// basic formatting: dec, hex, oct, prefixes, uppercase
TEST( fmt11("Hello {:d} {:x} {:o}", 42, 42, 42), "Hello 42 2a 52");
TEST( fmt11("Hello {:#d} {:#x} {:#o}", 42, 42, 42), "Hello 42 0x2a 052");
TEST( fmt11("Hello {0:d} {0:x} {0:o}", 42, 42, 42), "Hello 42 2a 52");
TEST( fmt11("Hello {0:d} {0:#x} {0:#o}", 42, 42, 42), "Hello 42 0x2a 052");
TEST( fmt11("Hello {:D} {:X} {:O}", 42, 42, 42), "Hello 42 2A 52");
TEST( fmt11("Hello {:#D} {:#X} {:#O}", 42, 42, 42), "Hello 42 0X2A 052");
TEST( fmt11("Hello {0:D} {0:X} {0:O}", 42, 42, 42), "Hello 42 2A 52");
TEST( fmt11("Hello {0:D} {0:#X} {0:#O}", 42, 42, 42), "Hello 42 0X2A 052");
TEST( fmt11("Hello {:d} {:x} {:o} {:#x} {:#o} {:#X} {:#O}", 42, 42, 42, 42, 42, 42, 42 ), "Hello 42 2a 52 0x2a 052 0X2A 052" );
// extra formatting: width, decimals, custom prefixes and alignment
TEST( fmt11("Hello {:8} {:12} {:16}", 3.14159, 3.14159, 3.14159 ), "Hello 3 3 3" );
TEST( fmt11("Hello {:8.2} {:12.3} {:16.4}", 3.14159, 3.14159, 3.14159 ), "Hello 3.14 3.142 3.1416" );
TEST( fmt11("Hello {:*8.2} {:|12.3} {:.16.4}", 3.14159, 3.14159, 3.14159 ), "Hello ****3.14 |||||||3.142 ..........3.1416" );
TEST( fmt11("Hello {:<*8.2} {:<|12.3} {:<.16.4}", 3.14159, 3.14159, 3.14159 ), "Hello 3.14**** 3.142||||||| 3.1416.........." );
TEST( fmt11("Hello {:.>10} Emmett {:!<10}", "Doc", "Brown" ), "Hello .......Doc Emmett Brown!!!!!" );
// context and {{mustaches}}
std::map< std::string, std::string > ctx { { "player1", "John" }, { "player2", "Doe" } };
TEST( fmt11map( ctx, "Hello {{player1}} & {{player2}}!!"), "Hello John & Doe!!");
TEST( fmt11map( ctx, "Hello {{player1}} & {{player2}}!! {0} {} {1}!!", 123, 456), "Hello John & Doe!! 123 123 456!!");
TEST( fmt11map( ctx, "Hello {{player1}:*>10} & {{player2}:*<10}!!"), "Hello ******John & Doe*******!!");
TEST( fmt11map( ctx,"{{player1}}{{player2}}"), "JohnDoe" );
ctx.clear();
// check for malformed input
TEST( fmt11(0), "" ); // null ptr
TEST( fmt11(""), "" ); // empty string
TEST( fmt11("{}{}{}"), "{}{}{}" ); // no args
TEST( fmt11("{}{}{}",1,2), "12{}" ); // not enough args
TEST( fmt11("", 1,2,3), ""); // too many args
TEST( fmt11("{}",1,2,3), "1" ); // too many args
TEST( fmt11("{"), "{" ); // unbalanced
TEST( fmt11("}"), "}" ); // unbalanced
TEST( fmt11("{{"), "{{" ); // unbalanced
TEST( fmt11("}}"), "}}" ); // unbalanced
TEST( fmt11("{{{"), "{{{" ); // unbalanced
TEST( fmt11("}}}"), "}}}" ); // unbalanced
TEST( fmt11("}{"), "}{" ); // mismatch
TEST( fmt11("}{}"), "}{}" ); // mismatch
TEST( fmt11("}}{"), "}}{" ); // mismatch
TEST( fmt11("{}{"), "{}{" ); // mismatch
TEST( fmt11("{}}"), "{}}" ); // mismatch
TEST( fmt11("{\t}", "hello"), "{\t}"); // invalid identifier
TEST( fmt11("{\"{0}\"}", "hello"), "{\"hello\"}"); // false positive \" is not part of an identifier
TEST( fmt11( std::string(128, '{').c_str() ), std::string(128, '{') ); // buffer overflow
TEST( fmt11( std::string(128, '}').c_str() ), std::string(128, '}') ); // buffer overflow
TEST( fmt11("{{player1}}{{player2}}"), "{{player1}}{{player2}}" ); // missing map
TEST( fmt11map( ctx,"{{player1}}{{player2}}"), "{{player1}}{{player2}}" ); // empty map
}
#endif
#endif
| 48.693277
| 132
| 0.426439
|
r-lyeh-archived
|
457d040916faaa4851bc08972031a8534c1dc4ca
| 32,518
|
cpp
|
C++
|
matlab/caffe/matcaffe.cpp
|
xiaomi646/caffe_2d_mlabel
|
912c92d6f3ba530e1abea79fb1ab2cb34aa5bd65
|
[
"BSD-2-Clause"
] | 1
|
2015-07-08T15:30:06.000Z
|
2015-07-08T15:30:06.000Z
|
matlab/caffe/matcaffe.cpp
|
xiaomi646/caffe_2d_mlabel
|
912c92d6f3ba530e1abea79fb1ab2cb34aa5bd65
|
[
"BSD-2-Clause"
] | null | null | null |
matlab/caffe/matcaffe.cpp
|
xiaomi646/caffe_2d_mlabel
|
912c92d6f3ba530e1abea79fb1ab2cb34aa5bd65
|
[
"BSD-2-Clause"
] | null | null | null |
//
// matcaffe.cpp provides a wrapper of the caffe::Net class as well as some
// caffe::Caffe functions so that one could easily call it from matlab.
// Note that for matlab, we will simply use float as the data type.
// these need to be included after boost on OS X
#include <string> // NOLINT(build/include_order)
#include <vector> // NOLINT(build/include_order)
#include <fstream> // NOLINT
#include <stdexcept>
#include "mex.h"
#include "caffe/caffe.hpp"
#define MEX_ARGS int nlhs, mxArray **plhs, int nrhs, const mxArray **prhs
// The interim macro that simply strips the excess
// and ends up with the required macro
#define CHECK_EQ_X(A, B, C, FUNC, ...) FUNC
// The macro that the programmer uses
#define CHECK_EQ_MEX(...) CHECK_EQ_X(__VA_ARGS__, \
CHECK_EQ_3(__VA_ARGS__), \
CHECK_EQ_2(__VA_ARGS__))
#define CHECK_EQ_2(a, b) do { \
if ( (a) != (b) ) { \
fprintf(stderr, "%s:%d: Check failed because %s != %s\n", \
__FILE__, __LINE__, #a, #b); \
mexErrMsgTxt("Error in CHECK"); \
} \
} while (0);
#define CHECK_EQ_3(a, b, m) do { \
if ( (a) != (b) ) { \
fprintf(stderr, "%s:%d: Check failed because %s != %s\n", \
__FILE__, __LINE__, #a, #b); \
fprintf(stderr, "%s:%d: %s\n", \
__FILE__, __LINE__, #m); \
mexErrMsgTxt(#m); \
} \
} while (0);
#define CUDA_CHECK_MEX(condition) \
/* Code block avoids redefinition of cudaError_t error */ \
do { \
cudaError_t error = condition; \
CHECK_EQ_MEX(error, cudaSuccess, "CUDA_CHECK") \
} while (0)
using namespace caffe; // NOLINT(build/namespaces)
// for convenience, check that input files can be opened, and raise an
// exception that boost will send to Python if not (caffe could still crash
// later if the input files are disturbed before they are actually used, but
// this saves frustration in most cases)
static void CheckFile(const string& filename) {
std::ifstream f(filename.c_str());
CHECK_EQ_MEX(f.good(), true, "Could not open file " + filename);
f.close();
}
// The pointer to the internal caffe::Net instance
static shared_ptr<Net<float> > net_;
static int init_key = -2;
// Five things to be aware of:
// caffe uses row-major order
// matlab uses column-major order
// caffe uses BGR color channel order
// matlab uses RGB color channel order
// images need to have the data mean subtracted
//
// Data coming in from matlab needs to be in the order
// [width, height, channels, images]
// where width is the fastest dimension.
// Here is the rough matlab for putting image data into the correct
// format:
// % convert from uint8 to single
// im = single(im);
// % reshape to a fixed size (e.g., 227x227)
// im = imresize(im, [IMAGE_DIM IMAGE_DIM], 'bilinear');
// % permute from RGB to BGR and subtract the data mean (already in BGR)
// im = im(:,:,[3 2 1]) - data_mean;
// % flip width and height to make width the fastest dimension
// im = permute(im, [2 1 3]);
//
// If you have multiple images, cat them with cat(4, ...)
//
// The actual forward function. It takes in a cell array of 4-D arrays as
// input and outputs a cell array.
//
//
// Functions to copy data from mxarray to blobs and viceversa
//
static mxArray* blob_data_to_mxarray(const Blob<float>* blob) {
mwSize dims[4] = {blob->width(), blob->height(),
blob->channels(), blob->num()};
DLOG(INFO) << dims[0] << " " << dims[1] << " " << dims[2] << " " << dims[3];
mxArray* mx_blob_data = mxCreateNumericArray(4, dims, mxSINGLE_CLASS, mxREAL);
float* blob_data_ptr = reinterpret_cast<float*>(mxGetPr(mx_blob_data));
switch (Caffe::mode()) {
case Caffe::CPU:
caffe_copy(blob->count(), blob->cpu_data(), blob_data_ptr);
break;
case Caffe::GPU:
caffe_copy(blob->count(), blob->gpu_data(), blob_data_ptr);
break;
default:
LOG(FATAL) << "Unknown caffe mode: " << Caffe::mode();
mexErrMsgTxt("Unknown caffe mode");
}
return mx_blob_data;
}
static mxArray* blob_data_to_mxarray(const shared_ptr<Blob<float> > blob) {
return blob_data_to_mxarray(blob.get());
}
static void mxarray_to_blob_data(const mxArray* data, Blob<float>* blob) {
mwSize dims[4] = {blob->width(), blob->height(),
blob->channels(), blob->num()};
DLOG(INFO) << dims[0] << " " << dims[1] << " " << dims[2] << " " << dims[3];
CHECK_EQ_MEX(blob->count(), mxGetNumberOfElements(data),
"blob->count() don't match with numel(data)");
const float* const data_ptr =
reinterpret_cast<const float* const>(mxGetPr(data));
switch (Caffe::mode()) {
case Caffe::CPU:
caffe_copy(blob->count(), data_ptr, blob->mutable_cpu_data());
break;
case Caffe::GPU:
caffe_copy(blob->count(), data_ptr, blob->mutable_gpu_data());
break;
default:
LOG(FATAL) << "Unknown Caffe mode.";
mexErrMsgTxt("Unknown caffe mode");
} // switch (Caffe::mode())
}
static void mxarray_to_blob_data(const mxArray* data,
shared_ptr<Blob<float> > blob) {
mxarray_to_blob_data(data, blob.get());
}
static mxArray* blob_diff_to_mxarray(const Blob<float>* blob) {
mwSize dims[4] = {blob->width(), blob->height(),
blob->channels(), blob->num()};
DLOG(INFO) << dims[0] << " " << dims[1] << " " << dims[2] << " " << dims[3];
mxArray* mx_blob_data = mxCreateNumericArray(4, dims, mxSINGLE_CLASS, mxREAL);
float* blob_data_ptr = reinterpret_cast<float*>(mxGetPr(mx_blob_data));
switch (Caffe::mode()) {
case Caffe::CPU:
caffe_copy(blob->count(), blob->cpu_diff(), blob_data_ptr);
break;
case Caffe::GPU:
caffe_copy(blob->count(), blob->gpu_diff(), blob_data_ptr);
break;
default:
LOG(FATAL) << "Unknown caffe mode: " << Caffe::mode();
mexErrMsgTxt("Unknown caffe mode");
}
return mx_blob_data;
}
static mxArray* blob_diff_to_mxarray(const shared_ptr<Blob<float> > blob) {
return blob_diff_to_mxarray(blob.get());
}
static void mxarray_to_blob_diff(const mxArray* data, Blob<float>* blob) {
mwSize dims[4] = {blob->width(), blob->height(),
blob->channels(), blob->num()};
DLOG(INFO) << dims[0] << " " << dims[1] << " " << dims[2] << " " << dims[3];
CHECK_EQ_MEX(blob->count(), mxGetNumberOfElements(data),
"blob->count() don't match with numel(data)");
const float* const data_ptr =
reinterpret_cast<const float* const>(mxGetPr(data));
switch (Caffe::mode()) {
case Caffe::CPU:
caffe_copy(blob->count(), data_ptr, blob->mutable_cpu_diff());
break;
case Caffe::GPU:
caffe_copy(blob->count(), data_ptr, blob->mutable_gpu_diff());
break;
default:
LOG(FATAL) << "Unknown Caffe mode.";
mexErrMsgTxt("Unknown caffe mode");
} // switch (Caffe::mode())
}
static void mxarray_to_blob_diff(const mxArray* data,
shared_ptr<Blob<float> > blob) {
mxarray_to_blob_diff(data, blob.get());
}
static mxArray* blobs_data_to_cell(const vector<Blob<float>* >& blobs) {
mxArray* mx_out = mxCreateCellMatrix(blobs.size(), 1);
for (unsigned int i = 0; i < blobs.size(); ++i) {
mxArray* mx_blob = blob_data_to_mxarray(blobs[i]);
mxSetCell(mx_out, i, mx_blob);
}
return mx_out;
}
static mxArray* blobs_data_to_cell(
const vector<shared_ptr<Blob<float> > >& blobs) {
mxArray* mx_out = mxCreateCellMatrix(blobs.size(), 1);
for (unsigned int i = 0; i < blobs.size(); ++i) {
mxArray* mx_blob = blob_data_to_mxarray(blobs[i]);
mxSetCell(mx_out, i, mx_blob);
}
return mx_out;
}
static mxArray* blobs_diff_to_cell(const vector<Blob<float>* >& blobs) {
mxArray* mx_out = mxCreateCellMatrix(blobs.size(), 1);
for (unsigned int i = 0; i < blobs.size(); ++i) {
mxArray* mx_blob = blob_diff_to_mxarray(blobs[i]);
mxSetCell(mx_out, i, mx_blob);
}
return mx_out;
}
static mxArray* blobs_diff_to_cell(
const vector<shared_ptr<Blob<float> > >& blobs) {
mxArray* mx_out = mxCreateCellMatrix(blobs.size(), 1);
for (unsigned int i = 0; i < blobs.size(); ++i) {
mxArray* mx_blob = blob_diff_to_mxarray(blobs[i]);
mxSetCell(mx_out, i, mx_blob);
}
return mx_out;
}
static mxArray* do_forward_prefilled(mxArray* mx_loss) {
float* loss_ptr = reinterpret_cast<float*>(mxGetPr(mx_loss));
const vector<Blob<float>*>& output_blobs = net_->ForwardPrefilled(loss_ptr);
DLOG(INFO) << "loss: " << mxGetScalar(mx_loss);
mxArray* mx_out = blobs_data_to_cell(output_blobs);
// mxArray* mx_out = mxCreateCellMatrix(output_blobs.size(), 1);
// for (unsigned int i = 0; i < output_blobs.size(); ++i) {
// mxArray* mx_blob = blob_data_to_mxarray(output_blobs[i]);
// mxSetCell(mx_out, i, mx_blob);
// }
return mx_out;
}
static void do_set_input_blobs(const mxArray* const bottom) {
vector<Blob<float>*>& input_blobs = net_->input_blobs();
//unsigned int botsize =static_cast<unsigned int>(mxGetDimensions(bottom)[0]);
//LOG(INFO)<<"input_blobs size is "<<input_blobs.size() <<" and bottom size is "<<botsize;
CHECK_EQ_MEX(static_cast<unsigned int>(mxGetDimensions(bottom)[0]),input_blobs.size());
// Copy values into input_blobs
for (unsigned int i = 0; i < input_blobs.size(); ++i) {
const mxArray* const elem = mxGetCell(bottom, i);
mxarray_to_blob_data(elem, input_blobs[i]);
}
}
static mxArray* do_forward(const mxArray* const bottom, mxArray* mx_loss) {
do_set_input_blobs(bottom);
return do_forward_prefilled(mx_loss);
}
static mxArray* do_backward_prefilled() {
vector<Blob<float>*>& input_blobs = net_->input_blobs();
DLOG(INFO) << "Start";
net_->Backward();
DLOG(INFO) << "End";
mxArray* mx_out = blobs_diff_to_cell(input_blobs);
// mxArray* mx_out = mxCreateCellMatrix(input_blobs.size(), 1);
// for (unsigned int i = 0; i < input_blobs.size(); ++i) {
// mxArray* mx_blob = blob_diff_to_mxarray(input_blobs[i]);
// mxSetCell(mx_out, i, mx_blob);
// }
return mx_out;
}
static void do_set_output_blobs(const mxArray* const top_diff) {
vector<Blob<float>*>& output_blobs = net_->output_blobs();
CHECK_EQ_MEX(static_cast<unsigned int>(mxGetDimensions(top_diff)[0]),
output_blobs.size());
// Copy top_diff to the output diff
for (unsigned int i = 0; i < output_blobs.size(); ++i) {
const mxArray* const elem = mxGetCell(top_diff, i);
mxarray_to_blob_diff(elem, output_blobs[i]);
}
}
static mxArray* do_backward(const mxArray* const top_diff) {
do_set_output_blobs(top_diff);
return do_backward_prefilled();
}
static mxArray* do_get_weights() {
const vector<shared_ptr<Layer<float> > >& layers = net_->layers();
const vector<string>& layer_names = net_->layer_names();
// Step 1: count the number of layers with weights
int num_layers = 0;
{
string prev_layer_name = "";
for (unsigned int i = 0; i < layers.size(); ++i) {
vector<shared_ptr<Blob<float> > >& layer_blobs = layers[i]->blobs();
if (layer_blobs.size() == 0) {
continue;
}
if (layer_names[i] != prev_layer_name) {
prev_layer_name = layer_names[i];
num_layers++;
}
}
}
// Step 2: prepare output array of structures
mxArray* mx_layers;
{
const mwSize dims[2] = {num_layers, 1};
const char* fnames[2] = {"layer_names", "weights"};
mx_layers = mxCreateStructArray(2, dims, 2, fnames);
}
// Step 3: copy weights into output
{
string prev_layer_name = "";
int mx_layer_index = 0;
for (unsigned int i = 0; i < layers.size(); ++i) {
vector<shared_ptr<Blob<float> > >& layer_blobs = layers[i]->blobs();
if (layer_blobs.size() == 0) {
continue;
}
mxArray* mx_layer_weights = NULL;
if (layer_names[i] != prev_layer_name) {
prev_layer_name = layer_names[i];
// Copy weights
mx_layer_weights = blobs_data_to_cell(layer_blobs);
// const mwSize dims[2] = {static_cast<mwSize>(layer_blobs.size()), 1};
// mx_layer_cells = mxCreateCellArray(2, dims);
// for (unsigned int j = 0; j < layer_blobs.size(); ++j) {
// mxArray* mx_weights = blob_data_to_mxarray(layer_blobs[j]);
// mxSetCell(mx_layer_cells, j, mx_weights);
// }
// Create Struct
mxSetField(mx_layers, mx_layer_index, "weights", mx_layer_weights);
mxSetField(mx_layers, mx_layer_index, "layer_names",
mxCreateString(layer_names[i].c_str()));
mx_layer_index++;
}
}
}
return mx_layers;
}
static mxArray* do_get_layer_weights(const mxArray* const layer_name) {
const vector<shared_ptr<Layer<float> > >& layers = net_->layers();
const vector<string>& layer_names = net_->layer_names();
char* c_layer_name = mxArrayToString(layer_name);
DLOG(INFO) << c_layer_name;
mxArray* mx_layer_weights = NULL;
for (unsigned int i = 0; i < layers.size(); ++i) {
DLOG(INFO) << layer_names[i];
if (strcmp(layer_names[i].c_str(), c_layer_name) == 0) {
vector<shared_ptr<Blob<float> > >& layer_blobs = layers[i]->blobs();
if (layer_blobs.size() == 0) {
continue;
}
mx_layer_weights = blobs_data_to_cell(layer_blobs);
// const mwSize dims[2] = {layer_blobs.size(), 1};
// mx_layer_weights = mxCreateCellArray(2, dims);
// DLOG(INFO) << "layer_blobs.size()" << layer_blobs.size();
// for (unsigned int j = 0; j < layer_blobs.size(); ++j) {
// // internally data is stored as (width, height, channels, num)
// // where width is the fastest dimension
// mxArray* mx_weights = blob_data_to_mxarray(layer_blobs[j]);
// mxSetCell(mx_layer_weights, j, mx_weights);
// }
}
}
return mx_layer_weights;
}
static void do_set_layer_weights(const mxArray* const layer_name,
const mxArray* const mx_layer_weights) {
const vector<shared_ptr<Layer<float> > >& layers = net_->layers();
const vector<string>& layer_names = net_->layer_names();
char* c_layer_name = mxArrayToString(layer_name);
DLOG(INFO) << "Looking for: " << c_layer_name;
for (unsigned int i = 0; i < layers.size(); ++i) {
DLOG(INFO) << layer_names[i];
if (strcmp(layer_names[i].c_str(), c_layer_name) == 0) {
vector<shared_ptr<Blob<float> > >& layer_blobs = layers[i]->blobs();
if (layer_blobs.size() == 0) {
continue;
}
DLOG(INFO) << "Found layer " << layer_names[i];
CHECK_EQ_MEX(static_cast<unsigned int>(
mxGetDimensions(mx_layer_weights)[0]),
layer_blobs.size(), "Num of cells don't match layer_blobs.size");
DLOG(INFO) << "layer_blobs.size() = " << layer_blobs.size();
for (unsigned int j = 0; j < layer_blobs.size(); ++j) {
// internally data is stored as (width, height, channels, num)
// where width is the fastest dimension
const mxArray* const elem = mxGetCell(mx_layer_weights, j);
mxarray_to_blob_data(elem, layer_blobs[j]);
}
}
}
}
static mxArray* do_get_layers_info() {
const vector<shared_ptr<Layer<float> > >& layers = net_->layers();
const vector<string>& layer_names = net_->layer_names();
const int num_layers[2] = {layers.size(), 1};
// Step 1: prepare output array of structures
mxArray* mx_layers;
{
const char* fnames[3] = {"name", "type", "weights"};
mx_layers = mxCreateStructArray(2, num_layers, 3, fnames);
}
// Step 2: copy info into output
{
mxArray* mx_blob;
const char* blobfnames[5] = {"num", "channels", "height", "width", "count"};
for (unsigned int i = 0; i < layers.size(); ++i) {
mxSetField(mx_layers, i, "name",
mxCreateString(layer_names[i].c_str()));
mxSetField(mx_layers, i, "type",
mxCreateString(layers[i]->type_name().c_str()));
vector<shared_ptr<Blob<float> > >& layer_blobs = layers[i]->blobs();
if (layer_blobs.size() == 0) {
continue;
}
const int num_blobs[1] = {layer_blobs.size()};
mx_blob = mxCreateStructArray(1, num_blobs, 5, blobfnames);
for (unsigned int j = 0; j < layer_blobs.size(); ++j) {
mxSetField(mx_blob, j, "num",
mxCreateDoubleScalar(layer_blobs[j]->num()));
mxSetField(mx_blob, j, "channels",
mxCreateDoubleScalar(layer_blobs[j]->channels()));
mxSetField(mx_blob, j, "height",
mxCreateDoubleScalar(layer_blobs[j]->height()));
mxSetField(mx_blob, j, "width",
mxCreateDoubleScalar(layer_blobs[j]->width()));
mxSetField(mx_blob, j, "count",
mxCreateDoubleScalar(layer_blobs[j]->count()));
}
mxSetField(mx_layers, i, "weights", mx_blob);
}
}
return mx_layers;
}
static mxArray* do_get_blobs_info() {
const vector<shared_ptr<Blob<float> > >& blobs = net_->blobs();
const vector<string>& blob_names = net_->blob_names();
// Step 1: prepare output array of structures
mxArray* mx_blobs;
{
const int num_blobs[1] = {blobs.size()};
const char* fnames[6] = {"name", "num", "channels",
"height", "width", "count"};
mx_blobs = mxCreateStructArray(1, num_blobs, 6, fnames);
}
// Step 2: copy info into output
{
for (unsigned int i = 0; i < blobs.size(); ++i) {
mxSetField(mx_blobs, i, "name",
mxCreateString(blob_names[i].c_str()));
mxSetField(mx_blobs, i, "num",
mxCreateDoubleScalar(blobs[i]->num()));
mxSetField(mx_blobs, i, "channels",
mxCreateDoubleScalar(blobs[i]->channels()));
mxSetField(mx_blobs, i, "height",
mxCreateDoubleScalar(blobs[i]->height()));
mxSetField(mx_blobs, i, "width",
mxCreateDoubleScalar(blobs[i]->width()));
mxSetField(mx_blobs, i, "count",
mxCreateDoubleScalar(blobs[i]->count()));
}
}
return mx_blobs;
}
static mxArray* do_get_blob_data(const mxArray* const blob_name) {
// const vector<shared_ptr<Blob<float> > >& blobs = net_->blobs();
// const vector<string>& blob_names = net_->blob_names();
char* c_blob_name = mxArrayToString(blob_name);
DLOG(INFO) << "Looking for: " << c_blob_name;
mxArray* mx_blob_data = NULL;
if (net_->has_blob(c_blob_name)) {
mx_blob_data = blob_data_to_mxarray(net_->blob_by_name(c_blob_name).get());
}
// for (unsigned int i = 0; i < blobs.size(); ++i) {
// DLOG(INFO) << blob_names[i];
// if (strcmp(blob_names[i].c_str(), c_blob_name) == 0) {
// mx_blob_data = blob_data_to_mxarray(blobs[i]);
// }
// }
return mx_blob_data;
}
static mxArray* do_get_blob_diff(const mxArray* const blob_name) {
// const vector<shared_ptr<Blob<float> > >& blobs = net_->blobs();
// const vector<string>& blob_names = net_->blob_names();
char* c_blob_name = mxArrayToString(blob_name);
DLOG(INFO) << "Looking for: " << c_blob_name;
mxArray* mx_blob_diff = NULL;
if (net_->has_blob(c_blob_name)) {
mx_blob_diff = blob_diff_to_mxarray(net_->blob_by_name(c_blob_name).get());
}
// for (unsigned int i = 0; i < blobs.size(); ++i) {
// DLOG(INFO) << blob_names[i];
// if (strcmp(blob_names[i].c_str(),c_blob_name) == 0) {
// mx_blob_diff = blob_diff_to_mxarray(blobs[i]);
// }
// }
return mx_blob_diff;
}
static mxArray* do_get_all_data() {
const vector<shared_ptr<Blob<float> > >& blobs = net_->blobs();
const vector<string>& blob_names = net_->blob_names();
// Step 1: prepare output array of structures
mxArray* mx_all_data;
{
const int num_blobs[1] = {blobs.size()};
const char* fnames[2] = {"name", "data"};
mx_all_data = mxCreateStructArray(1, num_blobs, 2, fnames);
}
for (unsigned int i = 0; i < blobs.size(); ++i) {
DLOG(INFO) << blob_names[i];
mwSize dims[4] = {blobs[i]->width(), blobs[i]->height(),
blobs[i]->channels(), blobs[i]->num()};
DLOG(INFO) << dims[0] << " " << dims[1] << " " << dims[2] << " " << dims[3];
mxArray* mx_blob_data = blob_data_to_mxarray(blobs[i]);
mxSetField(mx_all_data, i, "name",
mxCreateString(blob_names[i].c_str()));
mxSetField(mx_all_data, i, "data", mx_blob_data);
}
return mx_all_data;
}
static mxArray* do_get_all_diff() {
const vector<shared_ptr<Blob<float> > >& blobs = net_->blobs();
const vector<string>& blob_names = net_->blob_names();
// Step 1: prepare output array of structures
mxArray* mx_all_diff;
{
const int num_blobs[1] = {blobs.size()};
const char* fnames[2] = {"name", "diff"};
mx_all_diff = mxCreateStructArray(1, num_blobs, 2, fnames);
}
for (unsigned int i = 0; i < blobs.size(); ++i) {
DLOG(INFO) << blob_names[i];
mwSize dims[4] = {blobs[i]->width(), blobs[i]->height(),
blobs[i]->channels(), blobs[i]->num()};
DLOG(INFO) << dims[0] << " " << dims[1] << " " << dims[2] << " " << dims[3];
mxArray* mx_blob_diff = blob_diff_to_mxarray(blobs[i]);
mxSetField(mx_all_diff, i, "name",
mxCreateString(blob_names[i].c_str()));
mxSetField(mx_all_diff, i, "diff", mx_blob_diff);
}
return mx_all_diff;
}
static void get_weights(MEX_ARGS) {
plhs[0] = do_get_weights();
}
static void get_layer_weights(MEX_ARGS) {
if (nrhs != 1) {
LOG(ERROR) << "Only given " << nrhs << " arguments";
mexErrMsgTxt("Wrong number of arguments");
}
plhs[0] = do_get_layer_weights(prhs[0]);
}
static void set_weights(MEX_ARGS) {
if (nrhs != 1) {
LOG(ERROR) << "Given " << nrhs << " arguments expecting 1";
mexErrMsgTxt("Wrong number of arguments");
}
const mxArray* const mx_weights = prhs[0];
if (!mxIsStruct(mx_weights)) {
mexErrMsgTxt("Input needs to be struct");
}
int num_layers = mxGetNumberOfElements(mx_weights);
for (int i = 0; i < num_layers; ++i) {
const mxArray* layer_name= mxGetField(mx_weights, i, "layer_names");
const mxArray* weights= mxGetField(mx_weights, i, "weights");
do_set_layer_weights(layer_name, weights);
}
}
static void set_layer_weights(MEX_ARGS) {
if (nrhs != 2) {
LOG(ERROR) << "Only given " << nrhs << " arguments";
mexErrMsgTxt("You need 2 arguments layer_name and cell of weights");
}
do_set_layer_weights(prhs[0], prhs[1]);
}
static void get_layers_info(MEX_ARGS) {
plhs[0] = do_get_layers_info();
}
static void get_blobs_info(MEX_ARGS) {
plhs[0] = do_get_blobs_info();
}
static void get_blob_data(MEX_ARGS) {
if (nrhs != 1) {
LOG(ERROR) << "Only given " << nrhs << " arguments";
mexErrMsgTxt("Wrong number of arguments");
}
plhs[0] = do_get_blob_data(prhs[0]);
}
static void get_blob_diff(MEX_ARGS) {
if (nrhs != 1) {
LOG(ERROR) << "Only given " << nrhs << " arguments";
mexErrMsgTxt("Wrong number of arguments");
}
plhs[0] = do_get_blob_diff(prhs[0]);
}
static void get_all_data(MEX_ARGS) {
if (nrhs != 0) {
LOG(ERROR) << "Only given " << nrhs << " arguments";
mexErrMsgTxt("Wrong number of arguments");
}
plhs[0] = do_get_all_data();
}
static void get_all_diff(MEX_ARGS) {
if (nrhs != 0) {
LOG(ERROR) << "Only given " << nrhs << " arguments";
mexErrMsgTxt("Wrong number of arguments");
}
plhs[0] = do_get_all_diff();
}
static void set_mode_cpu(MEX_ARGS) {
Caffe::set_mode(Caffe::CPU);
}
static void set_mode_gpu(MEX_ARGS) {
Caffe::set_mode(Caffe::GPU);
}
static void get_mode(MEX_ARGS) {
int mode = Caffe::mode();
if (mode == Caffe::CPU) {
// CPU mode
plhs[0] = mxCreateString("CPU");
}
if (mode == Caffe::GPU) {
// GPU mode
plhs[0] = mxCreateString("GPU");
}
}
static void set_phase_train(MEX_ARGS) {
Caffe::set_phase(Caffe::TRAIN);
}
static void set_phase_test(MEX_ARGS) {
Caffe::set_phase(Caffe::TEST);
}
static void get_phase(MEX_ARGS) {
int phase = Caffe::phase();
if (phase == Caffe::TRAIN) {
// Train phase
plhs[0] = mxCreateString("TRAIN");
}
if (phase == Caffe::TEST) {
// Test phase
plhs[0] = mxCreateString("TEST");
}
}
static void set_device(MEX_ARGS) {
if (nrhs != 1) {
LOG(ERROR) << "Only given " << nrhs << " arguments";
mexErrMsgTxt("Wrong number of arguments");
}
int device_id = static_cast<int>(mxGetScalar(prhs[0]));
Caffe::SetDevice(device_id);
}
static void get_device(MEX_ARGS) {
int device_id = Caffe::GetDevice();
plhs[0] = mxCreateDoubleScalar(device_id);
}
static void get_init_key(MEX_ARGS) {
plhs[0] = mxCreateDoubleScalar(init_key);
}
static void init(MEX_ARGS) {
if (nrhs != 2) {
LOG(ERROR) << "Only given " << nrhs << " arguments";
mexErrMsgTxt("Needs 2 arguments param_file and model_file");
}
char* param_file = mxArrayToString(prhs[0]);
char* model_file = mxArrayToString(prhs[1]);
CheckFile(string(param_file));
net_.reset(new Net<float>(string(param_file)));
CheckFile(string(model_file));
// net_->CopyTrainedLayersFrom(string(model_file));
net_->CopyTrainedLayersWithMoreSourceChannelFrom(string(model_file));
mxFree(param_file);
mxFree(model_file);
init_key = random(); // NOLINT(caffe/random_fn)
if (nlhs == 1) {
plhs[0] = mxCreateDoubleScalar(init_key);
}
}
static void init_net(MEX_ARGS) {
if (nrhs != 1) {
LOG(ERROR) << "Only given " << nrhs << " arguments";
mexErrMsgTxt("Wrong number of arguments");
}
char* param_file = mxArrayToString(prhs[0]);
CheckFile(string(param_file));
net_.reset(new Net<float>(string(param_file)));
mxFree(param_file);
init_key = random(); // NOLINT(caffe/random_fn)
if (nlhs == 1) {
plhs[0] = mxCreateDoubleScalar(init_key);
}
}
static void load_net(MEX_ARGS) {
if (nrhs != 1) {
LOG(ERROR) << "Given " << nrhs << " arguments";
mexErrMsgTxt("Wrong number of arguments");
}
if (net_) {
char* model_file = mxArrayToString(prhs[0]);
CheckFile(string(model_file));
//net_->CopyTrainedLayersFrom(string(model_file));
LOG(INFO)<<"CopyTrainedLayersWithMoreSourceChannelFrom "<<string(model_file);
net_->CopyTrainedLayersWithMoreSourceChannelFrom(string(model_file));
mxFree(model_file);
init_key = random(); // NOLINT(caffe/random_fn)
if (nlhs == 1) {
plhs[0] = mxCreateDoubleScalar(init_key);
}
} else {
mexErrMsgTxt("Need to initialize the network first with init_net");
}
}
static void save_net(MEX_ARGS) {
if (nrhs != 1) {
LOG(ERROR) << "Only given " << nrhs << " arguments";
mexErrMsgTxt("Wrong number of arguments");
}
if (net_) {
char* model_file = mxArrayToString(prhs[0]);
NetParameter net_param;
net_->ToProto(&net_param, false);
WriteProtoToBinaryFile(net_param, model_file);
CheckFile(string(model_file));
mxFree(model_file);
} else {
mexErrMsgTxt("Need to have a network to save");
}
}
static void reset(MEX_ARGS) {
if (net_) {
net_.reset();
init_key = -2;
mexWarnMsgTxt("Network reset, call init before use it again");
}
}
static void forward(MEX_ARGS) {
if (nrhs > 1) {
LOG(ERROR) << "Given " << nrhs << " arguments";
mexErrMsgTxt("Too may arguments");
}
plhs[1] = mxCreateNumericMatrix(1, 1, mxSINGLE_CLASS, mxREAL);
//LOG(INFO)<<"# of nrhs in forward function = "<<nrhs;
if (nrhs == 0) {
// Forward without arguments behaves as forward_prefilled
plhs[0] = do_forward_prefilled(plhs[1]);
} else {
plhs[0] = do_forward(prhs[0], plhs[1]);
}
}
static void forward_prefilled(MEX_ARGS) {
if (nrhs != 0) {
LOG(ERROR) << "Given " << nrhs << " arguments";
mexErrMsgTxt("It takes no arguments");
}
plhs[1] = mxCreateNumericMatrix(1, 1, mxSINGLE_CLASS, mxREAL);
plhs[0] = do_forward_prefilled(plhs[1]);
}
static void set_input_blobs(MEX_ARGS) {
if (nrhs != 1) {
LOG(ERROR) << "Given " << nrhs << " arguments";
mexErrMsgTxt("It takes one argument");
}
do_set_input_blobs(prhs[0]);
}
static void backward(MEX_ARGS) {
if (nrhs > 1) {
LOG(ERROR) << "Given " << nrhs << " arguments";
mexErrMsgTxt("Too many input arguments");
}
if (nrhs == 0) {
// Backward without arguments behaves as backward_prefilled
plhs[0] = do_backward_prefilled();
} else {
plhs[0] = do_backward(prhs[0]);
}
}
static void backward_prefilled(MEX_ARGS) {
if (nrhs != 0) {
LOG(ERROR) << "Given " << nrhs << " arguments";
mexErrMsgTxt("It takes no arguments");
}
plhs[0] = do_backward_prefilled();
}
static void set_output_blobs(MEX_ARGS) {
if (nrhs != 1) {
LOG(ERROR) << "Given " << nrhs << " arguments";
mexErrMsgTxt("It takes one argument");
}
do_set_output_blobs(prhs[0]);
}
static void is_initialized(MEX_ARGS) {
if (!net_) {
plhs[0] = mxCreateDoubleScalar(0);
} else {
plhs[0] = mxCreateDoubleScalar(1);
}
}
static void read_mean(MEX_ARGS) {
if (nrhs != 1) {
mexErrMsgTxt("Usage: caffe('read_mean', 'path_to_binary_mean_file'");
return;
}
const string& mean_file = mxArrayToString(prhs[0]);
Blob<float> data_mean;
LOG(INFO) << "Loading mean file from" << mean_file;
BlobProto blob_proto;
bool result = ReadProtoFromBinaryFile(mean_file.c_str(), &blob_proto);
if (!result) {
mexErrMsgTxt("Couldn't read the file");
return;
}
data_mean.FromProto(blob_proto);
mwSize dims[4] = {data_mean.width(), data_mean.height(),
data_mean.channels(), data_mean.num() };
mxArray* mx_blob = mxCreateNumericArray(4, dims, mxSINGLE_CLASS, mxREAL);
float* data_ptr = reinterpret_cast<float*>(mxGetPr(mx_blob));
caffe_copy(data_mean.count(), data_mean.cpu_data(), data_ptr);
mexWarnMsgTxt("Remember that Caffe saves in [width, height, channels]"
" format and channels are also BGR!");
plhs[0] = mx_blob;
}
/** -----------------------------------------------------------------
** Available commands.
**/
struct handler_registry {
string cmd;
void (*func)(MEX_ARGS);
};
static handler_registry handlers[] = {
// Public API functions
{ "forward", forward },
{ "backward", backward },
{ "forward_prefilled", forward_prefilled },
{ "backward_prefilled", backward_prefilled},
{ "set_input_blobs", set_input_blobs },
{ "set_output_blobs", set_output_blobs },
{ "init", init },
{ "init_net", init_net },
{ "load_net", load_net },
{ "save_net", save_net },
{ "is_initialized", is_initialized },
{ "set_mode_cpu", set_mode_cpu },
{ "set_mode_gpu", set_mode_gpu },
{ "get_mode", get_mode },
{ "set_phase_train", set_phase_train },
{ "set_phase_test", set_phase_test },
{ "get_phase", get_phase },
{ "set_device", set_device },
{ "get_device", get_device },
{ "get_weights", get_weights },
{ "set_weights", set_weights },
{ "get_layer_weights", get_layer_weights },
{ "set_layer_weights", set_layer_weights },
{ "get_layers_info", get_layers_info },
{ "get_blobs_info", get_blobs_info },
{ "get_blob_data", get_blob_data },
{ "get_blob_diff", get_blob_diff },
{ "get_all_data", get_all_data },
{ "get_all_diff", get_all_diff },
{ "get_init_key", get_init_key },
{ "reset", reset },
{ "read_mean", read_mean },
// The end.
{ "END", NULL },
};
/** -----------------------------------------------------------------
** matlab entry point: caffe(api_command, arg1, arg2, ...)
**/
void mexFunction(MEX_ARGS) {
if (nrhs == 0) {
LOG(ERROR) << "No API command given";
mexErrMsgTxt("An API command is required");
return;
}
{ // Handle input command
char *cmd = mxArrayToString(prhs[0]);
bool dispatched = false;
// Dispatch to cmd handler
for (int i = 0; handlers[i].func != NULL; i++) {
if (handlers[i].cmd.compare(cmd) == 0) {
handlers[i].func(nlhs, plhs, nrhs-1, prhs+1);
dispatched = true;
break;
}
}
if (!dispatched) {
LOG(ERROR) << "Unknown command `" << cmd << "'";
mexErrMsgTxt("API command not recognized");
}
mxFree(cmd);
}
}
| 32.518
| 92
| 0.622486
|
xiaomi646
|
457dfbafaa9141a0f680038f32d9ed0a3f4be5c7
| 2,373
|
cpp
|
C++
|
zinot-utils/zinot-utils/zimesh-json/ZimeshJsonDao.cpp
|
patrykbajos/zinot-project
|
f5ab158bce6855b25b7f23c873f64bc4a9c867ba
|
[
"MIT"
] | null | null | null |
zinot-utils/zinot-utils/zimesh-json/ZimeshJsonDao.cpp
|
patrykbajos/zinot-project
|
f5ab158bce6855b25b7f23c873f64bc4a9c867ba
|
[
"MIT"
] | null | null | null |
zinot-utils/zinot-utils/zimesh-json/ZimeshJsonDao.cpp
|
patrykbajos/zinot-project
|
f5ab158bce6855b25b7f23c873f64bc4a9c867ba
|
[
"MIT"
] | null | null | null |
//
// Created by patryk on 01.11.16.
//
#include "ZimeshJsonDao.hpp"
namespace Zimesh
{
namespace RootKeys
{
static const QString matsKey = "materials";
static const QString meshesKey = "meshes";
static const QString objectsKey = "objects";
}
bool ZimeshJsonDao::loadFromJsonDoc(const QJsonDocument & jsonDoc)
{
if (!jsonDoc.isObject())
return false;
QJsonObject jsonObj = jsonDoc.object();
if (jsonObj.contains(RootKeys::matsKey))
{
QJsonValue matsVal = jsonObj[RootKeys::matsKey];
if (!loadMaterials(matsVal))
return false;
}
if (jsonObj.contains(RootKeys::meshesKey))
{
QJsonValue meshesVal = jsonObj[RootKeys::meshesKey];
if (!loadMeshes(meshesVal))
return false;
}
if (jsonObj.contains(RootKeys::objectsKey))
{
QJsonValue objsVal = jsonObj[RootKeys::objectsKey];
if (!loadObjects(objsVal))
return false;
}
return true;
}
bool ZimeshJsonDao::loadMaterials(const QJsonValue & jsonVal)
{
if (!jsonVal.isObject())
return false;
QJsonObject matsObj = jsonVal.toObject();
for (QJsonObject::Iterator it = matsObj.begin(); it != matsObj.end(); ++it)
{
QString matName = it.key();
QJsonValueRef matVal = it.value();
MaterialDao & matDao = materials[matName];
if (!matDao.loadFromJsonValue(matName, matVal))
return false;
}
return true;
}
bool ZimeshJsonDao::loadMeshes(const QJsonValue & jsonVal)
{
if (!jsonVal.isObject())
return false;
QJsonObject meshesObj = jsonVal.toObject();
for (QJsonObject::Iterator it = meshesObj.begin(); it != meshesObj.end(); ++it)
{
QString meshName = it.key();
QJsonValueRef meshVal = it.value();
MeshDao & meshDao = meshes[meshName];
if (!meshDao.loadFromJsonValue(meshName, meshVal))
return false;
}
return true;
}
bool ZimeshJsonDao::loadObjects(const QJsonValue & jsonVal)
{
if (!jsonVal.isObject())
return false;
QJsonObject objectsObj = jsonVal.toObject();
for (QJsonObject::Iterator it = objectsObj.begin(); it != objectsObj.end(); ++it)
{
QString objectName = it.key();
QJsonValueRef objectVal = it.value();
ObjectDao & objectDao = objects[objectName];
if (!objectDao.loadFromJsonValue(objectName, objectVal))
return false;
}
return true;
}
}
| 23.264706
| 84
| 0.654867
|
patrykbajos
|
4581249165c77cf827281593ce318225a20a6450
| 337
|
cpp
|
C++
|
Soldier_Alien/Medic.cpp
|
RoshanMhatre/cpp
|
689f5b7a0b65b783c6f20c501321dceb187f21c8
|
[
"MIT"
] | null | null | null |
Soldier_Alien/Medic.cpp
|
RoshanMhatre/cpp
|
689f5b7a0b65b783c6f20c501321dceb187f21c8
|
[
"MIT"
] | null | null | null |
Soldier_Alien/Medic.cpp
|
RoshanMhatre/cpp
|
689f5b7a0b65b783c6f20c501321dceb187f21c8
|
[
"MIT"
] | 1
|
2020-10-04T05:24:35.000Z
|
2020-10-04T05:24:35.000Z
|
#include <string>
#include "Medic.h"
void Medic::setHasMedicine(bool hasMedicineIn) {
hasMedicine = hasMedicineIn;
}
bool Medic:: getHasMedicine() {
return hasMedicine;
}
void Medic::attack(){
cout << "The Medic shoots his Laser Pistol at an enemy and quickly ducks behind cover to adminster pain meds to his comrade!!" << endl;
}
| 22.466667
| 136
| 0.732938
|
RoshanMhatre
|
458568cc1159697267ea27d53dc1042366646121
| 1,712
|
hpp
|
C++
|
Core/cpp/TBq25121.hpp
|
zaqwsx1277/prMobileReader
|
83a13b821458bbe8d1ec46570828aa69d57254e2
|
[
"MIT"
] | null | null | null |
Core/cpp/TBq25121.hpp
|
zaqwsx1277/prMobileReader
|
83a13b821458bbe8d1ec46570828aa69d57254e2
|
[
"MIT"
] | null | null | null |
Core/cpp/TBq25121.hpp
|
zaqwsx1277/prMobileReader
|
83a13b821458bbe8d1ec46570828aa69d57254e2
|
[
"MIT"
] | null | null | null |
/*
* TBq25121.hpp
*
* Created on: Jul 8, 2021
* Author: AAL
*/
#ifndef CPP_TBQ25121_HPP_
#define CPP_TBQ25121_HPP_
#include <i2c.h>
#include <TUnit.hpp>
namespace unit {
constexpr uint8_t defBq25121Adrr { 0x6A } ; ///< I2C адрес чипа BQ25121
constexpr uint8_t defBq25121AddrRead { (defBq25121Adrr << 1) + 1 } ;///< I2C адрес чипа BQ25121 для чтения
constexpr uint8_t defBq25121AddrWrite (defBq25121Adrr << 1) ; ///< I2C адрес чипа BQ25121 для записи
constexpr uint8_t defBq25121Cmd_00 [] { 0x00, 0x00 } ;
constexpr uint8_t defBq25121Cmd_01 [] { 0x01, 0x00 } ;
constexpr uint8_t defBq25121Cmd_02 [] { 0x02, 0x88 } ;
constexpr uint8_t defBq25121Cmd_03 [] { 0x03, 0x8C } ;
constexpr uint8_t defBq25121Cmd_04 [] { 0x04, 0x26 } ;
constexpr uint8_t defBq25121Cmd_05 [] { 0x05, 0x78 } ;
constexpr uint8_t defBq25121Cmd_06 [] { 0x06, 0xFE } ;
constexpr uint8_t defBq25121Cmd_07 [] { 0x07, 0xD0 } ;
constexpr uint8_t defBq25121Cmd_08 [] { 0x08, 0x48 } ;
constexpr uint8_t defBq25121Cmd_09 [] { 0x09, 0x3A } ;
constexpr uint8_t defBq25121Cmd_0B [] { 0x0B, 0x34 } ;
constexpr uint8_t defBq25121Cmd_reset [] { 0x09, 0x80 } ;
constexpr uint32_t defBq25121TimeOut { 100 } ; ///< Таймаут для работы по шине I2C
/*!
* Класс для работы с чипом BQ25121
*/
class TBq25121 : public unit::TUnit {
public:
TBq25121();
virtual ~TBq25121();
bool check () ; ///< Проверка работоспособности чипа BQ25121
void init () ; ///< Инициализация устройства
void sleep () { ; } ///< Перевод в режим энергосбережения
void wakeup () { ; } ///< Выход из режима энергосбережения
bool process () { return true ; } ///< Получение данных
};
} /* namespace unit */
#endif /* CPP_TBQ25121_HPP_ */
| 30.035088
| 106
| 0.691589
|
zaqwsx1277
|
458e0d25fdc92876ede8278f3fcca7c0005f644b
| 2,608
|
cpp
|
C++
|
src/Scene/TxWidgetPane.cpp
|
jimbo00000/Rift-Volume
|
478779c8c38403ed37b3a6a9a19cc222ca95b8b4
|
[
"MIT"
] | 1
|
2015-06-27T21:00:31.000Z
|
2015-06-27T21:00:31.000Z
|
src/Scene/TxWidgetPane.cpp
|
jimbo00000/Rift-Volume
|
478779c8c38403ed37b3a6a9a19cc222ca95b8b4
|
[
"MIT"
] | null | null | null |
src/Scene/TxWidgetPane.cpp
|
jimbo00000/Rift-Volume
|
478779c8c38403ed37b3a6a9a19cc222ca95b8b4
|
[
"MIT"
] | null | null | null |
// TxWidgetPane.cpp
#include "TxWidgetPane.h"
#ifdef __APPLE__
#include "opengl/gl.h"
#endif
#ifdef _WIN32
# define WINDOWS_LEAN_AND_MEAN
# define NOMINMAX
# include <windows.h>
#endif
#define _USE_MATH_DEFINES
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <GL/glew.h>
#include "Logger.h"
TxWidgetPane::TxWidgetPane()
: Pane()
, m_holdingMouseButton(false)
{
}
TxWidgetPane::~TxWidgetPane()
{
}
void TxWidgetPane::initGL()
{
Pane::initGL();
m_txWidg.initGL();
const int hm = 50;
const glm::ivec2 fbsz = GetFBOSize();
const glm::ivec4 r(hm, hm, fbsz.x - 2*hm, 300);
m_txWidg.SetRect(r);
}
void TxWidgetPane::DrawToFBO() const
{
if (MouseCursorActive() || !m_tx.m_lockedAtClickPos)
glClearColor(0.25f, 0.25f, 0.25f, 0.0f);
else
glClearColor(0,0,0,0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
///@todo Remove this fixed-function stuff
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
const glm::ivec2 fbsz = GetFBOSize();
glOrtho(0, fbsz.x, 0, fbsz.y, -2.0f, 2.0f);
GLint prog;
glGetIntegerv(GL_CURRENT_PROGRAM, &prog);
glUseProgram(0);
m_txWidg.Display();
glUseProgram(prog);
glDisable(GL_DEPTH_TEST);
DrawCursor();
glEnable(GL_DEPTH_TEST);
}
void TxWidgetPane::DrawPaneWithShader(
const glm::mat4&, // modelview
const glm::mat4&, // projection
const ShaderWithVariables& sh) const
{
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, m_paneRenderBuffer.tex);
glUniform1i(sh.GetUniLoc("fboTex"), 0);
glUniform1f(sh.GetUniLoc("u_brightness"), MouseCursorActive() ? 1.f : .5f);
sh.bindVAO();
{
glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
}
glBindVertexArray(0);
}
void TxWidgetPane::timestep(double absTime, double dt)
{
Pane::timestep(absTime, dt);
}
void TxWidgetPane::OnMouseClick(int state, int x, int y)
{
///@todo This seems redundant...
const glm::ivec2 fbsz = GetFBOSize();
const int mx = static_cast<int>( m_pointerCoords.x * static_cast<float>(fbsz.x) );
const int my = static_cast<int>( (1.0f-m_pointerCoords.y) * static_cast<float>(fbsz.y) );
m_txWidg.OnMouseClick(mx, my);
m_holdingMouseButton = (state == 1);
}
void TxWidgetPane::OnMouseMove(int x, int y)
{
if (m_holdingMouseButton)
{
const glm::ivec2 fbsz = GetFBOSize();
m_txWidg.OnMouseMove(x,fbsz.y-y);
}
}
| 22.678261
| 94
| 0.640337
|
jimbo00000
|
4594e56fa8091f501b33b73bce85c2bcafa76da4
| 758
|
cpp
|
C++
|
dataset/test/modification/1486_all/4/transformation_1.cpp
|
Karina5005/Plagiarism
|
ce11f72ba21a754ca84a27e5f26a31a19d6cb6fb
|
[
"MIT"
] | 3
|
2022-02-15T00:29:39.000Z
|
2022-03-15T08:36:44.000Z
|
dataset/test/modification/1486_all/4/transformation_1.cpp
|
Kira5005-code/Plagiarism
|
ce11f72ba21a754ca84a27e5f26a31a19d6cb6fb
|
[
"MIT"
] | null | null | null |
dataset/test/modification/1486_all/4/transformation_1.cpp
|
Kira5005-code/Plagiarism
|
ce11f72ba21a754ca84a27e5f26a31a19d6cb6fb
|
[
"MIT"
] | null | null | null |
#include <iomanip>
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
void ai() ;
int main() ;
void khi_beh() {
int ddk;
cin >> ddk;
vector<int> j(ddk);
for (auto &sdd_oyq : j)
cin >> sdd_oyq;
long long tj_ccb = 0, y = 0;
{
int pub_be = 0;
if (5 > 3) cout << "new code";for ( ; pub_be < ddk; )
/* 'for' inside */
{
y += pub_be;
tj_ccb += j[pub_be];
/* 'if' begin */
if (tj_ccb < y) /* 'if' inside */
{
cout << "NO\n";
return;
}
++pub_be;
}}
cout << "YES\n";
}
int main() {
int dx;
cin >> dx;
if (5 > 3) cout << "new code";for ( ; dx--; )
/* 'for' inside */
khi_beh();
return 0;
}
| 16.12766
| 58
| 0.435356
|
Karina5005
|
45aff9fed7cff72b5b613bab8974cb66edefd955
| 6,620
|
cpp
|
C++
|
AVTools/Module/PCMToWAV/PCMToWAV.cpp
|
XiaopingSun/AVTools
|
cd04e54036576c479debbb1f8cbefeceb0c16db9
|
[
"MIT"
] | null | null | null |
AVTools/Module/PCMToWAV/PCMToWAV.cpp
|
XiaopingSun/AVTools
|
cd04e54036576c479debbb1f8cbefeceb0c16db9
|
[
"MIT"
] | null | null | null |
AVTools/Module/PCMToWAV/PCMToWAV.cpp
|
XiaopingSun/AVTools
|
cd04e54036576c479debbb1f8cbefeceb0c16db9
|
[
"MIT"
] | 1
|
2021-11-08T12:13:57.000Z
|
2021-11-08T12:13:57.000Z
|
//
// PCMToWAV.cpp
// AVTools
//
// Created by WorkSpace_Sun on 2021/5/9.
//
#include "PCMToWAV.h"
#include <getopt.h>
#include <CoreFoundation/CoreFoundation.h>
#include <stdlib.h>
// 所谓的大端模式(Big Endian),是指数据的低位保存在内存的高地址中,而数据的高位,保存在内存的低地址中。
// 所谓的小端模式(Little Endian),是指数据的低位保存在内存的低地址中,而数据的高位保存在内存的高地址中。
#pragma pack(1)
typedef struct tag_WAV_RIFF_CHUNK {
uint32_t ID; // 'RIFF'标识 Big Endian 4Byte 内存:0x52494646
uint32_t size; // 整个wav文件的长度减去ID和size的长度 Little Endian 4Byte
uint32_t type; // type是'WAVE'标识后边需要两个字块:fmt区块和data区块 Big Endian 4Byte 内存:0x57415645
} WAV_RIFF_CHUNK;
#pragma pack(1)
typedef struct tag_WAV_FMT_CHUNK {
uint32_t ID; // 'fmt '标识 Big Endian 4Byte 内存:0x666D7420
uint32_t size; // fmt区块的长度 不包含ID和size的长度 Little Endian 4Byte 16
uint16_t audio_format; // 标识data区块存储的音频数据格式 PCM为1 Little Endian 2Byte
uint16_t num_channels; // 标识音频数据的声道数 1:单声道 2:双声道 Little Endian 2Byte
uint32_t sample_rate; // 标识音频数据的采样率 Little Endian 4Byte
uint32_t byte_rate; // 每秒数据字节数 = sample_rate * num_channels * bits_per_sample / 8 Little Endian 4Byte
uint16_t block_align; // 每个采样所需的字节数 = num_channels * bits_per_sample / 8 Little Endian 2Byte
uint16_t bits_per_sample; // 每个采样存储的bit数 Little Endian 2Byte
} WAV_FMT_CHUNK;
#pragma pack(1)
typedef struct tag_WAV_DATA_CHUNK {
uint32_t ID; // 'data'标识 Big Endian 4Byte 内存:0x64617461
uint32_t size; // 标识音频数据的长度 = byte_rate * seconds Little Endian 4Byte
void *data; // 音频数据 Little Endian
} WAV_DATA_CHUNK;
static struct option tool_long_options[] = {
{"help", no_argument, NULL, '`'}
};
static void convert(char *url, int sample_rate, int channel_count, int sample_bit_depth);
/**
* Print Module Help
*/
static void show_module_help() {
printf("Support Format:\n\n");
printf(" - U8\n");
printf(" - S16\n");
printf(" - S32\n");
printf("\n");
printf("Param:\n\n");
printf(" -i: Input File Local Path\n");
printf(" -r: Sample Rate\n");
printf(" -b: Sample Bit Depth\n");
printf(" -c: Channel Count\n");
printf("\n");
printf("Usage:\n\n");
printf(" AVTools PCMToWAV -r 44100 -c 2 -b 16 -i s16le.pcm\n\n");
printf("Get PCM With FFMpeg From Mp4 File:\n\n");
printf(" ffmpeg -i 1.mp4 -vn -ar 44100 -ac 2 -f s16le s16le.pcm\n");
}
/**
* Parse Cmd
* @param argc From main.cpp
* @param argv From main.cpp
*/
void pcm_to_wav_parse_cmd(int argc, char *argv[]) {
int option = 0; // getopt_long的返回值,返回匹配到字符的ascii码,没有匹配到可读参数时返回-1
char *url = NULL; // 输入文件路径
int sample_rate = 0;
int channel_count = 0;
int sample_bit_depth = 0;
while (EOF != (option = getopt_long(argc, argv, "i:r:c:b:", tool_long_options, NULL))) {
switch (option) {
case '`':
show_module_help();
return;
break;
case 'i':
url = optarg;
break;
case 'r':
sample_rate = atoi(optarg);
break;
case 'c':
channel_count = atoi(optarg);
break;
case 'b':
sample_bit_depth = atoi(optarg);
break;
case '?':
printf("Use 'AVTools %s --help' To Show Detail Usage.\n", argv[1]);
return;
break;
default:
break;
}
}
if (NULL == url || 0 == sample_rate || 0 == channel_count || 0 == sample_bit_depth) {
printf("PCMToWAV Param Error, Use 'AVTools %s --help' To Show Detail Usage.\n", argv[1]);
return;
}
convert(url, sample_rate, channel_count, sample_bit_depth);
}
/**
* Convert
* @param url Input PCM Url
* @param sample_rate Sample Rate
* @param channel_count Channel Count
* @param sample_bit_depth Sample Bit Depth
*/
static void convert(char *url, int sample_rate, int channel_count, int sample_bit_depth) {
WAV_RIFF_CHUNK riff_chunk = {0};
WAV_FMT_CHUNK fmt_chunk = {0};
WAV_DATA_CHUNK data_chunk = {0};
char output_url[100];
FILE *f_pcm = NULL;
FILE *f_wav = NULL;
size_t data_offset;
uint32_t data_length = 0;
// 拼接输出路径
sprintf(output_url, "%s.wav", url);
// 打开PCM文件
f_pcm = fopen(url, "rb");
if (!f_pcm) {
printf("PCMToWAV: Could Not Open PCM File.\n");
goto __FAIL;
}
// 打开WAV输出文件
f_wav = fopen(output_url, "wb+");
if (!f_wav) {
printf("PCMToWAV: Could Not Open Output Url.\n");
goto __FAIL;
}
// seek到音频数据的位置 先写入data
data_offset = sizeof(WAV_RIFF_CHUNK) + sizeof(WAV_FMT_CHUNK) + sizeof(data_chunk.ID) + sizeof(data_chunk.size);
fseek(f_wav, data_offset, SEEK_CUR);
data_chunk.data = (void *)malloc(channel_count * sample_bit_depth / 8);
// 写入data
while (!feof(f_pcm)) {
fread(data_chunk.data, 1, channel_count * sample_bit_depth / 8, f_pcm);
fwrite(data_chunk.data, 1, channel_count * sample_bit_depth / 8, f_wav);
data_length += channel_count * sample_bit_depth / 8;
}
// seek到wav文件头
rewind(f_wav);
// 写入WAV_RIFF_CHUNK
riff_chunk.ID = 0x46464952; // 'RIFF'
riff_chunk.size = sizeof(riff_chunk.type) + sizeof(WAV_FMT_CHUNK) + sizeof(data_chunk.ID) + sizeof(data_chunk.size) + data_length;
riff_chunk.type = 0x45564157; // 'WAVE'
fwrite(&riff_chunk, 1, sizeof(WAV_RIFF_CHUNK), f_wav);
// 写入WAV_FMT_CHUNK
fmt_chunk.ID = 0x20746D66; // 'fmt '
fmt_chunk.size = 0x00000010; // 16
fmt_chunk.audio_format = 0x0001; // 1:pcm
fmt_chunk.num_channels = channel_count;
fmt_chunk.sample_rate = sample_rate;
fmt_chunk.byte_rate = sample_rate * channel_count * sample_bit_depth / 8;
fmt_chunk.block_align = channel_count * sample_bit_depth / 8;
fmt_chunk.bits_per_sample = sample_bit_depth;
fwrite(&fmt_chunk, 1, sizeof(WAV_FMT_CHUNK), f_wav);
// 写WAV_DATA_CHUNK的ID和size
data_chunk.ID = 0x61746164; // 'data'
data_chunk.size = data_length;
fwrite(&data_chunk.ID, 1, sizeof(data_chunk.ID), f_wav);
fwrite(&data_chunk.size, 1, sizeof(data_chunk.size), f_wav);
free(data_chunk.data);
printf("Finish!\n");
__FAIL:
if (f_pcm) {
fclose(f_pcm);
}
if (f_wav) {
fclose(f_wav);
}
}
| 32.772277
| 134
| 0.601511
|
XiaopingSun
|
45b6295285df781545c08f304980377cfff86766
| 1,470
|
cpp
|
C++
|
KiteOpenGLDriverCore/manager/KiteDriverInputManager.cpp
|
awyhhwxz/KiteOpenGLDriver
|
cce0a67b93431d3958a485d0cc9420ecb6295d42
|
[
"BSD-3-Clause"
] | 2
|
2018-08-19T04:08:00.000Z
|
2018-08-19T04:08:44.000Z
|
KiteOpenGLDriverCore/manager/KiteDriverInputManager.cpp
|
awyhhwxz/KiteOpenGLDriver
|
cce0a67b93431d3958a485d0cc9420ecb6295d42
|
[
"BSD-3-Clause"
] | null | null | null |
KiteOpenGLDriverCore/manager/KiteDriverInputManager.cpp
|
awyhhwxz/KiteOpenGLDriver
|
cce0a67b93431d3958a485d0cc9420ecb6295d42
|
[
"BSD-3-Clause"
] | null | null | null |
#include "stdafx.h"
#include "KiteDriverInputManager.h"
namespace kite_driver
{
void KiteDriverInputManager::RegistryMouseMessageReceiver(std::shared_ptr<IMouseMessageReceiver> receiver)
{
_mouseMessageReceiver.push_back(receiver);
}
void KiteDriverInputManager::InvokeButtonDown(MouseButtonType button_type, const kite_math::Vector2f & screen_pos)
{
std::for_each(_mouseMessageReceiver.begin(), _mouseMessageReceiver.end(), [button_type, &screen_pos](const std::shared_ptr<IMouseMessageReceiver>& receiver)
{
receiver->OnButtonDown(button_type, screen_pos);
});
}
void KiteDriverInputManager::InvokeButtonUp(MouseButtonType button_type, const kite_math::Vector2f & screen_pos)
{
std::for_each(_mouseMessageReceiver.begin(), _mouseMessageReceiver.end(), [button_type, &screen_pos](const std::shared_ptr<IMouseMessageReceiver>& receiver)
{
receiver->OnButtonUp(button_type, screen_pos);
});
}
void KiteDriverInputManager::InvokeMouseMove(const kite_math::Vector2f & screen_pos)
{
std::for_each(_mouseMessageReceiver.begin(), _mouseMessageReceiver.end(), [&screen_pos](const std::shared_ptr<IMouseMessageReceiver>& receiver)
{
receiver->OnMouseMove(screen_pos);
});
}
void KiteDriverInputManager::OnMouseWheelRoll(float rollVal)
{
std::for_each(_mouseMessageReceiver.begin(), _mouseMessageReceiver.end(), [&rollVal](const std::shared_ptr<IMouseMessageReceiver>& receiver)
{
receiver->OnMouseWheelRoll(rollVal);
});
}
}
| 38.684211
| 158
| 0.785034
|
awyhhwxz
|
45b89169106cf3f68aeeb7eb3f8d04df6ef4e7f5
| 2,181
|
cpp
|
C++
|
test/test_02.cpp
|
shogun-toolbox/linger
|
953628ef636b7f87f5cdcbc6dd7367a1476ebc39
|
[
"BSD-3-Clause"
] | 1
|
2020-04-26T09:45:32.000Z
|
2020-04-26T09:45:32.000Z
|
test/test_02.cpp
|
shogun-toolbox/linger
|
953628ef636b7f87f5cdcbc6dd7367a1476ebc39
|
[
"BSD-3-Clause"
] | 2
|
2019-11-12T16:09:31.000Z
|
2020-09-09T18:52:43.000Z
|
test/test_02.cpp
|
shogun-toolbox/linger
|
953628ef636b7f87f5cdcbc6dd7367a1476ebc39
|
[
"BSD-3-Clause"
] | 3
|
2019-11-11T15:55:48.000Z
|
2020-06-02T20:33:48.000Z
|
#include "linear_algebra.hpp"
#include "test_new_number.hpp"
#include "test_new_engine.hpp"
#include "test_new_arithmetic.hpp"
using cx_float = std::complex<float>;
using cx_double = std::complex<double>;
using cx_newnum = std::complex<NewNum>;
using namespace STD_LA;
void t101()
{
PRINT_FN_NAME(t101);
fs_matrix<NewNum, 3, 4> fmp1;
fs_matrix<NewNum, 3, 4> fmp2;
dyn_matrix<NewNum> dmp1(3, 4);
fs_matrix<float, 3, 4> fmf1;
fs_matrix<double, 3, 4> fmd1;
dyn_matrix<double> dmd1(3, 4);
auto r0 = fmp1 + fmp2;
auto r1 = fmp1 + dmp1;
auto r2 = fmp1 + fmf1;
auto r3 = fmp1 + dmd1;
fs_matrix<cx_newnum, 3, 4> fmcp1;
auto r4 = fmcp1 + fmp2;
}
void t102()
{
PRINT_FN_NAME(t102);
fs_matrix<NewNum, 3, 4> fmp1;
fs_matrix<NewNum, 4, 5> fmp2;
dyn_matrix<NewNum> dmp1(4, 5);
fs_matrix<float, 4, 5> fmf1;
fs_matrix<double, 4, 5> fmd1;
dyn_matrix<double> dmd1(4, 5);
auto r0 = fmp1 * fmp2;
auto r1 = fmp1 * dmp1;
auto r2 = fmp1 * fmf1;
auto r3 = fmp1 * dmd1;
fs_matrix<cx_newnum, 3, 4> fmcp1;
auto r4 = fmcp1 * fmp2;
}
void t201()
{
PRINT_FN_NAME(t201);
fs_matrix_tst<NewNum, 3, 4> fmnn1;
fs_matrix_tst<NewNum, 3, 4> fmnn2;
dyn_matrix<NewNum> dmnn1(3, 4);
fs_matrix_tst<float, 3, 4> fmf1;
fs_matrix_tst<double, 3, 4> fmd1;
dyn_matrix<double> dmd1(3, 4);
auto r0 = fmnn1 + fmnn2;
auto r1 = fmnn1 + dmnn1;
auto r2 = fmnn1 + fmf1;
auto r3 = fmnn1 + dmd1;
fs_matrix<cx_newnum, 3, 4> fmcp1;
auto r4 = fmcp1 + fmnn2;
fs_matrix<float, 3, 4> fmf2;
fs_matrix<double, 3, 4> fmd2;
auto r5 = fmf1 + fmf2;
auto r6 = fmf2 + fmf1;
}
void t301()
{
PRINT_FN_NAME(t301);
fs_matrix<float, 4, 4> m1;
fs_vector<float, 4> v1, vr;
vr = m1 * v1;
}
void t100()
{
static_assert(is_matrix_element_v<NewNum>);
static_assert(is_matrix_element_v<cx_newnum>);
t101();
t102();
t201();
t301();
}
| 21.174757
| 50
| 0.559835
|
shogun-toolbox
|
45c1b6288ccde4ba47fe83d58fa7ff82b571c092
| 127
|
cpp
|
C++
|
src/engine/MeshRenderer.cpp
|
alextrevisan/3dfx-glide-game-engine
|
9a47c65d3705fb7b43e59cf90432b053f467e844
|
[
"MIT"
] | 4
|
2020-06-02T22:29:11.000Z
|
2021-03-01T18:38:18.000Z
|
src/engine/MeshRenderer.cpp
|
alextrevisan/3dfx-glide-game-engine
|
9a47c65d3705fb7b43e59cf90432b053f467e844
|
[
"MIT"
] | null | null | null |
src/engine/MeshRenderer.cpp
|
alextrevisan/3dfx-glide-game-engine
|
9a47c65d3705fb7b43e59cf90432b053f467e844
|
[
"MIT"
] | null | null | null |
#include "MeshRenderer.h"
MeshRenderer::MeshRenderer()
:GameObject("MeshRenderer")
{
}
void MeshRenderer::Update()
{
}
| 9.769231
| 31
| 0.692913
|
alextrevisan
|
68fc1d644f353ea4abead2552f172650cf4ae0aa
| 6,065
|
cpp
|
C++
|
src/matrix.cpp
|
BrettAM/Cs404DataMining
|
64a68725e35b9ba14f604cb4e6934e979048a97f
|
[
"Apache-2.0"
] | null | null | null |
src/matrix.cpp
|
BrettAM/Cs404DataMining
|
64a68725e35b9ba14f604cb4e6934e979048a97f
|
[
"Apache-2.0"
] | null | null | null |
src/matrix.cpp
|
BrettAM/Cs404DataMining
|
64a68725e35b9ba14f604cb4e6934e979048a97f
|
[
"Apache-2.0"
] | null | null | null |
#include "matrix.hpp"
Matrix::Matrix(size_t rows, size_t columns)
: rows(rows), cols(columns) {
data = new double[rows*cols];
}
Matrix::Matrix(size_t rows, size_t columns, double initialValue)
: rows(rows), cols(columns) {
data = new double[rows*cols];
fill(initialValue);
}
Matrix::Matrix(std::initializer_list<std::initializer_list<double>> values)
: rows(values.size()), cols(values.begin()->size()){
//all columns must have the same number of elements
for(auto row : values){
assert(row.size() == cols);
}
data = new double[rows*cols];
for(size_t r=0; r<rows; r++){
for(size_t c=0; c<cols; c++){
set(r,c, *((values.begin()+r)->begin()+c) );
}
}
}
Matrix::~Matrix(){
delete[] data;
}
Matrix::Matrix(const Matrix& other)
: rows(other.rows), cols(other.cols) {
data = new double[rows*cols];
std::copy(other.data, other.data+rows*cols, data);
}
Matrix& Matrix::operator=(const Matrix& other){
assert(rows == other.rows);
assert(cols == other.cols);
for(size_t r=0; r<rows; r++){
for(size_t c=0; c<cols; c++){
set(r,c, other.get(r,c));
}
}
return *this;
}
Matrix Matrix::Ident(size_t n){
Matrix r(n, n, 0.0);
for(size_t i=0; i<n; i++) r.set(i, i, 1.0);
return r;
}
/** Construct a Householder transformation around v
* v the unit column vector defining a hyperplane
* returns a Householder matrix which reflects vectors across
* the hyperplane defined by v
*/
Matrix Matrix::Householder(const Matrix& v){
assert(v.cols == 1);
double n = v.frobeniusNorm();
Matrix hh = Ident(v.rows) - v*v.T()*(2.0/(n*n));
return hh;
}
Matrix Matrix::T() const{ //transpose
Matrix nm(cols, rows);
for(size_t r = 0; r < rows; r++){
for(size_t c = 0; c < cols; c++){
nm.set(c, r, get(r,c));
}
}
return nm;
}
std::pair<Matrix, Matrix> Matrix::bisect(size_t splitAt) const {
assert(splitAt < cols);
Matrix left(rows, splitAt);
Matrix right(rows, cols-splitAt);
for(size_t r = 0; r < rows; r++){
for(size_t c = 0; c < splitAt; c++){
left.set(r,c,get(r,c));
}
}
for(size_t r = 0; r < rows; r++){
for(size_t c = splitAt; c < cols; c++){
right.set(r,c-splitAt,get(r,c));
}
}
return std::pair<Matrix,Matrix>(left,right);
}
void Matrix::fill(double value){
for(size_t r = 0; r < rows; r++){
for(size_t c = 0; c < cols; c++){
set(r, c, value);
}
}
}
void Matrix::map(std::function<double(double)> transform){
for(size_t r = 0; r < rows; r++){
for(size_t c = 0; c < cols; c++){
double value = transform(get(r,c));
set(r, c, value);
}
}
}
Matrix Matrix::elmult(const Matrix& rhs){
assert (this->rows == rhs.rows);
assert (this->cols == rhs.cols);
Matrix res(rows, cols);
for(size_t r = 0; r < rows; r++){
for(size_t c = 0; c < cols; c++){
res.set(r, c, this->get(r,c)*rhs.get(r,c));
}
}
return res;
}
double Matrix::frobeniusNorm() const{
double sum = 0.0;
for(size_t r = 0; r < rows; r++){
for(size_t c = 0; c < cols; c++){
double e = get(r,c);
sum += e*e;
}
}
return sqrt(sum);
}
Matrix Matrix::frobeniusNormalized() const{
Matrix r(*this);
double m = 1.0 / frobeniusNorm();
r.map([=](double v){return v*m;});
return r;
}
std::string Matrix::toString(int precision) const{
std::stringstream ss;
//ss.setf(std::ios::fixed,std::ios::floatfield);
ss.precision(precision);
for(size_t r = 0; r < rows; r++){
for(size_t c = 0; c < cols; c++){
ss << get(r,c) << " ";
}
ss << "\n";
}
return ss.str();
}
Matrix& Matrix::operator+= (const Matrix& rhs){
assert (this->rows == rhs.rows);
assert (this->cols == rhs.cols);
for(size_t r = 0; r < rows; r++){
for(size_t c = 0; c < cols; c++){
double value = this->get(r,c) + rhs.get(r,c);
set(r, c, value);
}
}
return *this;
}
Matrix Matrix::operator- (const Matrix& rhs) const{
assert (this->rows == rhs.rows);
assert (this->cols == rhs.cols);
Matrix nm(rows, cols);
for(size_t r = 0; r < rows; r++){
for(size_t c = 0; c < cols; c++){
double value = this->get(r,c) - rhs.get(r,c);
nm.set(r, c, value);
}
}
return nm;
}
Matrix Matrix::operator+ (const Matrix& rhs) const{
assert (this->rows == rhs.rows);
assert (this->cols == rhs.cols);
Matrix nm(rows, cols);
for(size_t r = 0; r < rows; r++){
for(size_t c = 0; c < cols; c++){
double value = this->get(r,c) + rhs.get(r,c);
nm.set(r, c, value);
}
}
return nm;
}
Matrix Matrix::operator* (const Matrix& rhs) const{
assert (this->cols == rhs.rows);
Matrix nm(rows, rhs.cols);
for(size_t r = 0; r < rows; r++){
for(size_t c = 0; c < rhs.cols; c++){
double value = 0.0;
for(size_t i=0; i<cols; i++){
value += get(r, i) * rhs.get(i, c);
}
nm.set(r, c, value);
}
}
return nm;
}
Matrix Matrix::operator| (const Matrix& rhs) const{
assert (this->rows == rhs.rows);
Matrix nm(rows, cols+rhs.cols);
for(size_t r = 0; r < rows; r++){
for(size_t c = 0; c < cols; c++){
nm.set(r, c, this->get(r,c));
}
}
for(size_t r = 0; r < rows; r++){
for(size_t c = 0; c < rhs.cols; c++){
nm.set(r, cols+c, rhs.get(r,c));
}
}
return nm;
}
Matrix operator* (double scalar, const Matrix& rhs){
Matrix nm = rhs;
nm.map([=](double v) -> double { return scalar*v; });
return nm;
}
Matrix operator* (const Matrix& rhs, double scalar){
return scalar*rhs;
}
std::ostream& operator<<(std::ostream& os, const Matrix& m){
os << m.toString(2);
return os;
}
| 28.209302
| 75
| 0.527947
|
BrettAM
|
68fe984a3f8775aa1fdfdcf7ba643fba84a6bcab
| 2,032
|
cpp
|
C++
|
test/feasibility_test_files/test_standardize_viz_data.cpp
|
stevenjj/icra2020locomanipulation
|
414085b68cc1b3b24f7b920b543bba9d95350c16
|
[
"MIT"
] | 5
|
2020-01-06T11:43:18.000Z
|
2021-12-14T22:59:09.000Z
|
test/feasibility_test_files/test_standardize_viz_data.cpp
|
stevenjj/icra2020locomanipulation
|
414085b68cc1b3b24f7b920b543bba9d95350c16
|
[
"MIT"
] | null | null | null |
test/feasibility_test_files/test_standardize_viz_data.cpp
|
stevenjj/icra2020locomanipulation
|
414085b68cc1b3b24f7b920b543bba9d95350c16
|
[
"MIT"
] | 2
|
2020-09-03T16:08:34.000Z
|
2022-02-17T11:13:49.000Z
|
#include <avatar_locomanipulation/helpers/yaml_data_saver.hpp>
#include <avatar_locomanipulation/helpers/param_handler.hpp>
#include <iostream>
#include <fstream>
int main(int argc, char ** argv){
// Define the strings for getting and printing values
std::string score_string;
std::string position_string;
// The max val to be standardized against
double max_val, temp, standardized;
// The x, y, z of position
double x, y, z;
// For the Yaml emitter
YAML::Emitter out;
out << YAML::BeginMap;
// Example loading of the file
ParamHandler param_handler;
param_handler.load_yaml_file("right_hand_feasibility.yaml");
// Define the temporary position for posting to standardized yaml
Eigen::Vector3d temp_rhand_pos;
score_string = "feasibility_score_" + std::to_string(1);
param_handler.getValue(score_string, max_val);
// Find the Maximum feasibility score for standardization
for(int i=2; i<=14973; ++i){
score_string = "feasibility_score_" + std::to_string(i);
param_handler.getValue(score_string, temp);
if(temp >= max_val){
max_val = temp;
}
std::cout << "get max\n";
}
// Divide all of the feasibility scores by the max
for(int w=1; w<=14973; ++w){
score_string = "feasibility_score_" + std::to_string(w);
position_string = "right_hand_position_" + std::to_string(w);
// Get, standardize, and emit the feasibility score
param_handler.getValue(score_string, temp);
standardized = temp/max_val;
data_saver::emit_value(out, score_string, standardized);
// Get and emit the rhand position
param_handler.getNestedValue({position_string, "x"}, x);
param_handler.getNestedValue({position_string, "y"}, y);
param_handler.getNestedValue({position_string, "z"}, z);
temp_rhand_pos[0] = x; temp_rhand_pos[1] = y; temp_rhand_pos[2] = z;
data_saver::emit_position(out, position_string, temp_rhand_pos);
std::cout << "emit\n";
}
out << YAML::EndMap;
std::ofstream file_output_stream("right_hand_standardized_feasibility.yaml");
file_output_stream << out.c_str();
}
| 32.253968
| 78
| 0.736713
|
stevenjj
|
ec0106a4543ee9b46abe4c2f844a07ebdec9e626
| 1,113
|
cpp
|
C++
|
src/timeAttack.cpp
|
CIA-hideout/pongstar
|
e32eb46963790895cad069a40b35f0616626ac70
|
[
"MIT"
] | 2
|
2017-01-15T07:08:39.000Z
|
2020-02-23T07:48:37.000Z
|
src/timeAttack.cpp
|
CIA-hideout/pongstar
|
e32eb46963790895cad069a40b35f0616626ac70
|
[
"MIT"
] | 47
|
2017-01-21T17:55:26.000Z
|
2021-03-22T10:12:48.000Z
|
src/timeAttack.cpp
|
CIA-hideout/pongstar
|
e32eb46963790895cad069a40b35f0616626ac70
|
[
"MIT"
] | 1
|
2018-04-09T13:09:50.000Z
|
2018-04-09T13:09:50.000Z
|
#include "timeAttack.h"
TimeAttack::TimeAttack(Game* g, Audio* a, DataManager* dm, FontManager* fm, TextureManagerMap t) :
PongstarBase(g, a, dm, fm, t) {
sceneType = sceneNS::TIME_ATK;
sceneData.gameMode = sceneNS::GM_TIME_ATK;
}
TimeAttack::~TimeAttack() {}
void TimeAttack::update(float frameTime) {
PongstarBase::update(frameTime);
int leftPaddleScore = entityManager->getPaddle(paddleNS::LEFT)->getScore();
int rightPaddleScore = entityManager->getPaddle(paddleNS::RIGHT)->getScore();
if (elapsedTime >= pongstarNS::TIME_PER_GAME) {
nextSceneType = sceneNS::GAMEOVER;
sceneData.scores.p1Score = leftPaddleScore;
sceneData.scores.p2Score = rightPaddleScore;
}
}
void TimeAttack::render() {
PongstarBase::render();
std::string timeLeft = std::to_string((pongstarNS::TIME_PER_GAME - elapsedTime) / 1000);
fontManager->print(
fontNS::SABO_FILLED,
elapsedTime > (pongstarNS::TIME_PER_GAME - pongstarNS::TEN_SECONDS) ? fontNS::RED : fontNS::WHITE,
GAME_WIDTH / 2 - fontManager->getTotalWidth(fontNS::SABO_FILLED, timeLeft) / 2 - fontNS::CENTER_OFFSET,
HUD_Y_POS,
timeLeft
);
}
| 29.289474
| 105
| 0.739443
|
CIA-hideout
|
ec0118b79e04964c3b0d13e96f510fbd14431049
| 15,632
|
hpp
|
C++
|
include/strf/detail/input_types/join.hpp
|
eyalroz/strf
|
94cd5aef40530269da0727178017cb4a8992c5dc
|
[
"BSL-1.0"
] | null | null | null |
include/strf/detail/input_types/join.hpp
|
eyalroz/strf
|
94cd5aef40530269da0727178017cb4a8992c5dc
|
[
"BSL-1.0"
] | 18
|
2019-12-13T15:52:26.000Z
|
2020-01-17T14:51:33.000Z
|
include/strf/detail/input_types/join.hpp
|
eyalroz/strf
|
94cd5aef40530269da0727178017cb4a8992c5dc
|
[
"BSL-1.0"
] | 1
|
2021-12-23T05:53:22.000Z
|
2021-12-23T05:53:22.000Z
|
#ifndef STRF_JOIN_HPP
#define STRF_JOIN_HPP
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <strf/detail/facets/encoding.hpp>
#include <strf/detail/printers_tuple.hpp>
#include <strf/detail/format_functions.hpp>
#if defined(_MSC_VER)
#include <tuple>
#endif
namespace strf {
template<bool Active>
struct split_pos_format;
template<bool Active, typename T>
class split_pos_format_fn;
template<typename T>
class split_pos_format_fn<true, T> {
public:
constexpr STRF_HD split_pos_format_fn() noexcept
{
}
constexpr STRF_HD explicit split_pos_format_fn(std::ptrdiff_t pos) noexcept
: _pos(pos)
{
}
template <bool B, typename U>
constexpr STRF_HD explicit split_pos_format_fn
( const split_pos_format_fn<B,U>& r ) noexcept
: _pos(r.split_pos())
{
}
constexpr STRF_HD T&& split_pos(std::ptrdiff_t pos) && noexcept
{
_pos = pos;
return static_cast<T&&>(*this);
}
constexpr STRF_HD std::ptrdiff_t split_pos() const noexcept
{
return _pos;
}
private:
std::ptrdiff_t _pos = 0;
};
template<typename T>
class split_pos_format_fn<false, T>
{
using _adapted_derived_type = strf::fmt_replace
< T
, strf::split_pos_format<false>
, strf::split_pos_format<true> >;
public:
constexpr STRF_HD split_pos_format_fn() noexcept
{
}
template<typename U>
constexpr STRF_HD explicit split_pos_format_fn(const strf::split_pos_format_fn<false, U>&) noexcept
{
}
constexpr STRF_HD _adapted_derived_type split_pos(std::ptrdiff_t pos) const noexcept
{
return { static_cast<const T&>(*this)
, strf::tag<strf::split_pos_format<true>> {}
, pos};
}
constexpr STRF_HD std::ptrdiff_t split_pos() const noexcept
{
return 0;
}
};
template<bool Active>
struct split_pos_format
{
template<typename T>
using fn = strf::split_pos_format_fn<Active, T>;
};
struct aligned_join_t
{
std::int16_t width = 0;
strf::text_alignment align = strf::text_alignment::right;
char32_t fillchar = U' ';
std::ptrdiff_t split_pos = 1;
template<typename ... Args>
constexpr STRF_HD strf::value_with_format
< strf::detail::simple_tuple< strf::detail::opt_val_or_cref<Args>...>
, strf::split_pos_format<true>
, strf::alignment_format_q<true> >
operator()(const Args& ... args) const
{
return { strf::detail::make_simple_tuple<Args...>(args...)
, strf::tag< strf::split_pos_format<true>
, strf::alignment_format_q<true> > {}
, split_pos
, strf::alignment_format_data {fillchar, width, align}};
}
};
namespace detail {
template<typename CharT>
STRF_HD void print_split
( strf::basic_outbuf<CharT>& ob
, strf::encoding<CharT> enc
, unsigned fillcount
, char32_t fillchar
, std::ptrdiff_t split_pos
, strf::encoding_error enc_err
, strf::surrogate_policy allow_surr)
{
(void) split_pos;
enc.encode_fill(ob, fillcount, fillchar, enc_err, allow_surr);
}
template<typename CharT, typename Printer, typename ... Printers>
STRF_HD void print_split
( strf::basic_outbuf<CharT>& ob
, strf::encoding<CharT> enc
, unsigned fillcount
, char32_t fillchar
, std::ptrdiff_t split_pos
, strf::encoding_error enc_err
, strf::surrogate_policy allow_surr
, const Printer& p
, const Printers& ... printers )
{
if (split_pos > 0) {
p.print_to(ob);
print_split(ob, enc, fillcount, fillchar, split_pos - 1, enc_err, allow_surr, printers...);
} else {
enc.encode_fill(ob, fillcount, fillchar, enc_err, allow_surr);
strf::detail::write_args(ob, p, printers...);
}
}
template<typename CharT, std::size_t ... I, typename ... Printers>
STRF_HD void print_split
( const strf::detail::printers_tuple_impl
< CharT, std::index_sequence<I...>, Printers... >& printers
, strf::basic_outbuf<CharT>& ob
, strf::encoding<CharT> enc
, unsigned fillcount
, char32_t fillchar
, std::ptrdiff_t split_pos
, strf::encoding_error enc_err
, strf::surrogate_policy allow_surr )
{
strf::detail::print_split( ob, enc, fillcount, fillchar, split_pos, enc_err
, allow_surr, printers.template get<I>()... );
}
template<typename CharT, typename ... Printers>
class aligned_join_printer_impl: public printer<CharT>
{
using _printers_tuple = strf::detail::printers_tuple<CharT, Printers...>;
public:
template<typename FPack, bool ReqSize, typename ... Args>
STRF_HD aligned_join_printer_impl
( const FPack& fp
, strf::print_preview<ReqSize, false>& preview
, const strf::detail::simple_tuple<Args...>& args
, std::ptrdiff_t split_pos
, strf::alignment_format_data afmt )
: _split_pos(split_pos)
, _afmt(afmt)
, _encoding(_get_facet<strf::encoding_c<CharT>>(fp))
, _enc_err(_get_facet<strf::encoding_error_c>(fp))
, _allow_surr(_get_facet<strf::surrogate_policy_c>(fp))
{
strf::print_preview<ReqSize, true> p { _afmt.width };
new (_printers_ptr()) _printers_tuple { fp, p, args };
if (p.remaining_width() > 0) {
_fillcount = p.remaining_width().round();
}
STRF_IF_CONSTEXPR (ReqSize) {
preview.add_size(p.get_size());
if (_fillcount > 0) {
auto fcharsize = _encoding.char_size(_afmt.fill);
preview.add_size(_fillcount * fcharsize);
}
}
(void) preview;
}
template<typename FPack, bool ReqSize, typename ... Args>
STRF_HD aligned_join_printer_impl
( const FPack& fp, strf::print_preview<ReqSize, true>& preview
, const strf::detail::simple_tuple<Args...>& args
, std::ptrdiff_t split_pos
, strf::alignment_format_data afmt )
: _split_pos(split_pos)
, _afmt(afmt)
, _encoding(_get_facet<strf::encoding_c<CharT>>(fp))
, _enc_err(_get_facet<strf::encoding_error_c>(fp))
, _allow_surr(_get_facet<strf::surrogate_policy_c>(fp))
{
if (_afmt.width < 0) {
_afmt.width = 0;
}
strf::width_t wmax = _afmt.width;
strf::width_t diff = 0;
if (preview.remaining_width() > _afmt.width) {
wmax = preview.remaining_width();
diff = preview.remaining_width() - _afmt.width;
}
strf::print_preview<ReqSize, true> p { wmax };
new (_printers_ptr()) _printers_tuple { fp, p, args }; // todo: what if this throws ?
if (p.remaining_width() > diff) {
_fillcount = (p.remaining_width() - diff).round();
}
width_t width = _fillcount + wmax - p.remaining_width();
preview.subtract_width(width);
STRF_IF_CONSTEXPR (ReqSize) {
preview.add_size(p.get_size());
if (_fillcount > 0) {
preview.add_size(_fillcount * _encoding.char_size(_afmt.fill));
}
}
}
STRF_HD ~aligned_join_printer_impl()
{
_printers_ptr()->~_printers_tuple();
}
STRF_HD void print_to(strf::basic_outbuf<CharT>& ob) const override
{
switch (_afmt.alignment) {
case strf::text_alignment::left: {
strf::detail::write(ob, _printers());
_write_fill(ob, _fillcount);
break;
}
case strf::text_alignment::right: {
_write_fill(ob, _fillcount);
strf::detail::write(ob, _printers());
break;
}
case strf::text_alignment::split: {
_print_split(ob);
break;
}
default: {
STRF_ASSERT(_afmt.alignment == strf::text_alignment::center);
auto half_fillcount = _fillcount >> 1;
_write_fill(ob, half_fillcount);
strf::detail::write(ob, _printers());
_write_fill(ob, _fillcount - half_fillcount);
break;
}
}
}
private:
using _printers_tuple_storage = typename std::aligned_storage_t
#if defined(_MSC_VER)
<sizeof(std::tuple<Printers...>), alignof(strf::printer<CharT>)>;
#else
<sizeof(_printers_tuple), alignof(_printers_tuple)>;
#endif
_printers_tuple_storage _pool;
std::ptrdiff_t _split_pos;
strf::alignment_format_data _afmt;
const strf::encoding<CharT> _encoding;
strf::width_t _width;
std::int16_t _fillcount = 0;
strf::encoding_error _enc_err;
strf::surrogate_policy _allow_surr;
STRF_HD _printers_tuple * _printers_ptr()
{
return reinterpret_cast<_printers_tuple*>(&_pool);
}
STRF_HD const _printers_tuple& _printers() const
{
return *reinterpret_cast<const _printers_tuple*>(&_pool);
}
template <typename Category, typename FPack>
static decltype(auto) STRF_HD _get_facet(const FPack& fp)
{
return fp.template get_facet<Category, strf::aligned_join_t>();
}
STRF_HD std::size_t _fill_length() const
{
if (_fillcount > 0) {
return _fillcount * _encoding.char_size(_afmt.fill);
}
return 0;
}
STRF_HD void _write_fill(strf::basic_outbuf<CharT>& ob, int count) const
{
_encoding.encode_fill(ob, count, _afmt.fill, _enc_err, _allow_surr);
}
STRF_HD void _print_split(strf::basic_outbuf<CharT>& ob) const;
};
template<typename CharT, typename ... Printers>
STRF_HD void aligned_join_printer_impl<CharT, Printers...>::_print_split(strf::basic_outbuf<CharT>& ob) const
{
strf::detail::print_split( _printers(), ob, _encoding, _fillcount, _afmt.fill
, _split_pos, _enc_err, _allow_surr );
}
template<typename CharT, typename FPack, typename Preview, typename ... Args>
using aligned_join_printer_impl_of
= aligned_join_printer_impl
< CharT
, decltype
( make_printer<CharT>
( strf::rank<5>()
, std::declval<const FPack&>()
, std::declval<strf::print_preview<Preview::size_required, true>&>()
, std::declval<const Args&>() )) ... >;
template<typename CharT, typename FPack, typename Preview, typename ... Args>
class aligned_join_printer
: public strf::detail::aligned_join_printer_impl_of<CharT, FPack, Preview, Args...>
{
using _aligned_join_impl = strf::detail::aligned_join_printer_impl_of
<CharT, FPack, Preview, Args...>;
public:
STRF_HD aligned_join_printer
( const FPack& fp
, Preview& preview
, const strf::detail::simple_tuple<Args...>& args
, std::ptrdiff_t split_pos
, strf::alignment_format_data afmt )
: _aligned_join_impl(fp, preview, args, split_pos, afmt)
{
}
virtual STRF_HD ~aligned_join_printer()
{
}
};
template<typename CharT, typename ... Printers>
class join_printer_impl: public printer<CharT> {
public:
template<typename FPack, typename Preview, typename ... Args>
STRF_HD join_printer_impl
( const FPack& fp
, Preview& preview
, const strf::detail::simple_tuple<Args...>& args )
: _printers { fp, preview, args }
{
}
STRF_HD ~join_printer_impl()
{
}
STRF_HD void print_to(strf::basic_outbuf<CharT>& ob) const override
{
strf::detail::write(ob, _printers);
}
private:
strf::detail::printers_tuple<CharT, Printers...> _printers;
};
template<typename CharT, typename FPack, typename Preview, typename ... Args>
class join_printer
: public strf::detail::join_printer_impl
< CharT
, decltype(make_printer<CharT>( strf::rank<5>()
, std::declval<const FPack&>()
, std::declval<Preview&>()
, std::declval<const Args&>() )) ...>
{
using _join_impl = strf::detail::join_printer_impl
< CharT
, decltype(make_printer<CharT>( strf::rank<5>()
, std::declval<const FPack&>()
, std::declval<Preview&>()
, std::declval<const Args&>() )) ... >;
public:
STRF_HD join_printer( const FPack& fp
, Preview& preview
, const strf::detail::simple_tuple<Args...>& args )
: _join_impl(fp, preview, args)
{
}
virtual STRF_HD ~join_printer()
{
}
};
} // namespace detail
template< typename CharT
, typename FPack
, typename Preview
, bool SplitPosActive
, typename ... Args >
inline STRF_HD strf::detail::join_printer<CharT, FPack, Preview, Args...> make_printer
( strf::rank<1>
, const FPack& fp
, Preview& preview
, const strf::value_with_format< strf::detail::simple_tuple<Args...>
, strf::split_pos_format<SplitPosActive>
, strf::alignment_format_q<false> > input )
{
return {fp, preview, input.value()};
}
template<typename ... Args>
constexpr STRF_HD strf::value_with_format
< strf::detail::simple_tuple<strf::detail::opt_val_or_cref<Args>...>
, strf::split_pos_format<false>
, strf::alignment_format_q<false> >
join(const Args& ... args)
{
return strf::value_with_format
< strf::detail::simple_tuple<strf::detail::opt_val_or_cref<Args>...>
, strf::split_pos_format<false>
, strf::alignment_format_q<false> >
{ strf::detail::make_simple_tuple(args...) };
}
template<typename CharT, typename FPack, typename Preview, bool SplitPosActive, typename ... Args>
inline STRF_HD strf::detail::aligned_join_printer<CharT, FPack, Preview, Args...> make_printer
( strf::rank<1>
, const FPack& fp
, Preview& preview
, const strf::value_with_format
< strf::detail::simple_tuple<Args...>
, strf::split_pos_format<SplitPosActive>
, strf::alignment_format_q<true> > input )
{
return { fp, preview, input.value(), input.split_pos()
, input.get_alignment_format_data() };
}
constexpr STRF_HD strf::aligned_join_t join_align
( std::int16_t width
, strf::text_alignment align
, char32_t fillchar = U' '
, int split_pos = 0 )
{
return {width, align, fillchar, split_pos};
}
constexpr STRF_HD strf::aligned_join_t join_center(std::int16_t width, char32_t fillchar = U' ') noexcept
{
return {width, strf::text_alignment::center, fillchar, 0};
}
constexpr STRF_HD strf::aligned_join_t join_left(std::int16_t width, char32_t fillchar = U' ') noexcept
{
return {width, strf::text_alignment::left, fillchar, 0};
}
constexpr STRF_HD strf::aligned_join_t join_right(std::int16_t width, char32_t fillchar = U' ') noexcept
{
return {width, strf::text_alignment::right, fillchar, 0};
}
constexpr STRF_HD strf::aligned_join_t join_split(std::int16_t width, char32_t fillchar,
std::ptrdiff_t split_pos) noexcept
{
return {width, strf::text_alignment::split, fillchar, split_pos};
}
constexpr STRF_HD strf::aligned_join_t join_split(std::int16_t width, std::ptrdiff_t split_pos) noexcept
{
return {width, strf::text_alignment::split, U' ', split_pos};
}
} // namespace strf
#endif // STRF_JOIN_HPP
| 30.711198
| 109
| 0.623912
|
eyalroz
|
ec0bc2f4c77ab6f3feabe0e28166fcc5edc76ffe
| 7,729
|
cpp
|
C++
|
tools/gentab/gentab_web.cpp
|
t-weber/libcrystal
|
2611288014047fe60010ee1b963a9e686b6ea77a
|
[
"BSL-1.0"
] | null | null | null |
tools/gentab/gentab_web.cpp
|
t-weber/libcrystal
|
2611288014047fe60010ee1b963a9e686b6ea77a
|
[
"BSL-1.0"
] | null | null | null |
tools/gentab/gentab_web.cpp
|
t-weber/libcrystal
|
2611288014047fe60010ee1b963a9e686b6ea77a
|
[
"BSL-1.0"
] | null | null | null |
/**
* Creates needed tables
* @author Tobias Weber <tobias.weber@tum.de>
* @date nov-2015
* @license GPLv2
*/
// ============================================================================
t_cplx get_number(std::string str)
{
tl::string_rm<std::string>(str, "(", ")");
if(tl::string_rm<std::string>(str, "<i>", "</i>"))
{ // complex number
std::size_t iSign = str.find_last_of("+-");
str.insert(iSign, ", ");
str.insert(0, "(");
str.push_back(')');
}
tl::trim(str);
if(str == "---") str = "";
t_cplx c;
std::istringstream istr(str);
istr >> c;
t_real dR = c.real(), dI = c.imag();
tl::set_eps_0(dR); tl::set_eps_0(dI);
c.real(dR); c.imag(dI);
return c;
}
bool get_abundance_or_hl(const std::string& _str, t_real& dAbOrHL)
{
bool bIsHL = (_str.find("a") != std::string::npos);
std::string str = tl::remove_chars(_str, std::string("()a"));
dAbOrHL = get_number(str).real();
if(!bIsHL) dAbOrHL /= t_real(100.);
return !bIsHL;
}
bool gen_scatlens()
{
std::ifstream ifstr("tmp/scatlens.html");
if(!ifstr)
{
tl::log_err("Cannot open \"tmp/scatlens.html\".");
return false;
}
bool bTableStarted = 0;
std::string strTable;
while(!ifstr.eof())
{
std::string strLine;
std::getline(ifstr, strLine);
if(!bTableStarted)
{
std::vector<std::string> vecHdr;
tl::get_tokens_seq<std::string, std::string, std::vector>(strLine, "<th>", vecHdr, 0);
if(vecHdr.size() < 9)
continue;
bTableStarted = 1;
}
else
{
// at end of table?
if(tl::str_to_lower(strLine).find("/table") != std::string::npos)
break;
strTable += strLine;
}
}
ifstr.close();
std::vector<std::string> vecRows;
tl::get_tokens_seq<std::string, std::string, std::vector>(strTable, "<tr>", vecRows, 0);
tl::Prop<std::string> prop;
prop.SetSeparator('.');
prop.Add("scatlens.source", "Scattering lengths and cross-sections extracted from NIST table"
" (which itself is based on <a href=\"http://dx.doi.org/10.1080/10448639208218770\">this paper</a>).");
prop.Add("scatlens.source_url", "https://www.ncnr.nist.gov/resources/n-lengths/list.html");
unsigned int iAtom = 0;
for(const std::string& strRow : vecRows)
{
if(strRow.length() == 0)
continue;
std::ostringstream ostr;
ostr << "scatlens.atom_" << iAtom;
std::string strAtom = ostr.str();
std::vector<std::string> vecCol;
tl::get_tokens_seq<std::string, std::string, std::vector>(strRow, "<td>", vecCol, 0);
if(vecCol.size() < 9)
{
tl::log_warn("Invalid number of table entries in row \"", strRow, "\".");
continue;
}
std::string strName = vecCol[1];
tl::trim(strName);
if(strName == "") continue;
t_cplx cCoh = get_number(vecCol[3]);
t_cplx cIncoh = get_number(vecCol[4]);
t_real dXsecCoh = get_number(vecCol[5]).real();
t_real dXsecIncoh = get_number(vecCol[6]).real();
t_real dXsecScat = get_number(vecCol[7]).real();
t_real dXsecAbsTherm = get_number(vecCol[8]).real();
t_real dAbOrHL = t_real(0);
bool bAb = get_abundance_or_hl(vecCol[2], dAbOrHL);
prop.Add(strAtom + ".name", strName);
prop.Add(strAtom + ".coh", tl::var_to_str(cCoh, g_iPrec));
prop.Add(strAtom + ".incoh", tl::var_to_str(cIncoh, g_iPrec));
prop.Add(strAtom + ".xsec_coh", tl::var_to_str(dXsecCoh, g_iPrec));
prop.Add(strAtom + ".xsec_incoh", tl::var_to_str(dXsecIncoh, g_iPrec));
prop.Add(strAtom + ".xsec_scat", tl::var_to_str(dXsecScat, g_iPrec));
prop.Add(strAtom + ".xsec_abs", tl::var_to_str(dXsecAbsTherm, g_iPrec));
if(bAb)
prop.Add(strAtom + ".abund", tl::var_to_str(dAbOrHL, g_iPrec));
else
prop.Add(strAtom + ".hl", tl::var_to_str(dAbOrHL, g_iPrec));
++iAtom;
}
prop.Add("scatlens.num_atoms", tl::var_to_str(iAtom));
if(!prop.Save("res/data/scatlens.xml.gz"))
{
tl::log_err("Cannot write \"res/data/scatlens.xml.gz\".");
return false;
}
return true;
}
// ============================================================================
bool gen_magformfacts()
{
tl::Prop<std::string> propOut;
propOut.SetSeparator('.');
propOut.Add("magffacts.source", "Magnetic form factor coefficients extracted from ILL table.");
propOut.Add("magffacts.source_url", "https://www.ill.eu/sites/ccsl/ffacts/");
std::size_t iAtom=0;
std::set<std::string> setAtoms;
std::vector<std::string> vecFiles =
{"tmp/j0_1.html", "tmp/j0_2.html",
"tmp/j0_3.html" , "tmp/j0_4.html",
"tmp/j2_1.html", "tmp/j2_2.html",
"tmp/j2_3.html", "tmp/j2_4.html",};
for(std::size_t iFile=0; iFile<vecFiles.size(); ++iFile)
{
const std::string& strFile = vecFiles[iFile];
std::string strJ = iFile < 4 ? "j0" : "j2";
// switching to j2 files
if(iFile==4)
{
iAtom = 0;
setAtoms.clear();
}
std::ifstream ifstr(strFile);
if(!ifstr)
{
tl::log_err("Cannot open \"", strFile, "\".");
return false;
}
std::string strTable;
bool bTableStarted=0;
while(!ifstr.eof())
{
std::string strLine;
std::getline(ifstr, strLine);
std::string strLineLower = tl::str_to_lower(strLine);
if(bTableStarted)
{
strTable += strLine + "\n";
if(strLineLower.find("</table") != std::string::npos)
break;
}
else
{
std::size_t iPos = strLineLower.find("<table");
if(iPos != std::string::npos)
{
std::string strSub = strLine.substr(iPos);
strTable += strSub + "\n";
bTableStarted = 1;
}
}
}
if(strTable.length() == 0)
{
tl::log_err("Invalid table: \"", strFile, "\".");
return 0;
}
// removing attributes
rex::basic_regex<char> rex("<([A-Za-z]*)[A-Za-z0-9\\=\\\"\\ ]*>", rex::regex::ECMAScript);
strTable = rex::regex_replace(strTable, rex, "<$1>");
tl::find_all_and_replace<std::string>(strTable, "<P>", "");
tl::find_all_and_replace<std::string>(strTable, "<p>", "");
//std::cout << strTable << std::endl;
std::istringstream istrTab(strTable);
tl::Prop<std::string> prop;
prop.Load(istrTab, tl::PropType::XML);
const auto& tab = prop.GetProp().begin()->second;
auto iter = tab.begin(); ++iter;
for(; iter!=tab.end(); ++iter)
{
auto iterElem = iter->second.begin();
std::string strElem = iterElem++->second.data();
tl::trim(strElem);
if(*strElem.rbegin() == '0')
strElem.resize(strElem.length()-1);
else
strElem += "+";
if(setAtoms.find(strElem) != setAtoms.end())
{
tl::log_warn("Atom ", strElem, " already in set. Ignoring.");
continue;
}
setAtoms.insert(strElem);
t_real dA = tl::str_to_var<t_real>(iterElem++->second.data());
t_real da = tl::str_to_var<t_real>(iterElem++->second.data());
t_real dB = tl::str_to_var<t_real>(iterElem++->second.data());
t_real db = tl::str_to_var<t_real>(iterElem++->second.data());
t_real dC = tl::str_to_var<t_real>(iterElem++->second.data());
t_real dc = tl::str_to_var<t_real>(iterElem++->second.data());
t_real dD = tl::str_to_var<t_real>(iterElem->second.data());
std::string strA = tl::var_to_str(dA, g_iPrec) + "; " +
tl::var_to_str(dB, g_iPrec) + "; " +
tl::var_to_str(dC, g_iPrec) + "; " +
tl::var_to_str(dD, g_iPrec);
std::string stra = tl::var_to_str(da, g_iPrec) + "; " +
tl::var_to_str(db, g_iPrec) + "; " +
tl::var_to_str(dc, g_iPrec);
std::ostringstream ostrAtom;
ostrAtom << "magffacts." + strJ + ".atom_" << iAtom;
propOut.Add(ostrAtom.str() + ".name", strElem);
propOut.Add(ostrAtom.str() + ".A", strA);
propOut.Add(ostrAtom.str() + ".a", stra);
++iAtom;
}
}
propOut.Add("magffacts.num_atoms", tl::var_to_str(iAtom));
if(!propOut.Save("res/data/magffacts.xml.gz"))
{
tl::log_err("Cannot write \"res/data/magffacts.xml.gz\".");
return false;
}
return true;
}
// ============================================================================
| 25.592715
| 105
| 0.608746
|
t-weber
|
ec0cc7d81f0abeeb5d90d161bacf346797f7866a
| 387
|
hxx
|
C++
|
source/code/framework/framework_base/public/ice/game_sprites.hxx
|
iceshard-engine/engine
|
4f2092af8d2d389ea72addc729d0c2c8d944c95c
|
[
"BSD-3-Clause-Clear"
] | 39
|
2019-08-17T09:08:51.000Z
|
2022-02-13T10:14:19.000Z
|
source/code/framework/framework_base/public/ice/game_sprites.hxx
|
iceshard-engine/engine
|
4f2092af8d2d389ea72addc729d0c2c8d944c95c
|
[
"BSD-3-Clause-Clear"
] | 63
|
2020-05-22T16:09:30.000Z
|
2022-01-21T14:24:05.000Z
|
source/code/framework/framework_base/public/ice/game_sprites.hxx
|
iceshard-engine/engine
|
4f2092af8d2d389ea72addc729d0c2c8d944c95c
|
[
"BSD-3-Clause-Clear"
] | null | null | null |
#pragma once
#include <ice/stringid.hxx>
namespace ice
{
struct Sprite
{
static constexpr ice::StringID Identifier = "ice.component.sprite"_sid;
ice::StringID material;
};
struct SpriteTile
{
static constexpr ice::StringID Identifier = "ice.component.sprite-tile"_sid;
ice::vec2u material_tile{ 0, 0 };
};
} // namespace ice
| 17.590909
| 84
| 0.633075
|
iceshard-engine
|
ec1e70a04fc642a55ae24914db9b39fef010b14b
| 2,248
|
cpp
|
C++
|
src/utils/hashUtils.cpp
|
athanor/athanor
|
0e7a654c360be05dc6f6e50427b2ee3df92c1aaf
|
[
"BSD-3-Clause"
] | 4
|
2018-08-31T09:44:52.000Z
|
2021-03-01T19:10:00.000Z
|
src/utils/hashUtils.cpp
|
athanor/athanor
|
0e7a654c360be05dc6f6e50427b2ee3df92c1aaf
|
[
"BSD-3-Clause"
] | 21
|
2019-12-29T08:33:34.000Z
|
2020-11-22T16:38:37.000Z
|
src/utils/hashUtils.cpp
|
athanor/athanor
|
0e7a654c360be05dc6f6e50427b2ee3df92c1aaf
|
[
"BSD-3-Clause"
] | null | null | null |
#include "utils/hashUtils.h"
#include <iostream>
#include <utility>
#include "MurmurHash3.h"
#include "base/intSize.h"
#include "picosha2.h"
HashType::HashType(UInt64 value) : value(value) {}
HashType HashType::operator+(const HashType other) const {
return HashType(value + other.value);
}
HashType HashType::operator-(const HashType other) const {
return HashType(value - other.value);
}
HashType& HashType::operator+=(const HashType other) {
value += other.value;
return *this;
}
HashType& HashType::operator-=(const HashType other) {
value -= other.value;
return *this;
}
HashType HashType::operator*(size_t repeatAmount) const {
return HashType(value * repeatAmount);
}
HashType operator*(size_t repeatAmount, HashType hash) {
return hash * repeatAmount;
}
bool HashType::operator==(const HashType& other) const {
return value == other.value;
}
bool HashType::operator!=(const HashType& other) const {
return value != other.value;
}
bool HashType::operator<(const HashType& other) const {
return value < other.value;
}
bool HashType::operator<=(const HashType& other) const {
return value <= other.value;
}
std::ostream& operator<<(std::ostream& os, const HashType& val) {
return os << val.value;
}
size_t std::hash<HashType>::operator()(const HashType& val) const {
return val.value;
}
UInt64 truncatedSha256(char* input, size_t inputSize) {
std::vector<unsigned char> hash(8);
picosha2::hash256(input, input + inputSize, hash);
UInt64 truncatedHash = 0;
for (int i = 0; i < 8; ++i) {
UInt64 temp = hash[i];
truncatedHash |= (temp << i * 8);
}
return truncatedHash;
}
UInt64 truncatedMurmurHash3(char* input, size_t inputSize) {
static const unsigned int MURMURHASH3_SEED = 0;
UInt64 result[2];
MurmurHash3_x64_128(input, inputSize, MURMURHASH3_SEED, result);
return result[0] ^ result[1];
}
extern bool useShaHashing;
HashType mix(char* input, size_t inputSize) {
return (!useShaHashing) ? HashType(truncatedMurmurHash3(input, inputSize))
: HashType(truncatedSha256(input, inputSize));
}
HashType mix(const HashType& val) {
return mix(((char*)&(val.value)), sizeof(HashType));
}
| 26.761905
| 78
| 0.686833
|
athanor
|
ec1fb3070f4db57c566db41aafab782eb10dd4f9
| 4,948
|
cpp
|
C++
|
source/tm/test/block.cpp
|
davidstone/technical-machine
|
fea3306e58cd026846b8f6c71d51ffe7bab05034
|
[
"BSL-1.0"
] | 7
|
2021-03-05T16:50:19.000Z
|
2022-02-02T04:30:07.000Z
|
source/tm/test/block.cpp
|
davidstone/technical-machine
|
fea3306e58cd026846b8f6c71d51ffe7bab05034
|
[
"BSL-1.0"
] | 47
|
2021-02-01T18:54:23.000Z
|
2022-03-06T19:06:16.000Z
|
source/tm/test/block.cpp
|
davidstone/technical-machine
|
fea3306e58cd026846b8f6c71d51ffe7bab05034
|
[
"BSL-1.0"
] | 1
|
2021-01-28T13:10:41.000Z
|
2021-01-28T13:10:41.000Z
|
// Copyright David Stone 2020.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <tm/block.hpp>
#include <tm/move/moves.hpp>
#include <tm/pokemon/species.hpp>
#include <tm/stat/ev.hpp>
#include <tm/stat/iv.hpp>
#include <tm/string_conversions/move.hpp>
#include <tm/team.hpp>
#include <tm/weather.hpp>
#include <containers/algorithms/concatenate.hpp>
#include <containers/front_back.hpp>
#include <containers/size.hpp>
#include <catch2/catch_test_macros.hpp>
namespace technicalmachine {
namespace {
using namespace std::string_view_literals;
constexpr auto generation = Generation::four;
constexpr auto moves(auto... move_names) {
return RegularMoves({Move(generation, move_names, 0_bi)...});
}
TEST_CASE("block with all legal moves", "[block]") {
auto user = Team<generation>(1_bi, true);
user.add_pokemon(Pokemon<generation>(
Species::Jolteon,
Level(100_bi),
Gender::male,
Item::Leftovers,
Ability::Volt_Absorb,
default_combined_stats<generation>,
moves(Moves::Thunderbolt, Moves::Charm, Moves::Thunder, Moves::Shadow_Ball)
));
auto weather = Weather();
user.pokemon().switch_in(weather);
auto other = Team<generation>(1_bi, false);
other.add_pokemon(Pokemon<generation>(
Species::Gyarados,
Level(100_bi),
Gender::male,
Item::Leftovers,
Ability::Intimidate,
default_combined_stats<generation>,
moves(Moves::Dragon_Dance, Moves::Waterfall, Moves::Stone_Edge, Moves::Taunt)
));
other.pokemon().switch_in(weather);
user.reset_start_of_turn();
auto const selections = legal_selections(user, other, weather);
CHECK(selections == StaticVectorMove({Moves::Thunderbolt, Moves::Charm, Moves::Thunder, Moves::Shadow_Ball}));
}
auto empty_pp(Move & move) {
auto remaining_pp = move.pp().remaining();
if (remaining_pp) {
move.reduce_pp(*remaining_pp);
}
};
TEST_CASE("Two moves with one out of pp", "[block]") {
auto weather = Weather();
auto user = Team<generation>(1_bi, true);
auto user_moves = moves(Moves::Thunder, Moves::Thunderbolt);
empty_pp(containers::front(user_moves));
user.add_pokemon(Pokemon<generation>(
Species::Pikachu,
Level(100_bi),
Gender::female,
Item::Leftovers,
Ability::Intimidate,
default_combined_stats<generation>,
user_moves
));
user.pokemon().switch_in(weather);
auto other = Team<generation>(1_bi, false);
other.add_pokemon(Pokemon<generation>(
Species::Pikachu,
Level(100_bi),
Gender::female,
Item::Leftovers,
Ability::Intimidate,
default_combined_stats<generation>,
moves(Moves::Thunder, Moves::Thunderbolt)
));
other.pokemon().switch_in(weather);
user.reset_start_of_turn();
auto const selections = legal_selections(user, other, weather);
CHECK(selections == StaticVectorMove({Moves::Thunderbolt}));
}
TEST_CASE("Two moves with both out of pp", "[block]") {
auto weather = Weather();
auto user = Team<generation>(1_bi, true);
auto user_moves = moves(Moves::Thunder, Moves::Thunderbolt);
for (auto & move : user_moves) {
empty_pp(move);
}
user.add_pokemon(Pokemon<generation>(
Species::Pikachu,
Level(100_bi),
Gender::female,
Item::Leftovers,
Ability::Intimidate,
default_combined_stats<generation>,
user_moves
));
user.pokemon().switch_in(weather);
auto other = Team<generation>(1_bi, false);
other.add_pokemon(Pokemon<generation>(
Species::Pikachu,
Level(100_bi),
Gender::female,
Item::Leftovers,
Ability::Intimidate,
default_combined_stats<generation>,
moves(Moves::Thunder, Moves::Thunderbolt)
));
other.pokemon().switch_in(weather);
user.reset_start_of_turn();
auto const selections = legal_selections(user, other, weather);
CHECK(selections == StaticVectorMove({Moves::Struggle}));
}
TEST_CASE("Replace fainted", "[block]") {
auto weather = Weather{};
auto team = Team<generation>(2_bi, true);
team.add_pokemon(Pokemon<generation>(
Species::Slugma,
Level(100_bi),
Gender::male,
Item::Choice_Specs,
Ability::Magma_Armor,
default_combined_stats<generation>,
moves(Moves::Flamethrower)
));
team.pokemon().switch_in(weather);
team.add_pokemon(Pokemon<generation>(
Species::Zapdos,
Level(100_bi),
Gender::genderless,
Item::Choice_Specs,
Ability::Pressure,
default_combined_stats<generation>,
moves(Moves::Thunderbolt)
));
team.reset_start_of_turn();
auto other = Team<generation>(1_bi);
other.add_pokemon(Pokemon<generation>(
Species::Suicune,
Level(100_bi),
Gender::genderless,
Item::Leftovers,
Ability::Pressure,
default_combined_stats<generation>,
moves(Moves::Surf)
));
other.pokemon().switch_in(weather);
other.reset_start_of_turn();
team.pokemon().set_hp(weather, 0_bi);
auto const expected = StaticVectorMove({Moves::Switch1});
auto const selections = legal_selections(team, other, weather);
CHECK(selections == expected);
}
} // namespace
} // namespace technicalmachine
| 25.244898
| 111
| 0.732215
|
davidstone
|
ec254026c4fed8d88ff0e1aa5250152369341426
| 2,653
|
hpp
|
C++
|
libember/Headers/ember/glow/CommandType.hpp
|
purefunsolutions/ember-plus
|
d022732f2533ad697238c6b5210d7fc3eb231bfc
|
[
"BSL-1.0"
] | 78
|
2015-07-31T14:46:38.000Z
|
2022-03-28T09:28:28.000Z
|
libember/Headers/ember/glow/CommandType.hpp
|
purefunsolutions/ember-plus
|
d022732f2533ad697238c6b5210d7fc3eb231bfc
|
[
"BSL-1.0"
] | 81
|
2015-08-03T07:58:19.000Z
|
2022-02-28T16:21:19.000Z
|
libember/Headers/ember/glow/CommandType.hpp
|
purefunsolutions/ember-plus
|
d022732f2533ad697238c6b5210d7fc3eb231bfc
|
[
"BSL-1.0"
] | 49
|
2015-08-03T12:53:10.000Z
|
2022-03-17T17:25:49.000Z
|
/*
libember -- C++ 03 implementation of the Ember+ Protocol
Copyright (C) 2012-2016 Lawo GmbH (http://www.lawo.com).
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 __LIBEMBER_GLOW_COMMANDTYPE_HPP
#define __LIBEMBER_GLOW_COMMANDTYPE_HPP
//SimianIgnore
namespace libember { namespace glow
{
/**
* A scoped enumeration type containing the symbolic names
* for the command types supported by Glow.
*/
class CommandType
{
public:
enum _Domain
{
/**
* This value is returned when a GlowCommand instance does not contain
* a command.
*/
None = 0,
/**
* The command number for a subscription request. The main
* purpose of this command is to subscribe to a stream parameter
* which contains audio level data.
*/
Subscribe = 30,
/**
* The command number for a unsubscribe request. The unsubscribe
* operation has to be performed for all child nodes and
* parameters.
*/
Unsubscribe = 31,
/**
* The command number for a GetDirectory command. This command
* is used to query the children of a node.
*/
GetDirectory = 32,
/**
* The command number for an invocation request. This command
* is used let the provider execute a function.
*/
Invoke = 33
};
typedef int value_type;
public:
/**
* Initializes a new instance.
* @param value The value to initialize this instance with.
*/
CommandType(_Domain value)
: m_value(value)
{}
/**
* Initializes a new instance.
* @param value The value to initialize this instance with.
*/
explicit CommandType(value_type value)
: m_value(value)
{}
/**
* Returns the value.
* @return The value.
*/
value_type value() const
{
return m_value;
}
private:
value_type m_value;
};
}
}
//EndSimianIgnore
#endif // __LIBEMBER_GLOW_COMMANDTYPE_HPP
| 27.635417
| 91
| 0.499435
|
purefunsolutions
|
ec25688944aeaa1f77c7dfe92e3e35517c030487
| 3,728
|
hpp
|
C++
|
packages/monte_carlo/collision/electron/src/MonteCarlo_CoupledElasticAdjointElectroatomicReaction.hpp
|
bam241/FRENSIE
|
e1760cd792928699c84f2bdce70ff54228e88094
|
[
"BSD-3-Clause"
] | 10
|
2019-11-14T19:58:30.000Z
|
2021-04-04T17:44:09.000Z
|
packages/monte_carlo/collision/electron/src/MonteCarlo_CoupledElasticAdjointElectroatomicReaction.hpp
|
bam241/FRENSIE
|
e1760cd792928699c84f2bdce70ff54228e88094
|
[
"BSD-3-Clause"
] | 43
|
2020-03-03T19:59:20.000Z
|
2021-09-08T03:36:08.000Z
|
packages/monte_carlo/collision/electron/src/MonteCarlo_CoupledElasticAdjointElectroatomicReaction.hpp
|
bam241/FRENSIE
|
e1760cd792928699c84f2bdce70ff54228e88094
|
[
"BSD-3-Clause"
] | 6
|
2020-02-12T17:37:07.000Z
|
2020-09-08T18:59:51.000Z
|
//---------------------------------------------------------------------------//
//!
//! \file MonteCarlo_CoupledElasticAdjointElectroatomicReaction.hpp
//! \author Luke Kersting
//! \brief The coupled scattering elastic adjoint electroatomic reaction class decl.
//!
//---------------------------------------------------------------------------//
#ifndef MONTE_CARLO_COUPLED_ELASTIC_ADJOINT_ELECTROATOMIC_REACTION_HPP
#define MONTE_CARLO_COUPLED_ELASTIC_ADJOINT_ELECTROATOMIC_REACTION_HPP
// FRENSIE Includes
#include "MonteCarlo_AdjointElectroatomicReaction.hpp"
#include "MonteCarlo_StandardReactionBaseImpl.hpp"
#include "MonteCarlo_CoupledElasticElectronScatteringDistribution.hpp"
namespace MonteCarlo{
//! The coupled elastic adjoint electroatomic reaction class
template<typename InterpPolicy, bool processed_cross_section = false>
class CoupledElasticAdjointElectroatomicReaction : public StandardReactionBaseImpl<AdjointElectroatomicReaction,InterpPolicy,processed_cross_section>
{
// Typedef for the base class type
typedef StandardReactionBaseImpl<AdjointElectroatomicReaction,InterpPolicy,processed_cross_section>
BaseType;
public:
//! Basic Constructor
CoupledElasticAdjointElectroatomicReaction(
const std::shared_ptr<const std::vector<double> >& incoming_energy_grid,
const std::shared_ptr<const std::vector<double> >& cross_section,
const size_t threshold_energy_index,
const std::shared_ptr<const CoupledElasticElectronScatteringDistribution>&
scattering_distribution );
//! Constructor
CoupledElasticAdjointElectroatomicReaction(
const std::shared_ptr<const std::vector<double> >& incoming_energy_grid,
const std::shared_ptr<const std::vector<double> >& cross_section,
const size_t threshold_energy_index,
const std::shared_ptr<const Utility::HashBasedGridSearcher<double>>& grid_searcher,
const std::shared_ptr<const CoupledElasticElectronScatteringDistribution>&
scattering_distribution );
//! Destructor
~CoupledElasticAdjointElectroatomicReaction()
{ /* ... */ }
//! Return the number of adjoint photons emitted from the rxn at the given energy
unsigned getNumberOfEmittedAdjointPhotons( const double energy ) const override;
//! Return the number of adjoint electrons emitted from the rxn at the given energy
unsigned getNumberOfEmittedAdjointElectrons( const double energy ) const override;
//! Return the number of adjoint positrons emitted from the rxn at the given energy
unsigned getNumberOfEmittedAdjointPositrons( const double energy ) const override;
//! Return the reaction type
AdjointElectroatomicReactionType getReactionType() const override;
//! Simulate the reaction
void react( AdjointElectronState& electron,
ParticleBank& bank,
Data::SubshellType& shell_of_interaction ) const override;
private:
// The coupled elastic scattering distribution
std::shared_ptr<const CoupledElasticElectronScatteringDistribution>
d_scattering_distribution;
};
} // end MonteCarlo namespace
//---------------------------------------------------------------------------//
// Template Includes
//---------------------------------------------------------------------------//
#include "MonteCarlo_CoupledElasticAdjointElectroatomicReaction_def.hpp"
//---------------------------------------------------------------------------//
#endif // end MONTE_CARLO_COUPLED_ELASTIC_ADJOINT_ELECTROATOMIC_REACTION_HPP
//---------------------------------------------------------------------------//
// end MonteCarlo_CoupledElasticAdjointElectroatomicReaction.hpp
//---------------------------------------------------------------------------//
| 41.422222
| 149
| 0.680258
|
bam241
|
ec2a8c285241a13f5eef844047fb1e57b4ff992e
| 2,777
|
cpp
|
C++
|
src/sources.cpp
|
jake-stewart/fcd
|
333d1195cd225f07d90ac487eaaae792af28b5bb
|
[
"MIT"
] | null | null | null |
src/sources.cpp
|
jake-stewart/fcd
|
333d1195cd225f07d90ac487eaaae792af28b5bb
|
[
"MIT"
] | null | null | null |
src/sources.cpp
|
jake-stewart/fcd
|
333d1195cd225f07d90ac487eaaae792af28b5bb
|
[
"MIT"
] | null | null | null |
#include "../include/sources.hpp"
#include "../include/util.hpp"
#include <fstream>
bool compareSources(Source& l, Source& r) {
return (l.getHeuristic() < r.getHeuristic());
}
bool compareSourcesAlpha(Source& l, Source& r) {
return (l.getName() > r.getName());
}
bool Sources::hasHeuristic() {
return m_has_heuristic;
}
void Sources::resetHeuristics() {
for (Source& source : m_sources) {
source.setHeuristic(0);
}
}
void Sources::sort(std::string query) {
if (query.size() < m_last_query_size) {
resetHeuristics();
}
m_last_query_size = query.size();
std::string lower = toLower(query);
std::vector<std::string> words = camelSplit(lower);
if (m_has_heuristic) {
for (int i = 0; i < m_sources.size(); i++) {
if (m_sources[i].getHeuristic() == INT_MAX) {
break;
}
m_sources[i].calcHeuristic(lower, words);
}
}
else {
for (Source& source : m_sources) {
source.calcHeuristic(lower, words);
}
}
std::sort(m_sources.begin(), m_sources.end(), compareSources);
m_has_heuristic = true;
}
size_t Sources::size() {
return m_sources.size();
}
Source& Sources::get(int idx) {
return m_sources[idx];
}
void Sources::push_back(Source& source) {
return m_sources.push_back(source);
}
bool Sources::read(char *src_path) {
std::string line;
std::ifstream file(src_path);
if (!file) {
return false;
}
int state = 0;
std::string name;
std::string source_path;
int history = 0;
while (std::getline(file, line)) {
strip(line);
if (!line.size()) {
continue;
}
switch (state) {
case 0:
name = line;
state++;
break;
case 1:
source_path = line;
state++;
break;
case 2:
sscanf(line.c_str(), "%d", &history);
Source source;
source.setName(name);
source.setPath(src_path);
source.setColor(4);
source.setHistory(history);
m_sources.push_back(source);
state = 0;
break;
}
}
file.close();
return true;
}
void Sources::updateHistory(int selected_index) {
for (int i = 0; i < m_sources.size(); i++) {
Source& source = m_sources[i];
if (i == selected_index) {
source.setHistory(10);
}
else {
int history = source.getHistory() - 1;
if (history < 0) {
history = 0;
}
source.setHistory(history);
}
}
}
| 23.141667
| 66
| 0.517465
|
jake-stewart
|
ec2d3aad781b11c012dd86e53a71902d93a544fa
| 9,466
|
cpp
|
C++
|
src/d3d12/D3D12TLAccelerationStructure.cpp
|
amc522/DX12Scrap
|
d00aa6ae27a9a0594ce08739af564992f773d916
|
[
"MIT"
] | 1
|
2022-03-23T23:50:58.000Z
|
2022-03-23T23:50:58.000Z
|
src/d3d12/D3D12TLAccelerationStructure.cpp
|
amc522/DX12Scrap
|
d00aa6ae27a9a0594ce08739af564992f773d916
|
[
"MIT"
] | null | null | null |
src/d3d12/D3D12TLAccelerationStructure.cpp
|
amc522/DX12Scrap
|
d00aa6ae27a9a0594ce08739af564992f773d916
|
[
"MIT"
] | null | null | null |
#include "D3D12TLAccelerationStructure.h"
#include "SpanUtility.h"
#include "d3d12/D3D12Context.h"
#include <d3dx12.h>
#include <fmt/format.h>
namespace scrap::d3d12
{
TLAccelerationStructure::TLAccelerationStructure(const TLAccelerationStructureParams& params): mParams(params)
{
resizeInstanceDescsBuffer((uint32_t)params.initialReservedObjects);
}
tl::expected<TlasInstanceAllocation, TlasError>
TLAccelerationStructure::addInstance(const TLAccelerationStructureInstanceParams& params)
{
const glm::mat3x4 transposedTransform = glm::transpose(params.transform);
uint8_t flags = 0;
if((params.flags & TlasInstanceFlags::TriangleCullDisable) == TlasInstanceFlags::TriangleCullDisable)
{
flags |= D3D12_RAYTRACING_INSTANCE_FLAG_TRIANGLE_CULL_DISABLE;
}
if((params.flags & TlasInstanceFlags::TriangleFrontCcw) == TlasInstanceFlags::TriangleFrontCcw)
{
flags |= D3D12_RAYTRACING_INSTANCE_FLAG_TRIANGLE_FRONT_COUNTERCLOCKWISE;
}
if((params.flags & TlasInstanceFlags::ForceOpaque) == TlasInstanceFlags::ForceOpaque)
{
flags |= D3D12_RAYTRACING_INSTANCE_FLAG_FORCE_OPAQUE;
}
if((params.flags & TlasInstanceFlags::ForceNonOpaque) == TlasInstanceFlags::ForceNonOpaque)
{
flags |= D3D12_RAYTRACING_INSTANCE_FLAG_FORCE_NON_OPAQUE;
}
InternalInstance& internalInstance = mInstances.emplace_back();
internalInstance.blas = params.accelerationStructure;
internalInstance.id = mNextId++;
D3D12_RAYTRACING_INSTANCE_DESC& instanceDesc = mInstanceDescs.emplace_back();
instanceDesc.AccelerationStructure =
params.accelerationStructure->getBuffer().getResource()->GetGPUVirtualAddress();
instanceDesc.Flags = flags;
instanceDesc.InstanceContributionToHitGroupIndex = params.instanceId + params.instanceContributionToHitGroupIndex;
instanceDesc.InstanceID = params.instanceId;
instanceDesc.InstanceMask = params.instanceMask;
std::memcpy(instanceDesc.Transform, glm::value_ptr(transposedTransform), sizeof(instanceDesc.Transform));
mIsDirty = true;
return TlasInstanceAllocation(*this, internalInstance.id);
}
void TLAccelerationStructure::removeInstanceById(size_t id)
{
auto itr = std::find_if(mInstances.begin(), mInstances.end(),
[id](const InternalInstance& params) { return params.id == id; });
if(itr == mInstances.end()) { return; }
mInstances.erase_unsorted(itr);
mInstanceDescs.erase_unsorted(mInstanceDescs.begin() + std::distance(mInstances.begin(), itr));
mIsDirty = true;
}
void TLAccelerationStructure::updateInstanceTransformById(size_t id, const glm::mat4x3& transform)
{
auto itr = std::find_if(mInstances.begin(), mInstances.end(),
[id](const InternalInstance& params) { return params.id == id; });
if(itr == mInstances.end()) { return; }
const glm::mat3x4 transposedTransform = glm::transpose(transform);
size_t instanceDescIndex = std::distance(mInstances.begin(), itr);
std::memcpy(mInstanceDescs[instanceDescIndex].Transform, glm::value_ptr(transposedTransform),
sizeof(D3D12_RAYTRACING_INSTANCE_DESC::Transform));
mIsDirty = true;
}
bool TLAccelerationStructure::build(const GraphicsCommandList& commandList)
{
auto device = d3d12::DeviceContext::instance().getDevice5();
if(doesInstanceDescsNeedResize((uint32_t)mInstances.size()))
{
resizeInstanceDescsBuffer((uint32_t)mInstances.size());
}
else if(mIsDirty)
{
{
GpuBufferWriteGuard writeGuard(*mInstanceDescsGpuBuffer, commandList.get());
auto writeBuffer = writeGuard.getWriteBufferAs<D3D12_RAYTRACING_INSTANCE_DESC>();
std::copy(mInstanceDescs.cbegin(), mInstanceDescs.cend(), writeBuffer.begin());
}
mInstanceDescsGpuBuffer->transition(commandList.get(), D3D12_RESOURCE_STATE_COPY_DEST,
D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
}
D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS inputs = {};
inputs.DescsLayout = D3D12_ELEMENTS_LAYOUT_ARRAY;
inputs.Flags = TranslateAccelerationStructureBuildFlags(mParams.flags, mParams.buildOption);
inputs.NumDescs = (uint32_t)mInstances.size();
inputs.InstanceDescs = mInstanceDescsGpuBuffer->getResource()->GetGPUVirtualAddress();
inputs.Type = D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE_TOP_LEVEL;
D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO prebuildInfo = {};
device->GetRaytracingAccelerationStructurePrebuildInfo(&inputs, &prebuildInfo);
if(prebuildInfo.ResultDataMaxSizeInBytes == 0) { return false; }
if(mScratchGpuBuffer == nullptr || mScratchGpuBuffer->getByteSize() < prebuildInfo.ScratchDataSizeInBytes)
{
mScratchGpuBuffer = std::make_unique<Buffer>();
std::string scratchBufferName = fmt::format("{} (Scratch Buffer)", mParams.name);
BufferSimpleParams params;
params.accessFlags = ResourceAccessFlags::None;
params.byteSize = prebuildInfo.ScratchDataSizeInBytes;
params.flags = BufferFlags::UavEnabled;
params.name = scratchBufferName;
mScratchGpuBuffer->init(params);
}
if(mAccelerationStructureGpuBuffer == nullptr ||
mAccelerationStructureGpuBuffer->getByteSize() < prebuildInfo.ResultDataMaxSizeInBytes)
{
mAccelerationStructureGpuBuffer = std::make_unique<Buffer>();
BufferSimpleParams accelerationStructureParams;
accelerationStructureParams.accessFlags = ResourceAccessFlags::None;
accelerationStructureParams.byteSize = prebuildInfo.ResultDataMaxSizeInBytes;
accelerationStructureParams.flags = BufferFlags::AccelerationStructure;
accelerationStructureParams.initialResourceState = D3D12_RESOURCE_STATE_RAYTRACING_ACCELERATION_STRUCTURE;
accelerationStructureParams.name = mParams.name;
mAccelerationStructureGpuBuffer->init(accelerationStructureParams);
}
D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC desc = {};
desc.ScratchAccelerationStructureData = mScratchGpuBuffer->getResource()->GetGPUVirtualAddress();
desc.DestAccelerationStructureData = mAccelerationStructureGpuBuffer->getResource()->GetGPUVirtualAddress();
desc.Inputs = inputs;
/*std::vector<D3D12_RESOURCE_BARRIER> blasTransitions;
blasTransitions.reserve(mInstanceAccelerationStructures.size());
for(size_t i = 0; i < mInstanceAccelerationStructures.size(); ++i)
{
blasTransitions.push_back(
CD3DX12_RESOURCE_BARRIER::UAV(mInstanceAccelerationStructures[i]->getBuffer().getResource()));
}*/
// commandList.get()->ResourceBarrier((uint32_t)blasTransitions.size(), blasTransitions.data());
commandList.get4()->BuildRaytracingAccelerationStructure(&desc, 0, nullptr);
mScratchGpuBuffer->markAsUsed(commandList.get());
mInstanceDescsGpuBuffer->markAsUsed(commandList.get());
mAccelerationStructureGpuBuffer->markAsUsed(commandList.get());
return true;
}
void TLAccelerationStructure::markAsUsed(const GraphicsCommandList& commandList)
{
mAccelerationStructureGpuBuffer->markAsUsed(commandList.get());
for(InternalInstance& instance : mInstances)
{
instance.blas->markAsUsed(commandList);
}
}
bool TLAccelerationStructure::isReady() const
{
return mAccelerationStructureGpuBuffer != nullptr && mAccelerationStructureGpuBuffer->isReady();
}
bool TLAccelerationStructure::doesInstanceDescsNeedResize(uint32_t newCapacity)
{
uint32_t requiredByteSize = AlignInteger((uint32_t)sizeof(D3D12_RAYTRACING_INSTANCE_DESC),
uint32_t(D3D12_RAYTRACING_INSTANCE_DESCS_BYTE_ALIGNMENT)) *
newCapacity;
return mInstanceDescsGpuBuffer == nullptr || mInstanceDescsGpuBuffer->getByteSize() < requiredByteSize;
}
void TLAccelerationStructure::resizeInstanceDescsBuffer(uint32_t capacity)
{
mInstanceDescsGpuBuffer = std::make_unique<d3d12::Buffer>();
std::string instanceDescsName = fmt::format("{} (InstanceDescs)", mParams.name);
BufferStructuredParams instanceDescsParams;
instanceDescsParams.accessFlags = mParams.instanceDescs.accessFlags | ResourceAccessFlags::CpuWrite;
instanceDescsParams.elementByteSize = AlignInteger((uint32_t)sizeof(D3D12_RAYTRACING_INSTANCE_DESC),
uint32_t(D3D12_RAYTRACING_INSTANCE_DESCS_BYTE_ALIGNMENT));
instanceDescsParams.flags = mParams.instanceDescs.bufferFlags | BufferFlags::NonPixelShaderResource;
instanceDescsParams.name = instanceDescsName;
instanceDescsParams.numElements = capacity;
mInstanceDescsGpuBuffer->init(instanceDescsParams, ToByteSpan(mInstanceDescs));
}
TlasInstanceAllocation& TlasInstanceAllocation::operator=(TlasInstanceAllocation&& other)
{
mAccelerationStructure = other.mAccelerationStructure;
other.mAccelerationStructure = nullptr;
mId = other.mId;
other.mId = std::numeric_limits<size_t>::max();
return *this;
}
TlasInstanceAllocation::~TlasInstanceAllocation()
{
if(mAccelerationStructure == nullptr) { return; }
mAccelerationStructure->removeInstanceById(mId);
}
void TlasInstanceAllocation::updateTransform(const glm::mat4x3& transform)
{
mAccelerationStructure->updateInstanceTransformById(mId, transform);
}
} // namespace scrap::d3d12
| 39.940928
| 118
| 0.745933
|
amc522
|
ec33efdf2740ea12d73fc3b379caa7e9e8e9037b
| 21,411
|
cpp
|
C++
|
Samples/Win7Samples/multimedia/WMP/Wizards/services/templates/1033/Type1/GetInfo.cpp
|
windows-development/Windows-classic-samples
|
96f883e4c900948e39660ec14a200a5164a3c7b7
|
[
"MIT"
] | 8
|
2017-04-30T17:38:27.000Z
|
2021-11-29T00:59:03.000Z
|
Samples/Win7Samples/multimedia/WMP/Wizards/services/templates/1033/Type1/GetInfo.cpp
|
TomeSq/Windows-classic-samples
|
96f883e4c900948e39660ec14a200a5164a3c7b7
|
[
"MIT"
] | null | null | null |
Samples/Win7Samples/multimedia/WMP/Wizards/services/templates/1033/Type1/GetInfo.cpp
|
TomeSq/Windows-classic-samples
|
96f883e4c900948e39660ec14a200a5164a3c7b7
|
[
"MIT"
] | 2
|
2020-08-11T13:21:49.000Z
|
2021-09-01T10:41:51.000Z
|
#include "stdafx.h"
#include "[!output root].h"
////////////////////////////////////////////////////////////////////
// C[!output Safe_root]
// GetItemInfo method
// GetContentPartnerInfo method
// GetStreamingURL method
// GetCatalogURL method
// GetTemplate method
//
// Copyright (c) Microsoft Corporation. All rights reserved.
////////////////////////////////////////////////////////////////////
extern CONTENT_PARTNER_GLOBALS g;
HRESULT STDMETHODCALLTYPE C[!output Safe_root]::GetItemInfo(
BSTR bstrInfoName, // in
VARIANT *pContext, // in
VARIANT *pData) // out
{
WCHAR url[INTERNET_MAX_URL_LENGTH] = L"";
HRESULT hr = S_OK;
// Set output parameter type to VT_EMPTY in case we fail.
if(NULL != pData)
{
VariantInit(pData);
}
if(NULL == bstrInfoName || NULL == pContext || NULL == pData)
{
return E_INVALIDARG;
}
ATLTRACE2("%x: GetItemInfo: pstrInfoName = %S.\n", GetCurrentThreadId(), bstrInfoName);
if( 0 == wcscmp(bstrInfoName, g_szItemInfo_PopupURL) )
{
// ToDo: Get the index of the popup by inspecting pContext->lVal.
wcscpy_s(url, INTERNET_MAX_URL_LENGTH, g_rootURL);
wcscat_s(url, INTERNET_MAX_URL_LENGTH, L"Pages/Popup.htm");
pData->bstrVal = SysAllocString(url);
if(NULL != pData->bstrVal)
{
pData->vt = VT_BSTR;
}
else
{
hr = E_OUTOFMEMORY;
}
// Note: The caller must free pData->bstrVal.
}
else if( 0 == wcscmp(bstrInfoName, g_szItemInfo_AuthenticationSuccessURL) )
{
if(VT_I4 == pContext->vt)
{
// pContext holds the index of an authentication-success Web page.
// The sample store has only one authentication-success Web page,
// and its index is 1.
switch (pContext->lVal)
{
case 1:
wcscpy_s(url, INTERNET_MAX_URL_LENGTH, g_rootURL);
wcscat_s(url, INTERNET_MAX_URL_LENGTH, L"Pages/AuthenticationSuccess1.htm");
pData->bstrVal = SysAllocString(url);
// The caller must free pData->bstrVal.
if(NULL != pData->bstrVal)
{
pData->vt = VT_BSTR;
}
else
{
hr = E_OUTOFMEMORY;
}
break;
default:
hr = E_INVALIDARG;
} // switch
} // if(VT_I4 == pContext->vt)
else
{
hr = E_INVALIDARG;
}
} // g_szItemInfo_AuthenticationSuccessURL
else if( 0 == wcscmp(bstrInfoName, g_szItemInfo_LoginFailureURL) )
{
// ToDo: Get the index by inspecting pContext->ulVal.
wcscpy_s(url, INTERNET_MAX_URL_LENGTH, g_rootURL);
wcscat_s(url, INTERNET_MAX_URL_LENGTH, L"Pages/LoginFailure.htm");
pData->bstrVal = SysAllocString(url);
if(NULL != pData->bstrVal)
{
pData->vt = VT_BSTR;
}
else
{
hr = E_OUTOFMEMORY;
}
// The caller must free pData->bstrVal.
}
else if( 0 == wcscmp(bstrInfoName, g_szItemInfo_HTMLViewURL) )
{
// We are passed a string value from an ASX file.
// <param name="HTMLFLINK" value="xxx">
// ToDo: Get the string by inspecting pContext->bstrVal.
wcscpy_s(url, INTERNET_MAX_URL_LENGTH, g_rootURL);
wcscat_s(url, INTERNET_MAX_URL_LENGTH, L"Pages/HtmlView.htm");
pData->bstrVal = SysAllocString(url);
if(NULL != pData->bstrVal)
{
pData->vt = VT_BSTR;
}
else
{
hr = E_OUTOFMEMORY;
}
// The caller must free pData->bstrVal;
}
else if( 0 == wcscmp(bstrInfoName, g_szItemInfo_PopupCaption) )
{
// ToDo: Get the index by inspecting pContext->lVal.
pData->bstrVal = SysAllocString(L"CP Test Popup Caption");
if(NULL != pData->bstrVal)
{
pData->vt = VT_BSTR;
}
else
{
hr = E_OUTOFMEMORY;
}
// The caller must free pData->bstrVal.
}
else if( 0 == wcscmp(bstrInfoName, g_szItemInfo_ForgetPasswordURL) )
{
wcscpy_s(url, INTERNET_MAX_URL_LENGTH, g_rootURL);
wcscat_s(url, INTERNET_MAX_URL_LENGTH, L"Pages/ForgotPassword.htm");
pData->bstrVal = SysAllocString(url);
if(NULL != pData->bstrVal)
{
pData->vt = VT_BSTR;
}
else
{
hr = E_OUTOFMEMORY;
}
// The caller must free pData->bstrVal.
}
else if( 0 == wcscmp(bstrInfoName, g_szItemInfo_CreateAccountURL) )
{
wcscpy_s(url, INTERNET_MAX_URL_LENGTH, g_rootURL);
wcscat_s(url, INTERNET_MAX_URL_LENGTH, L"Pages/CreateAccount.htm");
pData->bstrVal = SysAllocString(url);
if(NULL != pData->bstrVal)
{
pData->vt = VT_BSTR;
}
else
{
hr = E_OUTOFMEMORY;
}
// The caller must free pData->bstrVal.
}
else if( 0 == wcscmp(bstrInfoName, g_szItemInfo_ArtistArtURL) )
{
// ToDo: Get the artist ID by inspecting pContext->ulVal.
wcscpy_s(url, INTERNET_MAX_URL_LENGTH, g_rootURL);
wcscat_s(url, INTERNET_MAX_URL_LENGTH, L"Images/Artist.png");
pData->bstrVal = SysAllocString(url);
if(NULL != pData->bstrVal)
{
pData->vt = VT_BSTR;
}
else
{
hr = E_OUTOFMEMORY;
}
// The caller must free pData->bstrVal.
}
else if( 0 == wcscmp(bstrInfoName, g_szItemInfo_AlbumArtURL) )
{
// ToDo: Get the album ID by inspecting pContext->ulVal.
wcscpy_s(url, INTERNET_MAX_URL_LENGTH, g_rootURL);
wcscat_s(url, INTERNET_MAX_URL_LENGTH, L"Images/Album.png");
pData->bstrVal = SysAllocString(url);
if(NULL != pData->bstrVal)
{
pData->vt = VT_BSTR;
}
else
{
hr = E_OUTOFMEMORY;
}
// The caller must free pData->bstrVal.
}
else if( 0 == wcscmp(bstrInfoName, g_szItemInfo_ListArtURL) )
{
// ToDo: Get the list ID by inspecting pContext->ulVal.
wcscpy_s(url, INTERNET_MAX_URL_LENGTH, g_rootURL);
wcscat_s(url, INTERNET_MAX_URL_LENGTH, L"Images/List.png");
pData->bstrVal = SysAllocString(url);
if(NULL != pData->bstrVal)
{
pData->vt = VT_BSTR;
}
else
{
hr = E_OUTOFMEMORY;
}
// The caller must free pData->bstrVal.
}
else if( 0 == wcscmp(bstrInfoName, g_szItemInfo_GenreArtURL) )
{
// ToDo: Get the genre ID by inspecting pContext->ulVal.
wcscpy_s(url, INTERNET_MAX_URL_LENGTH, g_rootURL);
wcscat_s(url, INTERNET_MAX_URL_LENGTH, L"Images/Genre.png");
;
pData->bstrVal = SysAllocString(url);
if(NULL != pData->bstrVal)
{
pData->vt = VT_BSTR;
}
else
{
hr = E_OUTOFMEMORY;
}
// The caller must free pData->bstrVal.
}
else if( 0 == wcscmp(bstrInfoName, g_szItemInfo_SubGenreArtURL) )
{
// ToDo: Get the sub-genre ID by inspecting pContext->ulVal.
wcscpy_s(url, INTERNET_MAX_URL_LENGTH, g_rootURL);
wcscat_s(url, INTERNET_MAX_URL_LENGTH, L"Images/Subgenre.png");
pData->bstrVal = SysAllocString(url);
if(NULL != pData->bstrVal)
{
pData->vt = VT_BSTR;
}
else
{
hr = E_OUTOFMEMORY;
}
// The caller must free pData->bstrVal.
}
else if( 0 == wcscmp(bstrInfoName, g_szItemInfo_RadioArtURL) )
{
// ToDo: Get the radio playlist ID by inspecting pContext->ulVal.
wcscpy_s(url, INTERNET_MAX_URL_LENGTH, g_rootURL);
wcscat_s(url, INTERNET_MAX_URL_LENGTH, L"Images/Radio.png");
pData->bstrVal = SysAllocString(url);
if(NULL != pData->bstrVal)
{
pData->vt = VT_BSTR;
}
else
{
hr = E_OUTOFMEMORY;
}
// The caller must free pData->bstrVal.
}
else if( 0 == wcscmp(bstrInfoName, g_szItemInfo_TreeListIconURL) )
{
// ToDo: Get the list ID by inspecting pContext->ulVal.
wcscpy_s(url, INTERNET_MAX_URL_LENGTH, g_rootURL);
wcscat_s(url, INTERNET_MAX_URL_LENGTH, L"Images/Tree.png");
pData->bstrVal = SysAllocString(url);
if(NULL != pData->bstrVal)
{
pData->vt = VT_BSTR;
}
else
{
hr = E_OUTOFMEMORY;
}
// The caller must free pData->bstrVal.
}
else if( 0 == wcscmp(bstrInfoName, g_szItemInfo_ErrorDescription) )
{
// ToDo: Get the error code by inspecting pContext->scode.
pData->bstrVal = SysAllocString(L"Test error description. The operation was aborted.");
if(NULL != pData->bstrVal)
{
pData->vt = VT_BSTR;
}
else
{
hr = E_OUTOFMEMORY;
}
// The caller must free pData->bstrVal.
}
else if( 0 == wcscmp(bstrInfoName, g_szItemInfo_ErrorURL) )
{
// ToDo: Get the error code by inspecting pContext->scode.
wcscpy_s(url, INTERNET_MAX_URL_LENGTH, g_rootURL);
wcscat_s(url, INTERNET_MAX_URL_LENGTH, L"Pages/Error.htm");
pData->bstrVal = SysAllocString(url);
if(NULL != pData->bstrVal)
{
pData->vt = VT_BSTR;
}
else
{
hr = E_OUTOFMEMORY;
}
// The caller must free pData->bstrVal.
}
else if( 0 == wcscmp(bstrInfoName, g_szItemInfo_ErrorURLLinkText) )
{
// ToDo: Get the error code by inspecting pContext->scode.
pData->bstrVal = SysAllocString(L"Test error link text: Error Details");
if(NULL != pData->bstrVal)
{
pData->vt = VT_BSTR;
}
else
{
hr = E_OUTOFMEMORY;
}
// The caller must free pData->bstrVal.
}
else if( 0 == wcscmp(bstrInfoName, g_szItemInfo_ALTLoginURL) )
{
wcscpy_s(url, INTERNET_MAX_URL_LENGTH, g_rootURL);
wcscat_s(url, INTERNET_MAX_URL_LENGTH, L"Pages/AltLogin.htm?DlgX=800&DlgY=400");
pData->bstrVal = SysAllocString(url);
if(NULL != pData->bstrVal)
{
pData->vt = VT_BSTR;
}
else
{
hr = E_OUTOFMEMORY;
}
// The caller must free pData->bstrVal.
}
else if( 0 == wcscmp(bstrInfoName, g_szItemInfo_ALTLoginCaption) )
{
pData->bstrVal = SysAllocString(L"Alternative Login");
if(NULL != pData->bstrVal)
{
pData->vt = VT_BSTR;
}
else
{
hr = E_OUTOFMEMORY;
}
// The caller must free pData->bstrVal.
}
else
{
hr = E_UNEXPECTED;
}
return hr;
}
HRESULT STDMETHODCALLTYPE C[!output Safe_root]::GetContentPartnerInfo(
BSTR bstrInfoName,
VARIANT *pData)
{
HRESULT hr = S_OK;
// Set the output parameter type to VT_EMPTY in case we fail.
if(NULL != pData)
{
VariantInit(pData);
}
if(NULL == bstrInfoName || NULL == pData)
{
return E_INVALIDARG;
}
ATLTRACE2("%x: GetContentPartnerInfo: bstrInfoName = %S.\n", GetCurrentThreadId(), bstrInfoName);
if(0 == wcscmp(bstrInfoName, g_szContentPartnerInfo_LoginState))
{
pData->vt = VT_BOOL;
if( 1 == InterlockedCompareExchange( &(g.userLoggedIn), 0, 0 ) )
{
ATLTRACE2("%x: GetContentPartnerInfo: User is logged in.\n", GetCurrentThreadId());
pData->boolVal = VARIANT_TRUE;
}
else
{
ATLTRACE2("%x: GetContentPartnerInfo: User is not logged in.\n", GetCurrentThreadId());
pData->boolVal = VARIANT_FALSE;
}
}
else if(0 == wcscmp(bstrInfoName, g_szContentPartnerInfo_MediaPlayerAccountType))
{
// ToDo: Determine the account type.
pData->vt = VT_UI4;
pData->ulVal = wmpatSubscription; // or another enumeration member
}
else if(0 == wcscmp(bstrInfoName, g_szContentPartnerInfo_AccountType))
{
pData->bstrVal = SysAllocString(L"Super Subscription Account");
if(NULL != pData->bstrVal)
{
pData->vt = VT_BSTR;
}
else
{
hr = E_OUTOFMEMORY;
}
// The caller must free pData->bstrVal.
}
else if(0 == wcscmp(bstrInfoName, g_szContentPartnerInfo_HasCachedCredentials))
{
ATLTRACE2("%x: GetContentPartnerInfo: bstrInfoName = %S.\n", GetCurrentThreadId(), bstrInfoName);
pData->vt = VT_BOOL;
LONG cached = 0;
HaveCachedCredentials(&cached);
if(1 == cached)
{
pData->boolVal = VARIANT_TRUE;
ATLTRACE2("%x: GetContentPartnerInfo: Plug-in has cached credentials.\n", GetCurrentThreadId());
}
else
{
pData->boolVal = VARIANT_FALSE;
ATLTRACE2("%x: GetContentPartnerInfo: Plug-in does not have cached credentials.\n", GetCurrentThreadId());
}
}
else if(0 == wcscmp(bstrInfoName, g_szContentPartnerInfo_LicenseRefreshAdvanceWarning))
{
pData->vt = VT_UI4;
pData->ulVal = 5; // or some other number of days
}
else if(0 == wcscmp(bstrInfoName, g_szContentPartnerInfo_PurchasedTrackRequiresReDownload))
{
pData->vt= VT_BOOL;
pData->boolVal = VARIANT_TRUE; // or VARIANT_FALSE
}
else if(0 == wcscmp(bstrInfoName, g_szContentPartnerInfo_MaximumTrackPurchasePerPurchase))
{
pData->vt = VT_UI4;
pData->ulVal = 30; // or some other number of tracks
}
else if(0 == wcscmp(bstrInfoName, g_szContentPartnerInfo_AccountBalance))
{
pData->bstrVal = SysAllocString(L"$dd.cc");
if(NULL != pData->bstrVal)
{
pData->vt = VT_BSTR;
}
else
{
hr = E_OUTOFMEMORY;
}
// The caller must free pData->bstrVal.
}
else if(0 == wcscmp(bstrInfoName, g_szContentPartnerInfo_UserName))
{
pData->bstrVal = SysAllocString(L"xxx");
if(NULL != pData->bstrVal)
{
pData->vt = VT_BSTR;
}
else
{
hr = E_OUTOFMEMORY;
}
// The caller must free pData->bstrVal.
}
else
{
hr = E_UNEXPECTED;
}
return hr;
}
HRESULT STDMETHODCALLTYPE C[!output Safe_root]::GetStreamingURL(
WMPStreamingType st,
VARIANT *pStreamContext,
BSTR *pbstrURL)
{
HRESULT hr = S_OK;
WCHAR url[INTERNET_MAX_URL_LENGTH] = L"";
ULONG trackId = 0xffffffff;
ULONG availableUrlStrings = 0;
// Set the output parameter to NULL in case we fail.
if(NULL != pbstrURL)
{
*pbstrURL = NULL;
}
if(NULL == pStreamContext || NULL == pbstrURL)
{
return E_INVALIDARG;
}
if(VT_UI4 != pStreamContext->vt)
{
return E_INVALIDARG;
}
ATLTRACE2("%x: GetStreamingURL: st = %d.\n", GetCurrentThreadId(), st);
switch(st)
{
case wmpstMusic:
wcscpy_s(url, INTERNET_MAX_URL_LENGTH, g_audioRootURL);
// Get the track ID from pContext.
trackId = pStreamContext->ulVal;
availableUrlStrings = sizeof(g_tracks)/sizeof(g_tracks[0]);
if(trackId < availableUrlStrings)
{
wcscat_s(url, INTERNET_MAX_URL_LENGTH, g_tracks[trackId]);
}
else
{
wcscat_s(url, INTERNET_MAX_URL_LENGTH, g_placeholderTrack);
}
*pbstrURL = SysAllocString(url);
if(NULL == *pbstrURL)
{
hr = E_OUTOFMEMORY;
}
// The caller must free *pbstrURL.
break;
case wmpstVideo:
// ToDo: Get the media item ID by inspecting pStreamContext->ulVal.
// Return the URL.
case wmpstRadio:
// ToDo: Get the media item ID by inspecting pStreamContext->ulVal.
// Return the URL.
default:
*pbstrURL = NULL;
hr = E_UNEXPECTED;
break;
} // switch
return hr;
}
HRESULT STDMETHODCALLTYPE C[!output Safe_root]::GetCatalogURL(
DWORD dwCatalogVersion,
DWORD dwCatalogSchemaVersion,
LCID /*catalogLCID*/,
DWORD *pdwNewCatalogVersion, // out
BSTR *pbstrCatalogURL, // out
VARIANT *pExpirationDate) // out
{
WCHAR url[INTERNET_MAX_URL_LENGTH] = L"";
HRESULT hr = S_OK;
// Initialize output parameters in case we fail.
if(NULL != pdwNewCatalogVersion)
{
*pdwNewCatalogVersion = 0;
}
if(NULL != pbstrCatalogURL)
{
*pbstrCatalogURL = NULL;
}
if(NULL != pExpirationDate)
{
VariantInit(pExpirationDate);
}
if(NULL == pdwNewCatalogVersion ||
NULL == pbstrCatalogURL ||
NULL == pExpirationDate ||
NULL == pdwNewCatalogVersion ||
NULL == pbstrCatalogURL ||
NULL == pExpirationDate)
{
return E_INVALIDARG;
}
ATLTRACE("%x: GetCatalogURL:\n", GetCurrentThreadId());
ATLTRACE("%x: GetCatalogVersion: dwCatalogVersion = %d.\n", GetCurrentThreadId(), dwCatalogVersion);
ATLTRACE("%x: GetCatalogVersion: dwCatalogSchemaVersion = %d.\n", GetCurrentThreadId(), dwCatalogSchemaVersion);
*pdwNewCatalogVersion = 3;
wcscpy_s(url, INTERNET_MAX_URL_LENGTH, g_rootURL);
wcscat_s(url, INTERNET_MAX_URL_LENGTH, L"Catalog/3/catalog.wmdb.lz");
*pbstrCatalogURL = SysAllocString(url);
if(NULL == *pbstrCatalogURL)
{
hr = E_OUTOFMEMORY;
}
// The caller must free *pbstrCatalogURL.
pExpirationDate->vt = VT_DATE;
pExpirationDate->date = 43831.00; // January 1, 2020
return hr;
}
HRESULT STDMETHODCALLTYPE C[!output Safe_root]::GetTemplate(
WMPTaskType task,
BSTR location,
VARIANT* /*pContext*/,
BSTR /*clickLocation*/,
VARIANT* /*pClickContext*/,
BSTR /*bstrFilter*/,
BSTR /*bstrViewParams*/,
BSTR *pbstrTemplateURL, // out
WMPTemplateSize *pTemplateSize) // out
{
HRESULT hr = S_OK;
WCHAR url[INTERNET_MAX_URL_LENGTH] = L"";
// Initialize output parameters in case we fail.
if(NULL != pbstrTemplateURL)
{
*pbstrTemplateURL = NULL;
}
if(NULL != pTemplateSize)
{
*pTemplateSize = wmptsSmall; // wmpstSmall = 0
}
if(NULL == pbstrTemplateURL || NULL == pTemplateSize)
{
return E_INVALIDARG;
}
ATLTRACE2("%x: GetTemplate: task = %d, location = %S.\n", GetCurrentThreadId(), task, location);
switch(task)
{
case wmpttBrowse:
if( 0 == wcscmp(g_szRootLocation, location) )
{
*pTemplateSize = wmptsLarge;
}
else
{
*pTemplateSize = wmptsMedium;
}
wcscpy_s(url, INTERNET_MAX_URL_LENGTH, g_rootURL);
wcscat_s(url, INTERNET_MAX_URL_LENGTH, L"Pages/library.htm");
*pbstrTemplateURL = SysAllocString(url);
if(NULL == *pbstrTemplateURL)
{
hr = E_OUTOFMEMORY;
}
// The caller must free *pbstrTemplateURL.
break;
case wmpttSync:
*pTemplateSize = wmptsMedium;
wcscpy_s(url, INTERNET_MAX_URL_LENGTH, g_rootURL);
wcscat_s(url, INTERNET_MAX_URL_LENGTH, L"Pages/sync.htm");
*pbstrTemplateURL = SysAllocString(url);
if(NULL == *pbstrTemplateURL)
{
hr = E_OUTOFMEMORY;
}
// The caller must free *pbstrTemplateURL.
break;
case wmpttBurn:
if( 0 == wcscmp(g_szAllCPAlbumIDs, location) ||
0 == wcscmp(g_szCPAlbumID, location) )
{
*pTemplateSize = wmptsMedium;
wcscpy_s(url, INTERNET_MAX_URL_LENGTH, g_rootURL);
wcscat_s(url, INTERNET_MAX_URL_LENGTH, L"Pages/BurnAlbums.htm");
}
else if( 0 == wcscmp(g_szAllCPTrackIDs, location) ||
0 == wcscmp(g_szCPTrackID, location) )
{
*pTemplateSize = wmptsMedium;
wcscpy_s(url, INTERNET_MAX_URL_LENGTH, g_rootURL);
wcscat_s(url, INTERNET_MAX_URL_LENGTH, L"Pages/BurnSongs.htm");
}
else
{
*pTemplateSize = wmptsSmall;
wcscpy_s(url, INTERNET_MAX_URL_LENGTH, g_rootURL);
wcscat_s(url, INTERNET_MAX_URL_LENGTH, L"Pages/Burn.htm");
}
*pbstrTemplateURL = SysAllocString(url);
if(NULL == *pbstrTemplateURL)
{
hr = E_OUTOFMEMORY;
}
// The caller must free *pbstrTemplateURL.
break;
case wmpttCurrent:
*pTemplateSize = wmptsSmall;
wcscpy_s(url, INTERNET_MAX_URL_LENGTH, g_rootURL);
wcscat_s(url, INTERNET_MAX_URL_LENGTH, L"Pages/library.htm");
*pbstrTemplateURL = SysAllocString(url);
if(NULL == *pbstrTemplateURL)
{
hr = E_OUTOFMEMORY;
}
// The caller must free *pbstrTemplateURL.
break;
default:
*pbstrTemplateURL = NULL;
hr = E_INVALIDARG;
break;
}
return hr;
}
| 24.983664
| 116
| 0.570875
|
windows-development
|
ec341849a7e98609cf307c95d79d0d5b4ced21e4
| 4,904
|
hpp
|
C++
|
Source/AllProjects/CQCIntf/CQCIntfEd/CQCIntfEd_EditXlatsDlg_.hpp
|
MarkStega/CQC
|
c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07
|
[
"MIT"
] | 51
|
2020-12-26T18:17:16.000Z
|
2022-03-15T04:29:35.000Z
|
Source/AllProjects/CQCIntf/CQCIntfEd/CQCIntfEd_EditXlatsDlg_.hpp
|
MarkStega/CQC
|
c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07
|
[
"MIT"
] | null | null | null |
Source/AllProjects/CQCIntf/CQCIntfEd/CQCIntfEd_EditXlatsDlg_.hpp
|
MarkStega/CQC
|
c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07
|
[
"MIT"
] | 4
|
2020-12-28T07:24:39.000Z
|
2021-12-29T12:09:37.000Z
|
//
// FILE NAME: CQCIntfEd_EditXlatsDlg_.hpp
//
// AUTHOR: Dean Roddey
//
// CREATED: 12/21/2015
//
// COPYRIGHT: Charmed Quark Systems, Ltd @ 2020
//
// This software is copyrighted by 'Charmed Quark Systems, Ltd' and
// the author (Dean Roddey.) It is licensed under the MIT Open Source
// license:
//
// https://opensource.org/licenses/MIT
//
// DESCRIPTION:
//
// This is the header for the CQCIntfEd_EditXlatsDlg.cpp file, which allows the user
// to edit the attributes of the Xlats mixin class.
//
// CAVEATS/GOTCHAS:
//
// LOG:
//
// $Log$
//
#pragma once
#pragma CIDLIB_PACK(CIDLIBPACK)
// ---------------------------------------------------------------------------
// CLASS: TEditXlatsDlg
// PREFIX: dlg
// ---------------------------------------------------------------------------
class TEditXlatsDlg : public TDlgBox, public MMCLBIPEIntf
{
public :
// -------------------------------------------------------------------
// Constructors and Destructor
// -------------------------------------------------------------------
TEditXlatsDlg();
~TEditXlatsDlg();
// -------------------------------------------------------------------
// Public, inherited methods
// -------------------------------------------------------------------
tCIDLib::TBoolean bIPETestCanEdit
(
const tCIDCtrls::TWndId widSrc
, const tCIDLib::TCard4 c4ColInd
, TAttrData& adatFill
, tCIDLib::TBoolean& bValueSet
) override;
tCIDLib::TBoolean bIPEValidate
(
const TString& strSrc
, TAttrData& adatSrc
, const TString& strNewVal
, TString& strErrMsg
, tCIDLib::TCard8& c8UserId
) const override;
// -------------------------------------------------------------------
// Public, non-virtual methods
// -------------------------------------------------------------------
tCIDLib::TBoolean bRun
(
const TWindow& wndOwner
, TIEXlatsWrap& iewXlats
);
protected :
// -------------------------------------------------------------------
// Protected inherited methods
// -------------------------------------------------------------------
tCIDLib::TBoolean bCreated() override;
private :
// -------------------------------------------------------------------
// Unimplemented
// -------------------------------------------------------------------
TEditXlatsDlg(const TEditXlatsDlg&);
tCIDLib::TVoid operator=(const TEditXlatsDlg&);
// -------------------------------------------------------------------
// Private, non-virtual methods
// -------------------------------------------------------------------
tCIDCtrls::EEvResponses eClickHandler
(
TButtClickInfo& wnotEvent
);
tCIDCtrls::EEvResponses eListHandler
(
TListChangeInfo& wnotEvent
);
tCIDLib::TVoid GatherInfo
(
MCQCIntfXlatIntf& iewTar
);
// -------------------------------------------------------------------
// Private data members
//
// m_c4NextId
// For in place editing purposes, we assign a unique id to each item we
// put into the list box.
//
// m_iewEdit
// We have to have somewhere to put the edited data until we can get it
// back to the caller's parameter.
//
// m_piewOrg
// A pointer to the incoming data so that we can get the incoming data
// loaded up.
//
// m_pwndXXX
// Some typed pointers we get to some of our child widgets we need to
// interact with on a typed basis.
// -------------------------------------------------------------------
tCIDLib::TCard4 m_c4NextId;
TIEXlatsWrap m_iewEdit;
TIEXlatsWrap* m_piewOrg;
TPushButton* m_pwndAddButton;
TPushButton* m_pwndCancelButton;
TMultiColListBox* m_pwndList;
TPushButton* m_pwndRemoveButton;
TPushButton* m_pwndRemoveAllButton;
TPushButton* m_pwndSaveButton;
// -------------------------------------------------------------------
// Magic Macros
// -------------------------------------------------------------------
RTTIDefs(TEditXlatsDlg,TDlgBox)
};
#pragma CIDLIB_POPPACK
| 32.263158
| 85
| 0.385196
|
MarkStega
|
ec384b87b498a5ebbe84e053831d8c2e5ef35a3b
| 151
|
cpp
|
C++
|
chapters/fact.cpp
|
Raymain1944/CPPLv1
|
96e5fd5347a336870fc868206ebfe44f88ce69eb
|
[
"Apache-2.0"
] | null | null | null |
chapters/fact.cpp
|
Raymain1944/CPPLv1
|
96e5fd5347a336870fc868206ebfe44f88ce69eb
|
[
"Apache-2.0"
] | null | null | null |
chapters/fact.cpp
|
Raymain1944/CPPLv1
|
96e5fd5347a336870fc868206ebfe44f88ce69eb
|
[
"Apache-2.0"
] | null | null | null |
int fact(int number) {
int a = 1;
while (number > 1) {
a *= number--;
}
if (number == 0) {
a = 1;
}
return a;
}
| 15.1
| 24
| 0.384106
|
Raymain1944
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.