blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
2
247
content_id
stringlengths
40
40
detected_licenses
listlengths
0
57
license_type
stringclasses
2 values
repo_name
stringlengths
4
111
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
58
visit_date
timestamp[ns]date
2015-07-25 18:16:41
2023-09-06 10:45:08
revision_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
committer_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
github_id
int64
3.89k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
25 values
gha_event_created_at
timestamp[ns]date
2012-06-07 00:51:45
2023-09-14 21:58:52
gha_created_at
timestamp[ns]date
2008-03-27 23:40:48
2023-08-24 19:49:39
gha_language
stringclasses
159 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
7
10.5M
extension
stringclasses
111 values
filename
stringlengths
1
195
text
stringlengths
7
10.5M
ed6c4543aa3f9d446bdb2e1bba69949cf4ad07ac
111c3ebecfa9eac954bde34b38450b0519c45b86
/SDK_Perso/include/graphicsxp/Include/Renderer/Pass.h
75e44050c9aa97b1a9e58f5dd8fb1ec4caeea88b
[]
no_license
1059444127/NH90
25db189bb4f3b7129a3c6d97acb415265339dab7
a97da9d49b4d520ad169845603fd47c5ed870797
refs/heads/master
2021-05-29T14:14:33.309737
2015-10-05T17:06:10
2015-10-05T17:06:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
819
h
Pass.h
#ifndef _LOCKON_PASS_H_ #define _LOCKON_PASS_H_ #include "graphicsxp.h" namespace Graphics { class Context; class Pass { protected: int _passType; public: GRAPHICSXP_API Pass(int type); GRAPHICSXP_API ~Pass(); enum PassType { INVALID_PASS = -1, PASS_MAIN = 0, PASS_SHADOWMAP, // PASS_FLATSHADOW, PASS_ENV, PASS_MIRROR, PASS_MFD, PASS_MAP, PASS_MAP_SAT, // map view from satelite // PASS_Z_ONLY, PASS_IR, PASS_OLD_IR, // for full screen IR view PASS_CUSTOM, // for debug purposes PASS_REFRACTION, PASS_BOWWAVE, PASS_RADAR, ALL_PASSES }; GRAPHICSXP_API void setPassType(int type); inline int getPassType() const {return _passType;} GRAPHICSXP_API virtual bool begin(Context*); GRAPHICSXP_API virtual void end(Context*); }; }; #endif
060b959600ea28af67cf6b9940026a288c575d23
889e81bc910ba4ef7de55e7a61c24e49613bf179
/shareboard/classes/display/cVectorDrawWidget.cpp
a511e49176e0590f2fd3d9b3682619102d88fabc
[]
no_license
scuzzycheese/projects
8d4685b9e3afef2f344a9bf52ee329cb2dc45b33
274b0f3ee6b3f99c4971e4674d18b60c5a7eab76
refs/heads/master
2021-01-23T14:58:27.918080
2013-10-22T15:39:06
2013-10-22T15:39:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,855
cpp
cVectorDrawWidget.cpp
#include <QtGui> #include "cVectorDrawWidget.h" #include <iostream> cVectorDrawWidget::cVectorDrawWidget(QWidget *parent) : QWidget(parent) { setAttribute(Qt::WA_StaticContents); dScribbling = false; dScrolling = false; dCurrentPenWidth = 1; dCurrentPenColour = Qt::black; } void cVectorDrawWidget::setPenColorSlot(const QColor &newColor) { setPenColor(newColor); } void cVectorDrawWidget::setPenColor(const QColor &newColor) { dCurrentPenColour = newColor; } void cVectorDrawWidget::setPenWidthSlot(int newWidth) { setPenWidth(newWidth); } void cVectorDrawWidget::setPenWidth(int newWidth) { dCurrentPenWidth = 1 + newWidth; } void cVectorDrawWidget::clearImage() { engine->mClear(); dImage.fill(qRgb(255, 255, 255)); update(); } void cVectorDrawWidget::mResetMatrices() { QDial *angleDial = nativeParentWidget()->findChild<QDial *>("orientation"); angleDial->setValue(0); QSlider *scale = nativeParentWidget()->findChild<QSlider *>("scale"); scale->setValue(0); engine->mResetMatrices(); if(engine->mMatrixChanged()) emit mMatrixChanged(); } void cVectorDrawWidget::mousePressEvent(QMouseEvent *event) { if(event->button() == Qt::LeftButton) { //Set up the matrix to draw to, this is because //our world matrix could be rotated or moved or scaled. //TODO: Eventually the matrix inversion will take plave inside the //mStartNewLine method, because the engine will be the thing controlling //the matrices engine->mStartNewLine(event->pos(), dCurrentPenColour, dCurrentPenWidth); dScribbling = true; } if(event->button() == Qt::RightButton) { dScrolling = true; dLastPos = event->pos(); } } void cVectorDrawWidget::mouseMoveEvent(QMouseEvent *event) { if((event->buttons() & Qt::LeftButton) && dScribbling) { engine->mAddVectToLine(event->pos()); } if((event->buttons() & Qt::RightButton) && dScrolling) { QPoint diffPos = event->pos() - dLastPos; translate(diffPos); dLastPos = event->pos(); } } void cVectorDrawWidget::mouseReleaseEvent(QMouseEvent *event) { if(event->button() == Qt::LeftButton && dScribbling) { engine->mEndNewLine(); //Set the scribble state to false; dScribbling = false; } if((event->buttons() & Qt::RightButton) && dScrolling) { dScrolling = false; } } void cVectorDrawWidget::paintEvent(QPaintEvent * /* event */) { dImage.fill(qRgb(255, 255, 255)); deque<cVecLine> *lines = engine->mGetLines(); //Draw the existing lines in the queue for(deque<cVecLine>::iterator i = (*lines).begin(); i < (*lines).end(); i ++) { (*i).mDraw(dImage, engine->dWorldMatrix, engine->dScale); } //Draw the lines currently being drawn if(engine->mGetCurrentLine()) engine->mGetCurrentLine()->mDraw(dImage, engine->dWorldMatrix, engine->dScale); QPainter painter(this); painter.drawImage(QPoint(0, 0), dImage); //TODO: maybe take the update line out of the drawLine function update(); } void cVectorDrawWidget::resizeEvent(QResizeEvent *event) { if(width() > dImage.width() || height() > dImage.height()) { int newWidth = qMax(width() + 128, dImage.width()); int newHeight = qMax(height() + 128, dImage.height()); resizeImage(&dImage, QSize(newWidth, newHeight)); update(); } QWidget::resizeEvent(event); } //TODO: refactor this to redraw with vectors instead void cVectorDrawWidget::resizeImage(QImage *image, const QSize &newSize) { if(image->size() == newSize) return; QImage newImage(newSize, QImage::Format_RGB32); newImage.fill(qRgb(255, 255, 255)); QPainter painter(&newImage); painter.drawImage(QPoint(0, 0), *image); *image = newImage; } void cVectorDrawWidget::scaleSlot(const int &scale) { engine->mScale(scale); if(engine->mMatrixChanged()) emit mMatrixChanged(); } void cVectorDrawWidget::translate(const QPoint &transBy) { engine->mTranslate(transBy); if(engine->mMatrixChanged()) emit mMatrixChanged(); }
598af6882cc512e2ba17a77b86736f213b483b32
6a7959eeb89c330baaefd1062e7fea7c05cb0ff3
/cpp/src/VJGateDetector.cpp
7c5a9d62501213a5c7e78ee44bfbdb7590d457c7
[]
no_license
beeonlinecy/Gate_Detection_Viola_Jones
1687418869154c5cdc5caf0b02d2a9bb39491733
11fe5ffacfaca856b90dbc0dcd6abd820305c2b5
refs/heads/master
2023-05-01T05:37:26.091303
2018-11-13T23:30:22
2018-11-13T23:30:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
26,742
cpp
VJGateDetector.cpp
#include "opencv2/core.hpp" #include <opencv2/imgproc.hpp> #include "opencv2/objdetect/objdetect.hpp" #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include "stdio.h" #include <iostream> #include <Comm.h> #include <time.h> #include "Config.h" #include <cmath> #include "VJGateDetector.h" using namespace cv; using namespace std; namespace mav{ VJGateDetector::VJGateDetector() { this->tl_light.load("/jevois/modules/MavLab/FilterTest/model/0.8_30_t_l_corner_mad.xml"); this->tr_light.load("/jevois/modules/MavLab/FilterTest/model/0.8_30_t_r_corner_mad.xml"); this->br_light.load("/jevois/modules/MavLab/FilterTest/model/0.8_30_b_r_corner_mad.xml"); this->bl_light.load("/jevois/modules/MavLab/FilterTest/model/0.8_30_b_l_corner_mad.xml"); }; // VJGate::VJGate(Point _tl, Point _tr, Point _br, Point _bl) // { // this->tl = _tl; // this->tr = _tr; // this->br = _br; // this->bl = _bl; // }; Point_t Rect_center(Rect rect) { Point cvcenter = 0.5 * rect.tl() + 0.5 * rect.br(); Point_t center = {cvcenter.y, cvcenter.x}; return center; } void draw_corners(Mat& img, vector<Rect> corners, Scalar color) { for(int i = 0; i < corners.size(); i++) { circle(img, 0.5 * corners[i].tl() + 0.5 * corners[i].br(), 1, color, 5); } } vector<Polygon> VJGateDetector::extract_gates(vector<Rect> tl_corners, vector<Rect> tr_corners, vector<Rect> br_corners, vector<Rect> bl_corners) { vector<Polygon> gates; // tl -> tr -> br for(int tl = 0; tl < tl_corners.size(); tl++) { // connect tl -> tr for(int tr = 0; tr < tr_corners.size(); tr++) { // check connection tl -> tr if((tl_corners[tl].br().x < tr_corners[tr].tl().x) && \ (tl_corners[tl].br().y > tr_corners[tr].tl().y) && \ (tl_corners[tl].tl().y < tr_corners[tr].br().y)) { // connect tr -> br for(int br = 0; br < br_corners.size(); br++) { // check connection tr -> br if((tr_corners[tr].br().y < br_corners[br].tl().y) && \ (tr_corners[tr].tl().x < br_corners[br].br().x) && \ (tr_corners[tr].br().x > br_corners[br].tl().x)) { Point_t p_1 = Rect_center(tl_corners[tl]); Point_t p_2 = Rect_center(tr_corners[tr]); Point_t p_3 = Rect_center(br_corners[br]); float Len_1 = sqrtf(powf(p_1.col-p_2.col,2) + powf(p_1.row-p_2.row,2)); float Len_2 = sqrtf(powf(p_2.col-p_3.col,2) + powf(p_2.row-p_3.row,2)); if((Len_1 / Len_2 < 1.5) && (Len_2 / Len_1 < 1.5)) { Rect Virtual_corner(tl_corners[tl].tl() + \ br_corners[br].tl() - \ tr_corners[tr].tl() , tr_corners[tr].size()); Polygon detected_gate = {Rect_center(tl_corners[tl]), \ Rect_center(tr_corners[tr]), \ Rect_center(Virtual_corner), \ Rect_center(br_corners[br])}; gates.push_back(detected_gate); } } } } } } // tr -> br -> bl for(int tr = 0; tr < tr_corners.size(); tr++) { // connect tr -> br for(int br = 0; br < br_corners.size(); br++) { // check connection tr -> br if((tr_corners[tr].br().y < br_corners[br].tl().y) && \ (tr_corners[tr].tl().x < br_corners[br].br().x) && \ (tr_corners[tr].br().x > br_corners[br].tl().x)) { // connect br -> bl for(int bl = 0; bl < bl_corners.size(); bl++) { // check connection br -> bl if((br_corners[br].tl().x > bl_corners[bl].br().x) && \ (br_corners[br].tl().y < bl_corners[bl].br().y) && \ (br_corners[br].br().y > bl_corners[bl].tl().y)) { Point_t p_1 = Rect_center(tr_corners[tr]); Point_t p_2 = Rect_center(br_corners[br]); Point_t p_3 = Rect_center(bl_corners[bl]); float Len_1 = sqrtf(powf(p_1.col-p_2.col,2) + powf(p_1.row-p_2.row,2)); float Len_2 = sqrtf(powf(p_2.col-p_3.col,2) + powf(p_2.row-p_3.row,2)); if((Len_1 / Len_2 < 1.5) && (Len_2 / Len_1 < 1.5) && (Len_1 < 150) && (Len_2 < 150)) { Rect Virtual_corner(tr_corners[tr].tl() + \ bl_corners[bl].tl() - \ br_corners[br].tl() , br_corners[br].size()); Polygon detected_gate = {Rect_center(Virtual_corner), \ Rect_center(tr_corners[tr]), \ Rect_center(bl_corners[bl]), \ Rect_center(br_corners[br])}; gates.push_back(detected_gate); } } } } } } // br -> bl -> tl for(int br = 0; br < br_corners.size(); br++) { // connect br -> bl for(int bl = 0; bl < bl_corners.size(); bl++) { // check connection tr -> br if((br_corners[br].tl().x > bl_corners[bl].br().x) && \ (br_corners[br].tl().y < bl_corners[bl].br().y) && \ (br_corners[br].br().y > bl_corners[bl].tl().y)) { // connect bl -> tl for(int tl = 0; tl < tl_corners.size(); tl++) { // check connection bl -> tl if((tl_corners[tl].br().y < bl_corners[bl].tl().y) && \ (tl_corners[tl].tl().x < bl_corners[bl].br().x) && \ (tl_corners[tl].br().x > bl_corners[bl].tl().x)) { Point_t p_1 = Rect_center(br_corners[br]); Point_t p_2 = Rect_center(bl_corners[bl]); Point_t p_3 = Rect_center(tl_corners[tl]); float Len_1 = sqrtf(powf(p_1.col-p_2.col,2) + powf(p_1.row-p_2.row,2)); float Len_2 = sqrtf(powf(p_2.col-p_3.col,2) + powf(p_2.row-p_3.row,2)); if((Len_1 / Len_2 < 1.5) && (Len_2 / Len_1 < 1.5) && (Len_1 < 150) && (Len_2 < 150)) { Rect Virtual_corner(br_corners[br].tl() + \ tl_corners[tl].tl() - \ bl_corners[bl].tl() , bl_corners[bl].size()); Polygon detected_gate = {Rect_center(tl_corners[tl]), \ Rect_center(Virtual_corner), \ Rect_center(bl_corners[bl]), \ Rect_center(br_corners[br])}; gates.push_back(detected_gate); } } } } } } // bl -> tl -> tr for(int bl = 0; bl < bl_corners.size(); bl++) { // connect bl -> tl for(int tl = 0; tl < tl_corners.size(); tl++) { // check connection bl -> tl if((tl_corners[tl].br().y < bl_corners[bl].tl().y) && \ (tl_corners[tl].tl().x < bl_corners[bl].br().x) && \ (tl_corners[tl].br().x > bl_corners[bl].tl().x)) { // connect tl -> tr for(int tr = 0; tr < tr_corners.size(); tr++) { // check connection bl -> tl if((tl_corners[tl].br().x < tr_corners[tr].tl().x) && \ (tl_corners[tl].br().y > tr_corners[tr].tl().y) && \ (tl_corners[tl].tl().y < tr_corners[tr].br().y)) { Point_t p_1 = Rect_center(bl_corners[bl]); Point_t p_2 = Rect_center(tl_corners[tl]); Point_t p_3 = Rect_center(tr_corners[tr]); float Len_1 = sqrtf(powf(p_1.col-p_2.col,2) + powf(p_1.row-p_2.row,2)); float Len_2 = sqrtf(powf(p_2.col-p_3.col,2) + powf(p_2.row-p_3.row,2)); if((Len_1 / Len_2 < 1.5) && (Len_2 / Len_1 < 1.5) && (Len_1 < 150) && (Len_2 < 150)) { Rect Virtual_corner(bl_corners[bl].tl() + \ tr_corners[tr].tl() - \ tl_corners[tl].tl() , tl_corners[tl].size()); Polygon detected_gate = {Rect_center(tl_corners[tl]), \ Rect_center(tr_corners[tr]), \ Rect_center(bl_corners[bl]), \ Rect_center(Virtual_corner)}; gates.push_back(detected_gate); } } } } } } return gates; } vector<Polygon> extract_gates_3(vector<Rect> tl_corners, vector<Rect> tr_corners, vector<Rect> br_corners, vector<Rect> bl_corners, float ratio, float angle_c, float dist_c) { vector<Polygon> gates; //tl -> tr -> br for(int tl = 0; tl < tl_corners.size(); tl++) { // connect tl -> tr for(int tr = 0; tr < tr_corners.size(); tr++) { // check connection tl -> tr if((tl_corners[tl].br().x < tr_corners[tr].tl().x) && \ (tl_corners[tl].br().y > tr_corners[tr].tl().y) && \ (tl_corners[tl].tl().y < tr_corners[tr].br().y)) { // connect tr -> br for(int br = 0; br < br_corners.size(); br++) { // check connection tr -> br if((tr_corners[tr].br().y < br_corners[br].tl().y) && \ (tr_corners[tr].tl().x < br_corners[br].br().x) && \ (tr_corners[tr].br().x > br_corners[br].tl().x)) { Point_t p_1 = Rect_center(tl_corners[tl]); Point_t p_2 = Rect_center(tr_corners[tr]); Point_t p_3 = Rect_center(br_corners[br]); float Len_1 = sqrtf(powf(p_1.col-p_2.col,2) + powf(p_1.row-p_2.row,2)); float Len_2 = sqrtf(powf(p_2.col-p_3.col,2) + powf(p_2.row-p_3.row,2)); float Len_3 = sqrtf(powf(p_1.col-p_3.col,2) + powf(p_1.row-p_3.row,2)); float angle = acosf((powf(Len_1,2) + powf(Len_2,2) - powf(Len_3,2)) / (2 * Len_1 * Len_2)) / 3.14 * 180; if((Len_1 / Len_2 < ratio) && (Len_2 / Len_1 < ratio) && (angle > 90 - angle_c) && (angle < 90 + angle_c)) { Rect Virtual_corner(tl_corners[tl].tl() + \ br_corners[br].tl() - \ tr_corners[tr].tl() , tr_corners[tr].size()); Point_t Virtual_center = Rect_center(Virtual_corner); Point_t best_center = Virtual_center; float min_dist = 800; for(int bl = 0; bl < bl_corners.size(); bl++) { float dist = sqrtf(powf(Virtual_center.col - Rect_center(bl_corners[bl]).col,2) + powf(Virtual_center.row - Rect_center(bl_corners[bl]).row,2)); if((dist < dist_c) && (dist < min_dist)) { best_center = Rect_center(bl_corners[bl]); min_dist = dist; } } Polygon detected_gate = {Rect_center(tl_corners[tl]), \ Rect_center(tr_corners[tr]), \ best_center,\ Rect_center(br_corners[br])}; gates.push_back(detected_gate); } } } } } } // tr -> br -> bl for(int tr = 0; tr < tr_corners.size(); tr++) { // connect tr -> br for(int br = 0; br < br_corners.size(); br++) { // check connection tr -> br if((tr_corners[tr].br().y < br_corners[br].tl().y) && \ (tr_corners[tr].tl().x < br_corners[br].br().x) && \ (tr_corners[tr].br().x > br_corners[br].tl().x)) { // connect br -> bl for(int bl = 0; bl < bl_corners.size(); bl++) { // check connection br -> bl if((br_corners[br].tl().x > bl_corners[bl].br().x) && \ (br_corners[br].tl().y < bl_corners[bl].br().y) && \ (br_corners[br].br().y > bl_corners[bl].tl().y)) { Point_t p_1 = Rect_center(tr_corners[tr]); Point_t p_2 = Rect_center(br_corners[br]); Point_t p_3 = Rect_center(bl_corners[bl]); float Len_1 = sqrtf(powf(p_1.col-p_2.col,2) + powf(p_1.row-p_2.row,2)); float Len_2 = sqrtf(powf(p_2.col-p_3.col,2) + powf(p_2.row-p_3.row,2)); float Len_3 = sqrtf(powf(p_1.col-p_3.col,2) + powf(p_1.row-p_3.row,2)); float angle = acosf((powf(Len_1,2) + powf(Len_2,2) - powf(Len_3,2)) / (2 * Len_1 * Len_2)) / 3.14 * 180; if((Len_1 / Len_2 < ratio) && (Len_2 / Len_1 < ratio) && (angle > 90 - angle_c) && (angle < 90 + angle_c)) { Rect Virtual_corner(tr_corners[tr].tl() + \ bl_corners[bl].tl() - \ br_corners[br].tl() , br_corners[br].size()); Point_t Virtual_center = Rect_center(Virtual_corner); Point_t best_center = Virtual_center; float min_dist = 800; for(int tl = 0; tl < tl_corners.size(); tl++) { float dist = sqrtf(powf(Virtual_center.col - Rect_center(tl_corners[tl]).col,2) + powf(Virtual_center.row - Rect_center(tl_corners[tl]).row,2)); if((dist < dist_c) && (dist < min_dist)) { best_center = Rect_center(tl_corners[tl]); min_dist = dist; } } Polygon detected_gate = {best_center, \ Rect_center(tr_corners[tr]), \ Rect_center(bl_corners[bl]), \ Rect_center(br_corners[br])}; gates.push_back(detected_gate); } } } } } } // br -> bl -> tl for(int br = 0; br < br_corners.size(); br++) { // connect br -> bl for(int bl = 0; bl < bl_corners.size(); bl++) { // check connection tr -> br if((br_corners[br].tl().x > bl_corners[bl].br().x) && \ (br_corners[br].tl().y < bl_corners[bl].br().y) && \ (br_corners[br].br().y > bl_corners[bl].tl().y)) { // connect bl -> tl for(int tl = 0; tl < tl_corners.size(); tl++) { // check connection bl -> tl if((tl_corners[tl].br().y < bl_corners[bl].tl().y) && \ (tl_corners[tl].tl().x < bl_corners[bl].br().x) && \ (tl_corners[tl].br().x > bl_corners[bl].tl().x)) { Point_t p_1 = Rect_center(br_corners[br]); Point_t p_2 = Rect_center(bl_corners[bl]); Point_t p_3 = Rect_center(tl_corners[tl]); float Len_1 = sqrtf(powf(p_1.col-p_2.col,2) + powf(p_1.row-p_2.row,2)); float Len_2 = sqrtf(powf(p_2.col-p_3.col,2) + powf(p_2.row-p_3.row,2)); float Len_3 = sqrtf(powf(p_1.col-p_3.col,2) + powf(p_1.row-p_3.row,2)); float angle = acosf((powf(Len_1,2) + powf(Len_2,2) - powf(Len_3,2)) / (2 * Len_1 * Len_2)) / 3.14 * 180; if((Len_1 / Len_2 < ratio) && (Len_2 / Len_1 < ratio) && (angle > 90 - angle_c) && (angle < 90 + angle_c)) { Rect Virtual_corner(br_corners[br].tl() + \ tl_corners[tl].tl() - \ bl_corners[bl].tl() , bl_corners[bl].size()); Point_t Virtual_center = Rect_center(Virtual_corner); Point_t best_center = Virtual_center; float min_dist = 800; for(int tr = 0; tr < tr_corners.size(); tr++) { float dist = sqrtf(powf(Virtual_center.col - Rect_center(tr_corners[tr]).col,2) + powf(Virtual_center.row - Rect_center(tr_corners[tr]).row,2)); if((dist < dist_c) && (dist < min_dist)) { best_center = Rect_center(tr_corners[tr]); min_dist = dist; } } Polygon detected_gate = {Rect_center(tl_corners[tl]), \ best_center, \ Rect_center(bl_corners[bl]), \ Rect_center(br_corners[br])}; gates.push_back(detected_gate); } } } } } } // bl -> tl -> tr for(int bl = 0; bl < bl_corners.size(); bl++) { // connect bl -> tl for(int tl = 0; tl < tl_corners.size(); tl++) { // check connection bl -> tl if((tl_corners[tl].br().y < bl_corners[bl].tl().y) && \ (tl_corners[tl].tl().x < bl_corners[bl].br().x) && \ (tl_corners[tl].br().x > bl_corners[bl].tl().x)) { // connect tl -> tr for(int tr = 0; tr < tr_corners.size(); tr++) { // check connection bl -> tl if((tl_corners[tl].br().x < tr_corners[tr].tl().x) && \ (tl_corners[tl].br().y > tr_corners[tr].tl().y) && \ (tl_corners[tl].tl().y < tr_corners[tr].br().y)) { Point_t p_1 = Rect_center(bl_corners[bl]); Point_t p_2 = Rect_center(tl_corners[tl]); Point_t p_3 = Rect_center(tr_corners[tr]); float Len_1 = sqrtf(powf(p_1.col-p_2.col,2) + powf(p_1.row-p_2.row,2)); float Len_2 = sqrtf(powf(p_2.col-p_3.col,2) + powf(p_2.row-p_3.row,2)); float Len_3 = sqrtf(powf(p_1.col-p_3.col,2) + powf(p_1.row-p_3.row,2)); float angle = acosf((powf(Len_1,2) + powf(Len_2,2) - powf(Len_3,2)) / (2 * Len_1 * Len_2)) / 3.14 * 180; if((Len_1 / Len_2 < ratio) && (Len_2 / Len_1 < ratio) && (angle > 90 - angle_c) && (angle < 90 + angle_c)) { Rect Virtual_corner(bl_corners[bl].tl() + \ tr_corners[tr].tl() - \ tl_corners[tl].tl() , tl_corners[tl].size()); Point_t Virtual_center = Rect_center(Virtual_corner); Point_t best_center = Virtual_center; float min_dist = 800; for(int br = 0; br < br_corners.size(); br++) { float dist = sqrtf(powf(Virtual_center.col - Rect_center(br_corners[br]).col,2) + powf(Virtual_center.row - Rect_center(br_corners[br]).row,2)); if((dist < dist_c) && (dist < min_dist)) { best_center = Rect_center(br_corners[br]); min_dist = dist; } } Polygon detected_gate = {Rect_center(tl_corners[tl]), \ Rect_center(tr_corners[tr]), \ Rect_center(bl_corners[bl]), \ best_center}; gates.push_back(detected_gate); } } } } } } return gates; } void VJGateDetector::detect(Frame &frame) { clearNewGate(); Mat YCrCb, gray; YCrCb = frame.getMat(); cv::cvtColor(YCrCb, gray, CV_YUV2GRAY_YUYV); // extract corners vector<Rect> tl_corners; vector<Rect> tr_corners; vector<Rect> bl_corners; vector<Rect> br_corners; this->tl_light.detectMultiScale( gray, tl_corners, 1.1, 1, 0, Size(32, 32),Size(32,32)); this->tr_light.detectMultiScale( gray, tr_corners, 1.1, 1, 0, Size(32, 32),Size(32,32)); this->bl_light.detectMultiScale( gray, bl_corners, 1.1, 1, 0, Size(32, 32),Size(32,32)); this->br_light.detectMultiScale( gray, br_corners, 1.1, 1, 0, Size(32, 32),Size(32,32)); // extract rectangles based on corners // this->gates = extract_gates_3( tl_corners, tr_corners, br_corners, bl_corners, 1.15, 3, 15); this->gates = extract_gates(tl_corners, tr_corners, br_corners, bl_corners); // extract the largest gate if(this->gates.size() > 0) { setNewGate(); Polygon max_gate; float max_area = 0; float digonal_1 = 0; float digonal_2 = 0; for(int i = 0; i < gates.size(); i++) { Point_t tl_pt = gates[i].get_vertex(1); Point_t tr_pt = gates[i].get_vertex(2); Point_t bl_pt = gates[i].get_vertex(3); Point_t br_pt = gates[i].get_vertex(4); digonal_1 = sqrtf(powf((tl_pt.row - br_pt.row),2) + powf((tl_pt.col - br_pt.col),2)); digonal_2 = sqrtf(powf((tr_pt.row - bl_pt.row),2) + powf((tr_pt.col - bl_pt.col),2)); if(digonal_1 * digonal_2 > max_area) { max_area = digonal_1 * digonal_2; max_gate = gates[i]; } } this->best_gate = max_gate; } } void VJGateDetector::updateAhrs(SensorData &ahrs) { AHRS = ahrs; } Polygon VJGateDetector::getBestGate() { return best_gate; } std::vector<Polygon> VJGateDetector::getDetections() { return gates; } }
121bc99a12a2086fe3de1681396a5cc91d8e3c0d
16f6c6da6b671d1dcc624983cc5c2c5cbee6ea4a
/LinkedList.cpp
d2330a0160983706236b27aa80aae309d84bb9e8
[]
no_license
JorgeM313/L9Ro
32214f659610b11d3994d6ca2ddea864c5844bd8
db5fb5d3e9550b7de60f00bf278ce1f35ef202d4
refs/heads/master
2020-04-11T11:17:06.016911
2018-12-14T06:48:09
2018-12-14T06:48:09
161,743,563
0
0
null
null
null
null
UTF-8
C++
false
false
1,961
cpp
LinkedList.cpp
//Jorge Martinez //CPSC 121 //12/12/2018 #include "LinkedList.h" // Function Declarations #include <iostream> using namespace std; template <class T> int LinkedList<T>::recursiveSum(Node<T> * h) { if(h != NULL) { return h->data+recursiveSum(h->next); } else { return 0; } } template <class T> int LinkedList<T>::size() { int count = 0; Node<T> * curr = head; while(curr != NULL) { count++; curr= curr->next; } return count; } template <class T> void LinkedList<T>::display() { Node<T> * curr = head; if(curr == NULL) { cout << "List is empty" << endl; } while(curr!=NULL) { cout << curr->data << " "; curr = curr->next; } cout << endl; } template <class T> void LinkedList<T>::insertItemSorted(T item) { Node<T> *newNode = new Node<T>(); newNode->data = item; newNode->next = NULL; if(head==NULL) { //its the first node inserted head = newNode; return; } if(item<head->data) { //insert at first newNode->next = head; head = newNode; return; } Node<T> *curr = head; Node<T> *prev; while(curr!=NULL && curr->data < item) { prev = curr; curr = curr->next; } if(curr == NULL) { //insert at last prev->next = newNode; } else { //now curr->data is larger than the item, so it's inserted between prev and curr. prev->next = newNode; newNode->next = curr; } } template <class T> bool LinkedList<T>::findValue(T item) { Node<T> *curr = head; while(curr !=NULL) { if(curr->data == item) { return true; } curr = curr->next; } return false; } template <class T> void LinkedList<T>::remove(T item) { if(head == NULL) { cout << "List is empty" << endl; return; } if(head->data == item) { //if first item has to be removed head = head->next; return; } Node<T> *curr = head; Node<T> *prev; while(curr!=NULL && curr->data!=item) { prev = curr; curr=curr->next; } if(curr == NULL) { cout << "Item not found" << endl; } else { prev->next = curr->next; curr->next = NULL; } } template class LinkedList<int>;//Apparently the problem has to do with this, maybe?
8d5a56727a4e894fe6a1111c7ab829d311172437
1b20be60ffe1f8c6158f6285bdf2c0bad9523814
/src/densities.cc
2094f4e747738b03f1c8dfaddb8c30a28824b6ca
[ "LicenseRef-scancode-philippe-de-muyter", "LicenseRef-scancode-unknown-license-reference" ]
permissive
vivi235711/music-fork
ef0023413925111092df3b554b6d3e75e309cf7f
9142b06fd536d9e97928192d59e72cf9d8a15073
refs/heads/master
2023-08-01T00:08:27.250648
2020-07-23T09:29:55
2020-07-23T09:29:55
406,816,706
0
0
null
null
null
null
UTF-8
C++
false
false
32,943
cc
densities.cc
/* densities.cc - This file is part of MUSIC - a code to generate multi-scale initial conditions for cosmological simulations Copyright (C) 2010 Oliver Hahn */ #include <cstring> #include "densities.hh" #include "convolution_kernel.hh" //TODO: this should be a larger number by default, just to maintain consistency with old default #define DEF_RAN_CUBE_SIZE 32 double blend_sharpness = 0.5; double Blend_Function(double k, double kmax) { #if 0 const static double pihalf = 0.5*M_PI; if( fabs(k)>kmax ) return 0.0; return cos(k/kmax * pihalf ); #else float kabs = fabs(k); double const eps = blend_sharpness; float kp = (1.0f - 2.0f * eps) * kmax; if (kabs >= kmax) return 0.; if (kabs > kp) return 1.0f / (expf((kp - kmax) / (k - kp) + (kp - kmax) / (k - kmax)) + 1.0f); return 1.0f; #endif } template <typename m1, typename m2> void fft_coarsen(m1 &v, m2 &V) { size_t nxf = v.size(0), nyf = v.size(1), nzf = v.size(2), nzfp = nzf + 2; size_t nxF = V.size(0), nyF = V.size(1), nzF = V.size(2), nzFp = nzF + 2; fftw_real *rcoarse = new fftw_real[nxF * nyF * nzFp]; fftw_complex *ccoarse = reinterpret_cast<fftw_complex *>(rcoarse); fftw_real *rfine = new fftw_real[nxf * nyf * nzfp]; fftw_complex *cfine = reinterpret_cast<fftw_complex *>(rfine); #ifdef FFTW3 #ifdef SINGLE_PRECISION fftwf_plan pf = fftwf_plan_dft_r2c_3d(nxf, nyf, nzf, rfine, cfine, FFTW_ESTIMATE), ipc = fftwf_plan_dft_c2r_3d(nxF, nyF, nzF, ccoarse, rcoarse, FFTW_ESTIMATE); #else fftw_plan pf = fftw_plan_dft_r2c_3d(nxf, nyf, nzf, rfine, cfine, FFTW_ESTIMATE), ipc = fftw_plan_dft_c2r_3d(nxF, nyF, nzF, ccoarse, rcoarse, FFTW_ESTIMATE); #endif #else rfftwnd_plan pf = rfftw3d_create_plan(nxf, nyf, nzf, FFTW_REAL_TO_COMPLEX, FFTW_ESTIMATE | FFTW_IN_PLACE), ipc = rfftw3d_create_plan(nxF, nyF, nzF, FFTW_COMPLEX_TO_REAL, FFTW_ESTIMATE | FFTW_IN_PLACE); #endif #pragma omp parallel for for (int i = 0; i < (int)nxf; i++) for (int j = 0; j < (int)nyf; j++) for (int k = 0; k < (int)nzf; k++) { size_t q = ((size_t)i * nyf + (size_t)j) * nzfp + (size_t)k; rfine[q] = v(i, j, k); } #ifdef FFTW3 #ifdef SINGLE_PRECISION fftwf_execute(pf); #else fftw_execute(pf); #endif #else #ifndef SINGLETHREAD_FFTW rfftwnd_threads_one_real_to_complex(omp_get_max_threads(), pf, rfine, NULL); #else rfftwnd_one_real_to_complex(pf, rfine, NULL); #endif #endif double fftnorm = 1.0 / ((double)nxF * (double)nyF * (double)nzF); #pragma omp parallel for for (int i = 0; i < (int)nxF; i++) for (int j = 0; j < (int)nyF; j++) for (int k = 0; k < (int)nzF / 2 + 1; k++) { int ii(i), jj(j), kk(k); if (i > (int)nxF / 2) ii += (int)nxf / 2; if (j > (int)nyF / 2) jj += (int)nyf / 2; size_t qc, qf; double kx = (i <= (int)nxF / 2) ? (double)i : (double)(i - (int)nxF); double ky = (j <= (int)nyF / 2) ? (double)j : (double)(j - (int)nyF); double kz = (k <= (int)nzF / 2) ? (double)k : (double)(k - (int)nzF); qc = ((size_t)i * nyF + (size_t)j) * (nzF / 2 + 1) + (size_t)k; qf = ((size_t)ii * nyf + (size_t)jj) * (nzf / 2 + 1) + (size_t)kk; std::complex<double> val_fine(RE(cfine[qf]), IM(cfine[qf])); double phase = (kx / nxF + ky / nyF + kz / nzF) * 0.5 * M_PI; std::complex<double> val_phas(cos(phase), sin(phase)); val_fine *= val_phas * fftnorm / 8.0; //sqrt(8.0); RE(ccoarse[qc]) = val_fine.real(); IM(ccoarse[qc]) = val_fine.imag(); } delete[] rfine; #ifdef FFTW3 #ifdef SINGLE_PRECISION fftwf_execute(ipc); #else fftw_execute(ipc); #endif #else #ifndef SINGLETHREAD_FFTW rfftwnd_threads_one_complex_to_real(omp_get_max_threads(), ipc, ccoarse, NULL); #else rfftwnd_one_complex_to_real(ipc, ccoarse, NULL); #endif #endif #pragma omp parallel for for (int i = 0; i < (int)nxF; i++) for (int j = 0; j < (int)nyF; j++) for (int k = 0; k < (int)nzF; k++) { size_t q = ((size_t)i * nyF + (size_t)j) * nzFp + (size_t)k; V(i, j, k) = rcoarse[q]; } delete[] rcoarse; #ifdef FFTW3 #ifdef SINGLE_PRECISION fftwf_destroy_plan(pf); fftwf_destroy_plan(ipc); #else fftw_destroy_plan(pf); fftw_destroy_plan(ipc); #endif #else rfftwnd_destroy_plan(pf); rfftwnd_destroy_plan(ipc); #endif } //#define NO_COARSE_OVERLAP template <typename m1, typename m2> void fft_interpolate(m1 &V, m2 &v, bool from_basegrid = false) { int oxf = v.offset(0), oyf = v.offset(1), ozf = v.offset(2); size_t nxf = v.size(0), nyf = v.size(1), nzf = v.size(2), nzfp = nzf + 2; size_t nxF = V.size(0), nyF = V.size(1), nzF = V.size(2); if (!from_basegrid) { #ifdef NO_COARSE_OVERLAP oxf += nxF / 4; oyf += nyF / 4; ozf += nzF / 4; #else oxf += nxF / 4 - nxf / 8; oyf += nyF / 4 - nyf / 8; ozf += nzF / 4 - nzf / 8; } else { oxf -= nxf / 8; oyf -= nyf / 8; ozf -= nzf / 8; #endif } LOGUSER("FFT interpolate: offset=%d,%d,%d size=%d,%d,%d", oxf, oyf, ozf, nxf, nyf, nzf); // cut out piece of coarse grid that overlaps the fine: assert(nxf % 2 == 0 && nyf % 2 == 0 && nzf % 2 == 0); size_t nxc = nxf / 2, nyc = nyf / 2, nzc = nzf / 2, nzcp = nzf / 2 + 2; fftw_real *rcoarse = new fftw_real[nxc * nyc * nzcp]; fftw_complex *ccoarse = reinterpret_cast<fftw_complex *>(rcoarse); fftw_real *rfine = new fftw_real[nxf * nyf * nzfp]; fftw_complex *cfine = reinterpret_cast<fftw_complex *>(rfine); // copy coarse data to rcoarse[.] memset(rcoarse, 0, sizeof(fftw_real) * nxc * nyc * nzcp); #ifdef NO_COARSE_OVERLAP #pragma omp parallel for for (int i = 0; i < (int)nxc / 2; ++i) for (int j = 0; j < (int)nyc / 2; ++j) for (int k = 0; k < (int)nzc / 2; ++k) { int ii(i + nxc / 4); int jj(j + nyc / 4); int kk(k + nzc / 4); size_t q = ((size_t)ii * nyc + (size_t)jj) * nzcp + (size_t)kk; rcoarse[q] = V(oxf + i, oyf + j, ozf + k); } #else #pragma omp parallel for for (int i = 0; i < (int)nxc; ++i) for (int j = 0; j < (int)nyc; ++j) for (int k = 0; k < (int)nzc; ++k) { int ii(i); int jj(j); int kk(k); size_t q = ((size_t)ii * nyc + (size_t)jj) * nzcp + (size_t)kk; rcoarse[q] = V(oxf + i, oyf + j, ozf + k); } #endif #pragma omp parallel for for (int i = 0; i < (int)nxf; ++i) for (int j = 0; j < (int)nyf; ++j) for (int k = 0; k < (int)nzf; ++k) { size_t q = ((size_t)i * nyf + (size_t)j) * nzfp + (size_t)k; rfine[q] = v(i, j, k); } #ifdef FFTW3 #ifdef SINGLE_PRECISION fftwf_plan pc = fftwf_plan_dft_r2c_3d(nxc, nyc, nzc, rcoarse, ccoarse, FFTW_ESTIMATE), pf = fftwf_plan_dft_r2c_3d(nxf, nyf, nzf, rfine, cfine, FFTW_ESTIMATE), ipf = fftwf_plan_dft_c2r_3d(nxf, nyf, nzf, cfine, rfine, FFTW_ESTIMATE); fftwf_execute(pc); fftwf_execute(pf); #else fftw_plan pc = fftw_plan_dft_r2c_3d(nxc, nyc, nzc, rcoarse, ccoarse, FFTW_ESTIMATE), pf = fftw_plan_dft_r2c_3d(nxf, nyf, nzf, rfine, cfine, FFTW_ESTIMATE), ipf = fftw_plan_dft_c2r_3d(nxf, nyf, nzf, cfine, rfine, FFTW_ESTIMATE); fftw_execute(pc); fftw_execute(pf); #endif #else rfftwnd_plan pc = rfftw3d_create_plan(nxc, nyc, nzc, FFTW_REAL_TO_COMPLEX, FFTW_ESTIMATE | FFTW_IN_PLACE), pf = rfftw3d_create_plan(nxf, nyf, nzf, FFTW_REAL_TO_COMPLEX, FFTW_ESTIMATE | FFTW_IN_PLACE), ipf = rfftw3d_create_plan(nxf, nyf, nzf, FFTW_COMPLEX_TO_REAL, FFTW_ESTIMATE | FFTW_IN_PLACE); #ifndef SINGLETHREAD_FFTW rfftwnd_threads_one_real_to_complex(omp_get_max_threads(), pc, rcoarse, NULL); rfftwnd_threads_one_real_to_complex(omp_get_max_threads(), pf, rfine, NULL); #else rfftwnd_one_real_to_complex(pc, rcoarse, NULL); rfftwnd_one_real_to_complex(pf, rfine, NULL); #endif #endif /*************************************************/ //.. perform actual interpolation double fftnorm = 1.0 / ((double)nxf * (double)nyf * (double)nzf); double sqrt8 = 8.0; //sqrt(8.0); double phasefac = -0.5; // this enables filtered splicing of coarse and fine modes #if 1 for (int i = 0; i < (int)nxc; i++) for (int j = 0; j < (int)nyc; j++) for (int k = 0; k < (int)nzc / 2 + 1; k++) { int ii(i), jj(j), kk(k); if (i > (int)nxc / 2) ii += (int)nxf / 2; if (j > (int)nyc / 2) jj += (int)nyf / 2; if (k > (int)nzc / 2) kk += (int)nzf / 2; size_t qc, qf; qc = ((size_t)i * (size_t)nyc + (size_t)j) * (nzc / 2 + 1) + (size_t)k; qf = ((size_t)ii * (size_t)nyf + (size_t)jj) * (nzf / 2 + 1) + (size_t)kk; double kx = (i <= (int)nxc / 2) ? (double)i : (double)(i - (int)nxc); double ky = (j <= (int)nyc / 2) ? (double)j : (double)(j - (int)nyc); double kz = (k <= (int)nzc / 2) ? (double)k : (double)(k - (int)nzc); double phase = phasefac * (kx / nxc + ky / nyc + kz / nzc) * M_PI; std::complex<double> val_phas(cos(phase), sin(phase)); std::complex<double> val(RE(ccoarse[qc]), IM(ccoarse[qc])); val *= sqrt8 * val_phas; double blend_coarse = Blend_Function(sqrt(kx * kx + ky * ky + kz * kz), nxc / 2); double blend_fine = 1.0 - blend_coarse; RE(cfine[qf]) = blend_fine * RE(cfine[qf]) + blend_coarse * val.real(); IM(cfine[qf]) = blend_fine * IM(cfine[qf]) + blend_coarse * val.imag(); } #else // 0 0 #pragma omp parallel for for (int i = 0; i < (int)nxc / 2 + 1; i++) for (int j = 0; j < (int)nyc / 2 + 1; j++) for (int k = 0; k < (int)nzc / 2 + 1; k++) { int ii(i), jj(j), kk(k); size_t qc, qf; qc = ((size_t)i * (size_t)nyc + (size_t)j) * (nzc / 2 + 1) + (size_t)k; qf = ((size_t)ii * (size_t)nyf + (size_t)jj) * (nzf / 2 + 1) + (size_t)kk; double kx = (i <= (int)nxc / 2) ? (double)i : (double)(i - (int)nxc); double ky = (j <= (int)nyc / 2) ? (double)j : (double)(j - (int)nyc); double kz = (k <= (int)nzc / 2) ? (double)k : (double)(k - (int)nzc); double phase = phasefac * (kx / nxc + ky / nyc + kz / nzc) * M_PI; std::complex<double> val_phas(cos(phase), sin(phase)); std::complex<double> val(RE(ccoarse[qc]), IM(ccoarse[qc])); val *= sqrt8 * val_phas; RE(cfine[qf]) = val.real(); IM(cfine[qf]) = val.imag(); } // 1 0 #pragma omp parallel for for (int i = nxc / 2; i < (int)nxc; i++) for (int j = 0; j < (int)nyc / 2 + 1; j++) for (int k = 0; k < (int)nzc / 2 + 1; k++) { int ii(i + nxf / 2), jj(j), kk(k); size_t qc, qf; qc = ((size_t)i * (size_t)nyc + (size_t)j) * (nzc / 2 + 1) + (size_t)k; qf = ((size_t)ii * (size_t)nyf + (size_t)jj) * (nzf / 2 + 1) + (size_t)kk; double kx = (i <= (int)nxc / 2) ? (double)i : (double)(i - (int)nxc); double ky = (j <= (int)nyc / 2) ? (double)j : (double)(j - (int)nyc); double kz = (k <= (int)nzc / 2) ? (double)k : (double)(k - (int)nzc); double phase = phasefac * (kx / nxc + ky / nyc + kz / nzc) * M_PI; std::complex<double> val_phas(cos(phase), sin(phase)); std::complex<double> val(RE(ccoarse[qc]), IM(ccoarse[qc])); val *= sqrt8 * val_phas; RE(cfine[qf]) = val.real(); IM(cfine[qf]) = val.imag(); } // 0 1 #pragma omp parallel for for (int i = 0; i < (int)nxc / 2 + 1; i++) for (int j = nyc / 2; j < (int)nyc; j++) for (int k = 0; k < (int)nzc / 2 + 1; k++) { int ii(i), jj(j + nyf / 2), kk(k); size_t qc, qf; qc = ((size_t)i * (size_t)nyc + (size_t)j) * (nzc / 2 + 1) + (size_t)k; qf = ((size_t)ii * (size_t)nyf + (size_t)jj) * (nzf / 2 + 1) + (size_t)kk; double kx = (i <= (int)nxc / 2) ? (double)i : (double)(i - (int)nxc); double ky = (j <= (int)nyc / 2) ? (double)j : (double)(j - (int)nyc); double kz = (k <= (int)nzc / 2) ? (double)k : (double)(k - (int)nzc); double phase = phasefac * (kx / nxc + ky / nyc + kz / nzc) * M_PI; std::complex<double> val_phas(cos(phase), sin(phase)); std::complex<double> val(RE(ccoarse[qc]), IM(ccoarse[qc])); val *= sqrt8 * val_phas; RE(cfine[qf]) = val.real(); IM(cfine[qf]) = val.imag(); } // 1 1 #pragma omp parallel for for (int i = nxc / 2; i < (int)nxc; i++) for (int j = nyc / 2; j < (int)nyc; j++) for (int k = 0; k < (int)nzc / 2 + 1; k++) { int ii(i + nxf / 2), jj(j + nyf / 2), kk(k); size_t qc, qf; qc = ((size_t)i * (size_t)nyc + (size_t)j) * (nzc / 2 + 1) + (size_t)k; qf = ((size_t)ii * (size_t)nyf + (size_t)jj) * (nzf / 2 + 1) + (size_t)kk; double kx = (i <= (int)nxc / 2) ? (double)i : (double)(i - (int)nxc); double ky = (j <= (int)nyc / 2) ? (double)j : (double)(j - (int)nyc); double kz = (k <= (int)nzc / 2) ? (double)k : (double)(k - (int)nzc); double phase = phasefac * (kx / nxc + ky / nyc + kz / nzc) * M_PI; std::complex<double> val_phas(cos(phase), sin(phase)); std::complex<double> val(RE(ccoarse[qc]), IM(ccoarse[qc])); val *= sqrt8 * val_phas; RE(cfine[qf]) = val.real(); IM(cfine[qf]) = val.imag(); } #endif delete[] rcoarse; /*************************************************/ #ifdef FFTW3 #ifdef SINGLE_PRECISION fftwf_execute(ipf); fftwf_destroy_plan(pf); fftwf_destroy_plan(pc); fftwf_destroy_plan(ipf); #else fftw_execute(ipf); fftw_destroy_plan(pf); fftw_destroy_plan(pc); fftw_destroy_plan(ipf); #endif #else #ifndef SINGLETHREAD_FFTW rfftwnd_threads_one_complex_to_real(omp_get_max_threads(), ipf, cfine, NULL); #else rfftwnd_one_complex_to_real(ipf, cfine, NULL); #endif fftwnd_destroy_plan(pf); fftwnd_destroy_plan(pc); fftwnd_destroy_plan(ipf); #endif // copy back and normalize #pragma omp parallel for for (int i = 0; i < (int)nxf; ++i) for (int j = 0; j < (int)nyf; ++j) for (int k = 0; k < (int)nzf; ++k) { size_t q = ((size_t)i * nyf + (size_t)j) * nzfp + (size_t)k; v(i, j, k) = rfine[q] * fftnorm; } delete[] rfine; } /*******************************************************************************************/ /*******************************************************************************************/ /*******************************************************************************************/ void GenerateDensityUnigrid(config_file &cf, transfer_function *ptf, tf_type type, refinement_hierarchy &refh, rand_gen &rand, grid_hierarchy &delta, bool smooth, bool shift) { unsigned levelmin, levelmax, levelminPoisson; levelminPoisson = cf.getValue<unsigned>("setup", "levelmin"); levelmin = cf.getValueSafe<unsigned>("setup", "levelmin_TF", levelminPoisson); levelmax = cf.getValue<unsigned>("setup", "levelmax"); bool kspace = cf.getValue<bool>("setup", "kspace_TF"); bool fix = cf.getValueSafe<bool>("setup","fix_mode_amplitude",false); bool flip = cf.getValueSafe<bool>("setup","flip_mode_amplitude",false); unsigned nbase = 1 << levelmin; std::cerr << " - Running unigrid version\n"; LOGUSER("Running unigrid density convolution..."); //... select the transfer function to be used convolution::kernel_creator *the_kernel_creator; if (kspace) { std::cout << " - Using k-space transfer function kernel.\n"; LOGUSER("Using k-space transfer function kernel."); #ifdef SINGLE_PRECISION the_kernel_creator = convolution::get_kernel_map()["tf_kernel_k_float"]; #else the_kernel_creator = convolution::get_kernel_map()["tf_kernel_k_double"]; #endif } else { std::cout << " - Using real-space transfer function kernel.\n"; LOGUSER("Using real-space transfer function kernel."); #ifdef SINGLE_PRECISION the_kernel_creator = convolution::get_kernel_map()["tf_kernel_real_float"]; #else the_kernel_creator = convolution::get_kernel_map()["tf_kernel_real_double"]; #endif } //... initialize convolution kernel convolution::kernel *the_tf_kernel = the_kernel_creator->create(cf, ptf, refh, type); //... std::cout << " - Performing noise convolution on level " << std::setw(2) << levelmax << " ..." << std::endl; LOGUSER("Performing noise convolution on level %3d", levelmax); //... create convolution mesh DensityGrid<real_t> *top = new DensityGrid<real_t>(nbase, nbase, nbase); //... fill with random numbers rand.load(*top, levelmin); //... load convolution kernel the_tf_kernel->fetch_kernel(levelmin, false); //... perform convolution convolution::perform<real_t>(the_tf_kernel, reinterpret_cast<void *>(top->get_data_ptr()), shift, fix, flip); //... clean up kernel delete the_tf_kernel; //... create multi-grid hierarchy delta.create_base_hierarchy(levelmin); //... copy convolved field to multi-grid hierarchy top->copy(*delta.get_grid(levelmin)); //... delete convolution grid delete top; } /*******************************************************************************************/ /*******************************************************************************************/ /*******************************************************************************************/ void GenerateDensityHierarchy(config_file &cf, transfer_function *ptf, tf_type type, refinement_hierarchy &refh, rand_gen &rand, grid_hierarchy &delta, bool smooth, bool shift) { unsigned levelmin, levelmax, levelminPoisson; std::vector<long> rngseeds; std::vector<std::string> rngfnames; bool kspaceTF; double tstart, tend; #ifndef SINGLETHREAD_FFTW tstart = omp_get_wtime(); #else tstart = (double)clock() / CLOCKS_PER_SEC; #endif levelminPoisson = cf.getValue<unsigned>("setup", "levelmin"); levelmin = cf.getValueSafe<unsigned>("setup", "levelmin_TF", levelminPoisson); levelmax = cf.getValue<unsigned>("setup", "levelmax"); kspaceTF = cf.getValue<bool>("setup", "kspace_TF"); bool fix = cf.getValueSafe<bool>("setup","fix_mode_amplitude",false); bool flip = cf.getValueSafe<bool>("setup","flip_mode_amplitude",false); if( fix && levelmin != levelmax ){ LOGWARN("You have chosen mode fixing for a zoom. This is not well tested,\n please proceed at your own risk..."); } blend_sharpness = cf.getValueSafe<double>("setup", "kspace_filter", blend_sharpness); unsigned nbase = 1 << levelmin; convolution::kernel_creator *the_kernel_creator; if (kspaceTF) { std::cout << " - Using k-space transfer function kernel.\n"; LOGUSER("Using k-space transfer function kernel."); #ifdef SINGLE_PRECISION the_kernel_creator = convolution::get_kernel_map()["tf_kernel_k_float"]; #else the_kernel_creator = convolution::get_kernel_map()["tf_kernel_k_double"]; #endif } else { std::cout << " - Using real-space transfer function kernel.\n"; LOGUSER("Using real-space transfer function kernel."); #ifdef SINGLE_PRECISION the_kernel_creator = convolution::get_kernel_map()["tf_kernel_real_float"]; #else the_kernel_creator = convolution::get_kernel_map()["tf_kernel_real_double"]; #endif } convolution::kernel *the_tf_kernel = the_kernel_creator->create(cf, ptf, refh, type); /***** PERFORM CONVOLUTIONS *****/ if (kspaceTF) { //... create and initialize density grids with white noise DensityGrid<real_t> *top(NULL); PaddedDensitySubGrid<real_t> *coarse(NULL), *fine(NULL); int nlevels = (int)levelmax - (int)levelmin + 1; // do coarse level top = new DensityGrid<real_t>(nbase, nbase, nbase); LOGINFO("Performing noise convolution on level %3d", levelmin); rand.load(*top, levelmin); convolution::perform<real_t>(the_tf_kernel->fetch_kernel(levelmin, false), reinterpret_cast<void *>(top->get_data_ptr()), shift, fix, flip); delta.create_base_hierarchy(levelmin); top->copy(*delta.get_grid(levelmin)); for (int i = 1; i < nlevels; ++i) { LOGINFO("Performing noise convolution on level %3d...", levelmin + i); ///////////////////////////////////////////////////////////////////////// //... add new refinement patch LOGUSER("Allocating refinement patch"); LOGUSER(" offset=(%5d,%5d,%5d)", refh.offset(levelmin + i, 0), refh.offset(levelmin + i, 1), refh.offset(levelmin + i, 2)); LOGUSER(" size =(%5d,%5d,%5d)", refh.size(levelmin + i, 0), refh.size(levelmin + i, 1), refh.size(levelmin + i, 2)); fine = new PaddedDensitySubGrid<real_t>(refh.offset(levelmin + i, 0), refh.offset(levelmin + i, 1), refh.offset(levelmin + i, 2), refh.size(levelmin + i, 0), refh.size(levelmin + i, 1), refh.size(levelmin + i, 2)); ///////////////////////////////////////////////////////////////////////// // load white noise for patch rand.load(*fine, levelmin + i); convolution::perform<real_t>(the_tf_kernel->fetch_kernel(levelmin + i, true), reinterpret_cast<void *>(fine->get_data_ptr()), shift, fix, flip); if (i == 1) fft_interpolate(*top, *fine, true); else fft_interpolate(*coarse, *fine, false); delta.add_patch(refh.offset(levelmin + i, 0), refh.offset(levelmin + i, 1), refh.offset(levelmin + i, 2), refh.size(levelmin + i, 0), refh.size(levelmin + i, 1), refh.size(levelmin + i, 2)); fine->copy_unpad(*delta.get_grid(levelmin + i)); if (i == 1) delete top; else delete coarse; coarse = fine; } delete coarse; } else { //... create and initialize density grids with white noise PaddedDensitySubGrid<real_t> *coarse(NULL), *fine(NULL); DensityGrid<real_t> *top(NULL); if (levelmax == levelmin) { std::cout << " - Performing noise convolution on level " << std::setw(2) << levelmax << " ..." << std::endl; LOGUSER("Performing noise convolution on level %3d...", levelmax); top = new DensityGrid<real_t>(nbase, nbase, nbase); //rand_gen.load( *top, levelmin ); rand.load(*top, levelmin); convolution::perform<real_t>(the_tf_kernel->fetch_kernel(levelmax), reinterpret_cast<void *>(top->get_data_ptr()), shift, fix, flip); the_tf_kernel->deallocate(); delta.create_base_hierarchy(levelmin); top->copy(*delta.get_grid(levelmin)); delete top; } for (int i = 0; i < (int)levelmax - (int)levelmin; ++i) { //.......................................................................................................// //... GENERATE/FILL WITH RANDOM NUMBERS .................................................................// //.......................................................................................................// if (i == 0) { top = new DensityGrid<real_t>(nbase, nbase, nbase); rand.load(*top, levelmin); } fine = new PaddedDensitySubGrid<real_t>(refh.offset(levelmin + i + 1, 0), refh.offset(levelmin + i + 1, 1), refh.offset(levelmin + i + 1, 2), refh.size(levelmin + i + 1, 0), refh.size(levelmin + i + 1, 1), refh.size(levelmin + i + 1, 2)); rand.load(*fine, levelmin + i + 1); //.......................................................................................................// //... PERFORM CONVOLUTIONS ..............................................................................// //.......................................................................................................// if (i == 0) { /**********************************************************************************************************\ * multi-grid: top-level grid grids ..... \**********************************************************************************************************/ std::cout << " - Performing noise convolution on level " << std::setw(2) << levelmin + i << " ..." << std::endl; LOGUSER("Performing noise convolution on level %3d", levelmin + i); LOGUSER("Creating base hierarchy..."); delta.create_base_hierarchy(levelmin); DensityGrid<real_t> top_save(*top); the_tf_kernel->fetch_kernel(levelmin); //... 1) compute standard convolution for levelmin LOGUSER("Computing density self-contribution"); convolution::perform<real_t>(the_tf_kernel, reinterpret_cast<void *>(top->get_data_ptr()), shift, fix, flip); top->copy(*delta.get_grid(levelmin)); //... 2) compute contribution to finer grids from non-refined region LOGUSER("Computing long-range component for finer grid."); *top = top_save; top_save.clear(); top->zero_subgrid(refh.offset(levelmin + i + 1, 0), refh.offset(levelmin + i + 1, 1), refh.offset(levelmin + i + 1, 2), refh.size(levelmin + i + 1, 0) / 2, refh.size(levelmin + i + 1, 1) / 2, refh.size(levelmin + i + 1, 2) / 2); convolution::perform<real_t>(the_tf_kernel, reinterpret_cast<void *>(top->get_data_ptr()), shift, fix, flip); the_tf_kernel->deallocate(); meshvar_bnd delta_longrange(*delta.get_grid(levelmin)); top->copy(delta_longrange); delete top; //... inject these contributions to the next level LOGUSER("Allocating refinement patch"); LOGUSER(" offset=(%5d,%5d,%5d)", refh.offset(levelmin + 1, 0), refh.offset(levelmin + 1, 1), refh.offset(levelmin + 1, 2)); LOGUSER(" size =(%5d,%5d,%5d)", refh.size(levelmin + 1, 0), refh.size(levelmin + 1, 1), refh.size(levelmin + 1, 2)); delta.add_patch(refh.offset(levelmin + 1, 0), refh.offset(levelmin + 1, 1), refh.offset(levelmin + 1, 2), refh.size(levelmin + 1, 0), refh.size(levelmin + 1, 1), refh.size(levelmin + 1, 2)); LOGUSER("Injecting long range component"); //mg_straight().prolong( delta_longrange, *delta.get_grid(levelmin+1) ); //mg_cubic_mult().prolong( delta_longrange, *delta.get_grid(levelmin+1) ); mg_cubic().prolong(delta_longrange, *delta.get_grid(levelmin + 1)); } else { /**********************************************************************************************************\ * multi-grid: intermediate sub-grids ..... \**********************************************************************************************************/ std::cout << " - Performing noise convolution on level " << std::setw(2) << levelmin + i << " ..." << std::endl; LOGUSER("Performing noise convolution on level %3d", levelmin + i); //... add new refinement patch LOGUSER("Allocating refinement patch"); LOGUSER(" offset=(%5d,%5d,%5d)", refh.offset(levelmin + i + 1, 0), refh.offset(levelmin + i + 1, 1), refh.offset(levelmin + i + 1, 2)); LOGUSER(" size =(%5d,%5d,%5d)", refh.size(levelmin + i + 1, 0), refh.size(levelmin + i + 1, 1), refh.size(levelmin + i + 1, 2)); delta.add_patch(refh.offset(levelmin + i + 1, 0), refh.offset(levelmin + i + 1, 1), refh.offset(levelmin + i + 1, 2), refh.size(levelmin + i + 1, 0), refh.size(levelmin + i + 1, 1), refh.size(levelmin + i + 1, 2)); //... copy coarse grid long-range component to fine grid LOGUSER("Injecting long range component"); //mg_straight().prolong( *delta.get_grid(levelmin+i), *delta.get_grid(levelmin+i+1) ); mg_cubic().prolong(*delta.get_grid(levelmin + i), *delta.get_grid(levelmin + i + 1)); PaddedDensitySubGrid<real_t> coarse_save(*coarse); the_tf_kernel->fetch_kernel(levelmin + i); //... 1) the inner region LOGUSER("Computing density self-contribution"); coarse->subtract_boundary_oct_mean(); convolution::perform<real_t>(the_tf_kernel, reinterpret_cast<void *>(coarse->get_data_ptr()), shift, fix, flip); coarse->copy_add_unpad(*delta.get_grid(levelmin + i)); //... 2) the 'BC' for the next finer grid LOGUSER("Computing long-range component for finer grid."); *coarse = coarse_save; coarse->subtract_boundary_oct_mean(); coarse->zero_subgrid(refh.offset(levelmin + i + 1, 0), refh.offset(levelmin + i + 1, 1), refh.offset(levelmin + i + 1, 2), refh.size(levelmin + i + 1, 0) / 2, refh.size(levelmin + i + 1, 1) / 2, refh.size(levelmin + i + 1, 2) / 2); convolution::perform<real_t>(the_tf_kernel, reinterpret_cast<void *>(coarse->get_data_ptr()), shift, fix, flip); //... interpolate to finer grid(s) meshvar_bnd delta_longrange(*delta.get_grid(levelmin + i)); coarse->copy_unpad(delta_longrange); LOGUSER("Injecting long range component"); //mg_straight().prolong_add( delta_longrange, *delta.get_grid(levelmin+i+1) ); mg_cubic().prolong_add(delta_longrange, *delta.get_grid(levelmin + i + 1)); //... 3) the coarse-grid correction LOGUSER("Computing coarse grid correction"); *coarse = coarse_save; coarse->subtract_oct_mean(); convolution::perform<real_t>(the_tf_kernel, reinterpret_cast<void *>(coarse->get_data_ptr()), shift, fix, flip); coarse->subtract_mean(); coarse->upload_bnd_add(*delta.get_grid(levelmin + i - 1)); //... clean up the_tf_kernel->deallocate(); delete coarse; } coarse = fine; } //... and convolution for finest grid (outside loop) if (levelmax > levelmin) { /**********************************************************************************************************\ * multi-grid: finest sub-grid ..... \**********************************************************************************************************/ std::cout << " - Performing noise convolution on level " << std::setw(2) << levelmax << " ..." << std::endl; LOGUSER("Performing noise convolution on level %3d", levelmax); //... 1) grid self-contribution LOGUSER("Computing density self-contribution"); PaddedDensitySubGrid<real_t> coarse_save(*coarse); //... create convolution kernel the_tf_kernel->fetch_kernel(levelmax); //... subtract oct mean on boundary but not in interior coarse->subtract_boundary_oct_mean(); //... perform convolution convolution::perform<real_t>(the_tf_kernel, reinterpret_cast<void *>(coarse->get_data_ptr()), shift, fix, flip); //... copy to grid hierarchy coarse->copy_add_unpad(*delta.get_grid(levelmax)); //... 2) boundary correction to top grid LOGUSER("Computing coarse grid correction"); *coarse = coarse_save; //... subtract oct mean coarse->subtract_oct_mean(); //... perform convolution convolution::perform<real_t>(the_tf_kernel, reinterpret_cast<void *>(coarse->get_data_ptr()), shift, fix, flip); the_tf_kernel->deallocate(); coarse->subtract_mean(); //... upload data to coarser grid coarse->upload_bnd_add(*delta.get_grid(levelmax - 1)); delete coarse; } } delete the_tf_kernel; #ifndef SINGLETHREAD_FFTW tend = omp_get_wtime(); if (true) //verbosity > 1 ) std::cout << " - Density calculation took " << tend - tstart << "s with " << omp_get_max_threads() << " threads." << std::endl; #else tend = (double)clock() / CLOCKS_PER_SEC; if (true) //verbosity > 1 ) std::cout << " - Density calculation took " << tend - tstart << "s." << std::endl; #endif LOGUSER("Finished computing the density field in %fs", tend - tstart); } /*******************************************************************************************/ /*******************************************************************************************/ /*******************************************************************************************/ void normalize_density(grid_hierarchy &delta) { //return; long double sum = 0.0; unsigned levelmin = delta.levelmin(), levelmax = delta.levelmax(); { size_t nx, ny, nz; nx = delta.get_grid(levelmin)->size(0); ny = delta.get_grid(levelmin)->size(1); nz = delta.get_grid(levelmin)->size(2); #pragma omp parallel for reduction(+ \ : sum) for (int ix = 0; ix < (int)nx; ++ix) for (size_t iy = 0; iy < ny; ++iy) for (size_t iz = 0; iz < nz; ++iz) sum += (*delta.get_grid(levelmin))(ix, iy, iz); sum /= (double)(nx * ny * nz); } std::cout << " - Top grid mean density is off by " << sum << ", correcting..." << std::endl; LOGUSER("Grid mean density is %g. Correcting...", sum); for (unsigned i = levelmin; i <= levelmax; ++i) { size_t nx, ny, nz; nx = delta.get_grid(i)->size(0); ny = delta.get_grid(i)->size(1); nz = delta.get_grid(i)->size(2); #pragma omp parallel for for (int ix = 0; ix < (int)nx; ++ix) for (size_t iy = 0; iy < ny; ++iy) for (size_t iz = 0; iz < nz; ++iz) (*delta.get_grid(i))(ix, iy, iz) -= sum; } } void coarsen_density(const refinement_hierarchy &rh, GridHierarchy<real_t> &u, bool kspace) { unsigned levelmin_TF = u.levelmin(); /*for( int i=rh.levelmax(); i>0; --i ) mg_straight().restrict( *(u.get_grid(i)), *(u.get_grid(i-1)) );*/ if (kspace) { for (int i = levelmin_TF; i >= (int)rh.levelmin(); --i) fft_coarsen(*(u.get_grid(i)), *(u.get_grid(i - 1))); } else { for (int i = levelmin_TF; i >= (int)rh.levelmin(); --i) mg_straight().restrict(*(u.get_grid(i)), *(u.get_grid(i - 1))); } for (unsigned i = 1; i <= rh.levelmax(); ++i) { if (rh.offset(i, 0) != u.get_grid(i)->offset(0) || rh.offset(i, 1) != u.get_grid(i)->offset(1) || rh.offset(i, 2) != u.get_grid(i)->offset(2) || rh.size(i, 0) != u.get_grid(i)->size(0) || rh.size(i, 1) != u.get_grid(i)->size(1) || rh.size(i, 2) != u.get_grid(i)->size(2)) { u.cut_patch(i, rh.offset_abs(i, 0), rh.offset_abs(i, 1), rh.offset_abs(i, 2), rh.size(i, 0), rh.size(i, 1), rh.size(i, 2)); } } for (int i = rh.levelmax(); i > 0; --i) mg_straight().restrict(*(u.get_grid(i)), *(u.get_grid(i - 1))); }
3cf58fab92b692565f0b3123f58287f3656bc7d9
79143151a5f5c246a304fc4ee601e144f323fa97
/CodeForces/907B/14207333_AC_31ms_4kB.cpp
6eb7978971566bd3caf12324252e1ba4e10a1b54
[]
no_license
1468362286/Algorithm
919ab70d1d26a4852edc27b6ece39f3aec8329eb
571e957e369f5dc5644717371efcc3f4578a922d
refs/heads/master
2020-06-01T23:56:22.808465
2019-06-09T08:44:55
2019-06-09T08:44:55
190,970,478
0
0
null
null
null
null
UTF-8
C++
false
false
1,303
cpp
14207333_AC_31ms_4kB.cpp
#include <iostream> #include <string> using namespace std; char map[10][10]; int p[9][9]={1,2,3,1,2,3,1,2,3, 4,5,6,4,5,6,4,5,6, 7,8,9,7,8,9,7,8,9, 1,2,3,1,2,3,1,2,3, 4,5,6,4,5,6,4,5,6, 7,8,9,7,8,9,7,8,9, 1,2,3,1,2,3,1,2,3, 4,5,6,4,5,6,4,5,6, 7,8,9,7,8,9,7,8,9}; int q[9][9]={1,1,1,2,2,2,3,3,3, 1,1,1,2,2,2,3,3,3, 1,1,1,2,2,2,3,3,3, 4,4,4,5,5,5,6,6,6, 4,4,4,5,5,5,6,6,6, 4,4,4,5,5,5,6,6,6, 7,7,7,8,8,8,9,9,9, 7,7,7,8,8,8,9,9,9, 7,7,7,8,8,8,9,9,9}; int main() { //freopen("in.txt","r",stdin); int i,j,k,x,y; char ch[10]; for( i = 1 ; i <= 9 ; i++) for( j = 1 ; j <= 3 ; j++) { scanf("%s",&ch); for( k = 1 ; k <= 3 ; k++) { map[i][(j-1)*3+k]=ch[k-1]; } } scanf("%d%d",&x,&y); int tmp = p[x-1][y-1]; int cnt=0; for( i = 1 ; i <= 9 ; i++) for( j = 1 ; j <= 9 ; j++) { if(q[i-1][j-1]==tmp) { if(map[i][j]=='.') { map[i][j]='!'; cnt++; } } } if(cnt==0) { for( i = 1 ; i <= 9 ; i++) for( j = 1 ; j <= 9 ; j++) if(map[i][j]=='.') map[i][j]='!'; } for( i = 1 ; i <= 9 ; i++) { for( j = 1 ; j <= 9 ; j++) { printf("%c",map[i][j]); if(j==3||j==6) printf(" "); } if(i==3||i==6) printf("\n\n"); else printf("\n"); } return 0; }
9911731bef9ea037eb83cb3b75adbb4787997103
bb915a71f263a643c0522ab3faf7a69482211483
/stack_primary_linear/global.h
251220f8963056c37fb633a3bc60d1da66f42214
[]
no_license
logic-three-body/DataStructure_Stack
e90d2340154b3783ed9a043d677c5aa95c828d95
c06008a1b6d7d6bf68c00040ee81e127609320c2
refs/heads/master
2023-01-12T00:09:12.686018
2020-08-09T08:10:05
2020-08-09T08:10:05
286,191,193
0
0
null
2020-08-09T08:08:48
2020-08-09T07:46:27
null
GB18030
C++
false
false
376
h
global.h
#pragma once #include "stdio.h" #include<iostream> #include<cctype> #define OK 1 #define ERROR 0 #define TRUE 1 #define FALSE 0 #define MAXSIZE 20 /* 存储空间初始分配量 */ typedef int Status; typedef unsigned long SElemType; /* SElemType类型根据实际情况而定,这里假设为int */ inline Status visit(SElemType c) { std::cout << c << "\t"; return OK; }
f2a2a07761082ca17fd4f06e5b5547aac4ef5ca1
c4ac895830d35bdd7531c350ff328899960e8832
/FairyLand/Code/Engine/src/Database/DatabaseManager.h
9d664c15e86335a6ade1a7f890bf076fa760f4cf
[]
no_license
Qazwar/FairyLandEngine
08ccfe46556f3fc30fdd52fcbd86b1dd3d13fac1
39c5bb00f13b7676fbc14f6b92344ed69e7ed435
refs/heads/master
2020-04-26T03:29:59.415959
2016-01-12T09:53:48
2016-01-12T09:53:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
919
h
DatabaseManager.h
//============================================================================ // DatabaseManager.h // // Copyright 2006-2009 Possibility Space Incorporated. //============================================================================ #pragma once namespace FL { //---------------------------------------------------------------------------- // DatabaseManager //---------------------------------------------------------------------------- class DatabaseManager : public IDatabaseManager { private: _handle mSQLEnvironment; _dword mConnectionNumber; public: DatabaseManager( ); ~DatabaseManager( ); virtual _void Release( ); virtual _dword GetDatabaseConnectionNumber( ) const; virtual IDatabaseConnection* CreateDatabaseConnection( ); virtual _void ReleaseDatabaseConnection( IDatabaseConnection*& connection ); // Error virtual String GetLastError( ); }; };
ce2b98fc71c3264a1a4423fbfb6cf35da226a971
fd5f3128d177d63bae8ead833f409d8877ef2a48
/GLODBM/Chain.cpp
d9bf14bf00960df6db346cbd694fdacfc2300225
[]
no_license
Gorgonx7/GLO---GL-Online
ca56b0fdbe66f2743936096924c97012f9c3c299
9e5fe18eb6beebf786136454415bf9ae836ed275
refs/heads/master
2023-01-05T05:32:03.840663
2020-10-29T09:06:01
2020-10-29T09:06:01
129,157,626
1
0
null
null
null
null
UTF-8
C++
false
false
375
cpp
Chain.cpp
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: Chain.cpp * Author: jamesgordon * * Created on 10 July 2018, 22:31 */ #include "Chain.h" Chain::Chain() { } Chain::Chain(const Chain& orig) { } Chain::~Chain() { }
a004a21ca4ca0a68fc1964919a98fb9192659119
94c177a4ffdd26c0a29539fd2ff053edc07b8c9f
/Projekt/src/Engine/Graphics/Geometry/Quadtree.h
8fd76cd1d5c8a7fae7831b2fdf5a5feb5ed0d92d
[]
no_license
Praccen/EyetrackingHeightmap
8e0c1d3c2e99e4fe57f621828b4c7c909a43decd
86aac4f3c5cd0fedcc160f2788548f20961e1302
refs/heads/master
2020-05-17T23:37:34.385700
2019-05-17T08:53:34
2019-05-17T08:53:34
184,036,998
0
0
null
null
null
null
UTF-8
C++
false
false
983
h
Quadtree.h
#ifndef QUADTREE_H #define QUADTREE_H #include <vector> #include "..\Geometry\Model loading\Model.h" #include "..\Shader compilation\ShaderSet.h" //#include "..\Geometry\Structs.h" class Quadtree { private: /*struct Node { std::vector<Node> childNodes; std::vector<Model> models; BoundingBox boundingBox; int depth; }; float fixedHeight; void recursiveBuild(Node &node, int depth); void recursiveDraw(Node &node, BoxCorners frustum, GLuint shaderProgram); BoundingBox buildBoundingBox(float boxWidth, float boxLength, glm::vec3 boxCenter); glm::vec3 findCorner(glm::vec3 origin, Plane wall1, Plane wall2, Plane wall3); Node *root;*/ public: Quadtree(); ~Quadtree(); /*bool boundingBoxesTest(BoundingBox bb1, BoundingBox bb2); bool frustumTest(BoxCorners frustum, BoundingBox bb); void buildTree(std::vector<Model> models, float sceneWidth, float sceneLength, glm::vec3 sceneCenter); void drawVisible(BoxCorners frustum, GLuint shaderProgram);*/ }; #endif
3580498112199d56b250cb16bedd0c0b37493db4
e140e72119f30cd8e4969d56b184948c233ae10c
/polynome/EA/BitString.h
66f69af4bc3ac3698fb3542b6247fa2a66849783
[]
no_license
PSL-Central/central
c2db3d60bbd5be43daadcdd8956459bab97c900f
747b19c108139ae31fb26ee112928996f2359d88
refs/heads/master
2020-12-24T14:56:51.194341
2013-04-10T15:41:57
2013-04-10T15:41:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,394
h
BitString.h
// BitString.h // // SPECIAL VERSION THAT WORKS ONLY FOR STRINGS OF LENGTH LESS THAN 32 // Uses 0-based indexing #ifndef _VBI_POLYMATH_N_BITSTRING_H_ #define _VBI_POLYMATH_N_BITSTRING_H_ // TO DO // typedef std::vector<ULONG> WordArray; // typedef std::vector<ULONG>::iterator WordArrayIter; extern USHORT BitsPerWord; // NumOnes[k] contains the number of 1's in the binary representation of the integer k extern const int NumOnes[]; // Count the number of 1's in a single ULONG size_t BitCount( ULONG x ); class BitString { public: // Default constructor ( all zeros bitstring of num_bits ) BitString( size_t num_bits ) : mWords(0), mN( num_bits ) { } // Copy Contruct from another BitString BitString( const BitString& other ) : mWords( other.mWords ), mN( other.mN ) { } // Construct from UNLONG and # of bits BitString( ULONG x, size_t n ) : mWords( x ), mN( n ) { } // Return true if bit number i = 1 (can not be used for assignment) inline bool operator[]( size_t b ) const { return (((1 << b) & mWords) != 0); } // Bitwise AND operator (Performs * in F_2^n) inline BitString operator&( const BitString& other ) const { return BitString(mWords & other.mWords, mN );} // Bitwise XOR operator (Performs + in F_2^n) inline BitString operator^( const BitString& other ) const { return BitString(mWords ^ other.mWords, mN ); } // Bitwise OR operator BitString operator|( const BitString& other ) const { return BitString(mWords | other.mWords, mN ); } // Reset all bits of this bitstring inline void Reset() { mWords = 0; } // Equality test operator inline bool operator==( const BitString& other ) const { return mWords == other.mWords; } // Count the number of 1 bits in this BitString size_t Count( ) const { return BitCount( mWords ); } // Return the number of bits in this BitString inline size_t Size() const { return mN; } // Set - set the b'th bit of this term inline void Set( size_t b ) { mWords |= (1 << b); } // Reset - reset the b'th bit of this term inline void Reset( size_t b ) { mWords &= ~(1 << b); } // Flip the b'th bit of this term inline void Flip( size_t b ) { mWords ^= (1 << b); } // Support output of a BitString to a stream friend std::ostream& operator<<( std::ostream& out, const BitString& t ); private: // Number of bits size_t mN; ULONG mWords; }; #endif // _VBI_POLYMATH_N_BITSTRING_H_
9e1cf8499453b612f8169baffcc45ba83461eb42
094662cc6f16272eb1907cd235933aa1f5932652
/Sequential/src/Audio.cpp
84481818ef3dea173698cbc5b5ee9ef7805ac095
[ "Apache-2.0" ]
permissive
Cindytb/Convolution-Reverb-Benchmarks
80f6cb647a3522aee8057858b60ef2c85081abee
c4d9c8f91b5f3e16bfd4ad4e67f70d2ff95d9f59
refs/heads/master
2020-04-07T17:08:40.194843
2020-04-05T16:17:26
2020-04-05T16:17:26
158,558,442
2
0
Apache-2.0
2020-04-05T16:15:14
2018-11-21T14:14:22
C++
UTF-8
C++
false
false
4,586
cpp
Audio.cpp
#include "Audio.h" void errorCheck(int iCh, int iSR, int rSR){ if(iCh != 1){ fprintf(stderr, "ERROR: Program can only take mono files\n"); exit(100); } if (iSR != rSR) { fprintf(stderr, "ERROR: Input and reverb files are two different sample rates\n"); fprintf(stderr, "Input file is %i\n", iSR); fprintf(stderr, "Reverb sample rate is %i\n", rSR); exit(200); } } /*Input name, address to buffer to be written, and address of number of channels. Output size.*/ long long readFile(const char *name, float **buf, int *numCh, int *SR) { SF_INFO info; SNDFILE *sndfile; memset(&info, 0, sizeof(info)); info.format = 0; sndfile = sf_open(name, SFM_READ, &info); if (sndfile == NULL) { fprintf(stderr, "ERROR. Cannot open %s\n", name); exit(1); } sf_count_t size = info.frames; *numCh = info.channels; *SR = info.samplerate; *buf = (float*) malloc(sizeof(float) * size * info.channels); if(*buf == 0){ fprintf(stderr, "ERROR: Cannot allocate enough memory\n"); exit(2); } if (info.channels < 3) { sf_read_float(sndfile, *buf, size * info.channels); } else { fprintf(stderr, "ERROR: %s : Only mono or stereo accepted", name); } size *= *numCh; sf_close(sndfile); return size; } void readFileExperimental(const char *iname, const char *rname, int *iCh, int *iSR, long long *iframes, int *rCh, int *rSR, long long *rframes, float **ibuf, float **rbuf, long long *new_size, bool *blockProcessingOn, bool timeDomain) { float *buf; SF_INFO i_info, r_info; SNDFILE *i_sndfile, *r_sndfile; memset(&i_info, 0, sizeof(i_info)); memset(&r_info, 0, sizeof(r_info)); /*Read input*/ i_sndfile = sf_open(iname, SFM_READ, &i_info); if (i_sndfile == NULL) { fprintf(stderr, "ERROR. Cannot open %s\n", iname); exit(1); } /*Read reverb*/ r_sndfile = sf_open(rname, SFM_READ, &r_info); if (r_sndfile == NULL) { fprintf(stderr, "ERROR. Cannot open %s\n", rname); exit(1); } /*Store input & reverb metadata*/ *iSR = i_info.samplerate; *iframes = i_info.frames; *iCh = i_info.channels; *rSR = r_info.samplerate; *rframes = r_info.frames; *rCh = r_info.channels; /*Error check. Terminate program if requirements are not met*/ errorCheck(*iCh, *iSR, *rSR); long long totalSize = *iframes * *iCh; /*Find padded size for FFT*/ *new_size = pow(2, ceil(log2((double)(totalSize + *rframes * *rCh - 1)))); if( timeDomain || (*ibuf = fftwf_alloc_real(*new_size * 2)) ){ *blockProcessingOn = true; *ibuf = (float*) malloc(totalSize * sizeof(float)); if(*ibuf == 0){ fprintf(stderr, "ERROR: Cannot allocate enough memory\n"); exit(2); } if (*iCh < 3) { sf_read_float(i_sndfile, *ibuf, totalSize); } else { fprintf(stderr, "ERROR: %s : Only mono or stereo accepted", iname); } *rbuf = (float*) malloc( (*rframes * *rCh) * sizeof(float)); if(*rbuf == 0){ fprintf(stderr, "ERROR: Cannot allocate enough memory\n"); exit(2); } if (*rCh < 3) { sf_read_float(r_sndfile, *rbuf, *rframes * *rCh); } else { fprintf(stderr, "ERROR: %s : Only mono or stereo accepted", rname); } sf_close(i_sndfile); sf_close(r_sndfile); return; } *blockProcessingOn = false; *rbuf = *ibuf + *new_size; if (*iCh < 3) { sf_read_float(i_sndfile, *ibuf, totalSize); } else { fprintf(stderr, "ERROR: %s : Only mono or stereo accepted", iname); } if (*rCh < 3) { sf_read_float(r_sndfile, *rbuf, *rframes * *rCh); } else { fprintf(stderr, "ERROR: %s : Only mono or stereo accepted", rname); } /*Pad remaining values to 0*/ for(long long i = *rframes * *rCh; i < *new_size; i++){ (*rbuf)[i] = 0.0f; if(i >= totalSize){ (*ibuf)[i] = 0.0f; } } sf_close(i_sndfile); sf_close(r_sndfile); } /*Write file with 44.1k SR*/ /* void writeFile(const char * name, float * buf, long long size, int ch) { int format = 0; format |= SF_FORMAT_WAV; format |= SF_FORMAT_PCM_24; SndfileHandle file = SndfileHandle(name, SFM_WRITE, format, ch, 44100); file.writef(buf, size); } */ /*Write file with variable SR*/ void cpuWriteFile(const char * name, float * buf, long long size, int fs, int ch) { int format = 0; if(size < 1073741824){ format |= SF_FORMAT_WAV; } else{ format |= SF_FORMAT_W64; } format |= SF_FORMAT_FLOAT; SndfileHandle file = SndfileHandle(name, SFM_WRITE, format, ch, fs); file.writef(buf, size); }
bf8d473315c9b685af03d5ca354cdf09775b269f
f36408ec61640316d33fbed17139c09d7f1ed628
/inc/AudioPlayer.h
47af4657e7d4bec0ea823e071a79e3ca53aa3a8f
[]
no_license
jinhuafeng/RS-MAN
108a9d0ceffbf5f45283b0369a6beb08aa562c1d
38f8fd61d3e8947bbc748fca1533c836a963008e
refs/heads/master
2016-09-08T02:33:10.760059
2013-12-24T02:48:13
2013-12-24T02:48:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,005
h
AudioPlayer.h
/* * AudioPlayer.h * * Created on: 2010-9-13 * Author: jinhuafeng */ #ifndef AUDIOPLAYER_H_ #define AUDIOPLAYER_H_ #include <e32std.h> #include <MdaAudioSamplePlayer.h> class CAudioPlayer : public CBase, public MMdaAudioPlayerCallback { public: static CAudioPlayer* NewL(const TDesC& aFileName,TInt aSoundDegree); static CAudioPlayer* NewLC(const TDesC& aFileName,TInt aSoundDegree); ~CAudioPlayer(); private: CAudioPlayer(); void ConstructL(const TDesC& aFileName,TInt aSoundDegree); public: void Play(); void Stop(); void Pause(); public: // from MMdaAudioToneObserver void MapcInitComplete(TInt aError, const TTimeIntervalMicroSeconds& aDuration); void MapcPlayComplete(TInt aError); void SetSoundDegree(TInt aSoundDegree); public: TBool iIsPlayCompleted; TInt iSoundDegree; private: CMdaAudioPlayerUtility* iPlayUtility; }; #endif /* AUDIOPLAYER_H_ */
6ad968c1f570541000349d0e262d8da6eb31004d
937ca45e9896b845d404d4bec24761d954ed364d
/sandia/pmedian/pmedian_coek.cpp
6b27727d4e65ce4d2106ea8648bdd077217c420c
[]
no_license
jalving/OptimizationModelComparisons
566755c3b66d877a1a4019c09b34d7968d706a96
ab2b807842c4abdff8f7b16c9980991594fdd9aa
refs/heads/master
2023-01-27T15:52:40.164392
2020-12-09T20:40:28
2020-12-09T20:40:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,323
cpp
pmedian_coek.cpp
#include <map> #include <vector> #include <coek/coek.hpp> int main(int argc, char** argv) { int N = atoi(argv[1]); // Locations int M = N; // Customers int P = atoi(argv[2]); // Facilities coek::Model model; std::vector<std::vector<double>> d(N, std::vector<double>(M)); for (int n=0; n<N; n++) for (int m=0; m<M; m++) d[n][m] = 1.0+1.0/(n+m+1); std::vector<std::vector<coek::Variable>> x(N, std::vector<coek::Variable>(M)); for (int n=0; n<N; n++) for (int m=0; m<M; m++) x[n][m] = model.add_variable(0,1,0); std::vector<coek::Variable> y(N); for (int n=0; n<N; n++) y[n] = model.add_variable(0,1,0); // obj coek::Expression obj; for (int n=0; n<N; n++) for (int m=0; m<M; m++) obj += d[n][m]*x[n][m]; model.add_objective( obj ); // single_x for (int m=0; m<M; m++) { coek::Expression c; for (int n=0; n<N; n++) c += x[n][m]; model.add_constraint( c == 1 ); } // bound_y for (int n=0; n<N; n++) for (int m=0; m<M; m++) model.add_constraint( x[n][m] - y[n] <= 0 ); // num_facilities coek::Expression num_facilities; for (int n=0; n<N; n++) num_facilities += y[n]; model.add_constraint( num_facilities == P ); coek::Solver opt; opt.initialize("gurobi"); opt.set_option("TimeLimit", 0); opt.solve(model); return 0; }
3783be89ea9f79fece36cef7c27770127bbf5f8d
4dff595d59df71df9eaf3ea1fda1a880abf297ec
/src/WaveInteractorManager.cpp
794ee37cfa8d5da5b70061f046bf16202f0cfc45
[ "BSD-2-Clause" ]
permissive
dgi09/Tower-Defence
125254e30e4f5c1ed37dacbfb420fb650df29543
2edd53d50c9f913d00de26e7e2bdc5e8b950cc02
refs/heads/master
2021-03-12T19:18:59.871669
2015-09-17T10:55:17
2015-09-17T10:55:17
42,649,877
1
0
null
null
null
null
UTF-8
C++
false
false
380
cpp
WaveInteractorManager.cpp
#include "WaveInteractorManager.h" #include "Wave.h" WaveInteractorManager::WaveInteractorManager(void):Manager() { } WaveInteractorManager::~WaveInteractorManager(void) { } void WaveInteractorManager::interactAll(Wave ** waves,int size) { for(it = elements.begin();it != elements.end();++it) { (*it)->wavesInteract(waves,size); if(it == elements.end()) break; } }
474bfe2afc96eb87c89df976be81aed92156d1db
d071e6156cf23ddee37a612f71d71a650c27fcfe
/pojpass/poj1961_Period.cpp
bab523a29f1e31e4fce6bf2861cac875728b602f
[]
no_license
tsstss123/code
57f1f7d1a1bf68c47712897e2d8945a28e3e9862
e10795c35aac442345f84a58845ada9544a9c748
refs/heads/master
2021-01-24T23:00:08.749712
2013-04-30T12:33:24
2013-04-30T12:33:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
799
cpp
poj1961_Period.cpp
#include <stdio.h> const int MAXN = 1000000+5; char s[MAXN]; int next[MAXN]; int make_next(char s[], int next[]) { int i, k = -1; next[0] = -1; for (i = 1; s[i]; i++) { while (k >= 0 && s[k+1] != s[i]) { k = next[k]; } if (s[k+1] == s[i]) { k++; } next[i] = k; } return i; } int main() { int n, cs = 0; while (EOF != scanf("%d", &n) && n > 0) { if (cs != 0) { puts(""); } printf("Test case #%d\n", ++cs); scanf("%s", s); make_next(s, next); for (int i = 1; s[i]; i++) { int k = 0, l1 = i, l2 = i - next[i]; /* while (l1 >= 0 && (l1 - next[l1] == l2) && ((next[l1] + 1) % l2 == 0)) { k++; l1 = next[l1]; } */ if ((l1+1) % l2 == 0) { k = (l1+1) / l2; } if (k >= 2) { printf("%d %d\n", i+1, k); } } } return 0; }
a9d6c6c37d4e69614b18439488687a82f91f5d1e
e34b485dfa63c27351a87d979ff71382201f408f
/live-archive/4704.cpp
a7e5eb2b2553e82294adb1cba4839e11cfe65d46
[]
no_license
gabrielrussoc/competitive-programming
223146586e181fdc93822d8462d56fd899d25567
cd51b9af8daf5bab199b77d9642f7cd01bcaa8e3
refs/heads/master
2022-11-30T11:55:12.801388
2022-11-15T18:12:55
2022-11-15T18:12:55
44,883,370
10
2
null
null
null
null
UTF-8
C++
false
false
1,668
cpp
4704.cpp
#include <bits/stdc++.h> #define mp make_pair #define pb push_back #define ff first #define ss second using namespace std; typedef unsigned long long ll; typedef pair<int,int> pii; typedef pair<ll,ll> pll; const double eps = 1e-9; const int inf = INT_MAX; //////////////0123456789 const int N = 54; const int modn = 1000000007; int v[N], pr[N], a[N],n,t; ll k; ll calc (int j, int c){ memset(a,0,sizeof a); for(int i = t-j; i > 1; i--){ int q = i; while(q > 1){ a[pr[q]]++; q /= pr[q]; } } for(int i = 0; i < n; i++){ int q = v[i] - (i == c); for(int w = q; w > 1; w--) { int d = w; while(d > 1) { a[pr[d]]--; d /= pr[d]; } } } ll ret = 1; for(int i = 2; i < N; i++) while(a[i] > 0) { ret = ret * ll(i); a[i]--; if(ret > 1e19) return ret; } return ret; } int main() { for(int i = 2; i < N; i++) if(!pr[i]) for(int j = i; j < N; j += i) pr[j] = i; while(scanf("%d %llu",&n,&k) && n){ t = 0; for(int i = 0; i < n; i++) scanf("%d",v+i), t += v[i]; for(int i = 0; i < t; i++){ for(int c = 0; c < n; c++){ if(v[c]) { ll b = calc(i+1,c); if(k < b) { v[c]--; putchar(c+'a'); break; } else k -= b; } } } putchar('\n'); } }
ef7d8f76841d33d0e39f1db4db8db12aa4f8eb33
998d4ce1054987f24562219bd6f79c37cbaa19c2
/套题/2014 ACMICPC 西安赛区现场赛/2016-08-08-Contests/2016-08-08-Contests/sources/runs/site1run59/main.cpp
158edd7b13b51a5e318c0fdb24175e67074831b6
[]
no_license
tankche1/ACM-NOI
0cedccd7f5fa53070c03cbc1845d5de06385f52b
1cb3d1fc08493e62c5cb4396e0352abef65b93f8
refs/heads/master
2022-12-13T03:22:18.971576
2022-12-05T15:56:34
2022-12-05T15:56:34
98,779,042
2
0
null
null
null
null
UTF-8
C++
false
false
1,922
cpp
main.cpp
#include<cstdio> #include<cstring> #include<cstdlib> #include<cmath> #include<cctype> #include<climits> #include<iostream> #include<algorithm> #include<vector> #include<queue> #include<stack> #include<map> #include<set> #include<bitset> #include<complex> using namespace std; typedef pair<int, int> pii; typedef unsigned int uint; typedef unsigned long long ull; typedef long long LL; typedef long double ld; #define rep(i, x) for(int i = 0; i < (int)(x); i++) #define outint(x) printf("%d\n", (x)) const int INF = 0x3f3f3f3f; const double EPS = 1e-8; const double PI = 3.1415926535897932384626433832795; inline int get_int() { int res, t = 1; char c; while(!isdigit(c = getchar())) if(c == '-') t = -1; for(res = c - '0'; isdigit(c = getchar()); ) res = res * 10 + c - '0'; return res * t; } const int MOD = 1000000000 + 7; const int MAXK = 1000000; int Pow(int a, int n) { int res = 1; while(n) { if(n & 1) res = 1LL * res * a % MOD; a = 1LL * a * a % MOD; n >>= 1; } return res; } int inv[MAXK + 10]; int C(int n, int m) { int now = 1; for(int k = 1; k <= m; k++) { now = 1LL * now * (n - k + 1) % MOD * inv[k]; } return now; } int main() { for(int i = 1; i <= MAXK; i++) inv[i] = Pow(i, MOD - 2); int T = get_int(); for(int kase = 1; kase <= T; kase++) { int n = get_int(), m = get_int(), k = get_int(); int ans = 0; if(k == 1) { if(n == 1) ans = 1; else ans = 0; } else { ans = 1LL * k * Pow(k - 1, n - 1) % MOD; ans = (1LL * ans - 1LL * (k - 1) * Pow(k - 2, n - 1) ) % MOD; ans = (ans + MOD) % MOD; } printf("Case #%d: ", kase); cout << 1LL * ans * C(m, k) % MOD << endl; } return 0; }
876d177187e5b3a2ed3cb8bcb9e474efe401c531
0b87237bc73bf4ee439a8837fee861b7739265e3
/47_Add.cpp
c5a7667a561b44f4bdb4696d0ff276e39ed9dc7f
[]
no_license
YuanHei/6_Offer
9248b367850be191144b39adaa00c79ea557550f
83325b493b1d06cd2450cd036d94a4653e6eef19
refs/heads/master
2020-12-24T09:45:34.490017
2016-06-02T03:18:43
2016-06-02T03:18:43
60,228,854
0
0
null
null
null
null
UTF-8
C++
false
false
374
cpp
47_Add.cpp
#include <iostream> using namespace std; //不用加减乘除做加法 int Add(int num1, int num2) { int sum, carry; do { sum = num1 ^ num2; carry = (num1&num2) << 1; //两个数先做位与运算再左移一位 num1 = sum; num2 = carry; } while (num2 != 0); return num1; } //输入正数、负数、0 int main() { cout << Add(1,2) << endl; return 0; }
af31bb135fcad09c152b1372649423f9623f3c08
62148efea914d04c97afab0f80af430ff8ec3650
/test/mariadb_mock.cpp
82c5e39b80a920b30ecc4535a6058e8e2c519dab
[ "MIT" ]
permissive
Bergmann89/cpphibernate
370646cd58d1843b1d824d7c47cd28bb91d4a968
15c3cd8482365385aeebaa93c6740c273ab5dd30
refs/heads/master
2020-04-01T11:38:39.812730
2018-11-05T19:51:11
2018-11-05T19:51:11
153,171,169
4
0
null
null
null
null
UTF-8
C++
false
false
3,728
cpp
mariadb_mock.cpp
#include "mariadb_mock.h" mariadb_mock* mariadb_mock_instance; void mariadb_mock::setInstance(mariadb_mock* value) { mariadb_mock_instance = value; } void mariadb_mock::clearInstance(mariadb_mock* value) { if (mariadb_mock_instance == value) mariadb_mock_instance = nullptr; } my_ulonglong STDCALL mysql_num_rows (MYSQL_RES *res) { return (mariadb_mock_instance ? mariadb_mock_instance->mysql_num_rows(res) : 0); } unsigned int STDCALL mysql_num_fields (MYSQL_RES *res) { return (mariadb_mock_instance ? mariadb_mock_instance->mysql_num_fields(res) : 0); } MYSQL_ROWS* STDCALL mysql_row_tell (MYSQL_RES *res) { return (mariadb_mock_instance ? mariadb_mock_instance->mysql_row_tell(res) : nullptr); } void STDCALL mysql_free_result (MYSQL_RES *res) { if (mariadb_mock_instance) mariadb_mock_instance->mysql_free_result(res); } MYSQL_ROW_OFFSET STDCALL mysql_row_seek (MYSQL_RES *res, MYSQL_ROW_OFFSET offset) { return (mariadb_mock_instance ? mariadb_mock_instance->mysql_row_seek(res, offset) : nullptr); } void STDCALL mysql_data_seek (MYSQL_RES *res, unsigned long long offset) { if (mariadb_mock_instance) mariadb_mock_instance->mysql_data_seek(res, offset); } unsigned long* STDCALL mysql_fetch_lengths (MYSQL_RES *res) { return (mariadb_mock_instance ? mariadb_mock_instance->mysql_fetch_lengths(res) : nullptr); } MYSQL_ROW STDCALL mysql_fetch_row (MYSQL_RES *res) { return (mariadb_mock_instance ? mariadb_mock_instance->mysql_fetch_row(res) : nullptr); } MYSQL_FIELD* STDCALL mysql_fetch_fields (MYSQL_RES *res) { return (mariadb_mock_instance ? mariadb_mock_instance->mysql_fetch_fields(res) : nullptr); } int STDCALL mysql_real_query (MYSQL *mysql, const char *q, unsigned long length) { return (mariadb_mock_instance ? mariadb_mock_instance->mysql_real_query(mysql, q, length) : 0); } unsigned int STDCALL mysql_errno (MYSQL *mysql) { return (mariadb_mock_instance ? mariadb_mock_instance->mysql_errno(mysql) : 0); } const char* STDCALL mysql_error (MYSQL *mysql) { return (mariadb_mock_instance ? mariadb_mock_instance->mysql_error(mysql) : nullptr); } MYSQL_RES* STDCALL mysql_store_result (MYSQL *mysql) { return (mariadb_mock_instance ? mariadb_mock_instance->mysql_store_result(mysql) : nullptr); } MYSQL_RES* STDCALL mysql_use_result (MYSQL *mysql) { return (mariadb_mock_instance ? mariadb_mock_instance->mysql_use_result(mysql) : nullptr); } unsigned int STDCALL mysql_field_count (MYSQL *mysql) { return (mariadb_mock_instance ? mariadb_mock_instance->mysql_field_count(mysql) : 0); } my_ulonglong STDCALL mysql_affected_rows (MYSQL *mysql) { return (mariadb_mock_instance ? mariadb_mock_instance->mysql_affected_rows(mysql) : 0); } my_ulonglong STDCALL mysql_insert_id (MYSQL *mysql) { return (mariadb_mock_instance ? mariadb_mock_instance->mysql_insert_id(mysql) : 0); } unsigned long STDCALL mysql_real_escape_string(MYSQL *mysql, char *to,const char *from, unsigned long length) { return (mariadb_mock_instance ? mariadb_mock_instance->mysql_real_escape_string(mysql, to, from, length) : 0); } void STDCALL mysql_close (MYSQL *mysql) { if (mariadb_mock_instance) mariadb_mock_instance->mysql_close(mysql); } MYSQL* STDCALL mysql_real_connect (MYSQL *mysql, const char *host, const char *user, const char *passwd, const char *db, unsigned int port, const char *unix_socket, unsigned long clientflag) { return (mariadb_mock_instance ? mariadb_mock_instance->mysql_real_connect(mysql, host, user, passwd, db, port, unix_socket, clientflag) : nullptr); } MYSQL* STDCALL mysql_init (MYSQL *mysql) { return (mariadb_mock_instance ? mariadb_mock_instance->mysql_init(mysql) : nullptr); }
d098f6f8bdf956662d4ac63331eff878c657314d
4c18fd69acd5da1e5422acf56a01d85a61d927fb
/src/uvw/signal.cpp
0b5bb4f92996b1d51f25e00bb68c7643b797a407
[ "CC-BY-SA-4.0", "MIT" ]
permissive
stefanofiorentino/uvw
372d7a90ca25567edb2c5b82f67ddaba4ae5d0be
39b6aea2f101bd301877cbb087e558db165d5b4d
refs/heads/master
2023-07-22T00:36:09.917301
2023-01-05T17:00:27
2023-01-05T17:00:27
186,373,872
0
1
MIT
2022-03-11T14:23:30
2019-05-13T08:06:00
C++
UTF-8
C++
false
false
861
cpp
signal.cpp
#ifdef UVW_AS_LIB # include "signal.h" #endif #include "config.h" namespace uvw { UVW_INLINE SignalEvent::SignalEvent(int sig) noexcept : signum{sig} {} UVW_INLINE void SignalHandle::startCallback(uv_signal_t *handle, int signum) { SignalHandle &signal = *(static_cast<SignalHandle *>(handle->data)); signal.publish(SignalEvent{signum}); } UVW_INLINE bool SignalHandle::init() { return initialize(&uv_signal_init); } UVW_INLINE void SignalHandle::start(int signum) { invoke(&uv_signal_start, get(), &startCallback, signum); } UVW_INLINE void SignalHandle::oneShot(int signum) { invoke(&uv_signal_start_oneshot, get(), &startCallback, signum); } UVW_INLINE void SignalHandle::stop() { invoke(&uv_signal_stop, get()); } UVW_INLINE int SignalHandle::signal() const noexcept { return get()->signum; } } // namespace uvw
8940898b969386f208095dc871e08c734f19de9d
ed358c5aa5f018fe1de38def2d3e41b32f82ee89
/Src/CLIENT/Naked.cpp
231e04ce5426080afb140dcde93bdb4cfd074cb9
[]
no_license
bgarciaoliveira/WYD2-CrackPatch-7556
177acdc0ee3f7e7556852e4c105e727628237e3d
460a33b40ec6ca5c52d19c5fa52d2fee73ee6ad2
refs/heads/master
2021-08-31T15:09:33.792807
2017-12-21T20:57:06
2017-12-21T20:57:06
115,044,361
1
0
null
null
null
null
UTF-8
C++
false
false
990
cpp
Naked.cpp
/* Copyright (C) 2015 bgarcia and agateownz Contact: fb.com/bruunooliveira.2 or brunogarcia212@gmail.com 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. This program is distributed in the hope that it will be useful, but withouy any warranty. */ #include "DllMain.h" bool Naked::Initialize() { HookLib::SetHook(eHookType::JMP, 0x41D0CB, Naked::NKD_AddItemDescription, 4); return true; } NAKED Naked::NKD_AddItemDescription() { static char *pointer = NULL; static st_Item *item = NULL; __asm { MOV ECX, DWORD PTR SS : [EBP - 0x8] MOV EDX, DWORD PTR DS : [ECX + 0x670] MOV item, EDX LEA EDX, DWORD PTR SS : [EBP - 0xA8] MOV pointer, EDX } if (item->Index == 747) { AddLine("The king of Noatun!", Gold); } __asm { MOV ECX, DWORD PTR SS : [EBP - 0x8] MOV EDX, DWORD PTR DS : [ECX + 0x670] MOV EAX, 0041D0D4h JMP EAX } }
faf160ee389229212ecf07dfc71d023a954e821e
814b49df11675ac3664ac0198048961b5306e1c5
/Code/Engine/Utilities/ComponentExplosive.cpp
4a00a4306d720c44786dd3e699849bc7f395ac64
[]
no_license
Atridas/biogame
f6cb24d0c0b208316990e5bb0b52ef3fb8e83042
3b8e95b215da4d51ab856b4701c12e077cbd2587
refs/heads/master
2021-01-13T00:55:50.502395
2011-10-31T12:58:53
2011-10-31T12:58:53
43,897,729
0
0
null
null
null
null
ISO-8859-3
C++
false
false
2,133
cpp
ComponentExplosive.cpp
#include "ComponentExplosive.h" #include "PhysicsManager.h" #include "ComponentObject3D.h" #include "Core.h" CComponentExplosive* CComponentExplosive::AddToEntity(CGameEntity *_pEntity) { CComponentExplosive *l_pComp = new CComponentExplosive(); assert(_pEntity && _pEntity->IsOk()); if(l_pComp->Init(_pEntity)) { l_pComp->SetEntity(_pEntity); return l_pComp; } else { delete l_pComp; return 0; } } bool CComponentExplosive::Init(CGameEntity *_pEntity) { SetOk(true); return IsOk(); } void CComponentExplosive::Explode(Vect3f _vPos, float _fRadius) { vector<CPhysicUserData*> l_vImpactObjects; CPhysicsManager *l_pPM = PHYSICS_MANAGER; l_pPM->OverlapSphereActor(_fRadius,_vPos,l_vImpactObjects,l_pPM->GetCollisionMask(ECG_FORCE)); vector<CPhysicUserData*>::iterator l_itUserData; vector<CPhysicUserData*>::iterator l_itUserDataEnd = l_vImpactObjects.end(); set<CGameEntity*> l_vImpactEntities; for(l_itUserData = l_vImpactObjects.begin(); l_itUserData != l_itUserDataEnd; ++l_itUserData) { CPhysicUserData* l_pUserData = *l_itUserData; l_vImpactEntities.insert(l_pUserData->GetEntity()); } set<CGameEntity*>::iterator l_itEntity; set<CGameEntity*>::iterator l_itEntityEnd = l_vImpactEntities.end(); //missatge de força Vect3f l_v = GetEntity()->GetComponent<CComponentObject3D>()->GetPosition(); SEvent l_impacte; l_impacte.Msg = SEvent::REBRE_FORCE; l_impacte.Info[0].Type = SEventInfo::FLOAT; l_impacte.Info[0].f = 100; l_impacte.Info[1].Type = SEventInfo::VECTOR; l_impacte.Info[1].v.x = l_v.x; l_impacte.Info[1].v.y = l_v.y; l_impacte.Info[1].v.z = l_v.z; l_impacte.Sender = GetEntity()->GetGUID(); for(l_itEntity = l_vImpactEntities.begin(); l_itEntity != l_itEntityEnd; ++l_itEntity) { CGameEntity* l_pEntity = *l_itEntity; if(GetEntity() != l_pEntity) { l_impacte.Receiver = l_pEntity->GetGUID(); ENTITY_MANAGER->SendEvent(l_impacte); } } }
7fa6011c366a74380245001b9b6a6cf58fa09bc7
63a34d8b8b062e0fe9acf9e3b3e2cfa19a4ab95e
/is-Engine-Admob/app/src/main/cpp/isEngine/system/entity/parents/Step.h
5988d99945c34839990c58c0c3c6f959dd6399e6
[ "Zlib" ]
permissive
matheuszig/is-Engine-Example-Pack
6e58fa009644f92f78f374a4d8fef9de5bb730cb
87cd2c4afb16478f50045b478688c9a4b68c357d
refs/heads/main
2023-03-12T20:49:05.004175
2021-03-06T01:13:19
2021-03-06T01:13:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
673
h
Step.h
#ifndef STEP_H_INCLUDED #define STEP_H_INCLUDED namespace is { //////////////////////////////////////////////////////////// /// Provides methods to manage the step of an object mechanism //////////////////////////////////////////////////////////// class Step { public: Step() : m_step(0) {} Step(int step) : m_step(step) {} virtual void setStep(int val) { m_step = val; } virtual void addStep() { m_step++; } virtual void reduceStep() { m_step--; } virtual int getStep() const { return m_step; } protected: int m_step; }; } #endif // STEP_H_INCLUDED
609861846eb19d2eb6f54edccfc79edc7e2c350b
ddc0af4698e59e5cf7470885f69f6c66c36c3b3b
/geoff2/main.cpp
220941d3861233b861c2535fefc005bbd0dc5c62
[]
no_license
killinfidels/geoff
e84fc221157d491b47cf3629f8bdfa98cc9e7ddb
b3aa7ebeec1cd5d6d7f5ce612d82cb8c272f9bbc
refs/heads/master
2021-05-05T10:19:53.476490
2018-01-30T14:48:06
2018-01-30T14:48:06
117,994,257
0
0
null
null
null
null
UTF-8
C++
false
false
1,169
cpp
main.cpp
#include <iostream> #include <windows.h> using namespace std; int main() { SetConsoleTitle("Calculator"); system("color 0A"); float num1, num2, result; int choice; char yn; do { system("cls"); cout << "Input first number: " << endl; cin >> num1; cout << "Input second number: " << endl; cin >> num2; cout << "Select an operation: " << endl; cout << "1: Addition" << endl; cout << "2: Subtraction" << endl; cout << "3: Multiplication" << endl; cout << "4: Division" << endl; cin >> choice; switch(choice) { case 1: result = num1 + num2; break; case 2: result = num1 - num2; break; case 3: result = num1 * num2; break; case 4: result = num1 / num2; break; default: cout << "deadass" << endl; break; } cout << "The result is: " << result << endl << endl; cout << "Enter y to repeat: "; cin >> yn; } while(yn == 'y'); return 0; }
110b888cba93fc47214d615f5510ca43043dcc9f
75eade2aca1572cd137d08d80b83437e3ee269c8
/workspace/src/player/player.cpp
76f98ea68b99852bfc42557b60cce681c48e767e
[]
no_license
holwech/RoboSoccer
85e17645142fc0fd930ad54cc1bba9ba2e01f7fc
2b22730c8951808ae60fb0a62d98bee20ed2719f
refs/heads/master
2021-01-18T17:56:55.457223
2017-02-01T14:25:22
2017-02-01T14:25:22
72,448,406
1
0
null
null
null
null
UTF-8
C++
false
false
9,205
cpp
player.cpp
#include "player.h" #include "player/goalkeeper_actions.cpp" #include "player/general_actions.cpp" #include "player/attacker_actions.cpp" Player::Player(Channel* channel, RTDBConn &DBC, const int deviceNr) : state_before_kick(STEP1), DBC(DBC), deviceNr(deviceNr), positions(6), ball(DBC), channel(channel), robo(DBC, deviceNr), Gstate(DYNAMIC_DEFEND) { //ballangle = 0; //ballx = 0; //bally = 0; control = 0; delta = 0.09; playerTicker.start(); prevState.store(IDLE); prevPrevState = IDLE; counter = 0; phase = 0; passSpeed = 0; done(); } void Player::run() { cout << "Player " << deviceNr << " started" << endl; bool isDone = true; bool isGoalkeeper; while(1){ isGoalkeeper = false; if (playerTicker.getTime() > std::chrono::duration<double, std::milli>(34)) { cout << deviceNr << endl; cout << playerTicker.getTime().count() << endl; } switch(state) { case IDLE: idle(); break; case STOP: isDone = stop(); if (isDone){ done(); } break; case BEFORE_PASS: break; case PASS: isDone = pass(command.pos1); if (isDone){ done(); } break; case GOTO: isDone = goTo(command.pos1, command.speed, command.ca); if (isDone){ done(); } break; case BEFORE_KICK: isDone = before_kick_improved(command.pos1, command.pos2, command.speed); if (isDone){ done(); } //usleep(200000); break; case KICK: //drivingKick(command.pos1); isDone = kick(command.pos1, command.speed, command.approach_speed); if (isDone){ done(); } break; case BLOCK_BALL: isDone = block_ball(command.speed); if (isDone){ done(); } break; case DEFEND: isGoalkeeper = true; //defend_tom(); defend(); break; case KICK_OUT: break; case TEST: isDone = goTo(Position(0.0,0.0), 2, false); if (isDone){ done(); } break; default: cout << "Case for state: " << state << endl; break; } updateRobo(isGoalkeeper); readCommand(); usleep(30000); //cout << "State: " << state << endl; } } /** Reads commands sent through the channel, and sets state accordingly */ void Player::readCommand() { std::lock_guard<std::mutex> lock(mutex); if (channel->isRead()) { return; } command = channel->read(); /* if (getPrevPrevState() != getState()) { playerPrint("Received command " + action_names[command.action]); } */ switch(command.action) { case ACTION_GOTO: //cout << "GOTO: " << command.pos1.GetX() << ", " << command.pos1.GetY() << endl; setState(GOTO); playerPrintState("Robo in state GOTO"); break; case ACTION_STOP: setState(STOP); playerPrintState("Robo in state STOP"); break; case ACTION_TEST: setState(TEST); break; case ACTION_IDLE: robo.GotoPos(robo.GetPos()); setState(IDLE); break; case ACTION_DEFEND: setState(DEFEND); playerPrintState("Robo in state DEFENED"); break; case ACTION_BEFORE_KICK: setState(BEFORE_KICK); playerPrintState("Robo in state BEFORE_KICK"); break; case ACTION_KICK: setState(KICK); playerPrintState("Robo in state KICK"); break; case ACTION_PASS: setState(PASS); playerPrintState("Robo in state PASS"); break; case ACTION_BLOCK_BALL: setState(BLOCK_BALL); playerPrintState("Robo in state BLOCK_BALL"); break; default: playerPrintState("No case for this state"); break; } } void Player::playerPrintState(string message) { string color = "\033[1;31m"; if (deviceNr == 0 || deviceNr == 3) { color = "\033[1;32m"; } else if (deviceNr == 1 || deviceNr == 4) { color = "\033[1;33m"; } else { color = "\033[1;34m"; } if (getPrevPrevState() != getState()) { cout << color << "#P" << deviceNr << ": " << message << "\033[0m" << endl; } } void Player::playerPrint(string message) { string color = "\033[1;31m"; if (deviceNr == 0) { color = "\033[1;32m"; } else if (deviceNr == 1) { color = "\033[1;33m"; } else { color = "\033[1;34m"; } cout << color << "#P" << deviceNr << ": " << message << "\033[0m" << endl; } /** Updates the positions of other robos */ void Player::update(vector<Position> pos) { std::lock_guard<std::mutex> lock(mutex); positions = pos; } /** Because of risk of race conditions, this function is preferred over * getting the positions directly from the positions variable */ Position Player::position(int robot) { std::lock_guard<std::mutex> lock(mutex); return positions[robot]; } /** Used by master to get the current position of the robot */ Position Player::getPos() { std::lock_guard<std::mutex> lock(mutex); return robo.GetPos(); } double Player::getX() { std::lock_guard<std::mutex> lock(mutex); return robo.GetX(); } double Player::getY() { std::lock_guard<std::mutex> lock(mutex); return robo.GetY(); } /** Updates the robo functions */ void Player::updateRobo(bool isGoalkeeper) { ball.updateSample(); robo.updatePositions(positions); isGoalkeeper ? robo.goalieDrive() : robo.driveWithCA(); } void Player::done() { setState(IDLE); setBusy(false); kick_state = A_STEP1; pass_state = A_STEP1; state_before_kick = STEP1; block_state = A_STEP1; } /** Checks if the player is busy performing an action */ bool Player::isBusy() { return busy.load(); } /** Sets the player to busy when an action is started */ void Player::setBusy(bool flag) { busy.store(flag); if (busy.load() && deviceNr == 4) { playerPrint("Robot is busy"); } else if (deviceNr == 4) { playerPrint("Robot is not busy"); } } /** Gets the current state of the player */ PState Player::getState() { return state.load(); } /** Gets the previous state of the player */ PState Player::getPrevState() { return prevState.load(); } PState Player::getPrevPrevState() { return prevPrevState; } /** Sets the state of the player */ void Player::setState(PState newState) { prevPrevState = prevState.load(); prevState.store(state.load()); state.store(newState); } // These do not actually work, do not copy player. The result would not be good... // Only purpose is so that the program compiles. Player::Player(Player&& other) : DBC(other.DBC), ball(other.DBC), robo(other.DBC, other.deviceNr) { std::lock_guard<std::mutex> lock(other.mutex); positions = std::move(other.positions); channel = std::move(other.channel); command = std::move(other.command); deviceNr = std::move(other.deviceNr); prevState.store(std::move(other.prevState.load())); state_before_kick = std::move(other.state_before_kick); state.store(std::move(state.load())); busy.store(std::move(busy.load())); } Player::Player(const Player& other) : DBC(other.DBC), ball(other.DBC), robo(other.DBC, other.deviceNr) { std::lock_guard<std::mutex> lock(other.mutex); positions = other.positions; channel = other.channel; command = other.command; deviceNr = other.deviceNr; prevState.store(other.prevState.load()); state_before_kick = other.state_before_kick; state.store(state.load()); busy.store(busy.load()); } Player& Player::operator = (Player&& other) { std::lock(mutex, other.mutex); std::lock_guard<std::mutex> self_lock(mutex, std::adopt_lock); std::lock_guard<std::mutex> other_lock(other.mutex, std::adopt_lock); positions = std::move(other.positions); ball = std::move(other.ball); channel = std::move(other.channel); command = std::move(other.command); deviceNr = std::move(other.deviceNr); robo = std::move(other.robo); prevState.store(std::move(other.prevState.load())); state_before_kick = std::move(other.state_before_kick); state.store(std::move(state.load())); busy.store(std::move(busy.load())); return *this; } Player& Player::operator = (const Player& other) { std::lock(mutex, other.mutex); std::lock_guard<std::mutex> self_lock(mutex, std::adopt_lock); std::lock_guard<std::mutex> other_lock(other.mutex, std::adopt_lock); positions = other.positions; ball = other.ball; channel = other.channel; command = other.command; deviceNr = other.deviceNr; robo = other.robo; prevState.store(other.prevState.load()); state_before_kick = other.state_before_kick; state.store(state.load()); busy.store(busy.load()); return *this; }
bdefe1a64a48586d0a7070ade68e34a32707731f
7f73bb7c35e2d8f5fef33499856eff5d05c90cd5
/src/movement_controller.h
48f7a8036fe372e1cdbe9f706b4ad53f8db35927
[]
no_license
var-const/azureland
9446840415927371edf53ea563050b84b7c11a92
92b45caffd5dc50c4f993502d5f3dc183f2c859d
refs/heads/master
2021-01-23T07:20:57.088522
2015-10-12T03:08:17
2015-10-12T03:08:17
40,819,741
0
0
null
null
null
null
UTF-8
C++
false
false
436
h
movement_controller.h
#pragma once namespace cinder { template <typename T> class Vec2; } class Movable; class MovementController { public: void SetSpeed(float Speed); cinder::Vec2<float> GetVector(int Key) const; void Deccelerate(Movable& Object); void OnKeyDown(int Key, Movable& Object); void OnKeyUp(int key); private: // @TODO: need a flag for both movement keys bool m_IsMoveKeyPressed{}; float m_Speed{}; };
4e48c0ea70d5299e2abbb000a139b18a0cbf5792
5386865e2ea964397b8127aba4b2592d939cd9f2
/jboi2012/DOB 2/zadachi/zad 2 30.03.2008.cpp
008f38f60416fc7c2104fa975621edb0d950562a
[]
no_license
HekpoMaH/Olimpiads
e380538b3de39ada60b3572451ae53e6edbde1be
d358333e606e60ea83e0f4b47b61f649bd27890b
refs/heads/master
2021-07-07T14:51:03.193642
2017-10-04T16:38:11
2017-10-04T16:38:11
105,790,126
2
0
null
null
null
null
UTF-8
C++
false
false
201
cpp
zad 2 30.03.2008.cpp
#include<iostream> using namespace std; int main() { int min=200; while(min%17!=0) { min++; } cout<<min<<endl; system("pause"); return 0; }
56489e629ce8ea418517df929e85ea0deaa7a089
725d4ceec138f8f9ceefeaef8aac026767604a18
/ConsoleApplication4/tictactoe.h
2029e1ebbc791ff545dd7feb694aed22059fd7c5
[]
no_license
nathan-rees/AI
42fb48771dcd49b21bfafc5bc461c08ecff1f2fc
22c9c4936ecc878142003d62172457a78e2a4161
refs/heads/master
2023-01-04T19:48:17.671210
2020-05-01T09:37:13
2020-05-01T09:37:13
260,423,844
1
0
null
null
null
null
UTF-8
C++
false
false
1,141
h
tictactoe.h
#pragma once #include <vector> #include <iostream> using namespace std; class tictactoe { private: vector<vector<char>> board{ {'-','-','-'}, {'-','-','-'}, {'-','-','-'} }; public: void input(int col, int row, char inp) { board[col][row] = inp;//cos fuck 0 } void print() { for (int i = 0; i < board.size(); i++) { for (int j = 0; j < board[i].size(); j++) { cout << board[j][i]; cout << " "; } cout << endl; } } bool checkWin(char c) { if (board[0][0] == c && board[1][0] == c && board[2][0] == c)return true; else if (board[0][1] == c && board[2][1] == c && board[2][1] == c)return true; else if (board[0][2] == c && board[2][2] == c && board[2][2] == c)return true; else if (board[0][0] == c && board[0][1] == c && board[0][2] == c)return true; else if (board[1][0] == c && board[1][1] == c && board[1][2] == c)return true; else if (board[2][0] == c && board[2][1] == c && board[2][2] == c)return true; else if (board[0][0] == c && board[1][1] == c && board[2][2] == c)return true; else if (board[2][0] == c && board[1][1] == c && board[0][2] == c)return true; else return false; } };
d0d7bee6f9628db4b6de16ef87ccea5ec415cfd2
425df8036558a93c29fda8c61951298de9285562
/src/main.cpp
1f803f40c5636d97d0f8d87bf04ca5d4d00031c8
[]
no_license
Voodo13/Shark_tale_arcade
ff4cf85a4e7c020ecc105e9f097d2d3c85a6a92b
5a0539cfb3bb19bf7da7d227811b32134271c2de
refs/heads/master
2023-05-14T23:08:50.436972
2021-05-24T07:23:43
2021-05-24T07:23:43
370,263,732
0
0
null
null
null
null
UTF-8
C++
false
false
5,952
cpp
main.cpp
#include <Arduino.h> #include <avr/eeprom.h> #include "GyverTimer.h" #include "MaxButton.h" #include <Sensors.h> #include <Wire.h> #include <Adafruit_SSD1306.h> #include <Fonts/FreeSans9pt7b.h> #define SCREEN_WIDTH 128 // OLED display width, in pixels #define SCREEN_HEIGHT 64 // OLED display height, in pixels // Declaration for an SSD1306 display connected to I2C (SDA, SCL pins) Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1); struct Game { bool begin = false; byte coins = 0; int points = 0; } game; struct Dispensor { float ticketRatio = eeprom_read_float(0); byte ticketMax = eeprom_read_byte((uint8_t*)4); byte ticketMin = eeprom_read_byte((uint8_t*)5); int tickets = 0; } dispensor; bool menuON = true; GTimer gameTimer(MS); // ----------- Coin -------------- GButton coinBtn(4); void coinSetup() { coinBtn.setDebounce(10); } void coinFn() { if (coinBtn.isClick()) { game.coins++; menuON = true; } } // ------------------------------------ // ----------- Start Button ------------------ GButton startBtn(5); void startBtnSetup() { startBtn.setDebounce(10); } void startBtnFn() { if(startBtn.isPress()) { if(game.begin || game.coins < 1) return; game.coins--; game.begin = true; game.points = 0; gameTimer.setTimeout(60000); menuON = true; } } // ------------------------------------ // ----------- Dispensor -------------- GButton dspOut(3); void dispensorSetup() { dspOut.setDebounce(0); pinMode(2, OUTPUT); //dspIN } void ticketDec() { if(dispensor.tickets > 0) dispensor.tickets--; } void dispensorFn() { if(!dispensor.tickets) return; digitalWrite(2, HIGH); if(dspOut.isClick()) { dispensor.tickets--; menuON = true; if(!dispensor.tickets) digitalWrite(2, LOW); } } // ------------------------------------ // ----------- Sensors -------------- Sensors s1(7, HIGH_PULL, NORM_CLOSE); void sensorsFn() { if(s1.isPress()) { game.points++; menuON = true; } } // ------------------------------------ //+ ----------- Game ------------------ void gameSetup() { if(dispensor.ticketRatio > 100) dispensor.ticketRatio = 100; if(dispensor.ticketRatio < 0) dispensor.ticketRatio = 0; } void gameFn() { if(!game.begin) return; if(gameTimer.isReady()) { game.begin = false; dispensor.tickets += dispensor.ticketMin + (int)(game.points * dispensor.ticketRatio); if (dispensor.tickets > dispensor.ticketMax) dispensor.tickets = dispensor.ticketMax; } menuON = true; } // ------------------------------------ // -------------- Display ---------------------------- bool menuSetup = false; byte menuList = 1; void displaySetup() { if (menuList == 1) display.print("[ "); display.print("Cof - "); display.println(dispensor.ticketRatio); if (menuList == 2) display.print("[ "); display.print("max - "); display.println(dispensor.ticketMax); if (menuList == 3) display.print("[ "); display.print("min - "); display.println(dispensor.ticketMin); } void displayState() { display.print("Coins: "); display.println(game.coins); display.print("Points: "); display.println(game.points); display.print("Tickets: "); display.println(dispensor.tickets); } void displayRander() { if(!menuON) return; display.clearDisplay(); display.setFont(&FreeSans9pt7b); //display.setTextSize(1); display.setTextColor(WHITE); display.setCursor(0,15); if (menuSetup) { displaySetup(); } else { displayState(); } display.display(); menuON = false; } GButton btnLeft(15); GButton btnOk(16); GButton btnRight(17); void keyboardSetup() { btnLeft.setDebounce(30); btnOk.setDebounce(30); btnRight.setDebounce(30); btnOk.setTimeout(500); btnLeft.setTimeout(500); btnLeft.setStepTimeout(100); btnRight.setTimeout(500); btnRight.setStepTimeout(100); } // ---------------- КНОПКИ МЕНЮ ---------------------- void buttonMenu() { if (btnOk.isHolded()) { menuON = true; if (menuSetup) { if (dispensor.ticketMax < dispensor.ticketMin) dispensor.ticketMax = dispensor.ticketMin; eeprom_update_float(0, dispensor.ticketRatio); eeprom_update_byte((uint8_t*)4, dispensor.ticketMax); eeprom_update_byte((uint8_t*)5, dispensor.ticketMin); menuON = true; } menuSetup = !menuSetup; } // меню настроек if(!menuSetup) return; if (btnOk.isClick()) { menuON = true; if (!menuSetup) return; menuList++; if (menuList > 3) menuList = 1; } if(btnLeft.isClick() or btnLeft.isStep()) { menuON = true; if (!menuSetup) return; if(menuList == 1) dispensor.ticketRatio -= 0.25; if(dispensor.ticketRatio < 0) dispensor.ticketRatio = 100; if(menuList == 2) dispensor.ticketMax--; if(dispensor.ticketMax < dispensor.ticketMin) dispensor.ticketMax = dispensor.ticketMin; if(menuList == 3) dispensor.ticketMin--; } if(btnRight.isClick() or btnRight.isStep()) { menuON = true; if (!menuSetup) return; if(menuList == 1) dispensor.ticketRatio += 0.25; if(dispensor.ticketRatio > 100) dispensor.ticketRatio = 0; if(menuList == 2) dispensor.ticketMax++; if(menuList == 3) dispensor.ticketMin++; } } // --------------------------------------------------- void tick() { coinBtn.tick(); if(dispensor.tickets) dspOut.tick(); if(game.begin){ s1.tick(); } else { btnOk.tick(); if(menuSetup){ btnLeft.tick(); btnRight.tick(); } if(game.coins)startBtn.tick(); } } void sensorTick() { if(game.begin) s1.tick(); } void setup() { display.begin(SSD1306_SWITCHCAPVCC, 0x3C); delay(1000); display.clearDisplay(); display.display(); keyboardSetup(); gameSetup(); coinSetup(); startBtnSetup(); dispensorSetup(); } void loop() { tick(); coinFn(); startBtnFn(); sensorsFn(); dispensorFn(); gameFn(); buttonMenu(); //sensorTick(); displayRander(); }
fb213592a2e0bb217d0ec47e5b4e7fe19dad78c1
6c8b68bb25ce787725e90e4fe85748b6fa5b9596
/f8_templates/print.hpp
4cc1e6a17a71744de2548468fc1f2fe451947d27
[]
no_license
claudiouzelac/cpp_v2015
df8e348291249512e369bf3319b301dde1bf8d06
825989241f767206658cdb77f88aa20aefa8c99a
refs/heads/master
2022-10-18T23:50:45.058721
2015-06-01T13:19:08
2015-06-01T13:19:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
146
hpp
print.hpp
#ifndef PRINT_HPP #define PRINT_HPP #include <iostream> template<typename T> void print(const T c){ std::cout << c << std::endl; }; #endif
616d258887631dadf0f242a50bd21d5c8444172a
c6d109a9bf019e29aa07c5cd5159eb5f3b407fe3
/sheaves/template_instantiations/list_pool.inst.cc
fa2d60124e98e2becbf42b26d83626955b0b5d7e
[ "Apache-2.0" ]
permissive
LimitPointSystems/SheafSystem
883effa60ec9533a085e2d1442c83df721e8d264
617faf00175b1422be648b85146e43d2fc54f662
refs/heads/master
2020-09-12T20:01:59.763743
2017-05-02T20:48:52
2017-05-02T20:48:52
16,596,740
2
3
null
2017-05-02T20:48:52
2014-02-06T22:44:58
C++
UTF-8
C++
false
false
15,605
cc
list_pool.inst.cc
// // Copyright (c) 2014 Limit Point Systems, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // Explicit instantiations for class list_pool. #include "SheafSystem/list_pool.impl.h" #include "SheafSystem/array_implicit_index_space_iterator.h" #include "SheafSystem/array_index_space_handle.h" #include "SheafSystem/array_index_space_iterator.h" #include "SheafSystem/constant_implicit_index_space_iterator.h" #include "SheafSystem/explicit_index_space_handle.h" #include "SheafSystem/forwarding_index_space_handle.h" #include "SheafSystem/hash_index_space_handle.h" #include "SheafSystem/hash_index_space_iterator.h" #include "SheafSystem/hub_index_space_handle.h" #include "SheafSystem/hub_index_space_iterator.h" #include "SheafSystem/interval_index_space_handle.h" #include "SheafSystem/interval_index_space_iterator.h" #include "SheafSystem/list_index_space_iterator.h" #include "SheafSystem/list_index_space_handle.h" #include "SheafSystem/offset_index_space_handle.h" #include "SheafSystem/offset_index_space_iterator.h" #include "SheafSystem/primary_index_space_handle.h" #include "SheafSystem/primary_index_space_iterator.h" #include "SheafSystem/primitives_index_space_handle.h" #include "SheafSystem/primitives_index_space_iterator.h" #include "SheafSystem/ragged_array_implicit_index_space_iterator.h" #include "SheafSystem/reserved_primary_index_space_handle.h" #include "SheafSystem/reserved_primary_index_space_iterator.h" #include "SheafSystem/singleton_implicit_index_space_iterator.h" #include "SheafSystem/singleton_index_space_handle.h" #include "SheafSystem/singleton_index_space_iterator.h" //============================================================================== // EXPLICIT INSTANTIATIONS //============================================================================== //============================================================================== // array_implicit_index_space_iterator //============================================================================== template class SHEAF_DLL_SPEC sheaf::list_pool<sheaf::array_implicit_index_space_iterator>; #ifndef DOXYGEN_SKIP_INSTANTIATIONS template SHEAF_DLL_SPEC size_t sheaf::deep_size<sheaf::array_implicit_index_space_iterator>(const list_pool<array_implicit_index_space_iterator>& xpool, bool xinclude_shallow); #endif // ifndef DOXYGEN_SKIP_INSTANTIATIONS //============================================================================== // array_index_space_handle //============================================================================== template class SHEAF_DLL_SPEC sheaf::list_pool<sheaf::array_index_space_handle>; #ifndef DOXYGEN_SKIP_INSTANTIATIONS template SHEAF_DLL_SPEC size_t sheaf::deep_size<sheaf::array_index_space_handle>(const list_pool<array_index_space_handle>& xpool, bool xinclude_shallow); #endif // ifndef DOXYGEN_SKIP_INSTANTIATIONS //============================================================================== // array_index_space_iterator //============================================================================== template class SHEAF_DLL_SPEC sheaf::list_pool<sheaf::array_index_space_iterator>; #ifndef DOXYGEN_SKIP_INSTANTIATIONS template SHEAF_DLL_SPEC size_t sheaf::deep_size<sheaf::array_index_space_iterator>(const list_pool<array_index_space_iterator>& xpool, bool xinclude_shallow); #endif // ifndef DOXYGEN_SKIP_INSTANTIATIONS //============================================================================== // constant_implicit_index_space_iterator //============================================================================== template class SHEAF_DLL_SPEC sheaf::list_pool<sheaf::constant_implicit_index_space_iterator>; #ifndef DOXYGEN_SKIP_INSTANTIATIONS template SHEAF_DLL_SPEC size_t sheaf::deep_size<sheaf::constant_implicit_index_space_iterator>(const list_pool<constant_implicit_index_space_iterator>& xpool, bool xinclude_shallow); #endif // ifndef DOXYGEN_SKIP_INSTANTIATIONS //============================================================================== // forwarding_index_space_handle //============================================================================== template class SHEAF_DLL_SPEC sheaf::list_pool<sheaf::forwarding_index_space_handle>; #ifndef DOXYGEN_SKIP_INSTANTIATIONS template SHEAF_DLL_SPEC size_t sheaf::deep_size<sheaf::forwarding_index_space_handle>(const list_pool<forwarding_index_space_handle>& xpool, bool xinclude_shallow); #endif // ifndef DOXYGEN_SKIP_INSTANTIATIONS //============================================================================== // hash_index_space_handle //============================================================================== template class SHEAF_DLL_SPEC sheaf::list_pool<sheaf::hash_index_space_handle>; #ifndef DOXYGEN_SKIP_INSTANTIATIONS template SHEAF_DLL_SPEC size_t sheaf::deep_size<sheaf::hash_index_space_handle>(const list_pool<hash_index_space_handle>& xpool, bool xinclude_shallow); #endif // ifndef DOXYGEN_SKIP_INSTANTIATIONS //============================================================================== // hash_index_space_iterator //============================================================================== template class SHEAF_DLL_SPEC sheaf::list_pool<sheaf::hash_index_space_iterator>; #ifndef DOXYGEN_SKIP_INSTANTIATIONS template SHEAF_DLL_SPEC size_t sheaf::deep_size<sheaf::hash_index_space_iterator>(const list_pool<hash_index_space_iterator>& xpool, bool xinclude_shallow); #endif // ifndef DOXYGEN_SKIP_INSTANTIATIONS //============================================================================== // hub_index_space_handle //============================================================================== template class SHEAF_DLL_SPEC sheaf::list_pool<sheaf::hub_index_space_handle>; #ifndef DOXYGEN_SKIP_INSTANTIATIONS template SHEAF_DLL_SPEC size_t sheaf::deep_size<sheaf::hub_index_space_handle>(const list_pool<hub_index_space_handle>& xpool, bool xinclude_shallow); #endif // ifndef DOXYGEN_SKIP_INSTANTIATIONS //============================================================================== // hub_index_space_handle //============================================================================== template class SHEAF_DLL_SPEC sheaf::list_pool<sheaf::hub_index_space_iterator>; #ifndef DOXYGEN_SKIP_INSTANTIATIONS template SHEAF_DLL_SPEC size_t sheaf::deep_size<sheaf::hub_index_space_iterator>(const list_pool<hub_index_space_iterator>& xpool, bool xinclude_shallow); #endif // ifndef DOXYGEN_SKIP_INSTANTIATIONS //============================================================================== // interval_index_space_handle //============================================================================== template class SHEAF_DLL_SPEC sheaf::list_pool<sheaf::interval_index_space_handle>; #ifndef DOXYGEN_SKIP_INSTANTIATIONS template SHEAF_DLL_SPEC size_t sheaf::deep_size<sheaf::interval_index_space_handle>(const list_pool<interval_index_space_handle>& xpool, bool xinclude_shallow); #endif // ifndef DOXYGEN_SKIP_INSTANTIATIONS //============================================================================== // interval_index_space_iterator //============================================================================== template class SHEAF_DLL_SPEC sheaf::list_pool<sheaf::interval_index_space_iterator>; #ifndef DOXYGEN_SKIP_INSTANTIATIONS template SHEAF_DLL_SPEC size_t sheaf::deep_size<sheaf::interval_index_space_iterator>(const list_pool<interval_index_space_iterator>& xpool, bool xinclude_shallow); #endif // ifndef DOXYGEN_SKIP_INSTANTIATIONS //============================================================================== // list_index_space_handle //============================================================================== template class SHEAF_DLL_SPEC sheaf::list_pool<sheaf::list_index_space_handle>; #ifndef DOXYGEN_SKIP_INSTANTIATIONS template SHEAF_DLL_SPEC size_t sheaf::deep_size<sheaf::list_index_space_handle>(const list_pool<list_index_space_handle>& xpool, bool xinclude_shallow); #endif // ifndef DOXYGEN_SKIP_INSTANTIATIONS //============================================================================== // list_index_space_iterator //============================================================================== template class SHEAF_DLL_SPEC sheaf::list_pool<sheaf::list_index_space_iterator>; #ifndef DOXYGEN_SKIP_INSTANTIATIONS template SHEAF_DLL_SPEC size_t sheaf::deep_size<sheaf::list_index_space_iterator>(const list_pool<list_index_space_iterator>& xpool, bool xinclude_shallow); #endif // ifndef DOXYGEN_SKIP_INSTANTIATIONS //============================================================================== // offset_index_space_handle //============================================================================== template class SHEAF_DLL_SPEC sheaf::list_pool<sheaf::offset_index_space_handle>; #ifndef DOXYGEN_SKIP_INSTANTIATIONS template SHEAF_DLL_SPEC size_t sheaf::deep_size<sheaf::offset_index_space_handle>(const list_pool<offset_index_space_handle>& xpool, bool xinclude_shallow); #endif // ifndef DOXYGEN_SKIP_INSTANTIATIONS //============================================================================== // offset_index_space_iterator //============================================================================== template class SHEAF_DLL_SPEC sheaf::list_pool<sheaf::offset_index_space_iterator>; #ifndef DOXYGEN_SKIP_INSTANTIATIONS template SHEAF_DLL_SPEC size_t sheaf::deep_size<sheaf::offset_index_space_iterator>(const list_pool<offset_index_space_iterator>& xpool, bool xinclude_shallow); #endif // ifndef DOXYGEN_SKIP_INSTANTIATIONS //============================================================================== // primary_index_space_handle //============================================================================== template class SHEAF_DLL_SPEC sheaf::list_pool<sheaf::primary_index_space_handle>; #ifndef DOXYGEN_SKIP_INSTANTIATIONS template SHEAF_DLL_SPEC size_t sheaf::deep_size<sheaf::primary_index_space_handle>(const list_pool<primary_index_space_handle>& xpool, bool xinclude_shallow); #endif // ifndef DOXYGEN_SKIP_INSTANTIATIONS //============================================================================== // primary_index_space_iterator //============================================================================== template class SHEAF_DLL_SPEC sheaf::list_pool<sheaf::primary_index_space_iterator>; #ifndef DOXYGEN_SKIP_INSTANTIATIONS template SHEAF_DLL_SPEC size_t sheaf::deep_size<sheaf::primary_index_space_iterator>(const list_pool<primary_index_space_iterator>& xpool, bool xinclude_shallow); #endif // ifndef DOXYGEN_SKIP_INSTANTIATIONS //============================================================================== // primitives_index_space_handle //============================================================================== template class SHEAF_DLL_SPEC sheaf::list_pool<sheaf::primitives_index_space_handle>; #ifndef DOXYGEN_SKIP_INSTANTIATIONS template SHEAF_DLL_SPEC size_t sheaf::deep_size<sheaf::primitives_index_space_handle>(const list_pool<primitives_index_space_handle>& xpool, bool xinclude_shallow); #endif // ifndef DOXYGEN_SKIP_INSTANTIATIONS //============================================================================== // primitives_index_space_iterator //============================================================================== template class SHEAF_DLL_SPEC sheaf::list_pool<sheaf::primitives_index_space_iterator>; #ifndef DOXYGEN_SKIP_INSTANTIATIONS template SHEAF_DLL_SPEC size_t sheaf::deep_size<sheaf::primitives_index_space_iterator>(const list_pool<primitives_index_space_iterator>& xpool, bool xinclude_shallow); #endif // ifndef DOXYGEN_SKIP_INSTANTIATIONS //============================================================================== // ragged_array_implicit_index_space_iterator //============================================================================== template class SHEAF_DLL_SPEC sheaf::list_pool<sheaf::ragged_array_implicit_index_space_iterator>; #ifndef DOXYGEN_SKIP_INSTANTIATIONS template SHEAF_DLL_SPEC size_t sheaf::deep_size<sheaf::ragged_array_implicit_index_space_iterator>(const list_pool<ragged_array_implicit_index_space_iterator>& xpool, bool xinclude_shallow); #endif // ifndef DOXYGEN_SKIP_INSTANTIATIONS //============================================================================== // reserved_primary_index_space_handle //============================================================================== template class SHEAF_DLL_SPEC sheaf::list_pool<sheaf::reserved_primary_index_space_handle>; #ifndef DOXYGEN_SKIP_INSTANTIATIONS template SHEAF_DLL_SPEC size_t sheaf::deep_size<sheaf::reserved_primary_index_space_handle>(const list_pool<reserved_primary_index_space_handle>& xpool, bool xinclude_shallow); #endif // ifndef DOXYGEN_SKIP_INSTANTIATIONS //============================================================================== // reserved_primary_index_space_iterator //============================================================================== template class SHEAF_DLL_SPEC sheaf::list_pool<sheaf::reserved_primary_index_space_iterator>; #ifndef DOXYGEN_SKIP_INSTANTIATIONS template SHEAF_DLL_SPEC size_t sheaf::deep_size<sheaf::reserved_primary_index_space_iterator>(const list_pool<reserved_primary_index_space_iterator>& xpool, bool xinclude_shallow); #endif // ifndef DOXYGEN_SKIP_INSTANTIATIONS //============================================================================== // singleton_implicit_index_space_iterator //============================================================================== template class SHEAF_DLL_SPEC sheaf::list_pool<sheaf::singleton_implicit_index_space_iterator>; #ifndef DOXYGEN_SKIP_INSTANTIATIONS template SHEAF_DLL_SPEC size_t sheaf::deep_size<sheaf::singleton_implicit_index_space_iterator>(const list_pool<singleton_implicit_index_space_iterator>& xpool, bool xinclude_shallow); #endif // ifndef DOXYGEN_SKIP_INSTANTIATIONS //============================================================================== // singleton_index_space_handle //============================================================================== template class SHEAF_DLL_SPEC sheaf::list_pool<sheaf::singleton_index_space_handle>; #ifndef DOXYGEN_SKIP_INSTANTIATIONS template SHEAF_DLL_SPEC size_t sheaf::deep_size<sheaf::singleton_index_space_handle>(const list_pool<singleton_index_space_handle>& xpool, bool xinclude_shallow); #endif // ifndef DOXYGEN_SKIP_INSTANTIATIONS //============================================================================== // singleton_index_space_iterator //============================================================================== template class SHEAF_DLL_SPEC sheaf::list_pool<sheaf::singleton_index_space_iterator>; #ifndef DOXYGEN_SKIP_INSTANTIATIONS template SHEAF_DLL_SPEC size_t sheaf::deep_size<sheaf::singleton_index_space_iterator>(const list_pool<singleton_index_space_iterator>& xpool, bool xinclude_shallow); #endif // ifndef DOXYGEN_SKIP_INSTANTIATIONS
136cd1bb9daecc15e897ec0a81ef1bbae0d83b6f
997c0e00ca04232a42760e8d74561030f657175d
/treeclass.hpp
098747dbdbf6bf541d7bad8c2fbb2a590c893165
[]
no_license
ivababkin/tree
e13c0fc2095ea8b27b80b4b75e19a32c8c15df44
688df7d739fdf2a7faf2d2e92827f2831a5c74e7
refs/heads/master
2020-03-07T07:26:33.948741
2018-05-18T06:46:30
2018-05-18T06:46:30
127,349,397
0
0
null
null
null
null
UTF-8
C++
false
false
987
hpp
treeclass.hpp
#include <iostream> #include <stdio.h> #include <stdlib.h> //#ifndef treeclass_H //#define treeclass_H typedef struct Tree { struct Tree * left; struct Tree * right; struct Tree * back; int deep; int val; } tree; class treeclass { public: treeclass(); void insert(int value); bool exists(int value); void remove(int value); void printtree(); void balancetree(); ~treeclass(); protected: tree* newelement (int element); void printtree(tree* node); int setdeep(tree * head); int deep(tree * node); void addelement (tree* head, tree* element); tree * searchbyval(tree* head, int x); int deltree(tree ** phead); void destroy(tree * head); void smallright(tree ** phead); void smallleft(tree ** phead); void bigleft(tree ** phead); void bigright(tree ** phead); int bal(tree ** phead); int balance(tree ** phead, int * res); int balanceall(tree ** phead); tree * root; };
003adeb49b97f22f6de214388edbb269f643cda5
b2fad8c7e0ac2fadee108a6d8e5fc089755730ea
/C++/real_transitions.cpp
1126761f5924b9a31e1a69a0217ddcdec4f10a50
[]
no_license
yleo/aggregation
a98a89b0ee3eeded116f30301505891e99bf4688
45a8a963454efcc0543a58d396d21029e2f74745
refs/heads/master
2021-01-17T20:28:22.462727
2016-06-23T12:44:46
2016-06-23T12:44:46
61,802,449
0
0
null
null
null
null
UTF-8
C++
false
false
1,264
cpp
real_transitions.cpp
//cas t1=t2 et croissant par les ti //output not uniq #include <iostream> #include <vector> #include <map> #include <algorithm> #include <stdio.h> #include <stdlib.h> using namespace std; struct myclass { bool operator() (int i,int j) { return (i<j);} } myobject; struct Arete { int u; int v; }; int main(int argc, char *argv[]) { map < int, int > Convert; Arete arr, buf; int s1, s2, t1, t2; map < int, vector < Arete > > Graph; int maxT=atoi(argv[1]), maxN=0; // 274882 102543 int temp,i2,i4,x; i4=0; for (int i=maxT; i>0;i--) { i2=maxT/i; if (i2>i4) { i4=i2; Convert[i]=0; } } int n = 0; int p = 0; while (cin >> s1 >> s2 >> t1 >> t2) { for (std::map <int, int >::iterator it=Convert.begin(); it!=Convert.end(); ++it) { x=it->first; n = (int) (maxT+1)/x; p = (maxT+1)-n*x; if (t1<p*(n+1)) { temp=t1/(n+1); if ((temp+1)*(n+1)<=t1+t2) { Convert[it->first]++; } } else { temp=(t1-p*(n+1))/n; if (p*(n+1)+(temp+1)*n<t1+t2) { Convert[it->first]++; } } } } for (std::map <int, int >::iterator it=Convert.begin(); it!=Convert.end(); ++it) { cout << maxT/(it->first) << " " << Convert[it->first] << endl; } return 0; }
6f348e4f5643687dbfe967ec3ae9128fc8439db7
1b9c4830207821c069bdafbe33041602103f1afb
/Game.h
109a84725f4e7ad92f4de05bf023d66f97b81e37
[]
no_license
Patrikgyllvin/Input-Prototype
42ce3e3ab535e7b4b1943fc4bc8a0f66df875313
74a902c2d16ebf043fad1dba8c2daf6e54a3970c
refs/heads/master
2022-04-04T14:53:31.927456
2020-02-14T19:43:29
2020-02-14T19:43:29
240,585,938
0
0
null
null
null
null
UTF-8
C++
false
false
221
h
Game.h
#ifndef GAME_H #define GAME_H #include <iostream> #include "Core.h" class Game { public: Game(); ~Game(); void load(); void tick(); void render( Engine::Renderer& renderer ); }; #endif // GAME_H
1ca1873846c89d1e3882324cc9f94b7d2b7b6125
9cf8571a4d546e550b942b022a8728e1cacba2b6
/codingInterview/16.Power/power.cc
40a9cf5849605bd45b17feebb8569b6fdad37ad6
[ "MIT" ]
permissive
stdbilly/CS_Note
eebd7f1371f263272a4f71d96063fc5deb20867b
a8a87e135a525d53c283a4c70fb942c9ca59a758
refs/heads/master
2020-06-15T23:41:14.103914
2019-10-17T15:55:08
2019-10-17T15:55:08
195,422,963
2
0
null
null
null
null
UTF-8
C++
false
false
1,214
cc
power.cc
#include <iostream> #include <vector> using std::cout; using std::endl; using std::vector; class Solution { public: double Power(double base, int exponent) { if (equal(base, 0.0) && exponent < 0) return 0.0; unsigned int absExponent = (unsigned int)exponent; if (exponent < 0) { absExponent = (unsigned int)(-exponent); } double result = powWithUnsignedExponent(base, absExponent); if (exponent < 0) { result = 1.0 / result; } return result; } private: double powWithUnsignedExponent(double base, unsigned int exponent) { if (exponent == 0) { return 1; } if (exponent == 1) { return base; } double result = powWithUnsignedExponent(base, exponent >> 1); result *= result; if (exponent & 1) { result *= base; } return result; } bool equal(int num1, int num2) { if (num1 - num2 > -0.0000001 && num1 - num2 < 0.0000001) { return true; } return false; } }; int main() { Solution solution; cout << solution.Power(-2, 3) << endl; return 0; }
8a4c1ffe58c34ca6acc08ad891ec3a6748c862c2
0785c562353156926af018f2bb8a27d1fcc8b499
/flatland_viz/include/flatland_viz/spawn_model_tool.h
6766c90786991938bfaf875a5a3f76e4ea3faeda
[ "BSD-3-Clause", "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference" ]
permissive
avidbots/flatland
7cc8dd3a85f94390b78ccd89a8a2da631e9ef048
93096a21b917fdb66598d2578273aad4049d85d9
refs/heads/master
2023-07-06T23:20:21.765733
2023-02-06T20:55:40
2023-02-06T20:55:40
100,396,494
96
50
BSD-3-Clause
2023-08-30T17:30:16
2017-08-15T16:22:15
C++
UTF-8
C++
false
false
6,269
h
spawn_model_tool.h
/* * ______ __ __ __ * /\ _ \ __ /\ \/\ \ /\ \__ * \ \ \L\ \ __ __ /\_\ \_\ \ \ \____ ___\ \ ,_\ ____ * \ \ __ \/\ \/\ \\/\ \ /'_` \ \ '__`\ / __`\ \ \/ /',__\ * \ \ \/\ \ \ \_/ |\ \ \/\ \L\ \ \ \L\ \/\ \L\ \ \ \_/\__, `\ * \ \_\ \_\ \___/ \ \_\ \___,_\ \_,__/\ \____/\ \__\/\____/ * \/_/\/_/\/__/ \/_/\/__,_ /\/___/ \/___/ \/__/\/___/ * @copyright Copyright 2017 Avidbots Corp. * @name spawn_model_tool.h * @brief Rviz compatible tool for spawning flatland model * @author Joseph Duchesne * @author Mike Brousseau * * Software License Agreement (BSD License) * * Copyright (c) 2017, Avidbots Corp. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the Avidbots Corp. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef SPAWN_MODEL_TOOL_H #define SPAWN_MODEL_TOOL_H #include <rviz/tool.h> #include <memory> #include <vector> #include <OGRE/OgreEntity.h> #include <OGRE/OgreSceneManager.h> #include <OGRE/OgreSceneNode.h> #include <OgreVector3.h> #include <flatland_server/yaml_reader.h> #include <ros/ros.h> #include <rviz/ogre_helpers/billboard_line.h> #include "rviz/ogre_helpers/arrow.h" namespace flatland_viz { /** * @name SpawnModelTool * @brief Every tool which can be added to the tool bar is a * subclass of rviz::Tool. */ class SpawnModelTool : public rviz::Tool { Q_OBJECT public: SpawnModelTool(); ~SpawnModelTool(); /** * @name BeginPlacement * @brief Begin the placement phase, model follows cursor, left * click deposits model and starts rotation phase */ void BeginPlacement(); /** * @name SavePath * @brief Called from dialog to save path */ void SavePath(QString p); /** * @name SaveName * @brief Called from dialog to save name */ void SaveName(QString n); /** * @name SpawnModelInFlatland * @brief Spawns a model using ros service */ void SpawnModelInFlatland(); private: /** * @name onInitialize * @brief Initializes tools currently loaded when rviz starts */ virtual void onInitialize(); /** virtual void activate(); * @name activate * @brief Launch the model dialog */ virtual void activate(); /** * @name deactivate * @brief Cleanup when tool is removed */ virtual void deactivate(); /** * @name processMouseEvent * @brief Main loop of tool * @param event Mouse event */ virtual int processMouseEvent(rviz::ViewportMouseEvent &event); /** * @name SetMovingModelColor * @brief Set the color of the moving model * @param c QColor to set the 3d model */ void SetMovingModelColor(QColor c); /** * @name LoadPreview * @brief Load a vector preview of the model */ void LoadPreview(); /** * @name LoadPolygonFootprint * @brief Load a vector preview of the model's polygon footprint * @param footprint The footprint yaml node * @param pose x,y,theta pose of footprint */ void LoadPolygonFootprint(flatland_server::YamlReader &footprint, const flatland_server::Pose pose); /** * @name LoadCircleFootprint * @brief Load a vector preview of the model's circle footprint * @param footprint The footprint yaml node * @param pose x,y,theta pose of footprint */ void LoadCircleFootprint(flatland_server::YamlReader &footprint, const flatland_server::Pose pose); Ogre::Vector3 intersection; // location cursor intersects ground plane, ie the // location to create the model float initial_angle; // the angle to create the model at Ogre::SceneNode *moving_model_node_; // the node for the 3D object enum ModelState { m_hidden, m_dragging, m_rotating }; ModelState model_state; // model state, first hidden, then dragging to // intersection point, then rotating to desired angle static QString path_to_model_file_; // full path to model file (yaml) static QString model_name; // base file name with path and extension removed protected: rviz::Arrow *arrow_; // Rviz 3d arrow to show axis of rotation ros::NodeHandle nh; // ros service node handle ros::ServiceClient client; // ros service client std::vector<std::shared_ptr<rviz::BillboardLine>> lines_list_; }; } // end namespace flatland_viz #endif // SPAWN_MODEL_TOOL_H
468195f70b2aa868718f423f58902d49efe42827
68bad417713c72c66b56997d656ab55646098b5a
/Firmware/Controller.ino
8aec2ade6242b2164c3f21f40de6070d40eaa1fc
[ "MIT" ]
permissive
tfeldmann/QlockToo
f9fed6ab48bd1356f9923cd8453f930a6a29c200
778a955ac84348342db036b1989931c6d9be9242
refs/heads/master
2021-03-12T22:19:30.998054
2019-07-26T13:39:24
2019-07-26T13:39:24
8,914,985
2
1
null
null
null
null
UTF-8
C++
false
false
4,663
ino
Controller.ino
// // Controller.ino // #include <Bounce.h> #include "globals.h" // Buttons Bounce btn1 = Bounce(A5, 5); Bounce btn2 = Bounce(A4, 5); Bounce btn3 = Bounce(A3, 5); Bounce btn4 = Bounce(A2, 5); // the time module will care for setting this flag, just make sure to reset // it after you read it. extern volatile bool second_has_changed, minute_has_changed, hour_has_changed; extern volatile bool brightness_has_changed; void controller_init() { STATE_MACHINE_START(STATE_TIMEWORDS); } void controller_update() { brightness_update(); controller_statemachine(); time_resetFlags(); // reset the second / minute / hour has_updated flags controller_buttons(); } void controller_buttons() { btn1.update(); btn2.update(); btn3.update(); btn4.update(); if (btn1.risingEdge()) { STATE_SWITCH(STATE_TIMEWORDS); } if (btn2.risingEdge()) { STATE_SWITCH(STATE_SECONDS); } if (btn3.risingEdge()) { STATE_SWITCH(STATE_TEMPERATURE); } if (btn4.risingEdge()) { brightness_next_step(); } // cycle through demo modes if (btn1.read() && btn2.risingEdge()) { if (STATE_IS_ACTIVE(STATE_TIMEWORDS)) STATE_SWITCH(STATE_WHITE); if (STATE_IS_ACTIVE(STATE_WHITE)) STATE_SWITCH(STATE_GRADIENT); if (STATE_IS_ACTIVE(STATE_GRADIENT)) STATE_SWITCH(STATE_FADE); if (STATE_IS_ACTIVE(STATE_FADE)) STATE_SWITCH(STATE_MATRIX); if (STATE_IS_ACTIVE(STATE_MATRIX)) STATE_SWITCH(STATE_ES_LACHT_NE_KUH); if (STATE_IS_ACTIVE(STATE_ES_LACHT_NE_KUH)) STATE_SWITCH(STATE_TIMEWORDS); } // switch to automatic brightness mode if (btn4.read() && btn4.duration() > 1000) { brightness_enable_automatic(); } // wait for dcf signal if (btn1.read() && btn1.duration() > 1000 && btn2.read() && btn2.duration() > 1000 && btn3.read() && btn3.duration() > 1000) { STATE_SWITCH(STATE_WAIT_FOR_DCF); } } void controller_statemachine() { STATEMACHINE STATE_ENTER(STATE_TIMEWORDS) #ifdef DEBUG Serial.println("#State: Timewords"); #endif timewords_setup(); STATE_LOOP timewords_loop(); STATE_LEAVE END_OF_STATE STATE_ENTER(STATE_SECONDS) #ifdef DEBUG Serial.println("#State: Seconds"); #endif seconds_setup(); STATE_LOOP seconds_loop(); STATE_LEAVE END_OF_STATE STATE_ENTER(STATE_TEMPERATURE) #ifdef DEBUG Serial.println("#State: Temperature"); #endif temperature_setup(); STATE_LOOP temperature_loop(); STATE_LEAVE END_OF_STATE STATE_ENTER(STATE_WAIT_FOR_DCF) #ifdef DEBUG Serial.println("#State: Waiting for DCF Signal"); #endif display_clear(); corner_clear(); matrix[3][3] = BRIGHTNESS_FULL; // F matrix[3][4] = BRIGHTNESS_FULL; // U matrix[3][5] = BRIGHTNESS_FULL; // N matrix[3][6] = BRIGHTNESS_FULL; // K STATE_LOOP STATE_LEAVE END_OF_STATE STATE_ENTER(STATE_WHITE) display_fill(BRIGHTNESS_FULL); corner_fill(BRIGHTNESS_FULL); STATE_LOOP STATE_LEAVE END_OF_STATE STATE_ENTER(STATE_GRADIENT) display_clear(); corner_clear(); for (int row = 0; row < ROWS; row++) { for (int col = 0; col < COLS; col++) { matrix[row][col] = 255 - 255 * (row / (float)ROWS); } } STATE_LOOP STATE_LEAVE END_OF_STATE STATE_ENTER(STATE_FADE) demo_fade_setup(); STATE_LOOP demo_fade_loop(); STATE_LEAVE END_OF_STATE STATE_ENTER(STATE_MATRIX) demo_matrix_setup(); STATE_LOOP demo_matrix_loop(); STATE_LEAVE END_OF_STATE STATE_ENTER(STATE_ES_LACHT_NE_KUH) display_clear(); corner_clear(); matrix[0][0] = BRIGHTNESS_FULL; // E matrix[0][1] = BRIGHTNESS_FULL; // S matrix[7][6] = BRIGHTNESS_FULL; // L matrix[7][7] = BRIGHTNESS_FULL; // A matrix[7][8] = BRIGHTNESS_FULL; // C matrix[7][9] = BRIGHTNESS_FULL; // H matrix[7][10] = BRIGHTNESS_FULL; // T matrix[9][3] = BRIGHTNESS_FULL; // N matrix[9][4] = BRIGHTNESS_FULL; // E matrix[9][7] = BRIGHTNESS_FULL; // K matrix[9][8] = BRIGHTNESS_FULL; // U matrix[9][9] = BRIGHTNESS_FULL; // H STATE_LOOP STATE_LEAVE END_OF_STATE END_STATEMACHINE }
f54d6f9a2a4477f4b212b5709054df7e7677d683
ab5a29ae37ad263f672e6417ca7c9cacac9c0189
/[MS Visual Studio]/RainbowConsole/RainbowConsole/RainbowConsole.cpp
2101744f105e2830c08f95bee3309115782e3845
[]
no_license
gorp-misha/classworks
8c28e8ff0acf7d22a8c014911f579247a192e4c2
d1f2804929f57bcf915d94a99bc0280a52cf5bbd
refs/heads/master
2020-04-07T21:14:47.134863
2019-05-30T16:14:04
2019-05-30T16:14:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,208
cpp
RainbowConsole.cpp
// RainbowConsole.cpp : Этот файл содержит функцию "main". Здесь начинается и заканчивается выполнение программы. // #include "pch.h" #include <iostream> #include <stdio.h> #include <Windows.h> using namespace std; enum ConsoleColor { Black = 0, Blue = 1, Green = 2, Cyan = 3, Red = 4, Magenta = 5, Brown = 6, LightGray = 7, DarkGray = 8, LightBlue = 9, LightGreen = 10, LightCyan = 11, LightRed = 12, LightMagenta = 13, Yellow = 14, White = 15 }; int main() { HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE); setlocale(LC_ALL, "rus"); system("color F0"); SetConsoleTextAttribute(hConsole, (WORD)((White << 4) | Red)); printf("R"); SetConsoleTextAttribute(hConsole, (WORD)((White << 4) | LightRed)); printf("A"); SetConsoleTextAttribute(hConsole, (WORD)((White << 4) | Yellow)); printf("I"); SetConsoleTextAttribute(hConsole, (WORD)((White << 4) | Green)); printf("N"); SetConsoleTextAttribute(hConsole, (WORD)((White << 4) | LightBlue)); printf("B"); SetConsoleTextAttribute(hConsole, (WORD)((White << 4) | Blue)); printf("O"); SetConsoleTextAttribute(hConsole, (WORD)((White << 4) | Magenta)); printf("W"); SetConsoleTextAttribute(hConsole, (WORD)((White << 4) | Black)); cout << " CONSOLE!" << endl; cout << "Пользователь, виберите цвет фона:\n 1 - Темно-Красный\n 2 - Красный\n 3 - Желтый\n 4 - Зеленый\n 5 - Голубой\n 6 - Синий\n 7 - Фиолетовый\n 8 - Черный\n 9 - Белый" << endl; int bg; cin >> bg; cout << "Пользователь, выберите цвет шрифт:\n 1 - Темно-Красный\n 2 - Красный\n 3 - Желтый\n 4 - Зеленый\n 5 - Голубой\n 6 - Синий\n 7 - Фиолетовый\n 8 - Черный\n 9 - Белый" << endl; int text; cin >> text; cout << "Спасибо, Пользователь. Я прочитаю вам отрывок из интерактивного комикса PREQUEL -or- Making A Cat Cry: The Adventure.\nАвтор комикса - Kazerad.\n" << endl; switch (bg) { case 1: { system("color 40"); break; } case 2: { system("color C0"); break; } case 3: { system("color E0"); break; } case 4: { system("color 20"); break; } case 5: { system("color B0"); break; } case 6: { system("color 10"); break; } case 7: { system("color 50"); break; } case 8: { system("color 00"); break; } case 9: { system("color F0"); break; } default: { system("color F0"); break; } } // Я сидел несколько минут, обдумывая, как подставить заданный цвет заднего фона для выбора цвета шрифта. Ну, вначале я пытался подставить заместь первого числа переменную с bg. Понял, что это глупо. // Потом подумал насчет команд cout и cin, и можно ли с ними что-то сделать. // Потом понял, что можно подставить первый switch от заднего фона. Ну, программа вышла огромная и я уверен, ее можно было бы укоротить, но при моих знаниях - это максимум. // Надеюсь работать будет... switch (text) { case 1: { switch (bg) { case 1: { system("color 44"); break; } case 2: { system("color C4"); break; } case 3: { system("color E4"); break; } case 4: { system("color 24"); break; } case 5: { system("color B4"); break; } case 6: { system("color 14"); break; } case 7: { system("color 54"); break; } case 8: { system("color 04"); break; } case 9: { system("color F4"); break; } default: { system("color F0"); break; } } break; } case 2: { switch (bg) { case 1: { system("color 4C"); break; } case 2: { system("color CC"); break; } case 3: { system("color EC"); break; } case 4: { system("color 2C"); break; } case 5: { system("color BC"); break; } case 6: { system("color 1C"); break; } case 7: { system("color 5C"); break; } case 8: { system("color 0C"); break; } case 9: { system("color FC"); break; } default: { system("color F0"); break; } } break; } case 3: { switch (bg) { case 1: { system("color 4E"); break; } case 2: { system("color CE"); break; } case 3: { system("color EE"); break; } case 4: { system("color 2E"); break; } case 5: { system("color BE"); break; } case 6: { system("color 1E"); break; } case 7: { system("color 5E"); break; } case 8: { system("color 0E"); break; } case 9: { system("color FE"); break; } default: { system("color F0"); break; } } break; } case 4: { switch (bg) { case 1: { system("color 42"); break; } case 2: { system("color C2"); break; } case 3: { system("color E2"); break; } case 4: { system("color 22"); break; } case 5: { system("color B2"); break; } case 6: { system("color 12"); break; } case 7: { system("color 52"); break; } case 8: { system("color 02"); break; } case 9: { system("color F2"); break; } default: { system("color F0"); break; } } break; } case 5: { switch (bg) { case 1: { system("color 49"); break; } case 2: { system("color C9"); break; } case 3: { system("color E9"); break; } case 4: { system("color 29"); break; } case 5: { system("color B9"); break; } case 6: { system("color 19"); break; } case 7: { system("color 59"); break; } case 8: { system("color 09"); break; } case 9: { system("color F9"); break; } default: { system("color F0"); break; } } break; } case 6: { switch (bg) { case 1: { system("color 41"); break; } case 2: { system("color C1"); break; } case 3: { system("color E1"); break; } case 4: { system("color 21"); break; } case 5: { system("color B1"); break; } case 6: { system("color 11"); break; } case 7: { system("color 51"); break; } case 8: { system("color 01"); break; } case 9: { system("color F1"); break; } default: { system("color F0"); break; } } break; } case 7: { switch (bg) { case 1: { system("color 45"); break; } case 2: { system("color C5"); break; } case 3: { system("color E5"); break; } case 4: { system("color 25"); break; } case 5: { system("color B5"); break; } case 6: { system("color 15"); break; } case 7: { system("color 55"); break; } case 8: { system("color 05"); break; } case 9: { system("color F5"); break; } default: { system("color F0"); break; } } break; } case 8: { switch (bg) { case 1: { system("color 40"); break; } case 2: { system("color C0"); break; } case 3: { system("color E0"); break; } case 4: { system("color 20"); break; } case 5: { system("color B0"); break; } case 6: { system("color 10"); break; } case 7: { system("color 50"); break; } case 8: { system("color 00"); break; } case 9: { system("color F0"); break; } default: { system("color F0"); break; } } break; } case 9: { switch (bg) { case 1: { system("color 4F"); break; } case 2: { system("color CF"); break; } case 3: { system("color EF"); break; } case 4: { system("color 2F"); break; } case 5: { system("color BF"); break; } case 6: { system("color 1F"); break; } case 7: { system("color 5F"); break; } case 8: { system("color 0F"); break; } case 9: { system("color FF"); break; } default: { system("color F0"); break; } } break; } default: { switch (bg) { case 1: { system("color 40"); break; } case 2: { system("color C0"); break; } case 3: { system("color E0"); break; } case 4: { system("color 20"); break; } case 5: { system("color B0"); break; } case 6: { system("color 10"); break; } case 7: { system("color 50"); break; } case 8: { system("color 00"); break; } case 9: { system("color F0"); break; } default: { system("color F0"); break; } } break; } } cout << " PREQUEL: BEGIN\n" << endl; cout << " Today is the beginning of the new you.\n" << endl; cout << " One month ago you made yourself a promise: you were going to turn your life around. You were going to get a real\n job, stay out of jail, and not get into any more trouble with cults. Nobody thought you could do it; they said your\n questionable reputation, lack of any useful skills, and flagrant alcoholism would always hold you down.\n" << endl; cout << " But you had a plan.\n" << endl; cout << " You were going to start over, far from home. You pawned off your belongings, withdrew the rest of your inheritance,\n and narrowly managed to buy your way onto a merchant ship bound for Cyrodiil.\n" << endl; cout << " And now you have arrived, alone and penniless in a foreign country. Rounding up to the nearest week, you’ve been\n sober for an entire seven days. This is your chance to be whatever you want to be. Whoever you want to be.\n" << endl; cout << " You think you’ll start with a new name. Something less ethnic, maybe suitably Imperial, to fit in in your new home.\n\n\n\n\n\n"; // Не понимаю почему, но оно считало за ошибку последние cout и подчеркивало их, пока я не нажал за последнюю скобку(для int main). // У меня было много проблем с фигурными скобками, но я в конце концов все нашел и исправил. И это меня сбило. Я уже решил запустить без этого, и посмотреть, может, что-то измениться. // А оно загрузилось, и я удивился. Хоть какая-то награда за долгое исправление ошибок. return 0; }
575d602caa393b585aa3afb4170a323bd58f3f1e
a23c7c39bbc0d1f26592b0d31822ce56a204d145
/src/buffer.h
d224b6a4a39b53cfef3a337b84aa31ed3f2a2420
[ "BSD-2-Clause" ]
permissive
baitisj/samesame
8af10e5f330ff6858cca9048dc42656406f377a5
1525cc3b53d4b6cfac18b6304a078dc109030bcb
refs/heads/main
2023-03-19T13:27:49.284984
2021-03-07T17:49:32
2021-03-07T17:49:32
345,412,892
0
0
null
null
null
null
UTF-8
C++
false
false
1,097
h
buffer.h
/* ************************************************************************ * * Written by Alex de Kruijff * * ************************************************************************ * * This source was written with a tabstop every four characters * * In vi type :set ts=4 * * ************************************************************************ */ #include "configure.h" #include <new> class Buffer { friend class PreventBufferLeak; static Buffer *singleton; size_t n, capacity, pagesize; unsigned char *buf; public: static Buffer &getDefault(size_t capacity = 2 * MAXBSIZE); Buffer(size_t capacity = 2 * MAXBSIZE); ~Buffer() throw(); off_t getPageSize() const throw() { return pagesize; } off_t getCapacity() const throw() { return capacity; } void setAmountPages(size_t) throw(); #ifdef DEBUG unsigned char *operator[](size_t index) const throw(); #else unsigned char *operator[](size_t index) const throw() { return buf + index * pagesize; } #endif };
e04e42c3a65b31c271c9fe8f30715e1d64e222d0
6645d92d1eab8fc12b4fda41e4592f8cd4bbcc99
/fe.cpp
e2d63dc3868f6bd86b9435db3be220fbdb4f8371
[]
no_license
pBengt2/OrbCalculator
8974b495712d574d9c274596fa9b385b724aa9cb
25608a5b4cadc406e3c15c0caeb7518ca428b120
refs/heads/master
2021-09-01T22:51:45.377571
2017-12-29T02:05:32
2017-12-29T02:05:32
115,674,445
0
0
null
null
null
null
UTF-8
C++
false
false
2,082
cpp
fe.cpp
#include <iostream> #include <cstdlib> #include <ctime> using namespace std; const int numTrials = 50000; const int numOrbs = 200; const int startingAppearence = 1900; const int numToSummon = 2; bool sum(const int& appRate){ return ((rand()%10000) <= appRate); } int subOrbs(int i){ if (i==0) return 5; else if (i == 4) return 3; else return 4; } int summon(int& curOrbs, const int& appRate, int& numSinceFive, int n){ int curFive = 0; for (int i=0; i<n; i++){ curOrbs -= subOrbs(i); if (sum(appRate)){ curFive++; numSinceFive = 0; } else{ numSinceFive++; } } if (curFive != 0 && n != 5){ for (int i=n; i<5; i++){ if (curOrbs < subOrbs(i)) return curFive; curOrbs -= subOrbs(i); if (sum(appRate)){ curFive++; numSinceFive = 0; } else{ numSinceFive++; } } } return curFive; } int main(){ srand(time(NULL)); long int total = 0; cout << numTrials << " trials; " << numOrbs << " orbs; " << (double)startingAppearence/100.00 << "% appeareance rate; " << "summon " << numToSummon << " when >= 19.00%\n"; for (int i=0; i<numTrials; i++){ int curOrbs = numOrbs; int appRate = startingAppearence; int numFive = 0; int numSinceFive = 0; while (curOrbs >= 20){ int curFive = 0; if (appRate <= 1000) curFive += summon(curOrbs, appRate, numSinceFive, 5); else{ curFive += summon(curOrbs, appRate, numSinceFive, numToSummon); } numFive += curFive; if (numSinceFive >= 5){ numSinceFive -= 5; appRate += 50; } if (curFive != 0){ appRate = 600; } } if (curOrbs >= 17){ summon(curOrbs, appRate, numSinceFive, 4); } else if (curOrbs >= 13){ summon(curOrbs, appRate, numSinceFive, 3); } else if (curOrbs >= 8){ summon(curOrbs, appRate, numSinceFive, 2); } else if (curOrbs >= 5){ summon(curOrbs, appRate, numSinceFive, 1); } total+=numFive; } cout << "Total Five: " << total/(double)numTrials; }
959900dc8ad1f2474ca2f7edfe0c75cbbf9d45cb
0840896623f07254443f6f5dac6d3e9e0f8d5553
/tests/MadnexPOD.cxx
28449c8bd20b12f6dc6766787572fdbc3821150f
[]
no_license
FCurtit/madnex
5559ffadfe49209a257b463fbbbf3fe1c930ec2c
d117e1bbb244d4d487513973e31ab571ba088726
refs/heads/master
2022-10-12T13:23:56.533388
2020-06-11T13:13:46
2020-06-11T13:13:46
271,547,421
0
0
null
2020-06-11T13:01:42
2020-06-11T13:01:41
null
UTF-8
C++
false
false
2,976
cxx
MadnexPOD.cxx
/*! * \file tests/MadnexPOD.cxx * \brief * \author Thomas Helfer * \date 16/01/2017 */ #ifdef NDEBUG #undef NDEBUG #endif #include<cmath> #include<cstdlib> #include<limits> #include<iostream> #include"TFEL/Tests/TestCase.hxx" #include"TFEL/Tests/TestProxy.hxx" #include"TFEL/Tests/TestManager.hxx" #include"Madnex/HDF5.hxx" #include"Madnex/File.hxx" /*! * \brief structure in charge of testing read/write on plain old data * types in HDF5 files */ struct MadnexPOD final : public tfel::tests::TestCase { MadnexPOD() : tfel::tests::TestCase("Madnex","POD") {} // end of MadnexPOD virtual tfel::tests::TestResult execute() override { this->write_file(); this->read_file(); return this->result; } private: /*! * \brief this method create a file and stores various POD type in * it. */ void write_file(){ using namespace madnex; auto f = File("MadnexPOD.madnex",H5F_ACC_TRUNC); auto r = f.getRoot(); write(r,"boolean_value",true); write(r,"char_value",'c'); write(r,"integer_value",static_cast<std::int32_t>(12)); write(r,"float_value",12.f); write(r,"double_value",12.); write(r,"long_double_value",static_cast<long double>(12)); write(r,"string_value","lorem ipsum"); } /*! * \brief this method reads the file written by the `write_file` * method and checks that all the data can be retrieved without loss. */ void read_file(){ using namespace madnex; const auto f = File("MadnexPOD.madnex",H5F_ACC_RDONLY); const auto r = f.getRoot(); TFEL_TESTS_ASSERT(read<char>(r,"char_value")=='c'); TFEL_TESTS_ASSERT(read<std::int32_t>(r,"integer_value")==12); TFEL_TESTS_CHECK_THROW(read<double>(r,"boolean_value"), std::runtime_error); this->read_floatting_point_number<float>(r,"float_value",12.f); this->read_floatting_point_number<double>(r,"double_value",12.); this->read_floatting_point_number<long double>(r,"long_double_value",12.); std::cout << "v: " << read<std::string>(r,"string_value") << std::endl; TFEL_TESTS_ASSERT(read<std::string>(r,"string_value")=="lorem ipsum"); TFEL_TESTS_CHECK_THROW(read<double>(r,"string_value"), std::runtime_error); } /*! * \brief read a floatting_point value. * \param[in] g: group * \param[in] n: variable name * \param[in] v: expected value */ template<typename T> void read_floatting_point_number(const madnex::Group& g, const std::string& n, const T v){ const auto d = madnex::read<T>(g,n); TFEL_TESTS_ASSERT(std::abs(d-v)<v*std::numeric_limits<T>::epsilon()); TFEL_TESTS_CHECK_THROW(madnex::read<std::string>(g,n), std::runtime_error); } }; TFEL_TESTS_GENERATE_PROXY(MadnexPOD,"MadnexPOD"); int main() { auto& m = tfel::tests::TestManager::getTestManager(); m.addTestOutput(std::cout); m.addXMLTestOutput("MadnexPOD.xml"); return m.execute().success() ? EXIT_SUCCESS : EXIT_FAILURE; }
74666e7f5b474e886bd128b6eb249cf8d81cb40a
fe2836176ca940977734312801f647c12e32a297
/Codeforces/Contest/Round 271/B/main_iterative.cpp
c27327e71408d1a5fc1cc3eab4c2096696c1244c
[]
no_license
henrybear327/Sandbox
ef26d96bc5cbcdc1ce04bf507e19212ca3ceb064
d77627dd713035ab89c755a515da95ecb1b1121b
refs/heads/master
2022-12-25T16:11:03.363028
2022-12-10T21:08:41
2022-12-10T21:08:41
53,817,848
2
0
null
null
null
null
UTF-8
C++
false
false
843
cpp
main_iterative.cpp
#include <bits/stdc++.h> using namespace std; int main() { int n; scanf("%d", &n); int inp[n + 1]; inp[0] = 0; for (int i = 1; i <= n; i++) { int tmp; scanf("%d", &tmp); inp[i] = inp[i - 1] + tmp; } int q; scanf("%d", &q); for (int i = 0; i < q; i++) { int key; scanf("%d", &key); int l = 0, r = n; while (r - l > 1) { int mid = (r + l) / 2; if (inp[mid] < key) { // limit to left l = mid; } else if (key < inp[mid]) { // limit to right r = mid; } else { // spot on! r = mid; // crucial step break; } } if (inp[r] == key) printf("%d\n", r); else printf("%d\n", l + 1); } return 0; }
46114af28c697258396b54ac0304595b27b60cd2
02d8629d0a7dd7f37a306d43987bab567ba5f053
/webserver/coroutine.h
a221cac77cbc1163b8b552ad283366a3f335cc81
[]
no_license
Fiee-ma/webserver
c34b25c9bbbfebaac96f270614bbf9f8ef3a8e91
01802b01eee7efc6538fd45e73604b71a6a9b855
refs/heads/main
2023-03-11T14:18:25.249824
2021-02-24T13:24:39
2021-02-24T13:24:39
332,288,549
0
0
null
null
null
null
UTF-8
C++
false
false
2,125
h
coroutine.h
#ifndef __WEBSERVER_COROUTINE_H__ #define __WEBSERVER_COROUTINE_H__ #include <memory> #include <ucontext.h> #include <functional> #include "thread.h" namespace server_name { class Scheduler; class Coroutine : public std::enable_shared_from_this<Coroutine> { friend class Scheduler; public: typedef std::shared_ptr<Coroutine> ptr; enum State { INIT, HOLD, EXEC, TERM, READY, EXECPT }; private: Coroutine(); public: Coroutine(std::function<void()> cb, size_t stacksize = 0, bool use_caller = false); ~Coroutine(); //重置协程函数,并重置其状态 //INIT, TERM void reset(std::function<void()> cb); //切换到当前协程去执行 void swapIn(); //切换到后台执行 void swapOut(); uint64_t getId() const {return m_id;} State getState() const { return m_state;} void back(); void call(); public: //设置当前协程 static void SetThis(Coroutine *f); //返回当前协程 static Coroutine::ptr GetThis(); //协程切换到后台,并设置为Ready状态 static void YieldToReady(); //协程切换到后台,并设置为Hold状态 static void YieldToHold(); //返回总的协程数 static uint64_t TotalToHold(); //协程调用函数 static void MainFunc(); static void CallMainFunc(); static uint64_t GetCoroutineId(); private: //协程id uint64_t m_id = 0; //协程栈的大小 uint32_t m_stacksize = 0; //协程的状态 State m_state = INIT; //ucontext_t是一个协程的结构体 /*typedef struct ucontext_t { unsigned long int __ctx(uc_flags); struct ucontext_t *uc_link; //后继上下文 stack_t uc_stack; //该上下文中使用的栈 mcontext_t uc_mcontext; sigset_t uc_sigmask; ostruct _libc_fpstate __fpregs_mem; } ucontext_t;*/ ucontext_t m_ctx; //栈的内存空间 void *m_stack = nullptr; //协程执行的方法 std::function<void()> m_cb; }; } #endif
cd555889cd9614c57ec6abd5a88527f86f20c86f
eedd904304046caceb3e982dec1d829c529da653
/sdltest2/src/sdltest2.cpp
5152199c1e3974c48d7e553af6f214d038929d54
[]
no_license
PaulFSherwood/cplusplus
b550a9a573e9bca5b828b10849663e40fd614ff0
999c4d18d2dd4d0dd855e1547d2d2ad5eddc6938
refs/heads/master
2023-06-07T09:00:20.421362
2023-05-21T03:36:50
2023-05-21T03:36:50
12,607,904
4
0
null
null
null
null
UTF-8
C++
false
false
2,322
cpp
sdltest2.cpp
#include "SDL/SDL.h" #include "SDL/SDL_image.h" #include "SDL/SDL_ttf.h" #include <string> const int WINDOW_WIDTH = 640; const int WINDOW_HEIGHT = 480; const char* WINDOW_TITLE = "SDL Start"; void drawSprite(SDL_Surface* imageSurface, SDL_Surface* screenSurface, int srcX, int srcY, int dstX, int dstY, int width, int height); int main(int argc, char **argv) { SDL_Init( SDL_INIT_VIDEO ); SDL_Surface* screen = SDL_SetVideoMode( WINDOW_WIDTH, WINDOW_HEIGHT, 0, SDL_HWSURFACE | SDL_DOUBLEBUF ); SDL_WM_SetCaption( WINDOW_TITLE, 0 ); SDL_Surface* bitmap = SDL_LoadBMP("bat.bmp"); SDL_SetColorKey(bitmap, SDL_SRCCOLORKEY, SDL_MapRGB(bitmap->format, 255, 0, 255)); int batImageX = 24; int batImageY = 63; int batWidth = 65; int batHeight = 44; // We change these to make the bat move int batX = 100; int batY = 100; SDL_Event event; bool gameRunning = true; bool keysHeld[323] = {false}; // everything will be initialized to false while (gameRunning) { // Handle input if (SDL_PollEvent(&event)) { if (event.type == SDL_QUIT) { gameRunning = false; } if (event.type == SDL_KEYDOWN) { keysHeld[event.key.keysym.sym] = true; } if (event.type == SDL_KEYUP) { keysHeld[event.key.keysym.sym] = false; } } if ( keysHeld[SDLK_ESCAPE] ) { gameRunning = false; } if ( keysHeld[SDLK_LEFT] ) { batX -= 3; } if ( keysHeld[SDLK_RIGHT] ) { batX += 3; } if ( keysHeld[SDLK_UP] ) { batY -= 3; } if (keysHeld[SDLK_DOWN]) { batY += 3; } // Draw the scene SDL_FillRect(screen, NULL, SDL_MapRGB(screen->format, 0, 0, 0)); drawSprite(bitmap, screen, batImageX, batImageY, batX, batY, batWidth, batHeight); SDL_Flip(screen); } SDL_FreeSurface(bitmap); SDL_Quit(); return 0; } void drawSprite(SDL_Surface* imageSurface, SDL_Surface* screenSurface, int srcX, int srcY, int dstX, int dstY, int width, int height) { SDL_Rect srcRect; srcRect.x = srcX; srcRect.y = srcY; srcRect.w = width; srcRect.h = height; SDL_Rect dstRect; dstRect.x = dstX; dstRect.y = dstY; dstRect.w = width; dstRect.h = height; SDL_BlitSurface(imageSurface, &srcRect, screenSurface, &dstRect); }
e35a04c5ab357241ff4d5ce1219a94e19f47e88a
e91ed75849fcfe5b27a493483fa75bbb29428a81
/t-sne.cpp
f9a3028ab7d136bb24081ccd9bb3acad2944dcc8
[ "BSD-2-Clause" ]
permissive
lh3/bhtsne
4dde28f78268670a21fe24d1ce2dee65f55607df
1a62a5d3842944d832837b5522143cf892908f53
refs/heads/master
2021-01-17T07:59:21.635474
2016-08-23T03:39:00
2016-08-23T03:39:00
66,316,009
4
1
null
2016-08-22T23:37:22
2016-08-22T23:37:22
null
UTF-8
C++
false
false
333
cpp
t-sne.cpp
#include <stdlib.h> #include "tsne.h" #include "t-sne.h" double *ts_fit(int N, int n_in, double *x, int n_out, double theta, double perplexity, int seed) { double *y; TSNE *ts = new TSNE(); y = (double*)malloc(N * n_out * sizeof(double)); ts->run(x, N, n_in, y, n_out, perplexity, theta, seed, false); delete(ts); return y; }
2b5d0a9b39764ed13f0905516a5b773aa5c5440b
815a4a067c63c1aa00399e3aa14cf585a6199dec
/core/proteinstructure/mrf_features.h
8344793e17183a8a7415955200adb76ac799a1ca
[ "Apache-2.0" ]
permissive
tecdatalab/legacy
39ff4f4329d0dba043fef79f363a8c1fd504b5a9
9b5286d3375fff691a80ceb44172549e9a6bdee5
refs/heads/master
2020-04-18T06:00:16.559666
2019-01-24T17:27:54
2019-01-24T17:27:54
167,301,809
0
0
Apache-2.0
2019-10-18T15:27:24
2019-01-24T04:15:59
C
UTF-8
C++
false
false
2,186
h
mrf_features.h
#ifndef _MRF_FEATURES_H_ #define _MRF_FEATURES_H_ #include <fstream> #include "soroban_score.h" using std::ofstream; using std::string; class mrf_one_body_features { public: mrf_one_body_features(double alpha_z, double beta_y, double gamma_x, double translate_x, double translate_y, double translate_z, double rmsd, double correlation, double overlap, string label); void write(ofstream& data_stream); // Tab separated list of column names static void write_header(ofstream& data_stream); private: // Identifies the transformations that originated these feature values double alpha_z, beta_y, gamma_x, translate_x, translate_y, translate_z; // Derived from the difference between the transformed unit and // the c-alpha trace. This can later be used to label positive and // negative cases. double rmsd; // Derived from the unit EM map and the complete map. double correlation, overlap; string label; }; class mrf_two_body_features { public: mrf_two_body_features(double alpha_z_left, double beta_y_left, double gamma_x_left, double translate_x_left, double translate_y_left, double translate_z_left, double alpha_z_right, double beta_y_right, double gamma_x_right, double translate_x_right, double translate_y_right, double translate_z_right, double rmsd, soroban_score physics_score, string label_left, string label_right); void write(ofstream& data_stream); // Tab separated list of column names static void write_header(ofstream& data_stream); private: // Each of the two separate transformations applied to each unit. double alpha_z_left, beta_y_left, gamma_x_left, translate_x_left, translate_y_left, translate_z_left; double alpha_z_right, beta_y_right, gamma_x_right, translate_x_right, translate_y_right, translate_z_right; // Each pair of PDBs is transformed and then aligned as a whole on top // of the calpha trace to get the RMSD. double rmsd; // Physics score soroban_score physics_score; string label_left, label_right; // Shape terms // double overall_shape_score, excluded_volume, buried_sa, // shape_reward, shape_penalty; }; #endif
f3ed87bd621349ed009fc9a27a10f3b9ce96f894
39346979d79a6c0facbad08e6001ea86b140c87f
/P73_SetMatrixZeroes.cpp
5ed96d14229b84607c80f3375f8d0276b2c921e2
[]
no_license
BarryChenZ/Leetcode
3d76acab39a77efd8f6c02fb50af8791404e874b
532c3933259264b7f2e74dc8e6c7c379188006be
refs/heads/master
2021-06-27T14:47:53.824441
2020-11-20T02:19:36
2020-11-20T02:19:36
185,322,868
0
0
null
null
null
null
UTF-8
C++
false
false
1,345
cpp
P73_SetMatrixZeroes.cpp
class Solution { public: void setZeroes(vector<vector<int>>& matrix) { int row = matrix.size(); if(row == 0) return; int col = matrix[0].size(); vector<int> row_pos; vector<int> col_pos; cout << row << col << endl; for(int i = 0; i < row; i++){ for(int j = 0; j < col; j++){ if(matrix[i][j] == 0){ row_pos.push_back(i); col_pos.push_back(j); } } } sort(row_pos.begin(), row_pos.end()); sort(col_pos.begin(), col_pos.end()); cout << row_pos.size() << col_pos.size() << endl; if(row_pos.size() == 0) return; int temp = 0; temp = row_pos[0]; for(int i = 0; i < row_pos.size(); i++){ if(row_pos[i] != temp || i == 0){ temp = row_pos[i]; for(int j = 0; j < col; j++){ matrix[row_pos[i]][j] = 0; } } } temp = col_pos[0]; for(int i = 0; i < col_pos.size(); i++){ if(col_pos[i] != temp || i == 0){ temp = col_pos[i]; for(int j = 0; j < row; j++){ matrix[j][col_pos[i]] = 0; } } } return; } };
e76e8ad72b8d2c2dd2ca6d30b6efbb57f3a30f67
742ca431044ec6e0f6971984eb8479362d4c8e80
/src/qtgui/snowmaterialmanager.cpp
4a10c9a9f00e9a05b6ca0e70818bc8a1eaa69aa5
[]
no_license
Jerry-Jinfeng-Guo/mitsuba-renderer
b5e46f38c125c8479f8c8eb94f638b07fbce52b5
e685b423de928fb2a773aee76f01e1f9e62af590
refs/heads/master
2021-05-27T01:39:09.523734
2011-07-26T17:47:50
2011-07-26T17:47:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
19,638
cpp
snowmaterialmanager.cpp
#include "common.h" #include "snowmaterialmanager.h" #include <mitsuba/render/shape.h> #include <mitsuba/render/bsdf.h> #include <mitsuba/render/subsurface.h> #include <mitsuba/core/plugin.h> #include <mitsuba/core/properties.h> #include <mitsuba/core/fstream.h> //#define DEBUG_DIFF_PROF MTS_NAMESPACE_BEGIN void SnowMaterialManager::replaceMaterial(Shape *shape, SceneContext *context) { // get currently selected material BSDF *bsdfOld = shape->getBSDF(); Subsurface *subsurfaceOld = shape->getSubsurface(); // try to find shape in store ShapeMap::iterator it = snowShapes.find(shape); // If not found, add new. if (it == snowShapes.end()) { ShapeEntry newEntry; newEntry.originalBSDF = bsdfOld; if (bsdfOld != NULL) bsdfOld->incRef(); newEntry.originalSubsurface = subsurfaceOld; if (subsurfaceOld != NULL) subsurfaceOld->incRef(); shape->incRef(); snowShapes[shape] = newEntry; } PluginManager *pluginManager = PluginManager::getInstance(); SnowProperties &snow = context->snow; ESurfaceRenderMode surfaceMode = context->snowRenderSettings.surfaceRenderMode; ESubSurfaceRenderMode subsurfaceMode = context->snowRenderSettings.subsurfaceRenderMode; // common properties Properties properties; properties.setFloat("g", snow.g); properties.setSpectrum("sigmaA", snow.sigmaA); properties.setSpectrum("sigmaS", snow.sigmaS); properties.setSpectrum("sigmaT", snow.sigmaT); properties.setFloat("eta", snow.ior); // ToDo: eta is actually the relative IOR (no prob w/ air) BSDF *bsdf = NULL; Subsurface *subsurface = NULL; SnowRenderSettings &srs = context->snowRenderSettings; bool hasBSDF = true; if (surfaceMode == ENoSurface) { hasBSDF = false; } else if (surfaceMode == EWiscombeWarrenAlbedo) { properties.setPluginName("wiscombe"); properties.setFloat("depth",srs.wiscombeDepth); properties.setSpectrum("singleScatteringAlbedo", snow.singleScatteringAlbedo); } else if (surfaceMode == EWiscombeWarrenBRDF) { properties.setPluginName("wiscombe"); properties.setFloat("depth", srs.wiscombeDepth); properties.setSpectrum("singleScatteringAlbedo", snow.singleScatteringAlbedo); } else if (surfaceMode == EHanrahanKruegerBRDF) { properties.setPluginName("hanrahankrueger"); properties.setSpectrum("ssFactor", Spectrum(srs.hkSingleScatteringFactor)); properties.setSpectrum("drFactor", Spectrum(srs.hkMultipleScatteringFactor)); properties.setBoolean("diffuseReflectance", srs.hkUseMultipleScattering); } else if (surfaceMode == EMicrofacetBRDF) { properties.setPluginName("roughglass"); properties.setFloat("alpha", 0.9f); properties.setFloat("intIOR", snow.ior); properties.setString("distribution", "ggx"); } if (hasBSDF) bsdf = static_cast<BSDF *> (pluginManager->createObject( BSDF::m_theClass, properties)); if (subsurfaceMode == ENoSubSurface) { subsurface = NULL; } else if (subsurfaceMode == EJensenDipoleBSSRDF) { properties.setPluginName("dipole"); properties.setSpectrum("ssFactor", Spectrum(srs.dipoleDensityFactor)); properties.setFloat("sampleMultiplier", srs.dipoleSampleFactor); properties.setBoolean("singleScattering", srs.dipoleUseSingleScattering); properties.setBoolean("useMartelliD", srs.dipoleMartelliDC); properties.setBoolean("useTexture", srs.dipoleTexture); properties.setBoolean("dumpIrrtree", srs.dipoleDumpIrrtree); properties.setBoolean("hasRoughSurface", srs.dipoleHasRoughSurface); properties.setString("dumpIrrtreePath", srs.dipoleDumpIrrtreePath); if (srs.dipoleLutPredefineRmax) { properties.setFloat("lutRmax", srs.dipoleLutRmax); } else { properties.setInteger("mcIterations", srs.dipoleLutMCIterations); } if (srs.dipoleTexture) { properties.setString("zrFilename", srs.dipoleZrTexture); properties.setString("sigmaTrFilename", srs.dipoleSigmaTrTexture); properties.setFloat("texUScaling", srs.dipoleTextureUScaling); properties.setFloat("texVScaling", srs.dipoleTextureVScaling); } properties.setBoolean("useLookUpTable", srs.dipoleUseLut); properties.setFloat("lutResolution", srs.dipoleLutResolution); subsurface = static_cast<Subsurface *> (pluginManager->createObject( Subsurface::m_theClass, properties)); } else if (subsurfaceMode == EJensenMultipoleBSSRDF) { properties.setPluginName("multipole"); properties.setSpectrum("ssFactor", Spectrum(srs.multipoleDensityFactor)); properties.setFloat("sampleMultiplier", srs.multipoleSampleFactor); properties.setBoolean("singleScattering", srs.dipoleUseSingleScattering); properties.setFloat("slabThickness", srs.multipoleSlabThickness); properties.setInteger("extraDipoles", srs.multipoleExtraDipoles); properties.setBoolean("useMartelliD", srs.multipoleMartelliDC); properties.setBoolean("useLookUpTable", srs.multipoleUseLut); properties.setFloat("lutResolution", srs.multipoleLutResolution); if (srs.multipoleLutPredefineRmax) { properties.setFloat("lutRmax", srs.multipoleLutRmax); } else { properties.setInteger("mcIterations", srs.multipoleLutMCIterations); } subsurface = static_cast<Subsurface *> (pluginManager->createObject( Subsurface::m_theClass, properties)); } else if (subsurfaceMode == EJakobADipoleBSSRDF) { properties.setPluginName("adipole"); properties.setSpectrum("ssFactor", Spectrum(srs.adipoleDensityFactor)); properties.setFloat("sampleMultiplier", srs.adipoleSampleFactor); QString D = QString::fromStdString(srs.adipoleD); if (D.trimmed().length() == 0) properties.setString("D", getFlakeDistribution()); else properties.setString("D", srs.adipoleD); properties.setFloat("sigmaTn", srs.adipoleSigmaTn); subsurface = static_cast<Subsurface *> (pluginManager->createObject( Subsurface::m_theClass, properties)); } /* initialize new materials */ if (bsdf) { bsdf->setParent(shape); bsdf->configure(); bsdf->incRef(); } if (subsurface) { subsurface->setParent(shape); subsurface->configure(); subsurface->incRef(); // if a subsurface material has been selected, inform the scene about it context->scene->addSubsurface(subsurface); } shape->setBSDF(bsdf); shape->setSubsurface(subsurface); // allow the shape to react to this changes shape->configure(); /* if the subsurface integrator previously used (if any) is not * needed by other shapes, we can remove it for now. */ if (subsurfaceOld != NULL ) { context->scene->removeSubsurface(subsurfaceOld); } setMadeOfSnow(shape, true); std::string bsdfName = (bsdf == NULL) ? "None" : bsdf->getClass()->getName(); std::string subsurfaceName = (subsurface == NULL) ? "None" : subsurface->getClass()->getName(); SLog(EDebug, "[Snow Material Manager] Replaced material of shape \"%s\"", shape->getName().c_str()); SLog(EDebug, "\tnew BSDF: %s", bsdfName.c_str()); SLog(EDebug, "\tnew Subsurface: %s", subsurfaceName.c_str()); } std::string SnowMaterialManager::getFlakeDistribution() { // My (Tom) calculations (indefinite Matrizen, geht nicht): /* clamped cosin^20 flake distribution */ // return "0.01314, -0.00014, 0.00061, -0.00014, 0.01295, -0.00018, 0.00061, -0.00018, -0.07397"; /* sine^20 flake distribution */ //return "1.6307, -0.00049, 0.00069, -0.00049, 1.63148, 0.00001, 0.00067, 0.00002, 2.12596"; // Wenzels Berechnungen (definite Matrizen, notwendig) /* clamped cosin^20 flake distribution,hier ist D(w) = abs(dot(w, [0, 0, 1]))^20.000000 */ //return "0.043496, 4.0726e-10, -1.1039e-10, 4.0726e-10, 0.043496, 1.1632e-09, -1.1039e-10, 1.1632e-09, 0.91301"; /* sine^20 flake distribution, hier ist D(w) = (1-dot(w, [0, 0, 1])^2)^10.000000 */ return "0.47827, 7.5057e-09, -4.313e-10, 7.5057e-09, 0.47827, 2.5069e-10, -4.313e-10, 2.5069e-10, 0.043454"; } void SnowMaterialManager::resetMaterial(Shape *shape, SceneContext *context) { ShapeMap::iterator it = snowShapes.find(shape); if (it == snowShapes.end()) { SLog(EWarn, "Did not find requested shape to reset material."); return; } setMadeOfSnow(shape, false); ShapeEntry &e = it->second; // if found, use materials BSDF *bsdf = e.originalBSDF; if (bsdf != NULL) { bsdf->setParent(shape); bsdf->configure(); } shape->setBSDF( bsdf ); Subsurface *old_ss = shape->getSubsurface(); Subsurface *subsurface = e.originalSubsurface; if (subsurface != NULL) { subsurface->setParent(shape); subsurface->configure(); context->scene->addSubsurface(subsurface); } if (old_ss != NULL) context->scene->removeSubsurface(old_ss); shape->setSubsurface(subsurface); // allow the shape to react to this changes shape->configure(); std::cerr << "[Snow Material Manager] Reset material on shape " << shape->getName() << std::endl; } bool SnowMaterialManager::isMadeOfSnow(const Shape * shape) const { ShapeMap::const_iterator it = snowShapes.find(shape); if (it != snowShapes.end()) return it->second.madeOfSnow; else return false; } void SnowMaterialManager::removeShape(Shape *shape) { ShapeMap::iterator it = snowShapes.find(shape); if (it != snowShapes.end()) snowShapes.erase(it); } void SnowMaterialManager::setMadeOfSnow(Shape *shape, bool snow) { ShapeMap::iterator it = snowShapes.find(shape); if (it == snowShapes.end()) return; it->second.madeOfSnow = snow; } std::string SnowMaterialManager::toString() { std::ostringstream oss; oss << "SnowMaterialManager[" << std::endl; for (ShapeMap::iterator it = snowShapes.begin(); it != snowShapes.end(); it++) { const Shape *s = it->first; ShapeEntry &entry = it->second; if (entry.madeOfSnow && s != NULL) { const BSDF* bsdf = s->getBSDF(); const Subsurface* subsurface = s->getSubsurface(); oss << " " << s->getName() << ":" << std::endl << " BSDF: " << std::endl << (bsdf == NULL ? "None" : indent(bsdf->toString(), 3)) << std::endl << " Subsurface: " << std::endl << (subsurface == NULL ? "None" : indent(subsurface->toString(), 3)) << std::endl; } } oss << "]"; return oss.str(); } std::pair< ref<Bitmap>, Float > SnowMaterialManager::getCachedDiffusionProfile() const { return std::make_pair(diffusionProfileCache, diffusionProfileRmax); } bool SnowMaterialManager::hasCachedDiffusionProfile() const { return diffusionProfileCache.get() != NULL; } void SnowMaterialManager::refreshDiffusionProfile(const SceneContext *context) { typedef SubsurfaceMaterialManager::LUTType LUTType; const Float errThreshold = 0.01f; const Float lutResolution = 0.001f; const SnowProperties &sp = context->snow; const bool rMaxPredefined = context->snowRenderSettings.shahPredefineRmax; const Float predefinedRmax = context->snowRenderSettings.shahRmax; const Spectrum sigmaSPrime = sp.sigmaS * (1 - sp.g); const Spectrum sigmaTPrime = sigmaSPrime + sp.sigmaA; /* extinction coefficient */ const Spectrum sigmaT = sp.sigmaA + sp.sigmaS; /* Effective transport extinction coefficient */ const Spectrum sigmaTr = (sp.sigmaA * sigmaTPrime * 3.0f).sqrt(); /* Reduced albedo */ const Spectrum alphaPrime = sigmaSPrime / sigmaTPrime; /* Mean-free path (avg. distance traveled through the medium) */ const Spectrum mfp = Spectrum(1.0f) / sigmaTPrime; Float Fdr; if (sp.ior > 1) { /* Average reflectance due to mismatched indices of refraction at the boundary - [Groenhuis et al. 1983]*/ Fdr = -1.440f / (sp.ior * sp.ior) + 0.710f / sp.ior + 0.668f + 0.0636f * sp.ior; } else { /* Average reflectance due to mismatched indices of refraction at the boundary - [Egan et al. 1973]*/ Fdr = -0.4399f + 0.7099f / sp.ior - 0.3319f / (sp.ior * sp.ior) + 0.0636f / (sp.ior * sp.ior * sp.ior); } /* Average transmittance at the boundary */ Float Fdt = 1.0f - Fdr; if (sp.ior == 1.0f) { Fdr = (Float) 0.0f; Fdt = (Float) 1.0f; } /* Approximate dipole boundary condition term */ const Float A = (1 + Fdr) / Fdt; /* Distance of the dipole point sources to the surface */ const Spectrum zr = mfp; const Spectrum zv = mfp * (1.0f + 4.0f/3.0f * A); const Spectrum invSigmaTr = Spectrum(1.0f) / sigmaTr; const Float inv4Pi = 1.0f / (4 * M_PI); Float rMax = 0.0f; if (!rMaxPredefined) { ref<Random> random = new Random(); /* Find Rd for the whole area by monte carlo integration. The * sampling area is calculated from the max. mean free path. * A square area around with edge length 2 * maxMFP is used * for this. Hene, the sampling area is 4 * maxMFP * maxMFP. */ const int numSamples = context->snowRenderSettings.shahMCIterations; Spectrum Rd_A = Spectrum(0.0f); for (int n = 0; n < numSamples; ++n) { /* do importance sampling by choosing samples distributed * with sigmaTr^2 * e^(-sigmaTr * r). */ Spectrum r = invSigmaTr * -std::log( random->nextFloat() ); Rd_A += getRd(r, sigmaTr, zv, zr); } Float Area = 4 * invSigmaTr.max() * invSigmaTr.max(); Rd_A = Area * Rd_A * alphaPrime * inv4Pi / (Float)(numSamples - 1); SLog(EDebug, "After %i MC integration iterations, Rd seems to be %s", numSamples, Rd_A.toString().c_str()); /* Since we now have Rd integrated over the whole surface we can find a valid rmax * for the given threshold. */ const Float step = lutResolution; Spectrum err(std::numeric_limits<Float>::max()); while (err.max() > errThreshold) { rMax += step; /* Again, do MC integration, but with r clamped at rmax. */ Spectrum Rd_APrime(0.0f); for (int n = 0; n < numSamples; ++n) { /* do importance sampling by choosing samples distributed * with sigmaTr^2 * e^(-sigmaTr * r). */ Spectrum r = invSigmaTr * -std::log( random->nextFloat() ); // clamp samples to rMax for (int s=0; s<SPECTRUM_SAMPLES; ++s) { r[s] = std::min(rMax, r[s]); } Rd_APrime += getRd(r, sigmaTr, zv, zr); } Float APrime = 4 * rMax * rMax; Rd_APrime = APrime * Rd_APrime * alphaPrime * inv4Pi / (Float)(numSamples - 1); err = (Rd_A - Rd_APrime) / Rd_A; } SLog(EDebug, "Maximum distance for sampling surface is %f with an error of %f", rMax, errThreshold); } else { rMax = predefinedRmax; } /* Create the actual look-up-table */ const int numEntries = (int) (rMax / lutResolution) + 1; std::vector<Spectrum> diffusionProfile(numEntries); for (int i=0; i<numEntries; ++i) { Spectrum r = Spectrum(i * lutResolution); diffusionProfile.at(i) = getRd(r, sigmaTr, zv, zr); } SLog(EDebug, "Created Rd diffusion profile with %i entries.", numEntries); /* Create the diffuson profile bitmap */ diffusionProfileRmax = rMax; bool useHDR = true; if (useHDR) { diffusionProfileCache = new Bitmap(numEntries, 1, 128); float *data = diffusionProfileCache->getFloatData(); for (int i = 0; i < numEntries; ++i) { *data++ = diffusionProfile[i][0]; *data++ = diffusionProfile[i][1]; *data++ = diffusionProfile[i][2]; *data++ = 1.0f; } #ifdef DEBUG_DIFF_PROF data = diffusionProfileCache->getFloatData(); for (int i = 0; i < numEntries * 4; ++i) { std::cerr << *data++ << " "; } std::cerr << std::endl; diffusionProfileCache->save( Bitmap::EEXR, new FileStream("img-diffprof.exr", FileStream::ETruncWrite)); #endif } else { diffusionProfileCache = new Bitmap(numEntries, 1, 32); Float maxRd = diffusionProfile[0].max(); const Float scale = 255.0f / maxRd; const Float exposure = context->snowRenderSettings.shahExposure; unsigned char *data = diffusionProfileCache->getData(); for (int i = 0; i < numEntries; ++i) { *data++ = std::max( (unsigned int)1, (unsigned int) (diffusionProfile[i][0] * scale + 0.5)); *data++ = std::max( (unsigned int)1, (unsigned int) (diffusionProfile[i][1] * scale + 0.5)); *data++ = std::max( (unsigned int)1, (unsigned int) (diffusionProfile[i][2] * scale + 0.5)); //*data++ = int(255.0f * (1.0f - exp(diffusionProfile[i][0] * exposure))); //*data++ = int(255.0f * (1.0f - exp(diffusionProfile[i][1] * exposure))); //*data++ = int(255.0f * (1.0f - exp(diffusionProfile[i][2] * exposure))); *data++ = 255; } #ifdef DEBUG_DIFF_PROF data = diffusionProfileCache->getData(); for (int i = 0; i < numEntries * 4; ++i) { std::cerr << (int) (*data++) << " "; } std::cerr << std::endl; diffusionProfileCache->save( Bitmap::EPNG, new FileStream("img-diffprof.png", FileStream::ETruncWrite)); #endif } } /// Calculate Rd based on all dipoles and the requested distance Spectrum SnowMaterialManager::getRd(const Spectrum &r, const Spectrum &sigmaTr, const Spectrum &zv, const Spectrum &zr) { //Float dist = std::max((p - sample.p).lengthSquared(), zrMinSq); const Spectrum rSqr = r * r; const Spectrum one(1.0f); const Spectrum negSigmaTr = sigmaTr * (-1.0f); /* Distance to the real source */ Spectrum dr = (rSqr + zr*zr).sqrt(); /* Distance to the image point source */ Spectrum dv = (rSqr + zv*zv).sqrt(); Spectrum C1 = zr * (sigmaTr + one / dr); Spectrum C2 = zv * (sigmaTr + one / dv); /* Do not include the reduced albedo - will be canceled out later */ Spectrum Rd = Spectrum(0.25f * INV_PI) * (C1 * ((negSigmaTr * dr).exp()) / (dr * dr) + C2 * ((negSigmaTr * dv).exp()) / (dv * dv)); return Rd; } MTS_NAMESPACE_END
5140c363886c723f4dc0cd28776ec559d414696f
eded3490c7d55f4bcef33b720de1c822519d5e5a
/matpan.cpp
a17788d2e7d6b06c9592ac59966ac67ffab408b3
[]
no_license
asperaa/Codechef_Problems
a8da49ce1c2c057e25c5fb62c848318d5f2e4624
9ab4f4ab53d3fbe8788243fb4b0f8f1afcac839e
refs/heads/master
2021-01-23T21:47:19.485328
2017-09-08T21:09:52
2017-09-08T21:09:52
102,904,635
0
0
null
null
null
null
UTF-8
C++
false
false
589
cpp
matpan.cpp
#include <bits/stdc++.h> using namespace std; int main() { int t; cin>>t; int a[26],b[26]; char c[26]; for(int k=0;k<26;k++) c[k]=(97+k); string s; for(int i=0;i<t;i++) { int cost=0; for(int k=0;k<26;k++) b[k]=0; for(int j=0;j<26;j++) cin>>a[j]; cin>>s; set<char>s1; for(int j=0;j<s.length();j++) s1.insert(s[j]); vector<char>v1(s1.begin(),s1.end()); int p=0; for(int j=0;j<26;j++) { if(c[j]==v1[p]) { b[j]++; p++; } } for(int j=0;j<26;j++) { if(b[j]==0) cost+=a[j]; } cout<<cost<<endl; } }
397c65831d46119d642ab2cef278057e7e6f4b83
a3d6556180e74af7b555f8d47d3fea55b94bcbda
/third_party/blink/renderer/core/frame/remote_frame.cc
e5d0e24fa1cbfff6a16632103562042b9ae43708
[ "LGPL-2.0-or-later", "LicenseRef-scancode-warranty-disclaimer", "LGPL-2.1-only", "GPL-1.0-or-later", "GPL-2.0-only", "LGPL-2.0-only", "BSD-2-Clause", "LicenseRef-scancode-other-copyleft", "BSD-3-Clause", "MIT", "Apache-2.0" ]
permissive
chromium/chromium
aaa9eda10115b50b0616d2f1aed5ef35d1d779d6
a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c
refs/heads/main
2023-08-24T00:35:12.585945
2023-08-23T22:01:11
2023-08-23T22:01:11
120,360,765
17,408
7,102
BSD-3-Clause
2023-09-10T23:44:27
2018-02-05T20:55:32
null
UTF-8
C++
false
false
45,270
cc
remote_frame.cc
// Copyright 2014 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "third_party/blink/renderer/core/frame/remote_frame.h" #include "base/types/optional_util.h" #include "cc/layers/surface_layer.h" #include "services/network/public/mojom/web_sandbox_flags.mojom-blink.h" #include "third_party/blink/public/common/frame/frame_owner_element_type.h" #include "third_party/blink/public/common/navigation/navigation_policy.h" #include "third_party/blink/public/mojom/frame/frame.mojom-blink.h" #include "third_party/blink/public/mojom/frame/frame_owner_properties.mojom-blink.h" #include "third_party/blink/public/mojom/frame/frame_replication_state.mojom-blink.h" #include "third_party/blink/public/mojom/frame/fullscreen.mojom-blink.h" #include "third_party/blink/public/mojom/frame/intrinsic_sizing_info.mojom-blink.h" #include "third_party/blink/public/mojom/loader/referrer.mojom-blink.h" #include "third_party/blink/public/mojom/security_context/insecure_request_policy.mojom-blink.h" #include "third_party/blink/public/mojom/timing/resource_timing.mojom-blink-forward.h" #include "third_party/blink/public/platform/platform.h" #include "third_party/blink/public/platform/url_conversion.h" #include "third_party/blink/public/platform/web_url_request_util.h" #include "third_party/blink/public/web/web_frame.h" #include "third_party/blink/public/web/web_view.h" #include "third_party/blink/renderer/bindings/core/v8/v8_fullscreen_options.h" #include "third_party/blink/renderer/bindings/core/v8/window_proxy.h" #include "third_party/blink/renderer/bindings/core/v8/window_proxy_manager.h" #include "third_party/blink/renderer/core/accessibility/ax_object_cache.h" #include "third_party/blink/renderer/core/events/message_event.h" #include "third_party/blink/renderer/core/exported/web_view_impl.h" #include "third_party/blink/renderer/core/frame/child_frame_compositing_helper.h" #include "third_party/blink/renderer/core/frame/local_dom_window.h" #include "third_party/blink/renderer/core/frame/local_frame.h" #include "third_party/blink/renderer/core/frame/local_frame_client.h" #include "third_party/blink/renderer/core/frame/remote_dom_window.h" #include "third_party/blink/renderer/core/frame/remote_frame_client.h" #include "third_party/blink/renderer/core/frame/remote_frame_owner.h" #include "third_party/blink/renderer/core/frame/remote_frame_view.h" #include "third_party/blink/renderer/core/frame/user_activation.h" #include "third_party/blink/renderer/core/fullscreen/fullscreen.h" #include "third_party/blink/renderer/core/html/html_frame_owner_element.h" #include "third_party/blink/renderer/core/inspector/console_message.h" #include "third_party/blink/renderer/core/layout/geometry/physical_rect.h" #include "third_party/blink/renderer/core/layout/intrinsic_sizing_info.h" #include "third_party/blink/renderer/core/layout/layout_embedded_content.h" #include "third_party/blink/renderer/core/layout/layout_view.h" #include "third_party/blink/renderer/core/layout/text_autosizer.h" #include "third_party/blink/renderer/core/loader/frame_load_request.h" #include "third_party/blink/renderer/core/loader/frame_loader.h" #include "third_party/blink/renderer/core/loader/mixed_content_checker.h" #include "third_party/blink/renderer/core/messaging/blink_transferable_message.h" #include "third_party/blink/renderer/core/page/page.h" #include "third_party/blink/renderer/core/page/plugin_script_forbidden_scope.h" #include "third_party/blink/renderer/core/paint/paint_layer.h" #include "third_party/blink/renderer/core/probe/core_probes.h" #include "third_party/blink/renderer/core/scroll/scroll_into_view_util.h" #include "third_party/blink/renderer/core/timing/dom_window_performance.h" #include "third_party/blink/renderer/platform/exported/wrapped_resource_request.h" #include "third_party/blink/renderer/platform/heap/collection_support/heap_vector.h" #include "third_party/blink/renderer/platform/heap/garbage_collected.h" #include "third_party/blink/renderer/platform/loader/fetch/fetch_client_settings_object.h" #include "third_party/blink/renderer/platform/loader/fetch/resource_fetcher.h" #include "third_party/blink/renderer/platform/loader/fetch/resource_fetcher_properties.h" #include "third_party/blink/renderer/platform/loader/fetch/resource_request.h" #include "third_party/blink/renderer/platform/weborigin/security_policy.h" #include "third_party/blink/renderer/platform/wtf/casting.h" #include "ui/base/window_open_disposition.h" #include "ui/gfx/geometry/rect_conversions.h" #include "ui/gfx/geometry/rect_f.h" namespace blink { namespace { // Maintain a global (statically-allocated) hash map indexed by the the result // of hashing the |frame_token| passed on creation of a RemoteFrame object. typedef HeapHashMap<uint64_t, WeakMember<RemoteFrame>> RemoteFramesByTokenMap; static RemoteFramesByTokenMap& GetRemoteFramesMap() { DEFINE_STATIC_LOCAL(Persistent<RemoteFramesByTokenMap>, map, (MakeGarbageCollected<RemoteFramesByTokenMap>())); return *map; } } // namespace // static RemoteFrame* RemoteFrame::FromFrameToken(const RemoteFrameToken& frame_token) { RemoteFramesByTokenMap& remote_frames_map = GetRemoteFramesMap(); auto it = remote_frames_map.find(RemoteFrameToken::Hasher()(frame_token)); return it == remote_frames_map.end() ? nullptr : it->value.Get(); } RemoteFrame::RemoteFrame( RemoteFrameClient* client, Page& page, FrameOwner* owner, Frame* parent, Frame* previous_sibling, FrameInsertType insert_type, const RemoteFrameToken& frame_token, WindowAgentFactory* inheriting_agent_factory, WebFrameWidget* ancestor_widget, const base::UnguessableToken& devtools_frame_token, mojo::PendingAssociatedRemote<mojom::blink::RemoteFrameHost> remote_frame_host, mojo::PendingAssociatedReceiver<mojom::blink::RemoteFrame> receiver) : Frame(client, page, owner, parent, previous_sibling, insert_type, frame_token, devtools_frame_token, MakeGarbageCollected<RemoteWindowProxyManager>(*this), inheriting_agent_factory), // TODO(samans): Investigate if it is safe to delay creation of this // object until a FrameSinkId is provided. parent_local_surface_id_allocator_( std::make_unique<viz::ParentLocalSurfaceIdAllocator>()), ancestor_widget_(ancestor_widget), task_runner_(page.GetPageScheduler() ->GetAgentGroupScheduler() .DefaultTaskRunner()) { // TODO(crbug.com/1094850): Remove this check once the renderer is correctly // handling errors during the creation of HTML portal elements, which would // otherwise cause RemoteFrame() being created with empty frame tokens. if (!frame_token.value().is_empty()) { auto frame_tracking_result = GetRemoteFramesMap().insert( RemoteFrameToken::Hasher()(frame_token), this); CHECK(frame_tracking_result.stored_value) << "Inserting a duplicate item."; } dom_window_ = MakeGarbageCollected<RemoteDOMWindow>(*this); DCHECK(task_runner_); remote_frame_host_remote_.Bind(std::move(remote_frame_host), task_runner_); receiver_.Bind(std::move(receiver), task_runner_); UpdateInertIfPossible(); UpdateInheritedEffectiveTouchActionIfPossible(); UpdateVisibleToHitTesting(); Initialize(); if (ancestor_widget) compositing_helper_ = std::make_unique<ChildFrameCompositingHelper>(this); } RemoteFrame::~RemoteFrame() { DCHECK(!view_); } void RemoteFrame::DetachAndDispose() { DCHECK(!IsMainFrame()); Detach(FrameDetachType::kRemove); } void RemoteFrame::Trace(Visitor* visitor) const { visitor->Trace(view_); visitor->Trace(security_context_); visitor->Trace(remote_frame_host_remote_); visitor->Trace(receiver_); visitor->Trace(main_frame_receiver_); Frame::Trace(visitor); } void RemoteFrame::Navigate(FrameLoadRequest& frame_request, WebFrameLoadType frame_load_type) { // RemoteFrame::Navigate doesn't support policies like // kNavigationPolicyNewForegroundTab - such policies need to be handled via // local frames. DCHECK_EQ(kNavigationPolicyCurrentTab, frame_request.GetNavigationPolicy()); if (HTMLFrameOwnerElement* element = DeprecatedLocalOwner()) element->CancelPendingLazyLoad(); if (!navigation_rate_limiter().CanProceed()) return; frame_request.SetFrameType(IsMainFrame() ? mojom::RequestContextFrameType::kTopLevel : mojom::RequestContextFrameType::kNested); const KURL& url = frame_request.GetResourceRequest().Url(); auto* window = frame_request.GetOriginWindow(); // The only navigation paths which do not have an origin window are drag and // drop navigations, but they never navigate remote frames. DCHECK(window); // Note that even if |window| is not null, it could have just been detached // (so window->GetFrame() is null). This can happen for a form submission, if // the frame containing the form has been deleted in between. if (!frame_request.CanDisplay(url)) { window->AddConsoleMessage(MakeGarbageCollected<ConsoleMessage>( mojom::blink::ConsoleMessageSource::kSecurity, mojom::blink::ConsoleMessageLevel::kError, "Not allowed to load local resource: " + url.ElidedString())); return; } // The process where this frame actually lives won't have sufficient // information to upgrade the url, since it won't have access to the // origin context. Do it now. const FetchClientSettingsObject* fetch_client_settings_object = &window->Fetcher()->GetProperties().GetFetchClientSettingsObject(); MixedContentChecker::UpgradeInsecureRequest( frame_request.GetResourceRequest(), fetch_client_settings_object, window, frame_request.GetFrameType(), window->GetFrame() ? window->GetFrame()->GetContentSettingsClient() : nullptr); if (NavigationShouldReplaceCurrentHistoryEntry(frame_load_type)) frame_load_type = WebFrameLoadType::kReplaceCurrentItem; bool is_opener_navigation = false; bool initiator_frame_has_download_sandbox_flag = false; bool initiator_frame_is_ad = false; bool is_ad_script_in_stack = false; absl::optional<LocalFrameToken> initiator_frame_token = base::OptionalFromPtr(frame_request.GetInitiatorFrameToken()); mojo::PendingRemote<mojom::blink::PolicyContainerHostKeepAliveHandle> initiator_policy_container_keep_alive_handle = frame_request.TakeInitiatorPolicyContainerKeepAliveHandle(); // |initiator_frame_token| and |initiator_policy_container_keep_alive_handle| // should either be both specified or both null. DCHECK(!initiator_frame_token == !initiator_policy_container_keep_alive_handle); initiator_frame_has_download_sandbox_flag = window->IsSandboxed(network::mojom::blink::WebSandboxFlags::kDownloads); if (window->GetFrame()) { is_opener_navigation = window->GetFrame()->Opener() == this; initiator_frame_is_ad = window->GetFrame()->IsAdFrame(); is_ad_script_in_stack = window->GetFrame()->IsAdScriptInStack(); if (frame_request.ClientRedirectReason() != ClientNavigationReason::kNone) { probe::FrameRequestedNavigation(window->GetFrame(), this, url, frame_request.ClientRedirectReason(), kNavigationPolicyCurrentTab); } if (!initiator_frame_token) { initiator_frame_token = window->GetFrame()->GetLocalFrameToken(); initiator_policy_container_keep_alive_handle = window->GetPolicyContainer()->IssueKeepAliveHandle(); } } // TODO(https://crbug.com/1173409 and https://crbug.com/1059959): Check that // we always have valid |initiator_frame_token| and // |initiator_policy_container_keep_alive_handle|. ResourceRequest& request = frame_request.GetResourceRequest(); DCHECK(request.RequestorOrigin().get()); auto params = mojom::blink::OpenURLParams::New(); params->url = url; params->initiator_origin = request.RequestorOrigin(); if (features::IsNewBaseUrlInheritanceBehaviorEnabled() && (url.IsAboutBlankURL() || url.IsAboutSrcdocURL()) && !frame_request.GetRequestorBaseURL().IsEmpty()) { params->initiator_base_url = frame_request.GetRequestorBaseURL(); } params->post_body = blink::GetRequestBodyForWebURLRequest(WrappedResourceRequest(request)); DCHECK_EQ(!!params->post_body, request.HttpMethod().Utf8() == "POST"); params->extra_headers = blink::GetWebURLRequestHeadersAsString(WrappedResourceRequest(request)); params->referrer = mojom::blink::Referrer::New( KURL(NullURL(), request.ReferrerString()), request.GetReferrerPolicy()); params->is_form_submission = !!frame_request.Form(); params->disposition = ui::mojom::blink::WindowOpenDisposition::CURRENT_TAB; params->should_replace_current_entry = frame_load_type == WebFrameLoadType::kReplaceCurrentItem; params->user_gesture = request.HasUserGesture(); params->triggering_event_info = mojom::blink::TriggeringEventInfo::kUnknown; params->blob_url_token = frame_request.GetBlobURLToken(); params->href_translate = String(frame_request.HrefTranslate().Latin1().c_str()); params->initiator_policy_container_keep_alive_handle = std::move(initiator_policy_container_keep_alive_handle); params->initiator_frame_token = base::OptionalFromPtr(base::OptionalToPtr(initiator_frame_token)); params->source_location = network::mojom::blink::SourceLocation::New(); std::unique_ptr<SourceLocation> source_location = frame_request.TakeSourceLocation(); if (!source_location->IsUnknown()) { params->source_location->url = source_location->Url() ? source_location->Url() : ""; params->source_location->line = source_location->LineNumber(); params->source_location->column = source_location->ColumnNumber(); } params->impression = frame_request.Impression(); // Note: For the AdFrame/Sandbox download policy here it only covers the case // where the navigation initiator frame is ad. The download_policy may be // further augmented in RenderFrameProxyHost::OnOpenURL if the navigating // frame is ad or sandboxed. params->download_policy.ApplyDownloadFramePolicy( is_opener_navigation, request.HasUserGesture(), request.RequestorOrigin()->CanAccess( GetSecurityContext()->GetSecurityOrigin()), initiator_frame_has_download_sandbox_flag, initiator_frame_is_ad); params->initiator_activation_and_ad_status = GetNavigationInitiatorActivationAndAdStatus(request.HasUserGesture(), initiator_frame_is_ad, is_ad_script_in_stack); params->is_container_initiated = frame_request.IsContainerInitiated(); GetRemoteFrameHostRemote().OpenURL(std::move(params)); } bool RemoteFrame::NavigationShouldReplaceCurrentHistoryEntry( WebFrameLoadType frame_load_type) const { // Portal and Fenced Frame contexts do not create back/forward entries. // TODO(https:/crbug.com/1197384, https://crbug.com/1190644): We may want to // support a prerender in RemoteFrame. return (frame_load_type == WebFrameLoadType::kStandard && GetPage()->InsidePortal()) || IsInFencedFrameTree(); } bool RemoteFrame::DetachImpl(FrameDetachType type) { PluginScriptForbiddenScope forbid_plugin_destructor_scripting; if (!DetachChildren()) return false; // Clean up the frame's view if needed. A remote frame only has a view if // the parent is a local frame. if (view_) view_->Dispose(); SetView(nullptr); // ... the RemoteDOMWindow will need to be informed of detachment, // as otherwise it will keep a strong reference back to this RemoteFrame. // That combined with wrappers (owned and kept alive by RemoteFrame) keeping // persistent strong references to RemoteDOMWindow will prevent the GCing // of all these objects. Break the cycle by notifying of detachment. To<RemoteDOMWindow>(dom_window_.Get())->FrameDetached(); if (cc_layer_) SetCcLayer(nullptr, false); receiver_.reset(); main_frame_receiver_.reset(); return true; } const scoped_refptr<cc::Layer>& RemoteFrame::GetCcLayer() { return cc_layer_; } void RemoteFrame::SetCcLayer(scoped_refptr<cc::Layer> layer, bool is_surface_layer) { // |ancestor_widget_| can be null if this is a proxy for a remote // main frame, or a subframe of that proxy. However, we should not be setting // a layer on such a proxy (the layer is used for embedding a child proxy). DCHECK(ancestor_widget_); DCHECK(Owner()); cc_layer_ = std::move(layer); is_surface_layer_ = is_surface_layer; if (cc_layer_ && is_surface_layer_) { static_cast<cc::SurfaceLayer&>(*cc_layer_) .SetHasPointerEventsNone(IsIgnoredForHitTest()); } HTMLFrameOwnerElement* owner = To<HTMLFrameOwnerElement>(Owner()); owner->SetNeedsCompositingUpdate(); // Schedule an animation so that a new frame is produced with the updated // layer, otherwise this local root's visible content may not be up to date. owner->GetDocument().GetFrame()->View()->ScheduleAnimation(); } SkBitmap* RemoteFrame::GetSadPageBitmap() { return Platform::Current()->GetSadPageBitmap(); } bool RemoteFrame::DetachDocument() { return DetachChildren(); } void RemoteFrame::CheckCompleted() { // Notify the client so that the corresponding LocalFrame can do the check. GetRemoteFrameHostRemote().CheckCompleted(); } const RemoteSecurityContext* RemoteFrame::GetSecurityContext() const { return &security_context_; } bool RemoteFrame::ShouldClose() { // TODO(crbug.com/1407078): Implement running the beforeunload handler in the // actual LocalFrame running in a different process and getting back a real // result. return true; } void RemoteFrame::SetIsInert(bool inert) { if (inert != is_inert_) GetRemoteFrameHostRemote().SetIsInert(inert); is_inert_ = inert; } void RemoteFrame::SetInheritedEffectiveTouchAction(TouchAction touch_action) { if (inherited_effective_touch_action_ != touch_action) GetRemoteFrameHostRemote().SetInheritedEffectiveTouchAction(touch_action); inherited_effective_touch_action_ = touch_action; } void RemoteFrame::RenderFallbackContent() { Frame::RenderFallbackContent(); } void RemoteFrame::AddResourceTimingFromChild( mojom::blink::ResourceTimingInfoPtr timing) { HTMLFrameOwnerElement* owner_element = To<HTMLFrameOwnerElement>(Owner()); DCHECK(owner_element); owner_element->AddResourceTiming(std::move(timing)); } void RemoteFrame::DidStartLoading() { // If this proxy was created for a frame that hasn't yet finished loading, // let the renderer know so it can also mark the proxy as loading. See // https://crbug.com/916137. SetIsLoading(true); } void RemoteFrame::DidStopLoading() { SetIsLoading(false); // When a subframe finishes loading, the parent should check if *all* // subframes have finished loading (which may mean that the parent can declare // that the parent itself has finished loading). This remote-subframe-focused // code has a local-subframe equivalent in FrameLoader::DidFinishNavigation. Frame* parent = Tree().Parent(); if (parent) parent->CheckCompleted(); } void RemoteFrame::DidFocus() { GetRemoteFrameHostRemote().DidFocusFrame(); } void RemoteFrame::SetView(RemoteFrameView* view) { // Oilpan: as RemoteFrameView performs no finalization actions, // no explicit Dispose() of it needed here. (cf. LocalFrameView::Dispose().) view_ = view; } void RemoteFrame::CreateView() { // If the RemoteFrame does not have a LocalFrame parent, there's no need to // create a EmbeddedContentView for it. if (!DeprecatedLocalOwner()) return; DCHECK(!DeprecatedLocalOwner()->OwnedEmbeddedContentView()); SetView(MakeGarbageCollected<RemoteFrameView>(this)); if (OwnerLayoutObject()) DeprecatedLocalOwner()->SetEmbeddedContentView(view_); } void RemoteFrame::ForwardPostMessage( BlinkTransferableMessage transferable_message, LocalFrame* source_frame, scoped_refptr<const SecurityOrigin> source_security_origin, scoped_refptr<const SecurityOrigin> target_security_origin) { absl::optional<blink::LocalFrameToken> source_token; if (source_frame) source_token = source_frame->GetLocalFrameToken(); String source_origin = source_security_origin ? source_security_origin->ToString() : g_empty_string; String target_origin = target_security_origin ? target_security_origin->ToString() : g_empty_string; GetRemoteFrameHostRemote().RouteMessageEvent(source_token, source_origin, target_origin, std::move(transferable_message)); } bool RemoteFrame::IsRemoteFrameHostRemoteBound() { return remote_frame_host_remote_.is_bound(); } mojom::blink::RemoteFrameHost& RemoteFrame::GetRemoteFrameHostRemote() { return *remote_frame_host_remote_.get(); } RemoteFrameClient* RemoteFrame::Client() const { return static_cast<RemoteFrameClient*>(Frame::Client()); } void RemoteFrame::DidChangeVisibleToHitTesting() { if (!cc_layer_ || !is_surface_layer_) return; static_cast<cc::SurfaceLayer&>(*cc_layer_) .SetHasPointerEventsNone(IsIgnoredForHitTest()); } void RemoteFrame::SetReplicatedPermissionsPolicyHeader( const ParsedPermissionsPolicy& parsed_header) { permissions_policy_header_ = parsed_header; ApplyReplicatedPermissionsPolicyHeader(); } void RemoteFrame::SetReplicatedSandboxFlags( network::mojom::blink::WebSandboxFlags flags) { security_context_.ResetAndEnforceSandboxFlags(flags); } void RemoteFrame::SetInsecureRequestPolicy( mojom::blink::InsecureRequestPolicy policy) { security_context_.SetInsecureRequestPolicy(policy); } void RemoteFrame::FrameRectsChanged(const gfx::Size& local_frame_size, const gfx::Rect& rect_in_local_root) { pending_visual_properties_.rect_in_local_root = rect_in_local_root; pending_visual_properties_.local_frame_size = local_frame_size; SynchronizeVisualProperties(); } void RemoteFrame::InitializeFrameVisualProperties( const FrameVisualProperties& properties) { pending_visual_properties_ = properties; SynchronizeVisualProperties(); } void RemoteFrame::WillEnterFullscreen( mojom::blink::FullscreenOptionsPtr request_options) { // This should only ever be called when the FrameOwner is local. HTMLFrameOwnerElement* owner_element = To<HTMLFrameOwnerElement>(Owner()); // Call |requestFullscreen()| on |ownerElement| to make it the pending // fullscreen element in anticipation of the coming |didEnterFullscreen()| // call. // // ForCrossProcessDescendant is necessary because: // - The fullscreen element ready check and other checks should be bypassed. // - |ownerElement| will need :-webkit-full-screen-ancestor style in addition // to :fullscreen. FullscreenRequestType request_type = (request_options->is_prefixed ? FullscreenRequestType::kPrefixed : FullscreenRequestType::kUnprefixed) | (request_options->is_xr_overlay ? FullscreenRequestType::kForXrOverlay : FullscreenRequestType::kNull) | (request_options->prefers_status_bar ? FullscreenRequestType::kForXrArWithCamera : FullscreenRequestType::kNull) | FullscreenRequestType::kForCrossProcessDescendant; Fullscreen::RequestFullscreen(*owner_element, FullscreenOptions::Create(), request_type); } void RemoteFrame::EnforceInsecureNavigationsSet( const WTF::Vector<uint32_t>& set) { security_context_.SetInsecureNavigationsSet(set); } void RemoteFrame::SetFrameOwnerProperties( mojom::blink::FrameOwnerPropertiesPtr properties) { Frame::ApplyFrameOwnerProperties(std::move(properties)); } void RemoteFrame::EnforceInsecureRequestPolicy( mojom::blink::InsecureRequestPolicy policy) { SetInsecureRequestPolicy(policy); } void RemoteFrame::SetReplicatedOrigin( const scoped_refptr<const SecurityOrigin>& origin, bool is_potentially_trustworthy_unique_origin) { scoped_refptr<SecurityOrigin> security_origin = origin->IsolatedCopy(); security_origin->SetOpaqueOriginIsPotentiallyTrustworthy( is_potentially_trustworthy_unique_origin); security_context_.SetReplicatedOrigin(security_origin); ApplyReplicatedPermissionsPolicyHeader(); // If the origin of a remote frame changed, the accessibility object for the // owner element now points to a different child. // // TODO(dmazzoni, dcheng): there's probably a better way to solve this. // Run SitePerProcessAccessibilityBrowserTest.TwoCrossSiteNavigations to // ensure an alternate fix works. http://crbug.com/566222 FrameOwner* owner = Owner(); HTMLElement* owner_element = DynamicTo<HTMLFrameOwnerElement>(owner); if (owner_element) { AXObjectCache* cache = owner_element->GetDocument().ExistingAXObjectCache(); if (cache) cache->ChildrenChanged(owner_element); } } bool RemoteFrame::IsAdFrame() const { return is_ad_frame_; } void RemoteFrame::SetReplicatedIsAdFrame(bool is_ad_frame) { is_ad_frame_ = is_ad_frame; } void RemoteFrame::SetReplicatedName(const String& name, const String& unique_name) { Tree().SetName(AtomicString(name)); unique_name_ = unique_name; } void RemoteFrame::DispatchLoadEventForFrameOwner() { DCHECK(Owner()->IsLocal()); Owner()->DispatchLoad(); } void RemoteFrame::Collapse(bool collapsed) { FrameOwner* owner = Owner(); To<HTMLFrameOwnerElement>(owner)->SetCollapsed(collapsed); } void RemoteFrame::Focus() { FocusImpl(); } void RemoteFrame::SetHadStickyUserActivationBeforeNavigation(bool value) { Frame::SetHadStickyUserActivationBeforeNavigation(value); } void RemoteFrame::SetNeedsOcclusionTracking(bool needs_tracking) { View()->SetNeedsOcclusionTracking(needs_tracking); } void RemoteFrame::BubbleLogicalScroll(mojom::blink::ScrollDirection direction, ui::ScrollGranularity granularity) { LocalFrame* parent_frame = nullptr; if (auto* parent = DynamicTo<LocalFrame>(Parent())) { parent_frame = parent; } else { // This message can be received by an embedded frame tree's placeholder // RemoteFrame in which case Parent() is not connected to the outer frame // tree. auto* owner_element = DynamicTo<HTMLFrameOwnerElement>(Owner()); DCHECK(owner_element); parent_frame = owner_element->GetDocument().GetFrame(); } DCHECK(parent_frame); parent_frame->BubbleLogicalScrollFromChildFrame(direction, granularity, this); } void RemoteFrame::UpdateUserActivationState( mojom::blink::UserActivationUpdateType update_type, mojom::blink::UserActivationNotificationType notification_type) { switch (update_type) { case mojom::blink::UserActivationUpdateType::kNotifyActivation: NotifyUserActivationInFrameTree(notification_type); break; case mojom::blink::UserActivationUpdateType::kConsumeTransientActivation: ConsumeTransientUserActivationInFrameTree(); break; case mojom::blink::UserActivationUpdateType::kClearActivation: ClearUserActivationInFrameTree(); break; case mojom::blink::UserActivationUpdateType:: kNotifyActivationPendingBrowserVerification: NOTREACHED() << "Unexpected UserActivationUpdateType from browser"; break; } } void RemoteFrame::SetEmbeddingToken( const base::UnguessableToken& embedding_token) { DCHECK(IsA<HTMLFrameOwnerElement>(Owner())); Frame::SetEmbeddingToken(embedding_token); } void RemoteFrame::SetPageFocus(bool is_focused) { WebViewImpl* web_view = To<WebViewImpl>(WebFrame::FromCoreFrame(this)->View()); if (is_focused) { web_view->SetIsActive(true); } web_view->SetPageFocus(is_focused); } void RemoteFrame::ScrollRectToVisible( const gfx::RectF& rect_to_scroll, mojom::blink::ScrollIntoViewParamsPtr params) { Element* owner_element = DeprecatedLocalOwner(); LayoutObject* owner_object = owner_element->GetLayoutObject(); if (!owner_object) { // The LayoutObject could be nullptr by the time we get here. For instance // <iframe>'s style might have been set to 'display: none' right after // scrolling starts in the OOPIF's process (see https://crbug.com/777811). return; } scroll_into_view_util::ConvertParamsToParentFrame( params, rect_to_scroll, *owner_object, *owner_object->View()); PhysicalRect absolute_rect = owner_object->LocalToAncestorRect( PhysicalRect::EnclosingRect(rect_to_scroll), owner_object->View()); scroll_into_view_util::ScrollRectToVisible(*owner_object, absolute_rect, std::move(params), /*from_remote_frame=*/true); } void RemoteFrame::IntrinsicSizingInfoOfChildChanged( mojom::blink::IntrinsicSizingInfoPtr info) { FrameOwner* owner = Owner(); // Only communication from HTMLPluginElement-owned subframes is allowed // at present. This includes <embed> and <object> tags. if (!owner || !owner->IsPlugin()) return; // TODO(https://crbug.com/1044304): Should either remove the native // C++ Blink type and use the Mojo type everywhere or typemap the // Mojo type to the pre-existing native C++ Blink type. IntrinsicSizingInfo sizing_info; sizing_info.size = info->size; sizing_info.aspect_ratio = info->aspect_ratio; sizing_info.has_width = info->has_width; sizing_info.has_height = info->has_height; View()->SetIntrinsicSizeInfo(sizing_info); owner->IntrinsicSizingInfoChanged(); } // Update the proxy's SecurityContext with new sandbox flags or permissions // policy that were set during navigation. Unlike changes to the FrameOwner, // which are handled by RemoteFrame::DidUpdateFramePolicy, these changes should // be considered effective immediately. // // These flags / policy are needed on the remote frame's SecurityContext to // ensure that sandbox flags and permissions policy are inherited properly if // this proxy ever parents a local frame. void RemoteFrame::DidSetFramePolicyHeaders( network::mojom::blink::WebSandboxFlags sandbox_flags, const WTF::Vector<ParsedPermissionsPolicyDeclaration>& parsed_permissions_policy) { SetReplicatedSandboxFlags(sandbox_flags); // Convert from WTF::Vector<ParsedPermissionsPolicyDeclaration> // to std::vector<ParsedPermissionsPolicyDeclaration>, since // ParsedPermissionsPolicy is an alias for the later. // // TODO(crbug.com/1047273): Remove this conversion by switching // ParsedPermissionsPolicy to operate over Vector ParsedPermissionsPolicy parsed_permissions_policy_copy( parsed_permissions_policy.size()); for (wtf_size_t i = 0; i < parsed_permissions_policy.size(); ++i) parsed_permissions_policy_copy[i] = parsed_permissions_policy[i]; SetReplicatedPermissionsPolicyHeader(parsed_permissions_policy_copy); } // Update the proxy's FrameOwner with new sandbox flags and container policy // that were set by its parent in another process. // // Normally, when a frame's sandbox attribute is changed dynamically, the // frame's FrameOwner is updated with the new sandbox flags right away, while // the frame's SecurityContext is updated when the frame is navigated and the // new sandbox flags take effect. // // Currently, there is no use case for a proxy's pending FrameOwner sandbox // flags, so there's no message sent to proxies when the sandbox attribute is // first updated. Instead, the active flags are updated when they take effect, // by OnDidSetActiveSandboxFlags. The proxy's FrameOwner flags are updated here // with the caveat that the FrameOwner won't learn about updates to its flags // until they take effect. void RemoteFrame::DidUpdateFramePolicy(const FramePolicy& frame_policy) { // At the moment, this is only used to replicate sandbox flags and container // policy for frames with a remote owner. SECURITY_CHECK(IsA<RemoteFrameOwner>(Owner())); To<RemoteFrameOwner>(Owner())->SetFramePolicy(frame_policy); } void RemoteFrame::UpdateOpener( const absl::optional<blink::FrameToken>& opener_frame_token) { Frame* opener_frame = nullptr; if (opener_frame_token) opener_frame = Frame::ResolveFrame(opener_frame_token.value()); SetOpenerDoNotNotify(opener_frame); } gfx::Size RemoteFrame::GetOutermostMainFrameSize() const { HTMLFrameOwnerElement* owner = DeprecatedLocalOwner(); DCHECK(owner); DCHECK(owner->GetDocument().GetFrame()); return owner->GetDocument().GetFrame()->GetOutermostMainFrameSize(); } gfx::Point RemoteFrame::GetOutermostMainFrameScrollPosition() const { HTMLFrameOwnerElement* owner = DeprecatedLocalOwner(); DCHECK(owner); DCHECK(owner->GetDocument().GetFrame()); return owner->GetDocument().GetFrame()->GetOutermostMainFrameScrollPosition(); } void RemoteFrame::SetOpener(Frame* opener_frame) { if (Opener() == opener_frame) return; // A proxy shouldn't normally be disowning its opener. It is possible to // get here when a proxy that is being detached clears its opener, in // which case there is no need to notify the browser process. if (opener_frame) { // Only a LocalFrame (i.e., the caller of window.open) should be able to // update another frame's opener. DCHECK(opener_frame->IsLocalFrame()); GetRemoteFrameHostRemote().DidChangeOpener( opener_frame ? absl::optional<blink::LocalFrameToken>( opener_frame->GetFrameToken().GetAs<LocalFrameToken>()) : absl::nullopt); } SetOpenerDoNotNotify(opener_frame); } void RemoteFrame::UpdateTextAutosizerPageInfo( mojom::blink::TextAutosizerPageInfoPtr mojo_remote_page_info) { // Only propagate the remote page info if our main frame is remote. DCHECK(IsMainFrame()); Frame* root_frame = GetPage()->MainFrame(); DCHECK(root_frame->IsRemoteFrame()); if (*mojo_remote_page_info == GetPage()->TextAutosizerPageInfo()) return; GetPage()->SetTextAutosizerPageInfo(*mojo_remote_page_info); TextAutosizer::UpdatePageInfoInAllFrames(root_frame); } void RemoteFrame::WasAttachedAsRemoteMainFrame( mojo::PendingAssociatedReceiver<mojom::blink::RemoteMainFrame> main_frame) { main_frame_receiver_.Bind(std::move(main_frame), task_runner_); } const viz::LocalSurfaceId& RemoteFrame::GetLocalSurfaceId() const { return parent_local_surface_id_allocator_->GetCurrentLocalSurfaceId(); } void RemoteFrame::SetCcLayerForTesting(scoped_refptr<cc::Layer> layer, bool is_surface_layer) { SetCcLayer(layer, is_surface_layer); } viz::FrameSinkId RemoteFrame::GetFrameSinkId() { return frame_sink_id_; } void RemoteFrame::SetFrameSinkId(const viz::FrameSinkId& frame_sink_id) { remote_process_gone_ = false; // The same ParentLocalSurfaceIdAllocator cannot provide LocalSurfaceIds for // two different frame sinks, so recreate it here. if (frame_sink_id_ != frame_sink_id) { parent_local_surface_id_allocator_ = std::make_unique<viz::ParentLocalSurfaceIdAllocator>(); } frame_sink_id_ = frame_sink_id; // Resend the FrameRects and allocate a new viz::LocalSurfaceId when the view // changes. ResendVisualProperties(); } void RemoteFrame::ChildProcessGone() { remote_process_gone_ = true; compositing_helper_->ChildFrameGone( ancestor_widget_->GetOriginalScreenInfo().device_scale_factor); } bool RemoteFrame::IsIgnoredForHitTest() const { HTMLFrameOwnerElement* owner = DeprecatedLocalOwner(); if (!owner || !owner->GetLayoutObject()) return false; return owner->OwnerType() == FrameOwnerElementType::kPortal || !visible_to_hit_testing_; } void RemoteFrame::AdvanceFocus(mojom::blink::FocusType type, LocalFrame* source) { GetRemoteFrameHostRemote().AdvanceFocus(type, source->GetLocalFrameToken()); } bool RemoteFrame::DetachChildren() { using FrameVector = HeapVector<Member<Frame>>; FrameVector children_to_detach; children_to_detach.reserve(Tree().ChildCount()); for (Frame* child = Tree().FirstChild(); child; child = child->Tree().NextSibling()) children_to_detach.push_back(child); for (const auto& child : children_to_detach) child->Detach(FrameDetachType::kRemove); return !!Client(); } void RemoteFrame::ApplyReplicatedPermissionsPolicyHeader() { const PermissionsPolicy* parent_permissions_policy = nullptr; if (Frame* parent_frame = Parent()) { parent_permissions_policy = parent_frame->GetSecurityContext()->GetPermissionsPolicy(); } ParsedPermissionsPolicy container_policy; if (Owner()) container_policy = Owner()->GetFramePolicy().container_policy; security_context_.InitializePermissionsPolicy( permissions_policy_header_, container_policy, parent_permissions_policy); } bool RemoteFrame::SynchronizeVisualProperties(bool propagate) { if (!GetFrameSinkId().is_valid() || remote_process_gone_) return false; bool capture_sequence_number_changed = sent_visual_properties_ && sent_visual_properties_->capture_sequence_number != pending_visual_properties_.capture_sequence_number; if (view_) { pending_visual_properties_.compositor_viewport = view_->GetCompositingRect(); pending_visual_properties_.compositing_scale_factor = view_->GetCompositingScaleFactor(); } bool synchronized_props_changed = !sent_visual_properties_ || sent_visual_properties_->auto_resize_enabled != pending_visual_properties_.auto_resize_enabled || sent_visual_properties_->min_size_for_auto_resize != pending_visual_properties_.min_size_for_auto_resize || sent_visual_properties_->max_size_for_auto_resize != pending_visual_properties_.max_size_for_auto_resize || sent_visual_properties_->local_frame_size != pending_visual_properties_.local_frame_size || sent_visual_properties_->rect_in_local_root.size() != pending_visual_properties_.rect_in_local_root.size() || sent_visual_properties_->screen_infos != pending_visual_properties_.screen_infos || sent_visual_properties_->zoom_level != pending_visual_properties_.zoom_level || sent_visual_properties_->page_scale_factor != pending_visual_properties_.page_scale_factor || sent_visual_properties_->compositing_scale_factor != pending_visual_properties_.compositing_scale_factor || sent_visual_properties_->cursor_accessibility_scale_factor != pending_visual_properties_.cursor_accessibility_scale_factor || sent_visual_properties_->is_pinch_gesture_active != pending_visual_properties_.is_pinch_gesture_active || sent_visual_properties_->visible_viewport_size != pending_visual_properties_.visible_viewport_size || sent_visual_properties_->compositor_viewport != pending_visual_properties_.compositor_viewport || sent_visual_properties_->root_widget_window_segments != pending_visual_properties_.root_widget_window_segments || sent_visual_properties_->capture_sequence_number != pending_visual_properties_.capture_sequence_number; if (synchronized_props_changed) parent_local_surface_id_allocator_->GenerateId(); pending_visual_properties_.local_surface_id = GetLocalSurfaceId(); viz::SurfaceId surface_id(frame_sink_id_, pending_visual_properties_.local_surface_id); DCHECK(ancestor_widget_); DCHECK(surface_id.is_valid()); DCHECK(!remote_process_gone_); compositing_helper_->SetSurfaceId(surface_id, capture_sequence_number_changed); bool rect_changed = !sent_visual_properties_ || sent_visual_properties_->rect_in_local_root != pending_visual_properties_.rect_in_local_root; bool visual_properties_changed = synchronized_props_changed || rect_changed; if (visual_properties_changed && propagate) { GetRemoteFrameHostRemote().SynchronizeVisualProperties( pending_visual_properties_); RecordSentVisualProperties(); } return visual_properties_changed; } void RemoteFrame::RecordSentVisualProperties() { sent_visual_properties_ = pending_visual_properties_; TRACE_EVENT_WITH_FLOW2( TRACE_DISABLED_BY_DEFAULT("viz.surface_id_flow"), "RenderFrameProxy::SynchronizeVisualProperties Send Message", TRACE_ID_GLOBAL( pending_visual_properties_.local_surface_id.submission_trace_id()), TRACE_EVENT_FLAG_FLOW_OUT, "message", "FrameHostMsg_SynchronizeVisualProperties", "local_surface_id", pending_visual_properties_.local_surface_id.ToString()); } void RemoteFrame::ResendVisualProperties() { sent_visual_properties_ = absl::nullopt; SynchronizeVisualProperties(); } void RemoteFrame::DidUpdateVisualProperties( const cc::RenderFrameMetadata& metadata) { if (!parent_local_surface_id_allocator_->UpdateFromChild( metadata.local_surface_id.value_or(viz::LocalSurfaceId()))) { return; } // The viz::LocalSurfaceId has changed so we call SynchronizeVisualProperties // here to embed it. SynchronizeVisualProperties(); } void RemoteFrame::SetViewportIntersection( const mojom::blink::ViewportIntersectionState& intersection_state) { absl::optional<FrameVisualProperties> visual_properties; if (SynchronizeVisualProperties(/*propagate=*/false)) { visual_properties.emplace(pending_visual_properties_); RecordSentVisualProperties(); } GetRemoteFrameHostRemote().UpdateViewportIntersection( intersection_state.Clone(), visual_properties); } void RemoteFrame::UpdateCompositedLayerBounds() { if (cc_layer_) cc_layer_->SetBounds(pending_visual_properties_.local_frame_size); } void RemoteFrame::DidChangeScreenInfos( const display::ScreenInfos& screen_infos) { pending_visual_properties_.screen_infos = screen_infos; SynchronizeVisualProperties(); } void RemoteFrame::ZoomLevelChanged(double zoom_level) { pending_visual_properties_.zoom_level = zoom_level; SynchronizeVisualProperties(); } void RemoteFrame::DidChangeRootWindowSegments( const std::vector<gfx::Rect>& root_widget_window_segments) { pending_visual_properties_.root_widget_window_segments = std::move(root_widget_window_segments); SynchronizeVisualProperties(); } void RemoteFrame::PageScaleFactorChanged(float page_scale_factor, bool is_pinch_gesture_active) { pending_visual_properties_.page_scale_factor = page_scale_factor; pending_visual_properties_.is_pinch_gesture_active = is_pinch_gesture_active; SynchronizeVisualProperties(); } void RemoteFrame::DidChangeVisibleViewportSize( const gfx::Size& visible_viewport_size) { pending_visual_properties_.visible_viewport_size = visible_viewport_size; SynchronizeVisualProperties(); } void RemoteFrame::UpdateCaptureSequenceNumber( uint32_t capture_sequence_number) { pending_visual_properties_.capture_sequence_number = capture_sequence_number; SynchronizeVisualProperties(); } void RemoteFrame::CursorAccessibilityScaleFactorChanged(float scale_factor) { pending_visual_properties_.cursor_accessibility_scale_factor = scale_factor; SynchronizeVisualProperties(); } void RemoteFrame::EnableAutoResize(const gfx::Size& min_size, const gfx::Size& max_size) { pending_visual_properties_.auto_resize_enabled = true; pending_visual_properties_.min_size_for_auto_resize = min_size; pending_visual_properties_.max_size_for_auto_resize = max_size; SynchronizeVisualProperties(); } void RemoteFrame::DisableAutoResize() { pending_visual_properties_.auto_resize_enabled = false; SynchronizeVisualProperties(); } void RemoteFrame::CreateRemoteChild( const RemoteFrameToken& token, const absl::optional<FrameToken>& opener_frame_token, mojom::blink::TreeScopeType tree_scope_type, mojom::blink::FrameReplicationStatePtr replication_state, mojom::blink::FrameOwnerPropertiesPtr owner_properties, bool is_loading, const base::UnguessableToken& devtools_frame_token, mojom::blink::RemoteFrameInterfacesFromBrowserPtr remote_frame_interfaces) { Client()->CreateRemoteChild( token, opener_frame_token, tree_scope_type, std::move(replication_state), std::move(owner_properties), is_loading, devtools_frame_token, std::move(remote_frame_interfaces)); } void RemoteFrame::CreateRemoteChildren( Vector<mojom::blink::CreateRemoteChildParamsPtr> params) { Client()->CreateRemoteChildren(params); } } // namespace blink
dd4239bcf35d0c6bbc9a8fcc5b2a67f0cca32faa
6f8a060973c7a12316e14b4de80ca38de745fd40
/clang_delta/ClassTemplateToClass.cpp
2039882db7fe14d946ea547673695b84b384f6de
[ "NCSA", "LicenseRef-scancode-unknown-license-reference" ]
permissive
csmith-project/creduce
f88cd0ea5a01ff5d75ef43c460ce762392e14076
92502474f38e37d17a3404ea69fb4b6bb42b4233
refs/heads/master
2023-06-21T12:39:00.661693
2023-06-08T08:21:57
2023-06-08T08:21:57
3,572,572
918
118
NOASSERTION
2023-06-08T08:20:58
2012-02-28T15:55:07
C++
UTF-8
C++
false
false
11,287
cpp
ClassTemplateToClass.cpp
//===----------------------------------------------------------------------===// // // Copyright (c) 2012, 2013, 2014, 2015, 2017, 2019 The University of Utah // All rights reserved. // // This file is distributed under the University of Illinois Open Source // License. See the file COPYING for details. // //===----------------------------------------------------------------------===// #if HAVE_CONFIG_H # include <config.h> #endif #include "ClassTemplateToClass.h" #include "clang/AST/RecursiveASTVisitor.h" #include "clang/AST/ASTContext.h" #include "clang/Basic/SourceManager.h" #include "TransformationManager.h" using namespace clang; static const char *DescriptionMsg = "Change a class template to a class if this class template: \n\ * has only one parameter, and \n\ * the parameter is unused. \n"; static RegisterTransformation<ClassTemplateToClass> Trans("class-template-to-class", DescriptionMsg); class ClassTemplateToClassASTVisitor : public RecursiveASTVisitor<ClassTemplateToClassASTVisitor> { public: explicit ClassTemplateToClassASTVisitor(ClassTemplateToClass *Instance) : ConsumerInstance(Instance) { } bool VisitClassTemplateDecl(ClassTemplateDecl *D); private: ClassTemplateToClass *ConsumerInstance; }; class ClassTemplateToClassSpecializationTypeRewriteVisitor : public RecursiveASTVisitor<ClassTemplateToClassSpecializationTypeRewriteVisitor> { public: explicit ClassTemplateToClassSpecializationTypeRewriteVisitor( ClassTemplateToClass *Instance) : ConsumerInstance(Instance) { } bool VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc Loc); private: ClassTemplateToClass *ConsumerInstance; }; namespace { class TemplateParameterTypeVisitor : public RecursiveASTVisitor<TemplateParameterTypeVisitor> { public: typedef llvm::SmallPtrSet<TemplateTypeParmDecl *, 8> TypeParmDeclSet; typedef llvm::SmallPtrSet<TemplateName *, 8> TemplateNameSet; ~TemplateParameterTypeVisitor(void) { for (TemplateNameSet::iterator I = TmplNames.begin(), E = TmplNames.end(); I != E; ++I) delete (*I); } explicit TemplateParameterTypeVisitor(ASTContext *Ctx) : Context(Ctx) { } bool VisitTemplateTypeParmType(TemplateTypeParmType *Ty); bool VisitTemplateSpecializationType(TemplateSpecializationType *Ty); bool isAUsedParameter(NamedDecl *ND); private: TypeParmDeclSet ParmDecls; TemplateNameSet TmplNames; ASTContext *Context; }; bool TemplateParameterTypeVisitor::VisitTemplateTypeParmType( TemplateTypeParmType *Ty) { TemplateTypeParmDecl *D = Ty->getDecl(); ParmDecls.insert(D); return true; } bool TemplateParameterTypeVisitor::VisitTemplateSpecializationType( TemplateSpecializationType *Ty) { TemplateName Name = Ty->getTemplateName(); if (Name.getKind() != TemplateName::Template) return true; TemplateName *NewName = new TemplateName(Name.getAsTemplateDecl()); TmplNames.insert(NewName); return true; } bool TemplateParameterTypeVisitor::isAUsedParameter(NamedDecl *ND) { if (TemplateTypeParmDecl *ParmD = dyn_cast<TemplateTypeParmDecl>(ND)) { return ParmDecls.count(ParmD); } if (TemplateTemplateParmDecl *ParmD = dyn_cast<TemplateTemplateParmDecl>(ND)) { TemplateName Name(ParmD); for (TemplateNameSet::iterator I = TmplNames.begin(), E = TmplNames.end(); I != E; ++I) { if (Context->hasSameTemplateName(*(*I), Name)) return true; } return false; } TransAssert(0 && "Uncatched Template Parameter Kind!"); return false; } } bool ClassTemplateToClassASTVisitor::VisitClassTemplateDecl( ClassTemplateDecl *D) { if (ConsumerInstance->isInIncludedFile(D)) return true; ClassTemplateDecl *CanonicalD = D->getCanonicalDecl(); if (ConsumerInstance->VisitedDecls.count(CanonicalD)) return true; ConsumerInstance->VisitedDecls.insert(CanonicalD); if (ConsumerInstance->isValidClassTemplateDecl(D)) { ConsumerInstance->ValidInstanceNum++; if (ConsumerInstance->ValidInstanceNum == ConsumerInstance->TransformationCounter) { ConsumerInstance->TheClassTemplateDecl = CanonicalD; ConsumerInstance->TheTemplateName = new TemplateName(CanonicalD); } } return true; } bool ClassTemplateToClassSpecializationTypeRewriteVisitor:: VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc Loc) { const TemplateSpecializationType *Ty = dyn_cast<TemplateSpecializationType>(Loc.getTypePtr()); TransAssert(Ty && "Invalid TemplateSpecializationType!"); TemplateName TmplName = Ty->getTemplateName(); if (!ConsumerInstance->referToTheTemplateDecl(TmplName)) return true; SourceLocation TmplKeyLoc = Loc.getTemplateKeywordLoc(); if (TmplKeyLoc.isValid()) ConsumerInstance->TheRewriter.RemoveText(TmplKeyLoc, 8); // it's necessary to check the validity of locations, otherwise // we will get assertion errors... // note that some implicit typeloc has been visited by Clang, e.g. // template < typename > struct A { }; // struct B:A < int > { // B ( ) { } // }; // base initializer A<int> is not presented in the code but visited, // so, we need to make sure locations are valid. SourceLocation LAngleLoc = Loc.getLAngleLoc(); if (LAngleLoc.isInvalid()) return true; SourceLocation RAngleLoc = Loc.getRAngleLoc(); if (RAngleLoc.isInvalid()) return true; ConsumerInstance->TheRewriter.RemoveText(SourceRange(LAngleLoc, RAngleLoc)); return true; } void ClassTemplateToClass::Initialize(ASTContext &context) { Transformation::Initialize(context); CollectionVisitor = new ClassTemplateToClassASTVisitor(this); RewriteVisitor = new ClassTemplateToClassSpecializationTypeRewriteVisitor(this); } void ClassTemplateToClass::HandleTranslationUnit(ASTContext &Ctx) { if (TransformationManager::isCLangOpt() || TransformationManager::isOpenCLLangOpt()) { ValidInstanceNum = 0; } else { CollectionVisitor->TraverseDecl(Ctx.getTranslationUnitDecl()); } if (QueryInstanceOnly) return; if (TransformationCounter > ValidInstanceNum) { TransError = TransMaxInstanceError; return; } TransAssert(TheClassTemplateDecl && "NULL TheClassTemplateDecl!"); TransAssert(RewriteVisitor && "NULL RewriteVisitor!"); Ctx.getDiagnostics().setSuppressAllDiagnostics(false); rewriteClassTemplateDecls(); rewriteClassTemplatePartialSpecs(); RewriteVisitor->TraverseDecl(Ctx.getTranslationUnitDecl()); if (Ctx.getDiagnostics().hasErrorOccurred() || Ctx.getDiagnostics().hasFatalErrorOccurred()) TransError = TransInternalError; } void ClassTemplateToClass::removeTemplateAndParameter(SourceLocation LocStart, const TemplateParameterList *TPList) { SourceLocation LocEnd = TPList->getRAngleLoc(); TheRewriter.RemoveText(SourceRange(LocStart, LocEnd)); } void ClassTemplateToClass::rewriteClassTemplateDecls(void) { for (ClassTemplateDecl::redecl_iterator I = TheClassTemplateDecl->redecls_begin(), E = TheClassTemplateDecl->redecls_end(); I != E; ++I) { const TemplateParameterList *TPList = (*I)->getTemplateParameters(); SourceLocation LocStart = (*I)->getBeginLoc(); removeTemplateAndParameter(LocStart, TPList); } } void ClassTemplateToClass::rewriteClassTemplatePartialSpecs(void) { SmallVector<ClassTemplatePartialSpecializationDecl *, 10> PartialDecls; TheClassTemplateDecl->getPartialSpecializations(PartialDecls); for (SmallVector<ClassTemplatePartialSpecializationDecl *, 10>::iterator I = PartialDecls.begin(), E = PartialDecls.end(); I != E; ++I) { const ClassTemplatePartialSpecializationDecl *PartialD = (*I); removeTemplateAndParameter(PartialD->getSourceRange().getBegin(), PartialD->getTemplateParameters()); const ASTTemplateArgumentListInfo *ArgList = PartialD->getTemplateArgsAsWritten(); TransAssert(ArgList && "Invalid ArgList!"); const TemplateArgumentLoc *ArgLocs = ArgList->getTemplateArgs(); TransAssert(ArgLocs && "Invalid ArcLogs!"); unsigned NumArgs = ArgList->NumTemplateArgs; TransAssert((NumArgs > 0) && "Invalid NumArgs!"); const TemplateArgumentLoc FirstArgLoc = ArgLocs[0]; SourceLocation StartLoc = FirstArgLoc.getSourceRange().getBegin(); const TemplateArgumentLoc LastArgLoc = ArgLocs[NumArgs - 1]; SourceRange LastRange = LastArgLoc.getSourceRange(); SourceLocation EndLoc = RewriteHelper->getEndLocationUntil(LastRange, '>'); RewriteHelper->removeTextFromLeftAt(SourceRange(StartLoc, EndLoc), '<', EndLoc); } } bool ClassTemplateToClass::isUsedNamedDecl(NamedDecl *ND, Decl *D) { TemplateParameterTypeVisitor ParamVisitor(Context); ParamVisitor.TraverseDecl(D); return ParamVisitor.isAUsedParameter(ND); } bool ClassTemplateToClass::hasUsedNameDecl( ClassTemplatePartialSpecializationDecl *PartialD) { if (!PartialD->isCompleteDefinition()) return false; llvm::SmallPtrSet<NamedDecl *, 8> Params; TemplateParameterList *PartialTPList = PartialD->getTemplateParameters(); for (unsigned PI = 0; PI < PartialTPList->size(); ++PI) { NamedDecl *ND = PartialTPList->getParam(PI); if (dyn_cast<NonTypeTemplateParmDecl>(ND)) continue; Params.insert(ND); } TemplateParameterTypeVisitor ParamVisitor(Context); // Skip visiting parameters and arguments for (CXXRecordDecl::base_class_iterator I = PartialD->bases_begin(), E = PartialD->bases_end(); I != E; ++I) { ParamVisitor.TraverseType(I->getType()); } DeclContext *Ctx = dyn_cast<DeclContext>(PartialD); for (DeclContext::decl_iterator DI = Ctx->decls_begin(), DE = Ctx->decls_end(); DI != DE; ++DI) { ParamVisitor.TraverseDecl(*DI); } for (llvm::SmallPtrSet<NamedDecl *, 8>::iterator I = Params.begin(), E = Params.end(); I != E; ++I) { if (ParamVisitor.isAUsedParameter(*I)) return true; } return false; } bool ClassTemplateToClass::isValidClassTemplateDecl(ClassTemplateDecl *TmplD) { TemplateParameterList *TPList = TmplD->getTemplateParameters(); if (TPList->size() != 1) return false; CXXRecordDecl *CXXRD = TmplD->getTemplatedDecl(); CXXRecordDecl *Def = CXXRD->getDefinition(); if (!Def) return true; NamedDecl *ND = TPList->getParam(0); if (dyn_cast<NonTypeTemplateParmDecl>(ND)) return true; if (isUsedNamedDecl(ND, Def)) return false; SmallVector<ClassTemplatePartialSpecializationDecl *, 10> PartialDecls; TmplD->getPartialSpecializations(PartialDecls); for (SmallVector<ClassTemplatePartialSpecializationDecl *, 10>::iterator I = PartialDecls.begin(), E = PartialDecls.end(); I != E; ++I) { if (hasUsedNameDecl(*I)) return false; } return true; } bool ClassTemplateToClass::referToTheTemplateDecl(TemplateName TmplName) { return Context->hasSameTemplateName(*TheTemplateName, TmplName); } ClassTemplateToClass::~ClassTemplateToClass(void) { delete TheTemplateName; delete CollectionVisitor; delete RewriteVisitor; }
d0a96bffe671e922c345fb42b659b9d5456dbc48
6ee8d5b314917de6ede2d95e36c5c4f0e7dcdf34
/src/ClassifierMultiPlatform.cpp
4e7c9b093ccaf481bb6dfae11f581937376b18e9
[]
no_license
salehjg/DGCNN-GPGPU
a22b842b0a022492f3f009dd85ceee6d680bf3b2
d62b19aa9002d6601124792f85e982dbb7ee47c9
refs/heads/master
2023-02-06T06:02:53.544876
2018-12-01T18:02:41
2018-12-01T18:02:41
325,083,035
3
0
null
null
null
null
UTF-8
C++
false
false
2,116
cpp
ClassifierMultiPlatform.cpp
// // Created by saleh on 9/3/18. // #include "ModelArchTop05.h" #include <iostream> using namespace std; void CalculateAccuracy(TensorF* scores, TensorI* labels, int B, int classCount){ //find argmax(net) and compute bool array of corrects. bool *correct = new bool[B]; float accu =0; cout<<"STATUS: "<<"Computing Accuracy..."<<endl; { float max_cte = -numeric_limits<float>::infinity(); float max = 0; int max_indx=-1; int *a1 = new int[B]; for(int b=0;b<B;b++){ max = max_cte; for(int c=0;c<classCount;c++){ if(max < scores->_buff[b*classCount+c] ){ max = scores->_buff[b*classCount+c]; max_indx = c; } } //set maximum score for current batch index a1[b]=max_indx; } for(int b=0;b<B;b++){ if(a1[b]==(int)labels->_buff[b]){ correct[b]=true; } else{ correct[b]=false; } } free(a1); } //---------------------------------------------------------------------------------------- // compute accuracy using correct array. { float correct_cnt=0; for(int b=0;b<B;b++){ if(correct[b]==true) correct_cnt++; } accu = correct_cnt / (float)B; cout<<"Correct Count: "<< correct_cnt <<endl; cout<<"Accuracy: "<< accu<<endl; } } int main(){ WorkScheduler scheduler; int batchsize=5; ModelArchTop05 modelArchTop(0,batchsize,1024,20); modelArchTop.SetModelInput_data(REPO_DIR "/data/dataset/dataset_B5_pcl.npy"); modelArchTop.SetModelInput_labels(REPO_DIR"/data/dataset/dataset_B5_labels_int32.npy"); double timerStart = seconds(); TensorF* classScores = modelArchTop.Execute(scheduler); cout<< "Total model execution time with "<< batchsize <<" as batchsize: " << seconds() -timerStart<<" S"<<endl; CalculateAccuracy(classScores,modelArchTop.GetLabels(),modelArchTop.GetBatchSize(),40); }
e0fb657d9691f95b619db07cb3d18d67df2c6587
b0a86f997a3d579feee3531606e72f82f11099e2
/iOS/of_preRelease_v007_iphone/addons/ofxBullet/examples/Events/src/testApp.cpp
bbaa1a87bcccea1b7b83013519b806ad4f45b8da
[ "MIT" ]
permissive
matthewvroman/RGBlaster
abc9f4cd8399cdc2aeffc7ac6f2bddf47f8ba7ff
36aa1791959ecd0945b6a71504f01c20d19140e3
refs/heads/master
2021-01-23T06:26:29.638404
2012-05-11T22:06:47
2012-05-11T22:06:47
3,007,449
1
0
null
null
null
null
UTF-8
C++
false
false
8,347
cpp
testApp.cpp
#include "testApp.h" //-------------------------------------------------------------- void testApp::setup() { ofSetFrameRate(60); ofSetVerticalSync(true); ofBackground( 10, 10, 10); camera.setPosition(ofVec3f(0, -4.f, -40.f)); camera.lookAt(ofVec3f(0, 0, 0), ofVec3f(0, -1, 0)); camera.cacheMatrices(true); world.setup(); // enables mouse Pick events // world.enableGrabbing(); ofAddListener(world.MOUSE_PICK_EVENT, this, &testApp::mousePickEvent); world.enableCollisionEvents(); ofAddListener(world.COLLISION_EVENT, this, &testApp::onCollision); world.setCamera(&camera); world.setGravity( ofVec3f(0, 25., 0) ); int ii = 0; // let's make a shape that all of the rigid bodies use, since it is faster // // though all of the spheres will be the same radius // sphereShape = ofBtGetSphereCollisionShape(2.5); for (int i = 0; i < 4; i++) { shapes.push_back( new ofxBulletSphere() ); ii = shapes.size()-1; ((ofxBulletSphere*)shapes[ii])->init(sphereShape); // no need to pass radius, since we already created it in the sphereShape // ((ofxBulletSphere*)shapes[ii])->create(world.world, ofVec3f(ofRandom(-3, 3), ofRandom(-2, 2), ofRandom(-1, 1)), 0.1); shapes[ii]->setActivationState( DISABLE_DEACTIVATION ); shapes[ii]->add(); bColliding.push_back( false ); } // now lets add some boxes // boxShape = ofBtGetBoxCollisionShape(2.65, 2.65, 2.65); for (int i = 0; i < 4; i++) { shapes.push_back( new ofxBulletBox() ); ii = shapes.size()-1; ((ofxBulletBox*)shapes[ii])->init(boxShape); ((ofxBulletBox*)shapes[ii])->create(world.world, ofVec3f(ofRandom(-3, 3), ofRandom(-2, 2), ofRandom(-1, 1)), 0.2); shapes[ii]->setActivationState( DISABLE_DEACTIVATION ); shapes[ii]->add(); bColliding.push_back( false ); } ofVec3f startLoc; ofPoint dimens; boundsWidth = 30.; float hwidth = boundsWidth*.5; float depth = 2.; float hdepth = depth*.5; for(int i = 0; i < 6; i++) { bounds.push_back( new ofxBulletBox() ); if(i == 0) { // ground // startLoc.set( 0., hwidth+hdepth, 0. ); dimens.set(boundsWidth, depth, boundsWidth); } else if (i == 1) { // back wall // startLoc.set(0, 0, hwidth+hdepth); dimens.set(boundsWidth, boundsWidth, depth); } else if (i == 2) { // right wall // startLoc.set(hwidth+hdepth, 0, 0.); dimens.set(depth, boundsWidth, boundsWidth); } else if (i == 3) { // left wall // startLoc.set(-hwidth-hdepth, 0, 0.); dimens.set(depth, boundsWidth, boundsWidth); } else if (i == 4) { // ceiling // startLoc.set(0, -hwidth-hdepth, 0.); dimens.set(boundsWidth, depth, boundsWidth); } else if (i == 5) { // front wall // startLoc.set(0, 0, -hwidth-hdepth); dimens.set(boundsWidth, boundsWidth, depth); } bounds[i]->create( world.world, startLoc, 0., dimens.x, dimens.y, dimens.z ); bounds[i]->setProperties(.25, .95); bounds[i]->add(); } mousePickIndex = -1; bDrawDebug = false; bRenderShapes = true; bAddCenterAttract = true; bSpacebar = false; } //-------------------------------------------------------------- void testApp::update() { for(int i = 0; i < shapes.size(); i++) { bColliding[i] = false; } mousePickIndex = -1; if(bSpacebar) { ofVec3f mouseLoc = camera.screenToWorld( ofVec3f((float)ofGetMouseX(), (float)ofGetMouseY(), 0) ); mouseLoc.z += 15; ofVec3f diff; for(int i = 0; i < shapes.size(); i++) { diff = mouseLoc - shapes[i]->getPosition(); diff *= 2.f; if (!bAddCenterAttract) diff *= -1.f; shapes[i]->applyCentralForce( diff ); } } world.update(); ofSetWindowTitle(ofToString(ofGetFrameRate(), 0)); } //-------------------------------------------------------------- void testApp::draw() { glEnable( GL_DEPTH_TEST ); camera.begin(); ofSetLineWidth(1.f); ofSetColor(255, 0, 200); if(bDrawDebug) world.drawDebug(); ofEnableLighting(); light.enable(); if(bRenderShapes) { ofSetColor(100, 100, 100); for(int i = 0; i < bounds.size()-1; i++) { bounds[i]->draw(); } for(int i = 0; i < shapes.size(); i++) { if(shapes[i]->getType() == ofxBulletBaseShape::OFX_BULLET_BOX_SHAPE) { ofSetColor(15,197,138); } else { ofSetColor(220, 0, 220); } if(mousePickIndex == i) { ofSetColor(255, 0, 0); } else if (bColliding[i] == true) { if(shapes[i]->getType() == ofxBulletBaseShape::OFX_BULLET_BOX_SHAPE) { ofSetColor(220, 180, 60); } else { ofSetColor(255, 20, 50); } } shapes[i]->draw(); } } if(mousePickIndex > -1) { ofSetColor(255, 20, 255); ofSphere(mousePickPos.x, mousePickPos.y, mousePickPos.z, .1); } light.disable(); ofDisableLighting(); camera.end(); glDisable(GL_DEPTH_TEST); ofEnableAlphaBlending(); ofSetColor(0, 0, 0, 150); ofRect(0, 0, 250, 100); ofDisableAlphaBlending(); ofSetColor(255, 255, 255); stringstream ss; ss << "framerate: " << ofToString(ofGetFrameRate(),0) << endl; ss << "num shapes: " << (shapes.size()+bounds.size()) << endl; ss << "draw debug (d): " << ofToString(bDrawDebug, 0) << endl; ss << "render shapes (r): " << ofToString(bRenderShapes, 0) << endl; ss << "mouse force with spacebar: " << bSpacebar << endl; ss << "force direction(f): " << bAddCenterAttract << endl; ss << "add spherers (s)" << endl; ss << "add boxes (b)" << endl; ofDrawBitmapString(ss.str().c_str(), 10, 10); } //-------------------------------------------------------------- void testApp::onCollision(ofxBulletCollisionData& cdata) { for(int j = 0; j < bounds.size(); j++) { if(*bounds[j] == cdata) { return; } } for (int i = 0; i < shapes.size(); i++) { if(*shapes[i] == cdata) { bColliding[i] = true; } } } //-------------------------------------------------------------- void testApp::mousePickEvent( ofxBulletMousePickEvent &e ) { mousePickIndex = -1; for(int i = 0; i < shapes.size(); i++) { if(*shapes[i] == e) { mousePickIndex = i; mousePickPos = e.pickPosWorld; break; } } } //-------------------------------------------------------------- void testApp::keyPressed(int key) { int ii = 0; ofVec3f mouseLoc = camera.screenToWorld( ofVec3f((float)ofGetMouseX(), (float)ofGetMouseY(), 0) ); float rsize = ofRandom(.3, 1.8); mouseLoc.z += 15; switch (key) { case OF_KEY_DEL: case 127: if(mousePickIndex > -1) { if(shapes.size() > 0) { delete shapes[mousePickIndex]; shapes.erase( shapes.begin()+mousePickIndex ); } mousePickIndex = -1; } break; case 'd': bDrawDebug = !bDrawDebug; break; case 'b': shapes.push_back( new ofxBulletBox() ); ii = shapes.size()-1; ((ofxBulletBox*)shapes[ii])->create(world.world, mouseLoc, rsize*.2, rsize*2, rsize*2, rsize*2); shapes[ii]->setActivationState( DISABLE_DEACTIVATION ); shapes[ii]->add(); bColliding.push_back( false ); break; case 's': shapes.push_back( new ofxBulletSphere() ); ii = shapes.size()-1; ((ofxBulletSphere*)shapes[ii])->create(world.world, mouseLoc, rsize*.2, rsize); shapes[ii]->setActivationState( DISABLE_DEACTIVATION ); shapes[ii]->add(); bColliding.push_back( false ); break; case 'r': bRenderShapes = !bRenderShapes; break; case ' ': bSpacebar = true; break; case 'f': bAddCenterAttract = !bAddCenterAttract; break; default: break; } bColliding.clear(); for(int i = 0; i < shapes.size(); i++) { bColliding.push_back( false ); } } //-------------------------------------------------------------- void testApp::keyReleased(int key) { if(key == ' ') bSpacebar = false; } //-------------------------------------------------------------- void testApp::mouseMoved(int x, int y) { } //-------------------------------------------------------------- void testApp::mouseDragged(int x, int y, int button) { } //-------------------------------------------------------------- void testApp::mousePressed(int x, int y, int button) { } //-------------------------------------------------------------- void testApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void testApp::windowResized(int w, int h) { } //-------------------------------------------------------------- void testApp::gotMessage(ofMessage msg) { } //-------------------------------------------------------------- void testApp::dragEvent(ofDragInfo dragInfo) { }
6b89a54541fa6e340fd13cf293340c7b948ca86e
1577a53881c0d2bf13a7bc4a597037c08ac2e80d
/qt_code/v1.6.1/ClientSdWireless/mainwindow.h
ed80a951c03580a878e9191e490e746331c8828f
[]
no_license
xiaoweilai/wireless
ff3205de883cca17ad0a332705519d0235f81f8c
2130a7f4d7947ec7cd985160ed74a04410318189
refs/heads/master
2021-01-13T01:27:48.808776
2015-05-31T09:07:47
2015-05-31T09:07:47
29,049,725
0
0
null
null
null
null
GB18030
C++
false
false
2,713
h
mainwindow.h
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <QAbstractSocket> #include <QTcpSocket> #include <QHostAddress> #include "dosendthread.h" namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = 0); ~MainWindow(); private://var Ui::MainWindow *ui; DoSendThread *getImgThd; QList<QImage> imglist; QList<QTimer*> timerlist; QList<QTimer*> savetimerlist; /* socket 变量 */ QTcpSocket *tcpClient; /* 传输相关变量 */ quint64 picNametime; qint64 TotalBytes; qint64 byteWritten; qint64 bytesToWrite; enum { RET_SUC, RET_ERR, ERT_UNKNOWN }; enum { FLAG_USED, FLAG_NOUSE, FLAG_UNKNOWN }; QString m_connedipaddr; //已经连接的ip地址 QBuffer buffer; quint8 flagbuf0; QBuffer buffer1; quint8 flagbuf1; QList<QBuffer> bufferlst; QBuffer buffertmp; QByteArray outBlock; float time_total; int m_transfered; enum { STAT_TRANSFERED, STAT_TRANSFERING, STAT_UNKNOWN }; // QBuffer buffer1; QBuffer buffer2; QBuffer buffer3; QBuffer buffer4; QBuffer buffer5; QBuffer buffer6; QBuffer buffer7; QBuffer buffer8; QBuffer buffer9; QBuffer buffer10; quint8 bufused1; quint8 bufused2; quint8 bufused3; quint8 bufused4; quint8 bufused5; quint8 bufused6; quint8 bufused7; quint8 bufused8; quint8 bufused9; quint8 bufused10; enum { BUF_USED, BUF_NOUSE, BUF_UNKNOWN }; private://func QImage grabframeGeometry(); QImage grabDeskScreen(); QImage covertPixTo1024768(QImage img); void TimerSets(); void ButtonSets(); void SocketSets(); void socketVarSets(); quint32 getPort(); QString getIP(); void statusBarText(QString text); void PushBtnBegin(); void PushBtnPause(); void PushBtnAllFalse(); void PushBtnRestart(); void SignalSets(); void transferring(); void transfered(); int gettransfered(); void BufferSets(); private slots: void receiveMsgBoxSignal(); void grabScreenSignal(); void savetimertobuf(); void startActive(); void pauseActive(); void quitActive(); void startTransfer(); void transferjpg(); void displayErr(QAbstractSocket::SocketError socketError); void startConnect(); void stopConnect(); void updateClientProgress(qint64 numBytes); void removelist(); signals: void removelistonesig(); void transfersig(); }; #endif // MAINWINDOW_H
2e131e0a9594b627033cdf5acaa84c01f119cdd8
84a37dac3109f6c75e5ec985a024a7943e8a8aeb
/SoftRender/SoftRender/inc/Vec3.h
ca748a67f0b4e9553440ee9e3c6df913679c4a1e
[]
no_license
plinx/CG
1ea8b00f4d32ed24d264290851d4dca5c78da6b8
942d73a54c9ddd5414306f571557973c7e917998
refs/heads/master
2021-01-19T14:53:24.764008
2015-07-07T20:22:28
2015-07-07T20:22:28
29,869,223
5
0
null
null
null
null
UTF-8
C++
false
false
1,035
h
Vec3.h
#ifndef Vec3_h #define Vec3_h #include <math.h> class Vec3 { private: double x, y, z; public: Vec3() : x(0), y(0), z(0) {} Vec3(double fx, double fy, double fz) : x(fx), y(fy), z(fz) {} ~Vec3() = default; double getx() { return x; } double gety() { return y; } double getz() { return z; } Vec3 copy() { return Vec3(x, y, z); } double length() { return sqrt(x * x + y * y + z * z); } double sqrLength() { return x * x + y * y + z * z; } Vec3 normalize() { double inv = 1 / length(); return Vec3(x * inv, y * inv, z * inv); } Vec3 negate() { return Vec3(-x, -y, -z); } Vec3 add(Vec3 v) { return Vec3(x + v.x, y + v.y, z + v.z); } Vec3 sub(Vec3 v) { return Vec3(x - v.x, y - v.y, z - v.z); } Vec3 mul(double f) { return Vec3(x * f, y * f, z * f); } Vec3 divide(double f) { double invf = 1 / f; return Vec3(x * invf, y * invf, z * invf); } double dot(Vec3 v) { return x * v.x + y * v.y + z * v.z; } Vec3 cross(Vec3 v) { return Vec3(-z * v.y + y * v.z, z * v.x - x * v.z, -y * x + x * v.y); } }; #endif
e32cb4a52201bc7dd6e181108c32dd72a1f26949
c888a67a41b9cd064ea7fcad0086e180887382ed
/CUI_game/ソースコード/lib/source/sup/include/sup/boost_extend/boost_python.hpp
60a785683ff383e3cd094a1c77abbd6201096159
[]
no_license
k-higashimoto/Megurimasu
492cf54ce29ce7a4ec627e71b895277c2f65bcfc
8537c370c1dbd83c28c7cb20aacb7804b57234f5
refs/heads/master
2020-06-15T21:38:05.659763
2019-07-15T09:48:52
2019-07-15T09:48:52
195,398,444
2
0
null
null
null
null
SHIFT_JIS
C++
false
false
2,231
hpp
boost_python.hpp
/** * @file boost_python.hpp * @brief boost_pythonの拡張ファイル */ #ifndef SUP_LIB_BOOST_EXTEND_BOOST_PYTHON_HPP #define SUP_LIB_BOOST_EXTEND_BOOST_PYTHON_HPP #include<map> #include<vector> #include<boost/python/dict.hpp> #include<boost/python/list.hpp> namespace sup { inline namespace boost_extend { /** * @brief 辞書型の値をmapに変換する * @tparam T mapのキー型 * @tparam U mapの値の型 * @param dict pythonの値 * @return 変換結果 */ template<typename T, typename U> std::map<T, U> ConvertDictToMap(const ::boost::python::dict& dict) { std::map<T, U> ans{}; int len = static_cast<int>(::boost::python::len(dict)); auto keys = dict.keys(); for (int i = 0; i < len; ++i) { //Tでなくautoで受け取ろうとするとTに変換されずextract<T>を受け取ろうとしてエラーが出る T key_val = ::boost::python::extract<T>(keys[i]); ans[key_val] = ::boost::python::extract<U>(dict[key_val]); } return ans; } /** * @brief mapを辞書型に変換する * @tparam T mapのキーの型 * @tparam U mapの格納する型 * @param map 変換したいmapの値 * @return 変換結果 */ template<typename T, typename U> ::boost::python::dict ConvertMapToDict(const std::map<T, U>& map) { ::boost::python::dict ans{}; for (const auto& it : map) { ans[it.first] = it.second; } return ans; } /** * @brief リストをvectorに変換する * @tparam T vectorテンプレート引数に渡す型 * @param list 変換元 * @return 変換後のデータ */ template<typename T> std::vector<T> ConvertListToVector(const ::boost::python::list& list) { std::vector<T> ans{}; int len = static_cast<int>(::boost::python::len(list)); for(int i = 0; i < len; ++i) { ans.push_back(::boost::python::extract<T>(list[i])); } return ans; } /** * @brief vectorをリストに変換する * @tparam T vectorテンプレート引数に渡す型 * @param vector 変換元 * @return 変換結果 */ template<typename T> ::boost::python::list ConvertVectorToList(const std::vector<T>& vector) { ::boost::python::list ans{}; for (const auto& it : vector) { ans.append(it); } return ans; } } } #endif
70fffcacb07621324ec2e41d0fc3e561ea04fa95
78cf7c7a3dcf19dde3f9858409b339297d3b8584
/HowToUMG/Plugins/GVoice/Source/GVoice/Public/GCloudVoiceErrno.h
0f2a8f69f10d423edcec778c0cbd95a60c81b27a
[]
no_license
littleshuang/UnrealLearning
cc02866d907a573ef30cbe70ad638a8a6404e129
a9de6fdcc44187587c02e79c62fcb7342a8d01de
refs/heads/master
2020-04-03T10:59:47.722816
2018-10-30T03:05:27
2018-10-30T03:05:27
155,208,672
1
2
null
null
null
null
UTF-8
C++
false
false
8,796
h
GCloudVoiceErrno.h
/*******************************************************************************\ ** File: GCloudVoiceErrno.h ** Module: GVoice ** Version: 1.0 ** Author: CZ \*******************************************************************************/ #ifndef _GCloud_GVoice_GCloudVoiceErrno_h #define _GCloud_GVoice_GCloudVoiceErrno_h #if defined(WIN32) || defined(_WIN32) #ifdef GCLOUD_VOICE_EXPORTS #define GCLOUD_VOICE_API __declspec(dllexport) #else #define GCLOUD_VOICE_API __declspec(dllimport) #endif #else #if defined __ANDROID__ #define GCLOUD_VOICE_API __attribute__ ((visibility ("default"))) #else #define GCLOUD_VOICE_API #endif #endif namespace GCloud { namespace GVoice { enum ErrorNo { kErrorNoSucc = 0, //0, no error //common base err kErrorNoParamNULL = 0x1001, //4097, some param is null kErrorNoNeedSetAppInfo = 0x1002, //4098, you should call SetAppInfo first before call other api kErrorNoInitErr = 0x1003, //4099, Init Erro kErrorNoRecordingErr = 0x1004, //4100, now is recording, can't do other operator kErrorNoPollBuffErr = 0x1005, //4101, poll buffer is not enough or null kErrorNoModeStateErr = 0x1006, //4102, call some api, but the mode is not correct, maybe you shoud call SetMode first and correct kErrorNoParamInvalid = 0x1007, //4103, some param is null or value is invalid for our request, used right param and make sure is value range is correct by our comment kErrorNoOpenFileErr = 0x1008, //4104, open a file err kErrorNoNeedInit = 0x1009, //4105, you should call Init before do this operator kErrorNoEngineErr = 0x100A, //4106, you have not get engine instance, this common in use c# api, but not get gcloudvoice instance first kErrorNoPollMsgParseErr = 0x100B, //4107, this common in c# api, parse poll msg err kErrorNoPollMsgNo = 0x100C, //4108, poll, no msg to update //realtime err kErrorNoRealtimeStateErr = 0x2001, //8193, call some realtime api, but state err, such as OpenMic but you have not Join Room first kErrorNoJoinErr = 0x2002, //8194, join room failed kErrorNoQuitRoomNameErr = 0x2003, //8195, quit room err, the quit roomname not equal join roomname kErrorNoOpenMicNotAnchorErr = 0x2004,//8196, open mic in bigroom,but not anchor role kErrorNoCreateRoomErr = 0x2005, // 8197, create room error kErrorNoNoRoom = 0x2006, // 8198, no such room kErrorNoQuitRoomErr = 0x2007, //8199, quit room error kErrorNoAlreadyInTheRoom = 0x2008, // 8200, already in the room which in JoinXxxxRoom //message err kErrorNoAuthKeyErr = 0x3001, //12289, apply authkey api error kErrorNoPathAccessErr = 0x3002, //12290, the path can not access ,may be path file not exists or deny to access kErrorNoPermissionMicErr = 0x3003, //12291, you have not right to access micphone in android kErrorNoNeedAuthKey = 0x3004, //12292,you have not get authkey, call ApplyMessageKey first kErrorNoUploadErr = 0x3005, //12293, upload file err kErrorNoHttpBusy = 0x3006, //12294, http is busy,maybe the last upload/download not finish. kErrorNoDownloadErr = 0x3007, //12295, download file err kErrorNoSpeakerErr = 0x3008, //12296, open or close speaker tve error kErrorNoTVEPlaySoundErr = 0x3009, //12297, tve play file error kErrorNoAuthing = 0x300a, // 12298, Already in applying auth key processing kErrorNoLimit = 0x300b, //12299, upload limit kErrorNoInternalTVEErr = 0x5001, //20481, internal TVE err, our used kErrorNoInternalVisitErr = 0x5002, //20482, internal Not TVE err, out used kErrorNoInternalUsed = 0x5003, //20483, internal used, you should not get this err num kErrorNoBadServer = 0x06001, // 24577, bad server address,should be "udp://capi.xxx.xxx.com" kErrorNoSTTing = 0x07001, // 28673, Already in speach to text processing kErrorNoChangeRole = 0x08001, // 32769, change role error kErrorNoChangingRole = 0x08002, // 32770, is in changing role kErrorNoNotInRoom = 0x08003, // 32771, no in room kErrorNoCoordinate = 0x09001, // 36865, sync coordinate error kErrorNoSmallRoomName = 0x09002, // 36866, query with a small roomname }; enum CompleteCode { kCompleteCodeJoinRoomSucc = 1, //join room succ kCompleteCodeJoinRoomTimeout, //join room timeout kCompleteCodeJoinRoomSVRErr, //communication with svr occur some err, such as err data recv from svr kCompleteCodeJoinRoomUnknown, //reserved, our internal unknow err kCompleteCodeNetErr, //net err,may be can't connect to network kCompleteCodeQuitRoomSucc, //quitroom succ, if you have join room succ first, quit room will alway return succ kCompleteCodeMessageKeyAppliedSucc, //apply message authkey succ kCompleteCodeMessageKeyAppliedTimeout, //apply message authkey timeout kCompleteCodeMessageKeyAppliedSVRErr, //communication with svr occur some err, such as err data recv from svr kCompleteCodeMessageKeyAppliedUnknown, //reserved, our internal unknow err kCompleteCodeUploadRecordDone, //upload record file succ kCompleteCodeUploadRecordError, //upload record file occur error kCompleteCodeDownloadRecordDone, //download record file succ kCompleteCodeDownloadRecordError, //download record file occur error kCompleteCodeSTTSucc, // speech to text successful kCompleteCodeSTTTimeout, // speech to text with timeout kCompleteCodeSTTAPIErr, // server's error kCompleteCodeRSTTSucc, // speech to text successful kCompleteCodeRSTTTimeout, // speech to text with timeout kCompleteCodeRSTTAPIErr, // server's error kCompleteCodePlayFileDone, //the record file played end kCompleteCodeRoomOffline, // Dropped from the room kCompleteCodeUnknown, kCompleteCodeRoleSucc, // Change Role Success kCompleteCodeRoleTimeout, // Change Role with tiemout kCompleteCodeRoleMaxAnchor, // To much Anchor kCompleteCodeRoleNoChange, // The same role kCompleteCodeRoleSvrErr, // server's error kCompleteCodeRSTTRetry, // need retry stt }; /** * Event of GCloudVoice. * */ enum Event { kEventNoDeviceConnected = 0, // not any device is connected kEventHeadsetDisconnected = 10, // a headset device is connected kEventHeadsetConnected = 11, // a headset device is disconnected kEventBluetoothHeadsetDisconnected = 20, // a bluetooth device is connected kEventBluetoothHeadsetConnected = 21, // a bluetooth device is disconnected kEventMicStateOpenSucc = 30, // open microphone kEventMicStateOpenErr = 31, // open microphone kEventMicStateNoOpen = 32, // close micrphone kEventSpeakerStateOpenSucc = 40, // open speaker kEventSpeakerStateOpenErr = 41, // open speaker error kEventSpeakerStateNoOpen = 42, // close speaker }; /** * Event of GCloudVoice. * */ enum DeviceState { kDeviceStateUnconnected = 0, // not any audio device is connected kDeviceStateWriteHeadsetConnected = 1, // have a wiredheadset device is connected kDeviceStateBluetoothConnected = 2, // have a bluetooth device is disconnected }; } // endof namespace GVoice } // endof namespace GCloud #endif /* _GCloud_GVoice_GCloudVoiceErrno_h */
afb9d86f354f90199c4375b15f25c48bec3b4d43
42e833ca1eee7ae01d73d0f62898524034f50fe5
/IDE-GUI v6/logic/If.cpp
195b41d9a75ce5499fbd7957a24094d8ece3af0c
[]
no_license
KJeanpol/LaunchPadInterpreter
654a35a66921c005049d7d54f513aef66d775bf3
b10d0e8aea262bcd5ff9862290d3e231582f7200
refs/heads/master
2021-07-10T14:29:17.414188
2017-10-11T18:56:05
2017-10-11T18:56:05
103,405,392
1
0
null
null
null
null
UTF-8
C++
false
false
1,414
cpp
If.cpp
// // Created by Luis on 2/10/2017. // #include "If.h" If::If() { } void If::execute(){ for(int i=0;i!=vals1.size();i++){ cout<<"If "<<getVar(vals1[i])<< " equals " <<vals2[i]<<endl; cout<<i<<endl; if(getVar(vals1[i])!=0){ cout<<"Size "<<vals2.size()<<endl; cout<<"Size1 "<<vals1.size()<<endl; if(getVar(vals1[i])==vals2[i]){ cout<<sentences[i]->getName()<<endl; for(int j=0;j!=sentences.size();j++){ if(sentences[j]->If==i+1){ cout<<sentences[j]->getName()<<endl; sentences[j]->execute(); } }return; } }else{ QString ss = QString::fromStdString(vals1[i]); ID->console("Error: "+ ss+" No esta inicializada"); return; } }for(int i=vals1.size();i!=sentences.size();i++){ if(sentences[i]->If==0){ sentences[i]->execute(); }} } If:: ~If(){ while(!sentences.empty()){ delete sentences.back(); sentences.pop_back(); } while(!vals1.empty()){ delete Variables.back(); Variables.pop_back(); } while(!vals2.empty()){ delete Variables.back(); Variables.pop_back(); } }
53a67f007f4aba2df526326ef5d217e6c010af94
924fa2bc282e15283507bf6f07c61cddfbede3f1
/main.cc
034248b915877672adc138e6977727f06a9bc3ea
[]
no_license
PBS590/CS244proj3
49571a4cb7a50c6c4e4b2ea8700fce6a92e50cae
80c12b1f5ee2fa4dceaf3b9a9c7b63d5fa01c416
refs/heads/master
2020-05-25T19:15:51.509679
2019-06-05T03:20:39
2019-06-05T03:20:39
187,947,186
1
0
null
null
null
null
UTF-8
C++
false
false
304
cc
main.cc
#include <stdio.h> #include "zipf_generator.h" #include <iostream> #include <fstream> using namespace std; int main () { ZipfGenerator z = ZipfGenerator(0.01, 40359450); ofstream f; f.open ("zipf.txt"); for (int i = 0; i < 10000; i++) { f << z.Next() << "\n"; } f.close(); return 0; }
02782b6ad2f36ae1d6d2a4a2f65c3404fa239633
cc3fd3a55992b7c59d2148c16f05db5ca884bfbf
/Codesignal/core/27.magicalWell.cpp
247044bf317127ff3103cdf625404944e6f8b555
[]
no_license
karlsmarx/Challenges
541b0b608d440afdd4ef1e1757e1df2f8b70fe7d
b24adcc466d9ad2b2ce8b52d1301c932b27e5af3
refs/heads/master
2021-06-18T06:15:42.231961
2021-03-16T10:20:25
2021-03-16T10:20:25
176,175,410
0
0
null
null
null
null
UTF-8
C++
false
false
146
cpp
27.magicalWell.cpp
int magicalWell(int a, int b, int n) { int sum = 0; for (int i = 0; i < n; i++) { sum += a * b; ++a; ++b; } return sum; }
0cf6150a37961a714a492f016137a197c608b2c9
73bf5c4a8ae19036cc0e0d32a87a0f6ecc26a8fd
/src/loopct.cc
6cb8829c2d967aca34de1090d8399585035cb96a
[]
no_license
damobin/Rsp_Play
c8afffb781824b73fb884686e89217f98f6cfa57
0868a4848a428aa8c9b85fa732680465094cd1c1
refs/heads/main
2023-07-25T18:21:10.648317
2021-08-22T18:23:50
2021-08-22T18:23:50
394,662,974
0
0
null
null
null
null
UTF-8
C++
false
false
5,291
cc
loopct.cc
#include "loopct.h" #include "unistd.h" #include "string" #include "fstream" #include "capImags.h" #include <pthread.h> #include <csignal> #define REPET_TIMES 7 static void MulOpenTimes(string fileName,int times); //多用重复多次开空调 因为树莓派离空调有三米远,有的时候开两次成功一次 目前成功率在60%以上 缩短距离可以提高 离空调半米近98的成功率 static void LogTimeWriteFile(string ofname,struct tm *strtm,string dummy,double tempDS18B20); //如果出现调控写个log enum selfMon{ JAN = 0, FEB = 1, MAR = 2, APR = 3, MAY = 4, JUN = 5, JUL = 6, AUG = 7, SET = 8, OCT = 9, NOV = 10, DEC = 11 }; void *loopControl(void* arg) { //获取现在时间 年--月--日 //判断现在的季节 春 - 夏 - 秋 - 冬 //获取当地经纬度 判断这个区域的温度 bool action=0; uint16_t AIR_STATUS=AIR_OFF; double tempDS18B20; struct tm *usertimes; localTimeExc(&usertimes); loop_printf("usertimes.min = %d\r\n",usertimes->tm_min); loop_printf("usertimes.hour = %d\r\n",usertimes->tm_hour); loop_printf("usertimes.day = %d\r\n",usertimes->tm_mday); loop_printf("usertimes.mon = %d\r\n",usertimes->tm_mon); loop_printf("usertimes.year = %d\r\n",usertimes->tm_year); loop_printf("usertimes.wday = %d\r\n",usertimes->tm_wday); loop_printf("%s",asctime(usertimes)); cout<<exec("pwd")<<endl; while(1){ localTimeExc(&usertimes); if(usertimes->tm_wday<5){ //周末我要睡懒觉 不关空调 #if 1 if(usertimes->tm_hour>10 && usertimes->tm_hour<16){//早上10点后 下午4点前 关空调 周末还是得出去走走 MulOpenTimes("../data/close.bin",REPET_TIMES); AIR_STATUS=AIR_OFF; loop_printf("usertimes.min = %d\r\n",usertimes->tm_min); loop_printf("usertimes.hour = %d\r\n",usertimes->tm_hour); loop_printf("usertimes.day = %d\r\n",usertimes->tm_mday); loop_printf("usertimes.mon = %d\r\n",usertimes->tm_mon); loop_printf("usertimes.year = %d\r\n",usertimes->tm_year); loop_printf("usertimes.wday = %d\r\n",usertimes->tm_wday); while(usertimes->tm_hour>10 && usertimes->tm_hour<16){ sleep(600); //每10分钟监测一次时间 localTimeExc(&usertimes); } } #endif } tempDS18B20 = AveTempGet(); //获取温度 让温度处于 29~32区间 if(tempDS18B20<=0){ //温度获取异常CRC异常 continue; } //判断季节 经纬度 //没钱买 //固定使用地区为杭州-- // 月份从0开始算 所以降1 if(usertimes->tm_mon>=2 && usertimes->tm_mon<=4){ // spring 春季 }else if(usertimes->tm_mon>=5 && usertimes->tm_mon<=7){ // summer 夏季 if(tempDS18B20 > 36){ if(usertimes->tm_mon==5){ cout<<tempDS18B20<<endl; if((AIR_STATUS & (AIR_ON|AIR_COLD) ) != (AIR_ON|AIR_COLD)){ AIR_STATUS |= (AIR_ON|AIR_COLD); MulOpenTimes("../data/open_cold27.bin",REPET_TIMES); //夏季前两个月 27度 action ^= 1; } }else if(usertimes->tm_mon==6){ cout<<tempDS18B20<<endl; if((AIR_STATUS & (AIR_ON|AIR_COLD) ) != (AIR_ON|AIR_COLD)){ AIR_STATUS |= (AIR_ON|AIR_COLD); MulOpenTimes("../data/open_cold28.bin",REPET_TIMES); //夏季前两个月 27度 action ^= 1; } }else{ cout<<tempDS18B20<<endl; if((AIR_STATUS & (AIR_ON|AIR_COLD) ) != (AIR_ON|AIR_COLD)){ AIR_STATUS |= (AIR_ON|AIR_COLD); MulOpenTimes("../data/open_cold28.bin",REPET_TIMES); //夏季前两个月 27度 action ^= 1; } } LogTimeWriteFile("../data/log.txt",usertimes,"Temp>34",tempDS18B20); }else if(tempDS18B20 < 30){ cout<<usertimes<<endl; cout<<tempDS18B20<<endl; if((AIR_STATUS & (AIR_ON|AIR_COLD) ) == (AIR_ON|AIR_COLD)){ AIR_STATUS = AIR_OFF; MulOpenTimes("../data/close.bin",REPET_TIMES); LogTimeWriteFile("../data/log.txt",usertimes,"Temp<30",tempDS18B20); action ^= 1; } }else{ } }else if(usertimes->tm_mon>=8 && usertimes->tm_mon<=10){ //autumn 秋季 }else{ //冬季 } loop_printf("temp=%lf AIR_statu=%04x\r\n",tempDS18B20,AIR_STATUS); sleep(10); if(action==1){ //完成开机 或者 关机 需要等待 1min后再次观测 sleep(60); action ^= 1; } } return NULL; } static void MulOpenTimes(string fileName,int times) { for(int i=0;i<times;i++){ test(1,fileName); //多关几次 防止失败 cout<<"file:"<<fileName<<" "<<"times = "<<i<<endl; sleep(3); } } static void LogTimeWriteFile(string ofname,struct tm *strtm,string dummy,double tempDS18B20) { ofstream ofs; ofs.open(ofname,ios::app|ios::out); if(!ofs){ cout<<"Err file Write!!!"<<endl; return ; } ofs<<asctime(strtm)<<endl; ofs<<dummy<<endl; ofs<<tempDS18B20<<endl; ofs<<endl; ofs.close(); } static volatile int keepRunning = 1; void sig_handler( int sig ) { if ( sig == SIGINT){ keepRunning = 0; exit(0); } } void MulThreadCnt() { void *threadret; signal( SIGINT, sig_handler ); pthread_t tempretureThread,ImagThread; pthread_create(&tempretureThread,NULL,loopControl,NULL); pthread_create(&ImagThread,NULL,ActJdLoop,NULL); pthread_join(tempretureThread,&threadret); //pthread_detach(tempretureThread); #if 1 pthread_join(ImagThread,NULL); #else pthread_detach(ImagThread); while( keepRunning ){ sleep(10); } #endif }
4c85c1ab6666cc2b4feb278272cb8984f8dfe191
fbf2ec75c72daf57d6a44522c2f60605434ad7fa
/sun_pivoting_planner/include/sun_pivoting_planner/utility.h
594341d101937704bc17862de91b9434a81b994b
[]
no_license
marcocostanzo/sun_pivoting_planner
ff9d8f379d2e7e89e89200e4cafff88c10151480
85df126243fc6730a10b123c6c7d91933c07db28
refs/heads/master
2023-02-15T12:09:08.010711
2021-01-14T10:00:09
2021-01-14T10:00:09
274,436,903
2
0
null
null
null
null
UTF-8
C++
false
false
3,406
h
utility.h
#ifndef SUN_PIVOTING_PLANNER_UTILITY #define SUN_PIVOTING_PLANNER_UTILITY #include "trajectory_msgs/JointTrajectory.h" #include <moveit/move_group_interface/move_group_interface.h> #include <moveit/planning_scene_interface/planning_scene_interface.h> #include <moveit/planning_scene_monitor/planning_scene_monitor.h> #include "sun_pivoting_planner/exceptions.h" #include <tf2_geometry_msgs/tf2_geometry_msgs.h> #include "tf2_eigen/tf2_eigen.h" #include "yaml-cpp/yaml.h" namespace sun { struct Joint_Conf_Constraint { std::vector<std::string> joint_names; std::vector<double> move_range; }; // DEBUG void print_collision_obj_state(planning_scene_monitor::PlanningSceneMonitorPtr& planning_scene_monitor, const std::string& robot_description_id); double compute_traj_length(const trajectory_msgs::JointTrajectory& traj); void add_joint_configuration_constraints(const Joint_Conf_Constraint& joint_conf_constraint, moveit::planning_interface::MoveGroupInterface& move_group, const moveit_msgs::Constraints& path_constraints_in, moveit_msgs::Constraints& path_constraints_out, double move_range_multiplier); moveit_msgs::CollisionObject getMoveitCollisionObject(planning_scene_monitor::PlanningSceneMonitorPtr& planning_scene_monitor, const std::string& object_id, const std::string& error_append = ""); moveit_msgs::AttachedCollisionObject getMoveitAttachedCollisionObject(planning_scene_monitor::PlanningSceneMonitorPtr& planning_scene_monitor, const std::string& object_id, const std::string& error_append = ""); moveit_msgs::CollisionObject getMoveitPossiblyAttachedCollisionObject(planning_scene_monitor::PlanningSceneMonitorPtr& planning_scene_monitor, const std::string& object_id, const std::string& error_append = ""); void applyMoveitCollisionObject(moveit_msgs::CollisionObject obj); // Return the link to which the object was attached std::string detachCollisionObject(planning_scene_monitor::PlanningSceneMonitorPtr& planning_scene_monitor, const std::string& attached_object_id, const std::string& robot_description_id); void attachCollisionObject(const std::string& object_id, const std::string& link_name); geometry_msgs::PoseStamped getCollisionObjectSubframePose(const moveit_msgs::CollisionObject& collision_obj, const std::string& subframe_name); geometry_msgs::PoseStamped getCollisionObjectSubframePose(planning_scene_monitor::PlanningSceneMonitorPtr& planning_scene_monitor, const std::string& object_id, const std::string& subframe_name); void moveCollisionObject(planning_scene_monitor::PlanningSceneMonitorPtr& planning_scene_monitor, const std::string& object_id, geometry_msgs::PoseStamped desired_pose, const std::string& ref_subframe_name); void removeCollisionObject(planning_scene_monitor::PlanningSceneMonitorPtr& planning_scene_monitor, const std::string& obj_id); void removeAllCollisionObjects(planning_scene_monitor::PlanningSceneMonitorPtr& planning_scene_monitor); } // namespace sun #endif
181e91fa27272079df607144dd4df0efed8346e5
1154814c89c84b7e23ec1feed96be67491a5b7eb
/crest/simulation/obj_vertexringsolid.cpp
f91ae4fb750a35c6d7297bdd4de1d749d758e372
[]
no_license
linlut/View3dn
cc8e741a9a6967277a65a01793ddc61f7ac5ead9
4ba9a3b5414d95ac358d0e05f2834ebb451efedd
refs/heads/master
2020-03-26T23:43:41.132808
2014-02-21T01:28:11
2014-02-21T01:28:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,874
cpp
obj_vertexringsolid.cpp
//FILE: obj_vertexringsolid.cpp #include <vector> #include <geomath.h> #include <view3dn/edgetable.h> #include "obj_vertexringsolid.h" void CSimuVertexRingSolid::_initClassVars(void) { m_nElementType = 0; m_pElement = NULL; m_nSurfaceType = 0; m_nSurfacePoly = 0; m_pSurfacePoly = NULL; } CSimuVertexRingSolid::~CSimuVertexRingSolid(void) { SafeDeleteArray(m_pElement); SafeDeleteArray(m_pSurfacePoly); } void CSimuVertexRingSolid::_computeNodeMass( const Vector3d *pVertex, const int *pElement, const int nv_per_elm, const int nelm, const double &rho) { if ((m_pVertInfo==NULL) || (m_nVertexCount <=0)){ printf("Error: object not initialized!\n"); return; } if (nv_per_elm==4){ //Tetrahedral mesh ComputeNodeMassTet(pVertex, m_nVertexCount, pElement, nelm, rho, m_pVertInfo); } else{ //Hexahedral mesh ComputeNodeMassHex(pVertex, m_nVertexCount, pElement, nelm, rho, m_pVertInfo); } } void ConvertEdgeMapToEdgeInput( const Vector3d *pVertex, const CMeMaterialProperty *pmat, CEdgeMap& edgemap, //input vector<CSimuEdgeInput> &edgeinput) //output { edgeinput.clear(); CEdgeMap::iterator itr = edgemap.begin(); while (itr!=edgemap.end()){ const CSpringAuxStruct &e = itr->second; const int v0 = e.m_vertID[0]; const int v1 = e.m_vertID[1]; const double area = e.m_crossarea; const double mass = e.m_mass; CSimuEdgeInput x(v0, v1, area, mass, pmat); edgeinput.push_back(x); ++itr; } } void CSimuVertexRingSolid::_init( const Vector3d *pVertex, //vertex buffer const int springtype, //methods: 0: van Galder, 1: Lloyd 08TVCG const int *pElement, //element buffer const int nv_per_elm, //vertex # in each element, tet=3, hexahedron=4 const int nelm, //element information const CMeMaterialProperty &_mtl ) { _initClassVars(); //init element buffer m_nElementType = nv_per_elm; const int nsize = nv_per_elm * nelm; m_pElement = new int[nsize]; assert(m_pElement!=NULL); for (int i=0; i<nsize; i++) m_pElement[i] = pElement[i]; //first, need to decide mass m_mtl = _mtl; m_mtl.init(); const double rho = m_mtl.getDensity(); _computeNodeMass(pVertex, pElement, nv_per_elm, nelm, rho); //create strings using different tech to assign the stiffness ratio assert(m_nElementType==4 || m_nElementType==8); CEdgeMap edgemap; buildEdgeMapFromSolidElements(springtype, pVertex, m_nElementType, pElement, nelm, rho, edgemap); //construct the input buffer vector<CSimuEdgeInput> edgeinput; ConvertEdgeMapToEdgeInput(pVertex, &m_mtl, edgemap, edgeinput); //continue to init the vertexring obj const CSimuEdgeInput *pedge = &edgeinput[0]; const int nedge = edgeinput.size(); CSimuVertexRingObj::init(pedge, nedge, m_mtl); } void CSimuVertexRingSolid::setBoundarySurface( const int* pSurfacePoly, //surface polygon array const int nSurfaceType, //=3 or 4, number of nodes per surface element const int nSurfacePoly) //# of surface polygon { SafeDeleteArray(m_pSurfacePoly); const int nsize = nSurfaceType * nSurfacePoly; m_pSurfacePoly = new int [nsize]; assert(m_pSurfacePoly!=NULL); for (int i=0; i<nsize; i++) m_pSurfacePoly[i]=pSurfacePoly[i]; m_nSurfaceType = nSurfaceType; m_nSurfacePoly = nSurfacePoly; } //export mesh bool CSimuVertexRingSolid::_exportMeshPLT(FILE *fp) { return ExportMeshPLTSurface(m_pVertInfo, m_nVertexCount, m_pSurfacePoly, m_nSurfaceType, m_nSurfacePoly, fp); } int CSimuVertexRingSolid::exportOBJFileObject( const int stepid, const int objid, const int vertexbaseid, const int texbaseid, FILE *fp) const { const float *m_pTextureCoord = NULL; const int m_nTextureCoordStride = 2; const bool r = ExportMeshOBJSurface(stepid, objid, m_pVertInfo, m_nVertexCount, m_pSurfacePoly, m_nSurfaceType, m_nSurfacePoly, vertexbaseid, m_pTextureCoord, m_nTextureCoordStride, texbaseid, fp); return m_nVertexCount; }
01de8f1d852992274cb35f4bede7e3b9980bca8d
e4f90d2635817ae0a1c219c82d1fef26e11469b4
/client/values.h
d47bde4e62141cf508dbfc89f638960ba86dcce4
[ "Apache-2.0" ]
permissive
liuwons/rControl
9029988a1cae991884e007ed9936f345c605ad4a
d8de29eb14af426b805686da87cdb83caf88c80d
refs/heads/master
2021-01-01T19:55:14.595790
2015-05-22T03:24:04
2015-05-22T03:24:04
35,338,932
0
0
null
null
null
null
UTF-8
C++
false
false
352
h
values.h
#ifndef VALUES_H #define VALUES_H #include <stdio.h> #include <QDateTime> #include "version.h" class QTime; extern int screen_width; extern int screen_height; extern bool control; extern QString addr; extern int rq_width; extern int rq_height; extern FILE* tlog; extern QTime* ttime; #ifdef DEBUG extern QDateTime dt; #endif #endif // VALUES_H
e4c95a2b076c64c4ec77b9a76802b74ca4596ec7
0c83640cf0c7c24f7125a68d82b25f485f836601
/abc168/a/main.cpp
05eabb5523b51e5d2b109a73718c2455da71a8d9
[]
no_license
tiqwab/atcoder
f7f3fdc0c72ea7dea276bd2228b0b9fee9ba9aea
c338b12954e8cbe983077c428d0a36eb7ba2876f
refs/heads/master
2023-07-26T11:51:14.608775
2023-07-16T08:48:45
2023-07-16T08:48:45
216,480,686
0
0
null
null
null
null
UTF-8
C++
false
false
753
cpp
main.cpp
#include <algorithm> #include <cassert> #include <iostream> #include <map> #include <queue> #include <set> #include <vector> #include <limits.h> using namespace std; typedef long long ll; template<class T> inline bool chmax(T &a, T b) { if(a < b) { a = b; return true; } return false; } template<class T> inline bool chmin(T &a, T b) { if(a > b) { a = b; return true; } return false; } int main(void) { int N; cin >> N; int x = N % 10; if (x == 2 || x == 4 || x == 5 || x == 7 || x == 9) { cout << "hon" << endl; } else if (x == 0 || x == 1 || x == 6 || x == 8) { cout << "pon" << endl; } else { cout << "bon" << endl; } return 0; }
4448ef1e2468d4993e0923e0e9666a03ebcf7acb
e3236a7ab9b46ff3d5a0e8d3981c9678a724d701
/20190118/Class_src/VariadicTemplates/VariadicTemplates.cc
bba4101bdaba2f68dd78a4e23ac6e977ce533e76
[]
no_license
ProgrammerKyleYang/Cpractice
35da9e78dbe2fe7877f65ac44cd79af0a240a413
c2016abe920c7194f53628fcd21944930abe289a
refs/heads/master
2020-04-15T16:45:30.125637
2020-02-09T15:12:07
2020-02-09T15:12:07
164,849,465
0
0
null
null
null
null
UTF-8
C++
false
false
1,486
cc
VariadicTemplates.cc
/// /// @file VariadicTemplates.cc /// @author kyle(kyleyang58@gmail.com) /// @date 2019-01-27 20:23:57 /// #include <string> #include <iostream> using std::cout; using std::endl; using std::string; template <typename... Args>//Args模板参数包 void print(Args... args)//args函数参数包 { cout<< "参数包Args中元素个数[sizeof... (Args)]= " << sizeof...(Args) << endl; cout<< "参数包args中元素个数[sizeof... (args)]= " << sizeof...(args) << endl; } //display()递归条件的出口 //是一个自顶向下 void display() { cout << endl;//递归调用出口 } template <class T, class... Args> void display(T t, Args... args)//函数参数包递声明时...在左边 { cout << t << " "; display(args...);//当三个点放在函数函数参数包右边的时候表示对参数包进行展开 //递归调用打印 } template <class T> T sum(T t) { return t; } template <class T, class... Args> T sum(T t, Args... args) { return t + sum(args...); } void test0() { cout<< "sum (1, 2, 3, 4, 5) = " << sum(1, 2, 3, 4, 5) << endl; } int test1()//打印元素个数 { string s1 = "world"; print(3, 4.4, "hello", 'c'); print(2, 5); print('a', true, "hello", s1); print(); return 0; } int test2()//打印元素内容,使用递归调用 { string s1 = "world"; display(3, 4.4, "hello", 'c'); display(2, 5); display('a', true, "hello", s1); display(); return 0; } int main(void) { test0(); test1(); test2(); return 0; }
dee2e2eb905c8ba02db79162a20288628c43c69b
f20e965e19b749e84281cb35baea6787f815f777
/Gauss/Gen/EvtGenExtras/EvtGenModels/EvtXLL.hh
96c9617ce05c7f957d32f22b5a90d53c3eed79af
[]
no_license
marromlam/lhcb-software
f677abc9c6a27aa82a9b68c062eab587e6883906
f3a80ecab090d9ec1b33e12b987d3d743884dc24
refs/heads/master
2020-12-23T15:26:01.606128
2016-04-08T15:48:59
2016-04-08T15:48:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,563
hh
EvtXLL.hh
//-------------------------------------------------------------------------- // // Environment: // This software is part of the EvtGen package developed jointly // for the BaBar and CLEO collaborations. If you use all or part // of it, please give an appropriate acknowledgement. // // Copyright Information: See EvtGen/COPYRIGHT // Copyright (C) 1998 Caltech, UCSB // // Module: EvtGen/EvtXLL.hh // // Description: {B,Lb}->{Kpi,KK,pK,pipi,...}ell ell, w/ optimized dihadron, cos_theta, spectra // // Modification history: // // Biplab Dey, 4/09/2015 Module created // //------------------------------------------------------------------------ #ifndef EVTXLL_HH #define EVTXLL_HH #include "EvtGenBase/EvtDecayProb.hh" class EvtParticle; class EvtXLL: public EvtDecayProb { public: EvtXLL() {} virtual ~EvtXLL(); std::string getName(); EvtDecayBase* clone(); void init(); void initProbMax(); void decay(EvtParticle *p); private: // to get the m(hh) spectra pdf // -1 (flat), 0 (Kpi), 1 (KK), 2 (pK) int _chan; // masses of the (up to four) daughters double _masses[4]; // limits on the m(hh) mass range double _MX_LO, _MX_HI; // calculate the maximum prob channel by channel double _MY_MAX_PROB; // Maximum number of phase space iterations int _nLoop; double fn_p_Mm1m2(double M, double m1, double m2); double fn_cth(double cth); double fn_wt_dihadron(double mX, int chan); bool genValidPhaseSpace(EvtParticle* p); }; #endif
6559730403d982bdde8040b8ae0ed0eec43f5513
24d75ffa3af1b85325b39dc909343a8d945e9171
/SceniX/inc/nvsg/nvsg/IteratingRenderListProcessor.h
c9adc457eb4f3fecd172718635fc74f60c5e41d2
[]
no_license
assafyariv/PSG
0c2bf874166c7a7df18e8537ae5841bf8805f166
ce932ca9a72a5553f8d1826f3058e186619a4ec8
refs/heads/master
2016-08-12T02:57:17.021428
2015-09-24T17:14:51
2015-09-24T17:14:51
43,080,715
0
0
null
null
null
null
UTF-8
C++
false
false
8,313
h
IteratingRenderListProcessor.h
// Copyright NVIDIA Corporation 2010-2011 // TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THIS SOFTWARE IS PROVIDED // *AS IS* AND NVIDIA AND ITS SUPPLIERS DISCLAIM ALL WARRANTIES, EITHER EXPRESS // OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY // AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL NVIDIA OR ITS SUPPLIERS // BE LIABLE FOR ANY SPECIAL, INCIDENTAL, INDIRECT, OR CONSEQUENTIAL DAMAGES // WHATSOEVER (INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF BUSINESS PROFITS, // BUSINESS INTERRUPTION, LOSS OF BUSINESS INFORMATION, OR ANY OTHER PECUNIARY LOSS) // ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF NVIDIA HAS // BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES #pragma once #include <nvsg/Camera.h> #include <nvsg/RenderListProcessor.h> #include <nvsg/ViewState.h> #include <nvui/RendererOptions.h> namespace nvsg { class IteratingRenderListProcessor : public RenderListProcessor , public nvui::RendererOptionsProvider { public: NVSG_API static const std::string & getOptionStringFrustumCulling() { static std::string s( "IteratingRenderListProcessor::FrustumCulling" ); return( s ); } NVSG_API static const std::string & getOptionStringSizeCulling() { static std::string s( "IteratingRenderListProcessor::SizeCulling" ); return( s ); } NVSG_API static const std::string & getOptionStringSizeCullingFactor() { static std::string s( "IteratingRenderListProcessor::SizeCullingFactor" ); return( s ); } NVSG_API static const std::string & getOptionStringRenderModeGroup() { static std::string s( "IteratingRenderListProcessor::RenderModeGroup" ); return( s ); } NVSG_API static const std::string & getOptionStringTraversalMaskOverride() { static std::string s( "IteratingRenderListProcessor::TraversalMaskOverride" ); return( s ); } public: NVSG_API IteratingRenderListProcessor(); NVSG_API virtual ~IteratingRenderListProcessor() { /*NOP*/ }; NVSG_API virtual RenderList2SharedPtr process( const RenderList2SharedPtr& ); NVSG_API virtual void setRenderTarget( const nvui::SmartRenderTarget & renderTarget ) { m_renderTarget = renderTarget; } NVSG_API virtual const nvui::SmartRenderTarget & getRenderTarget() const { return( m_renderTarget ); } NVSG_API virtual void setViewState( const ViewStateSharedPtr & viewState ) { m_viewState = viewState; } NVSG_API virtual const ViewStateSharedPtr & getViewState() const { return( m_viewState ); } NVSG_API virtual void doAddRendererOptions( const nvui::RendererOptionsSharedPtr& rendererOptions ); NVSG_API virtual void doSetRendererOptions( const nvui::RendererOptionsSharedPtr& rendererOptions ); REFLECTION_INFO_API( NVSG_API, IteratingRenderListProcessor ); BEGIN_DECLARE_STATIC_PROPERTIES END_DECLARE_STATIC_PROPERTIES protected: // call these functions in derived implementations if you want control flow virtual bool beginHandle( const RenderList2SharedPtr& ); virtual bool beginHandle( const RenderModeGroupSharedPtr& ); virtual bool beginHandle( const MaterialGroupSharedPtr& ); // no need to call these in derived implementations virtual bool handleChildren( const RenderList2SharedPtr& ); virtual bool handleChildren( const RenderModeGroupSharedPtr& ); virtual bool handleChildren( const MaterialGroupSharedPtr& ); virtual bool handleChildrenAgain( const RenderList2SharedPtr& ); virtual bool handleChildrenAgain( const RenderModeGroupSharedPtr& ); virtual bool handleChildrenAgain( const MaterialGroupSharedPtr& ); virtual void endHandle( const RenderList2SharedPtr& ); virtual void endHandle( const RenderModeGroupSharedPtr& ); virtual void endHandle( const MaterialGroupSharedPtr& ); virtual void handle( const DrawableInstanceSharedPtr& ); nvui::SmartRenderTarget & renderTarget() { return( m_renderTarget ); } ViewStateSharedPtr & viewState() { return( m_viewState ); } protected: // property ids nvutil::PropertyId m_frustumCulling; nvutil::PropertyId m_sizeCulling; nvutil::PropertyId m_sizeCullingFactor; nvutil::PropertyId m_selectedRenderMode; nvutil::PropertyId m_traversalMaskOverride; // property value caches bool m_currentFrustumCulling; bool m_currentSizeCulling; float m_currentSizeCullingFactor; int m_currentSelectedRenderMode; unsigned int m_currentTraversalMaskOverride; // data caches nvmath::Mat44f m_worldToViewMatrix; unsigned int m_traversalMask; nvmath::Vec4f m_projectionSizeVector; private: template< typename T > void doProcess( const nvutil::SmartPtr<T>&, CullCode ); void doProcess( const DrawableInstanceSharedPtr&, CullCode ); void initOptions( const nvui::RendererOptionsSharedPtr& rendererOptions ); void initPropertyIds(); private: nvui::SmartRenderTarget m_renderTarget; ViewStateSharedPtr m_viewState; }; template< typename T > void IteratingRenderListProcessor::doProcess( const nvutil::SmartPtr<T>& item, CullCode cc ) { NVSG_ASSERT(item); NVSG_ASSERT( cc != CC_OUT ); if( beginHandle( item ) ) { if( handleChildren( item ) ) { do { typename T::ChildIterator it; typename T::ChildIterator it_end = item->end(); if ( cc == CC_IN ) { if ( ! m_currentSizeCulling ) { // the simple path: item is trivial in, and no size culling for ( it = item->begin(); it != it_end; ++it ) { doProcess( *it, CC_IN ); } } else { // less simple path: item is trivial in, but size culling might cull some things for ( it = item->begin(); it != it_end; ++it ) { // check if a DrawableInstance below this RenderList node has NVSG_HINT_ALWAYS_VISIBLE set if( (*it)->containsHints( Object::NVSG_HINT_ALWAYS_VISIBLE ) ) { doProcess( *it, CC_IN ); } else { nvmath::Sphere3f bs = (*it)->getBoundingSphere(); if ( isValid( bs ) ) { float minRadius = ( nvmath::Vec4f( bs.getCenter(), 1.0f ) * m_projectionSizeVector ) * m_currentSizeCullingFactor; if ( minRadius <= bs.getRadius() ) { doProcess( *it, CC_IN ); } } } } } } else { // the complex path: item is partial (that is: frustum culling is on), // and frustum or size culling might cull some things NVSG_ASSERT( m_currentFrustumCulling ); CameraReadLock camera( ViewStateReadLock( m_viewState )->getCamera() ); for ( it = item->begin(); it != it_end; ++it ) { nvmath::Sphere3f bs = (*it)->getBoundingSphere(); if ( isValid( bs ) ) { nvmath::Vec4f bsc = nvmath::Vec4f( bs.getCenter(), 1.0f ); bs.setCenter( nvmath::Vec3f( bsc * m_worldToViewMatrix ) ); cc = camera->determineCullCode( bs ); if ( ( cc != CC_OUT ) && m_currentSizeCulling ) { // m_projectionSizeVector needs to be used with world-space bounding sphere center float minRadius = ( bsc * m_projectionSizeVector ) * m_currentSizeCullingFactor; if ( bs.getRadius() < minRadius ) { cc = CC_OUT; } } // check if a DrawableInstance below this RenderList node has NVSG_HINT_ALWAYS_VISIBLE set if( cc == CC_OUT && (*it)->containsHints( Object::NVSG_HINT_ALWAYS_VISIBLE ) ) { cc = CC_PART; } if ( cc != CC_OUT ) { doProcess( *it, cc ); } } } } } while( handleChildrenAgain( item ) ); } endHandle( item ); } } } // namespace nvsg
5830b90fae58b33d7f2dbe6db09f6a77cbf17c35
5d01a2a16078b78fbb7380a6ee548fc87a80e333
/ETS/IVManager/VolaManagementDlg.h
3387e89b8e4e52b673dd8e414e07c188c3cb35bc
[]
no_license
WilliamQf-AI/IVRMstandard
2fd66ae6e81976d39705614cfab3dbfb4e8553c5
761bbdd0343012e7367ea111869bb6a9d8f043c0
refs/heads/master
2023-04-04T22:06:48.237586
2013-04-17T13:56:40
2013-04-17T13:56:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,778
h
VolaManagementDlg.h
#if !defined(AFX_VOLAMANAGEMENTDLG_H__11473FED_DBF3_46BE_A847_31B6F1C21117__INCLUDED_) #define AFX_VOLAMANAGEMENTDLG_H__11473FED_DBF3_46BE_A847_31B6F1C21117__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 // VolaManagementDlg.h : header file // //{{AFX_INCLUDES() #include "EGButton.h" #include "FlatComboBox.h" #include "NumericEditEx.h" #include "..\\EGOcx\\vsflexgrid.h" //}}AFX_INCLUDES ///////////////////////////////////////////////////////////////////////////// // CVolaManagementDlg dialog class CVolaManagementDlg : public CDialog { // Properties bool m_bInitialized; bool m_bNexdDaySurfaceMode; CString m_strTitle; long m_nContractID; VME::IVMSymbolVolatilitySurfacePtr m_spSurface; double m_dIFactor; long m_nIFactor; bool m_bEditing; CSurfacesVector m_vecSurfaces; long m_nCurrentSurface; CRulesVector m_vecRules; long m_nCurrentRule; bool m_bGroupRuleSet; bool m_bContractRuleSet; std::vector<DATE> m_months; long m_nMinW, m_nMinH; long m_nMargine; long m_nMouseRow; long m_nMouseCol; bool m_bNeedSave; // Construction public: CVolaManagementDlg(CWnd* pParent = NULL); // standard constructor // Dialog Data //{{AFX_DATA(CVolaManagementDlg) enum { IDD = IDD_VOLA_MANAGEMENT_DIALOG }; CStatic m_stcUpperLine; CEGButton m_btnClose; CButton m_chkDiscreteAccel; CButton m_chkPriceOverride; CNumericEditEx m_edtLoVoly; CNumericEditEx m_edtHiVoly; CNumericEditEx m_edtUnderlinePrice; CNumericEditEx m_edtAccelerator; CSliderCtrl m_sldFactor; CNumericEditEx m_edtFactor; CEGButton m_btnVolaFitToImplied; CEGButton m_btnVolaClear; CEGButton m_btnVolaRegenerate; CEGButton m_btnVolaUpdate; CEGButton m_btnVolaRestore; CEGButton m_btnNewRule; CEGButton m_btnUpdateRule; CEGButton m_btnDeleteRule; CFlatComboBox m_cmbCurrentRule; CVSFlexGrid m_fgVola; CEGButton m_btnDualQuadPar; //}}AFX_DATA bool m_bAlwaysOnTop; bool m_bUseExtrapolation; void UpdateSymbolData( int nID, const std::vector<DATE>& months ); void UpdateView(); void UpdateByPrice(); void UpdateRules(); void PostNotification( UINT nMessage ); void PostNotification( UINT nMessage, CCustomVolaNotification::Type enType, double dtMonth = 0 ); double GetInterpolationFactor(); bool OpenNextDaySurface( long nSurfaceID ); bool OpenDefaultSurface( long nSurfaceID ); // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CVolaManagementDlg) public: virtual BOOL PreTranslateMessage(MSG* pMsg); protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support //}}AFX_VIRTUAL // Implementation protected: void GridInit(); void GridFormat(); void GridFill( bool bForceFocus = false ); void GridDrawATMMarks(); void SetupDialog( double dUnderlinePrice ); bool SetupSurfaces(); void SetupRules(); void SetupControls(); void EnableControls( bool bForceDisable ); void SetupUnderlinePrice( CSurfaceData& sd ); // Generated message map functions //{{AFX_MSG(CVolaManagementDlg) virtual BOOL OnInitDialog(); afx_msg void OnCancel(); afx_msg void OnOK(); afx_msg void OnHScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar); afx_msg void OnChangeFactor(); afx_msg void OnComboCurrentRuleSelchange(); afx_msg void OnPriceOverrideCheck(); afx_msg void OnClose(); afx_msg void OnVolaStartEdit(long Row, long Col, BOOL FAR* Cancel); afx_msg void OnVolaValidateEdit(long Row, long Col, BOOL FAR* Cancel); afx_msg void OnVolaAfterEdit(long Row, long Col); afx_msg void OnUpdateRule(); afx_msg void OnDiscreteAccelCheck(); afx_msg void OnChangeHiVolatility(); afx_msg void OnChangeLoVolatility(); afx_msg void OnVolaRegenerate(); afx_msg void OnVolaUpdate(); afx_msg void OnVolaRestore(); afx_msg void OnGetMinMaxInfo(MINMAXINFO FAR* lpMMI); afx_msg void OnSize(UINT nType, int cx, int cy); afx_msg void OnVolaKeyUp(short FAR* KeyCode, short Shift); afx_msg void OnVolaMouseUp(short Button, short Shift, float X, float Y); afx_msg void OnVmMakeBasePoint(); afx_msg void OnVmMakeComomonPoint(); afx_msg void OnVmSurfaceOpen(); afx_msg void OnVmSurfaceNew(); afx_msg void OnVmSurfaceEdit(); afx_msg void OnVmSurfaceDelete(); afx_msg void OnVmViewGenerationOptions(); afx_msg void OnVmSelectAll(); afx_msg void OnNewRule(); afx_msg void OnDeleteRule(); afx_msg void OnVmSurfaceSetAsDefault(); afx_msg void OnChangeAccelerator(); afx_msg void OnDestroy(); afx_msg void OnVmSurfaceNextday(); afx_msg void OnVmViewAlwaysontop(); afx_msg void OnShowWindow(BOOL bShow, UINT nStatus); afx_msg void OnActivate(UINT nState, CWnd* pWndOther, BOOL bMinimized); afx_msg void OnVolaClear(); afx_msg void OnVolaFittoimplied(); afx_msg void OnVmViewShowAll(); afx_msg void OnVmSurfaceSaveas(); afx_msg void OnDualquadrPar(); DECLARE_EVENTSINK_MAP() //}}AFX_MSG afx_msg void OnCommitUnderlinePrice(); afx_msg LRESULT OnUpdateView( WPARAM wParam, LPARAM lParam ); DECLARE_MESSAGE_MAP() // Helpers long _GetATMStrikeRow( long col ); void _AlignControls( bool bShowOptions ); void _UnbasePoints(); void _ChangeCurrentSurface( size_t nNewCurrentSurface ); void _ExtrapolateVolatility(); void _ExtrapolateMonthVolatility( long col, const VME::IVMStrikeSkewVolatilitiesPtr& spSkew, bool bIsFlatWings = false, double dStrikeLow = 0.0f, double dStrikeHi = 0.0f); void _SelectAll(); }; //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_VOLAMANAGEMENTDLG_H__11473FED_DBF3_46BE_A847_31B6F1C21117__INCLUDED_)
fd1d346b37864d54a823c318a42935dc0be5a279
905ca7346160210cc97bb194a7703290c7d7c915
/src/Scene/Scene.h
6f7b80cffc58b756b334ecac8a23e25b5c5f188d
[]
no_license
JeffreyGoncalves/CPP
7ecccfebe90b0537e7e5625099184c9cd8a7bf69
3419d64f68b35802ee32dc48683c3ccd31e219ff
refs/heads/master
2021-09-02T05:46:47.081199
2017-12-30T20:52:45
2017-12-30T20:52:45
112,477,716
0
0
null
null
null
null
UTF-8
C++
false
false
2,143
h
Scene.h
#ifndef SCENE_H #define SCENE_H #include <iostream> #include <math.h> #include <vector> #include <algorithm> #include "Object3D.h" #include "Point3D.h" #include "sphere.h" #include "tPyramid.h" #include "color.h" #include "source.h" #include "Camera.h" #include "ecran.h" #include "ray3D.h" #include "vec3D.h" class Scene { public : Scene(Camera cam, Ecran e); Scene(Color c, Camera cam, Ecran e); ~Scene(); //Gestion des objets void addObject(Object3D *o); //Gestion des lumieres void addLightSource(Source *newLight); //Getters Object3D* const getObject(int i); Source* const getLightSource(int i); Color const& getBackgroundColor(); Ecran const& getEcran(); ////////////////////////////////// //Setters void setBackgroundColor(Color newBackColor); void setCamera(Camera newCamera); ////////////////////////////////// //Static setter for interpolation factor inline void setInterpolationFactor(unsigned int factor){if(factor != 0) interpolationFactor = factor;} inline void setNbMaxRecursions(unsigned int factor){nb_max_recursions = factor;} inline void setAmbientLight(Color newAmbientLight){ambientLight = newAmbientLight;} //Methode de calcul d'image Color** calcScenePicture(bool interpolate); private : std::vector<Object3D*> sceneObjects; std::vector<Source*> sceneLights; Color backgroundColor; Camera sceneCamera; Ecran ecran; //Methode de calcul d'un pixel, utilise uniquement par calcScenePicture Color calcScenePixel(ray3D ray, Object3D *previousObject, unsigned int nb_rec); //nb_rec : nombre de recursions autorises Color interpolationLoop(unsigned int i, unsigned int j, Ecran screenToInterpolate); //Constantes statiques : parametres par defaut static const int default_nb_max_recursions = 1; //Nombre maximal de passes pour le calcul de la reflexion speculaire static const unsigned int defaultInterpolationFactor = 2; //Facteur d'interpolation static const Color defaultAmbientLight; //Parametres de la scene unsigned int nb_max_recursions; unsigned int interpolationFactor; Color ambientLight; }; #endif
0c3fac6875db46cfb53b51d8fbe26eb0bd5ec6fe
42b07b341242937dc520fb91f2b04d04fc5fdbc9
/Attack2/B.cpp
6964a62c30e28912bed8885d73a6af3287c1cc77
[]
no_license
woowei0102/CompilerAssignment
fbc78e1d5c819c7626b6e0109e45531d1949169b
e8b368af14b7a0e0dad4e921f0fa1a3d3dac3b68
refs/heads/main
2023-06-17T03:21:03.944687
2021-07-15T12:46:53
2021-07-15T12:46:53
386,285,890
0
0
null
null
null
null
UTF-8
C++
false
false
2,052
cpp
B.cpp
#include<iostream> #include<iomanip> #include<cstring> using namespace std; char str[1000],s; int t=0; void arrange(){ while(cin>>s){ if((s=='w')||(s=='x')||(s=='a')||(s=='d')||(s=='s')||(s=='t')||(s=='`')){ str[t++] =s; } } } /////////////////////////////////////////////////////////////////////////////////// void skill(){ int temp = 0; while(temp<t){ if(((str[temp]=='a')&&(str[temp+1]=='a')&&(str[temp+2]=='s'))||((str[temp]=='d')&&(str[temp+1]=='d')&&(str[temp+2]=='s'))){ printf("Soul_Punch\n"); temp+=2; } else if(str[temp]=='`'){ temp++; if(str[temp]=='w'){ temp++; if(str[temp]=='s'){ printf("Uppercut\n"); } else if(str[temp]=='t'){ printf("Big_Bang\n"); } else temp-=2; } else if((str[temp]=='t')){ temp++; if(str[temp]=='s'){ temp++; if(str[temp]=='t'){ printf("Mirror_Image\n"); while(str[temp+1]=='t'){ temp++; } } else temp-=3; } } else if((str[temp]=='d')){ temp++; if(str[temp]=='t'){ printf("Soul_Bomb\n"); } else if(str[temp]=='s'){ printf("Skull_Blast\n"); while(str[temp+1]=='s'){ temp++; } } else temp-=2; } else temp--; } temp++; } } int main(){ arrange(); skill(); // cout<<str; }
9bbda17763a753f7b870dafd24dc848a9e978a6b
9f9d44dabad1ac1b89eccb011925e10032d97c4f
/Projet_station_meteo_multi/pluvio.cpp
c73238a6b22aad01711c0599670c935b764cebdb
[]
no_license
StationMeteoDIY/pluviometre
00689821680913e0735b5423eaa142c2a80dc4fa
4929549121fa316d0bc72c11a2b318e1c186fd8c
refs/heads/main
2023-02-05T22:39:36.123015
2020-12-29T17:15:55
2020-12-29T17:15:55
325,342,976
1
0
null
null
null
null
UTF-8
C++
false
false
2,669
cpp
pluvio.cpp
#include <Arduino.h> #include <CircularBuffer.h> #include "mqtt.h" const byte rainPin = D5; // PIN de connexion de capteur. unsigned int raincnt = 0; // Initialisation du compteur. int idxpluviometre = 1; // Index du Device de pluviométrie. static int jourCourant = 0; // Numéro du jour courant. static float pluieJour = 0; // Enregistre le total de pluie tombé dans la journée. CircularBuffer<float, 3> h_fifo; // On initialise la taille du buffer pour 6 mn glissantes. (3 = 1 relevé toutes les 2 min) ICACHE_RAM_ATTR void cntRain() { raincnt++; Serial.println("Action... "); } void init_pluvio() { // Initialisation du PIN et création de l'interruption. pinMode(rainPin, INPUT_PULLUP); // Montage PullUp avec Condensateur pour éviter l'éffet rebond. attachInterrupt(digitalPinToInterrupt(rainPin), cntRain, FALLING); // CHANGE: Déclenche de HIGH à LOW ou de LOW à HIGH - FALLING : HIGH à LOW - RISING : LOW à HIGH. } void getDataPluvio() { Serial.println("Execution de la fonction getDataPluvio()."); float h_total = 0.00; // Initialisation de la variable qui contiendra le nbre total d'eau tombée sur 1 heure // On calcul le niveau depuis la dernière interogation. float pluie = raincnt * 0.2794; // Nombre d'impulsion multiplié par la hauteur d'eau en mm d'un godet raincnt = 0; // On réinitialise le compteur. // On ajoute le niveau à h_fifo h_fifo.push(pluie); Serial.print("Pluie = "); Serial.print(String(pluie)); Serial.println(" mm "); // Calcul des précipitations en mm/h, On récupére la hauteur d'eau tombée sur les 6 dernières minutes. using index_h = decltype(h_fifo)::index_t; for (index_h i = 0; i < h_fifo.size(); i++) { h_total += h_fifo[i]; } // On calcul la valeur à envoyer à Domoticz pour une heure. h_total = h_total * 10; // envoi des données (RAINRATE;RAINCOUNTER) if (idxpluviometre != 0) { Serial.print("RAINRATE = "); Serial.println(String((int)(round(h_total)))); // Calcul de quantité pluie par jour. int currentJour = NTP_Jour(); if(currentJour != jourCourant) { jourCourant = currentJour; pluieJour = 0; } pluieJour += pluie; Serial.print("RAINCOUNT = "); Serial.println(String((round(pluieJour*100)/100))); // Envoi des données à Domoticz String svalue = String(round(h_total*100)) + ";" + String(round(pluieJour*100)/100); SendData("udevice", idxpluviometre, 0, svalue); } }
8e1d956254b554b990e02bf5a77d5cfb77b2b205
959e9b7b5b730afabc84411fefc4a028b758bc43
/context.h
486086aa573e2fc94afee33a9c258ffe924da682
[]
no_license
tjjeon/tjjeon1019
c9af3a89c95662f8a2eb4f31d928e32d45ef5c3c
d40e2ceb024aa86f779e523855a1f36a79c8eb2f
refs/heads/main
2023-01-04T00:04:01.704099
2020-10-22T07:01:10
2020-10-22T07:01:10
305,224,732
0
0
null
null
null
null
UTF-8
C++
false
false
304
h
context.h
#define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <string> #include <time.h> class Context { public: Context(const std::string& f, int l) : function(f), line(l) {} // foo:42 std::string toString() const; private: std::string function; int line; };
59471494e17c5ceb6d8dfbe4f1a6e3e39f2112ac
6146bb2c6a293377cb959d3d5240bff9544fb1fd
/projects/rpi-video/openmax/BroadcomAACEncode.h
884d46435ed9fc8bcd26b108e5a92c9c625dcd4c
[ "MIT" ]
permissive
southdy/OpenGLStarter
f743d0948a8434c944830fcb1b6acf6d7724fa5b
0552513f24ce3820b4957b1e453e615a9b77c8ff
refs/heads/master
2023-07-05T18:21:01.931563
2021-08-30T19:58:48
2021-08-30T19:58:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,536
h
BroadcomAACEncode.h
#include "OMXComponentBase.h" #include <aribeiro/aribeiro.h> using namespace aRibeiro; class BroadcomAACEncode : public OMXComponentBase { public: OMX_HANDLETYPE encoder; OMX_BUFFERHEADERTYPE *inputBuffer; OMX_BUFFERHEADERTYPE *outputBuffer; volatile bool canFillInputBuffer; volatile bool needOutBuffer; volatile bool outputPortChanged; PlatformTime time; int stdout_fd; BroadcomAACEncode(OMX_U32 samplingrate, OMX_U32 bitrate):OMXComponentBase() { stdout_fd = fileno(stdout); needOutBuffer = false; canFillInputBuffer = true; encoder = OMX::createHandle("OMX.broadcom.audio_encode",this); fprintf(stderr,"\nBroadcomAACEncode\n\n"); //input port OMX::printPort(encoder,160); OMX::printPortSupportedFormats(encoder,160); //output port OMX::printPort(encoder,161); OMX::printPortSupportedFormats(encoder,161); // // Audio Input setup // OMX_PARAM_PORTDEFINITIONTYPE portdef = OMX::getPortDefinition(encoder,160); //OMX_INIT_STRUCTURE(portdef); portdef.nPortIndex = 160; portdef.format.audio.eEncoding = OMX_AUDIO_CodingPCM; OMX::setPortDefinition(encoder, portdef); fprintf(stderr, " setPortDefinition 160, OK\n"); //input port configuration (2 channels, signed interleaved 16 bits, little endian, linear OMX::setAudioPCMParam(encoder, 160, samplingrate); fprintf(stderr, " setAudioPCMParam 160, OK\n"); OMX::printPort(encoder,160); // // Audio Output setup // //set output port using the input as basis portdef = OMX::getPortDefinition(encoder,161); portdef.nPortIndex = 161; portdef.format.audio.eEncoding = OMX_AUDIO_CodingAAC; OMX::setPortDefinition(encoder, portdef); fprintf(stderr, " setPortDefinition 161, OK\n"); //OMX::setVideoBitrate(encoder, 201, OMX_Video_ControlRateVariable, bitrate); //OMX::setVideoPortFormat(encoder, 201, OMX_VIDEO_CodingAVC); OMX::setAudioAACParam(encoder, 161, bitrate, samplingrate); fprintf(stderr, " setAudioAACParam 161, OK\n"); OMX::printPort(encoder,161); fprintf(stderr,"\nBefore OMX_StateIdle\n\n"); OMX::setState(encoder, OMX_StateIdle); fprintf(stderr,"\nOMX::setEnablePort(encoder, 160, OMX_TRUE)\n\n"); OMX::setEnablePort(encoder, 160, OMX_TRUE); fprintf(stderr,"\nOMX::setEnablePort(encoder, 161, OMX_TRUE)\n\n"); OMX::setEnablePort(encoder, 161, OMX_TRUE); //allocate buffers fprintf(stderr,"\nBefore allocate 1\n\n"); inputBuffer = OMX::allocateBuffer(encoder, 160); fprintf(stderr,"\nBefore allocate 2\n\n"); outputBuffer = OMX::allocateBuffer(encoder, 161); //outputBuffer = NULL; //clear input buffer memset(inputBuffer->pBuffer, 0, inputBuffer->nAllocLen); outputPortChanged = false; fprintf(stderr,"\nBefore Initialization\n\n"); OMX::setState(encoder, OMX_StateExecuting); fprintf(stderr,"\nAfter Initialization\n\n"); OMX::printPort(encoder,160); OMX::printPort(encoder,161); OMX::postFillThisBuffer(encoder, outputBuffer); } virtual ~BroadcomAACEncode() { OMX::portFlush(this, encoder, 160); OMX::portFlush(this, encoder, 161); OMX::setEnablePort(encoder, 160, OMX_FALSE); if (outputBuffer != NULL) OMX::setEnablePort(encoder, 161, OMX_FALSE); OMX::freeBuffer(encoder, 160, inputBuffer); if (outputBuffer != NULL) OMX::freeBuffer(encoder, 161, outputBuffer); OMX::setState(encoder, OMX_StateIdle); OMX::setState(encoder, OMX_StateLoaded); OMX::freeHandle(encoder); } void postPCM16bitSignedInterleaved(int16_t *buffer, int length) { if (!canFillInputBuffer) return; time.update(); canFillInputBuffer = false; for (int i=0;i<inputBuffer->nAllocLen;i++) inputBuffer->pBuffer[rand() % inputBuffer->nAllocLen ] = rand() % 256; inputBuffer->nOffset = 0; inputBuffer->nFilledLen = inputBuffer->nAllocLen; //fprintf(stderr,"postYUV filledLength: %i \n",inputBuffer->nFilledLen); //if EOF //inputBuffer->nFlags = OMX_BUFFERFLAG_EOS; //uint64_t timestamp = (uint64_t)inputBuffer->nTimeStamp.nHighPart; //timestamp = timestamp << 32; //timestamp |= (uint64_t)inputBuffer->nTimeStamp.nLowPart; static uint64_t timestamp = -time.deltaTimeMicro; //((uint32_t*)&timestamp)[0] = inputBuffer->nTimeStamp.nLowPart; //((uint32_t*)&timestamp)[1] = inputBuffer->nTimeStamp.nHighPart; timestamp += time.deltaTimeMicro; inputBuffer->nTimeStamp.nLowPart = ((uint32_t*)&timestamp)[0]; inputBuffer->nTimeStamp.nHighPart = ((uint32_t*)&timestamp)[1]; //fprintf(stderr,"time: %llu\n", timestamp); //fprintf(stderr," low: %u\n", inputBuffer->nTimeStamp.nLowPart); //fprintf(stderr," high: %u\n", inputBuffer->nTimeStamp.nHighPart); //inputBuffer->nTimeStamp; OMX::postEmptyThisBuffer(encoder, inputBuffer); } void makeOutBufferAvailable(){ if (outputPortChanged){ outputPortChanged = false; if (outputBuffer != NULL) { OMX::setEnablePort(encoder, 161, OMX_FALSE); OMX::freeBuffer(encoder, 161, outputBuffer); outputBuffer = NULL; } OMX::setEnablePort(encoder, 161, OMX_TRUE); outputBuffer = OMX::allocateBuffer(encoder, 161); OMX::postFillThisBuffer(encoder, outputBuffer); fprintf(stderr,"*******\nOUTPUT PORT CHANGED!!!\n*******\n"); OMX::printPort(encoder, 161); return; } if (!needOutBuffer) return; needOutBuffer = false; //printf("[BroadcomVideoEncode] makeOutBufferAvailable\n"); OMX::postFillThisBuffer(encoder, outputBuffer); } OMX_ERRORTYPE eventHandler(OMX_HANDLETYPE hComponent,OMX_PTR pAppData,OMX_EVENTTYPE eEvent,OMX_U32 nData1,OMX_U32 nData2,OMX_PTR pEventData){ OMXComponentBase::eventHandler(hComponent,pAppData,eEvent,nData1,nData2,pEventData); switch(eEvent) { case OMX_EventPortSettingsChanged: if (nData1 == 161) { outputPortChanged = true; // the nBufferSize changed fprintf(stderr," -- output port changed --\n"); } break; default: break; } return OMX_ErrorNone; } // OMX callbacks OMX_ERRORTYPE emptyBufferDone(OMX_HANDLETYPE hComponent,OMX_PTR pAppData,OMX_BUFFERHEADERTYPE* pBuffer){ //fprintf(stderr,"[BroadcomVideoEncode] emptyBufferDone\n"); canFillInputBuffer = true; return OMX_ErrorNone; } // OMX callbacks OMX_ERRORTYPE fillBufferDone(OMX_HANDLETYPE hComponent,OMX_PTR pAppData,OMX_BUFFERHEADERTYPE* pBuffer){ if(pBuffer->nFlags & OMX_BUFFERFLAG_ENDOFFRAME) { //fprintf(stderr,"encoding frameout...\n"); //frame_out++; } // Flush buffer to output file //fwrite(pBuffer->pBuffer + pBuffer->nOffset, 1, pBuffer->nFilledLen, stdout); write(stdout_fd, pBuffer->pBuffer + pBuffer->nOffset, pBuffer->nFilledLen); needOutBuffer = true; //OMX::postFillThisBuffer(encoder, outputBuffer); //fprintf(stderr,"[BroadcomVideoEncode] fillBufferDone\n"); return OMX_ErrorNone; } };
36f45106e363542312373f6c048fc7f89a69a19b
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_5695413893988352_0/C++/Gwittaegi/CloseMatch.cpp
55b5ec628c0e2b7f0f88e597b91f74b4a839408d
[]
no_license
alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417992
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
UTF-8
C++
false
false
2,690
cpp
CloseMatch.cpp
#include <cstdio> #include <string> #include <iostream> #define MAX 999999999999999999 #define ABS(a,b) ((a)>(b)?(a-b):(b-a)) using namespace std; long long min, resC, resJ; string cStr, jStr; void Pro(int l, int n, long long cN, long long jN, int comp) { if (l == n) { int k = ABS(cN, jN); if (min > k || (min == k && (resC > cN || (resC == cN && resJ > jN)))) { min = k; resC = cN; resJ = jN; } } else { if (cStr[l] == '?' && jStr[l] == '?') { if (comp == 0) { Pro(l + 1, n, cN * 10, jN * 10, 0); Pro(l + 1, n, cN * 10 + 1, jN * 10, 1); Pro(l + 1, n, cN * 10, jN * 10 + 1, -1); } else if (comp == -1) Pro(l + 1, n, cN * 10 + 9, jN * 10, comp); else Pro(l + 1, n, cN * 10, jN * 10 + 9, comp); } else if (cStr[l] == '?') { if (comp == 0) { Pro(l + 1, n, cN * 10 + (jStr[l] - '0'), jN * 10 + (jStr[l] - '0'), 0); if (jStr[l] != '0')Pro(l + 1, n, cN * 10 + (jStr[l] - '0') - 1, jN * 10 + (jStr[l] - '0'), -1); if (jStr[l] != '9')Pro(l + 1, n, cN * 10 + (jStr[l] - '0') + 1, jN * 10 + (jStr[l] - '0'), 1); } else if (comp == -1) Pro(l + 1, n, cN * 10 + 9, jN * 10 + (jStr[l] - '0'), comp); else Pro(l + 1, n, cN * 10, jN * 10 + (jStr[l] - '0'), comp); } else if (jStr[l] == '?') { if (comp == 0) { Pro(l + 1, n, cN * 10 + (cStr[l] - '0'), jN * 10 + (cStr[l] - '0'), 0); if (cStr[l] != '0')Pro(l + 1, n, cN * 10 + (cStr[l] - '0'), jN * 10 + (cStr[l] - '0') - 1, 1); if (cStr[l] != '9')Pro(l + 1, n, cN * 10 + (cStr[l] - '0'), jN * 10 + (cStr[l] - '0') + 1, -1); } else if (comp == -1) Pro(l + 1, n, cN * 10 + (cStr[l] - '0'), jN * 10, comp); else Pro(l + 1, n, cN * 10 + (cStr[l] - '0'), jN * 10 + 9, comp); } else { int k; if (comp == 0) { if (cStr[l] > jStr[l]) k = 1; else if (cStr[l] < jStr[l])k = -1; else k = 0; } else k = comp; Pro(l + 1, n, cN * 10 + (cStr[l] - '0'), jN * 10 + (jStr[l] - '0'), k); } } } int main() { freopen("B-small-attempt1.in", "r", stdin); freopen("output.txt", "w", stdout); int t; scanf("%d", &t); for (int tc = 0;++tc <= t;tc) { cin >> cStr >> jStr; int len = cStr.length(); resC = resJ = min = 999999999999999999; Pro(0, len, 0, 0, 0); printf("Case #%d: ", tc); int i = 0; for (long long k = resC;k;++i, k /= 10); for (;i < len;++i)printf("0"); if (resC != 0)printf("%lld", resC); printf(" "); i = 0; for (long long k = resJ;k;++i, k /= 10); for (;i < len;++i)printf("0"); if (resJ != 0)printf("%lld", resJ); printf("\n"); } fclose(stdin); fclose(stdout); return 0; }
d1086029923746481bef5be6877c12aa0bbe2fc1
00add89b1c9712db1a29a73f34864854a7738686
/packages/utility/system/test/tstCartesianSpatialCoordinateConversionPolicy.cpp
138a01cabb5ab021024f3a1bf64c04cdebc5d0f6
[ "BSD-3-Clause" ]
permissive
FRENSIE/FRENSIE
a4f533faa02e456ec641815886bc530a53f525f9
1735b1c8841f23d415a4998743515c56f980f654
refs/heads/master
2021-11-19T02:37:26.311426
2021-09-08T11:51:24
2021-09-08T11:51:24
7,826,404
11
6
NOASSERTION
2021-09-08T11:51:25
2013-01-25T19:03:09
C++
UTF-8
C++
false
false
3,753
cpp
tstCartesianSpatialCoordinateConversionPolicy.cpp
//---------------------------------------------------------------------------// //! //! \file tstCartesianSpatialCoordinateConversionPolicy.cpp //! \author Alex Robinson //! \brief Cartesian spatial coordinate conversion policy unit tests //! //---------------------------------------------------------------------------// // Std Lib Includes #include <iostream> // FRENSIE Includes #include "Utility_CartesianSpatialCoordinateConversionPolicy.hpp" #include "Utility_Array.hpp" #include "Utility_Vector.hpp" #include "Utility_UnitTestHarnessWithMain.hpp" //---------------------------------------------------------------------------// // Tests. //---------------------------------------------------------------------------// // Check that input spatial coordinates can be converted to output // spatial coordinates FRENSIE_UNIT_TEST( CartesianSpatialCoordinateConversionPolicy, convertFromCartesianPosition ) { std::vector<double> input_position( 3 ); input_position[0] = 1.0; input_position[1] = 1.0; input_position[2] = 1.0; std::vector<double> output_position( 3 ); Utility::CartesianSpatialCoordinateConversionPolicy::convertFromCartesianPosition( input_position.data(), output_position.data() ); FRENSIE_CHECK_EQUAL( input_position, output_position ); input_position[0] = 2.0; input_position[1] = -1.0; input_position[2] = 0.1; Utility::CartesianSpatialCoordinateConversionPolicy::convertFromCartesianPosition( input_position[0], input_position[1], input_position[2], output_position[0], output_position[1], output_position[2] ); FRENSIE_CHECK_EQUAL( input_position, output_position ); } //---------------------------------------------------------------------------// // Check that input spatial coordinates can be converted to output // spatial coordinates FRENSIE_UNIT_TEST( CartesianSpatialCoordinateConversionPolicy, convertToCartesianPosition) { std::vector<double> input_position( 3 ); input_position[0] = 1.0; input_position[1] = 1.0; input_position[2] = 1.0; std::vector<double> output_position( 3 ); Utility::CartesianSpatialCoordinateConversionPolicy::convertToCartesianPosition( input_position.data(), output_position.data() ); FRENSIE_CHECK_EQUAL( input_position, output_position ); input_position[0] = 2.0; input_position[1] = -1.0; input_position[2] = 0.1; Utility::CartesianSpatialCoordinateConversionPolicy::convertToCartesianPosition( input_position[0], input_position[1], input_position[2], output_position[0], output_position[1], output_position[2] ); FRENSIE_CHECK_EQUAL( input_position, output_position ); } //---------------------------------------------------------------------------// // end tstCartesianSpatialCoordinateConversionPolicy.cpp //---------------------------------------------------------------------------//
8001002d9d0d09cae206221fee925100c4bfb89d
41c1b5fca1bc80885caa8a0459346a5a2f5a2234
/hype/Circle.h
2b304ddeef747e6127ee189fb5c385c0e2fd7adb
[]
no_license
kylestew/uHype
6fbfbeee31ce1178839a865693a4a84c9708901e
9c1e0de43c63692ec376350f69bc95d5815c53e9
refs/heads/master
2021-01-12T12:16:23.204815
2017-05-27T18:13:00
2017-05-27T18:13:00
72,397,461
0
0
null
null
null
null
UTF-8
C++
false
false
237
h
Circle.h
class Circle : public Drawable { public: Circle(float x, float y, float rad) : Shape(x, y), rad{rad} {} void draw() const override { cout << "Circle: (" << x << ", " << y << ", " << rad << ")\n"; } private: float rad; };
866a3d688e58fd5f30ee3396588dabdcde815ec8
1df7f7bcc635b69571fc861b77540fea91151b0e
/src/System/Misc/tm_configure.hpp
fc6b5d26444c847f3fdad1d18147a5af3cf4ca65
[]
no_license
texmacs/TimScheme
a04e48fb7e47ff489cd7809bf4ca3e73f27494e2
e7ab2b52ac00b60942d07e7a250cd4e0ef2b7407
refs/heads/master
2020-03-21T16:26:04.323859
2019-04-24T09:27:47
2019-04-24T09:27:47
138,769,436
7
0
null
null
null
null
UTF-8
C++
false
false
1,270
hpp
tm_configure.hpp
/****************************************************************************** * MODULE : tm_configure.gen.in or tm_configure.gen.h * DESCRIPTION: Defines system dependent macros (using autoconf) * COPYRIGHT : (C) 1999 Joris van der Hoeven ******************************************************************************* * This software falls under the GNU general public license version 3 or later. * It comes WITHOUT ANY WARRANTY WHATSOEVER. For details, see the file LICENSE * in the root directory or <http://www.gnu.org/licenses/gpl-3.0.html>. ******************************************************************************/ #ifndef TM_CONFIGURE_H #define TM_CONFIGURE_H #define STD_SETENV #define TEXMACS_VERSION "1.99.8" #define TEXMACS_SOURCES "" #define OS_GNU_LINUX #define WORD_LENGTH 8 #define WORD_LENGTH_INC 7 #define WORD_MASK 0xfffffffffffffff8 #define MAX_FAST 264 // WORD_LENGTH more than power of 2 #define HOST_OS "linux-gnu" #define HOST_VENDOR "pc" #define HOST_CPU "x86_64" #define BUILD_USER "rendong" #define BUILD_DATE "2018-12-23T21:14:12" #define TM_DEVEL "TeXmacs-1.99.8" #define TM_DEVEL_RELEASE "TeXmacs-1.99.8-1" #define TM_STABLE "TeXmacs-1.99.8" #define TM_STABLE_RELEASE "TeXmacs-1.99.8-1" #endif // defined TM_CONFIGURE_H
300a7e27c472bf9b36dffd055302a83a16dde6b1
0188ab147c4b0a02c7e2261af704c7fc93ece563
/src/conf.h
4cf7bdbc3ded00d5cf96921d27f5bb4d35d73565
[]
no_license
soladj/ESP8266-NODEMCUV3-PIO-home-main-board
c1c4a2b905253b80dc646b4f0355f412f9b8ba90
9aaad20748689a6a2603e83e508a1c6cd2a7fb3a
refs/heads/main
2023-08-24T06:08:42.300010
2021-11-06T08:44:51
2021-11-06T08:44:51
410,191,056
0
0
null
null
null
null
UTF-8
C++
false
false
2,919
h
conf.h
#include <iostream> #include "data.h" #define DEVICE_ZONE 0 //0...15 #define DEVICE_ZONE_CHAR "0" #define CODE_LENGTH 24 #define MQTT_SUB_TOPIC_NUMBER 3 #define MQTT_SUB_TOPIC_STORED 2 #define MQTT_PUB_TOPIC_NUMBER 3 #define MQTT_FLOAT_TOPIC_NUMBER 2 #define MQTT_ALARM_VAR_NUMBER 1 #define MQTT_MAIN_TOPIC "asshome" #define MQTT_CALEFACTOR_TOPIC "calefactor" #define MQTT_TMP_TOPIC "temperature" #define MQTT_TSEL_TOPIC "temperaturesel" #define MQTT_STATUS_TOPIC "status" #define MQTT_REFRESH_TOPIC MQTT_MAIN_TOPIC "/" "refresh" #define MQTT_HELLO_TOPIC MQTT_MAIN_TOPIC "/" "hello" #define MQTT_HELLO_RESPONSE_TOPIC MQTT_MAIN_TOPIC "/" "hello_response" #define MQTT_CALEFACTOR_TSEL_TOPIC MQTT_MAIN_TOPIC "/" MQTT_CALEFACTOR_TOPIC "/" MQTT_TSEL_TOPIC "/" DEVICE_ZONE_CHAR #define MQTT_CALEFACTOR_TMP_TOPIC MQTT_MAIN_TOPIC "/" MQTT_CALEFACTOR_TOPIC "/" MQTT_TMP_TOPIC "/" DEVICE_ZONE_CHAR #define MQTT_CALEFACTOR_STATUS_TOPIC MQTT_MAIN_TOPIC "/" MQTT_CALEFACTOR_TOPIC "/" MQTT_STATUS_TOPIC #define MQTT_CALEFACTOR_TSEL_TOPIC_ENUM 1 #define MQTT_CALEFACTOR_TMP_TOPIC_ENUM 2 #define MQTT_CALEFACTOR_STATUS_TOPIC_ENUM 3 #define MQTT_CALEFACTOR_TSEL_VALUE_ALARM 2000 #define MQTT_CALEFACTOR_TMP_VALUE_ALARM 2000 #define MQTT_CALEFACTOR_POWER_VALUE_ALARM 1 #define MQTT_CALEFACTOR_STATUS_VALUE_ALARM 0 #define MQTT_CALEFACTOR_TSEL_NAME_ALARM MQTT_CALEFACTOR_TSEL_TOPIC #define MQTT_CALEFACTOR_TMP_NAME_ALARM MQTT_CALEFACTOR_TMP_TOPIC #define MQTT_CALEFACTOR_POWER_NAME_ALARM MQTT_CALEFACTOR_POWER_TOPIC #define MQTT_CALEFACTOR_STATUS_NAME_ALARM MQTT_CALEFACTOR_STATUS_TOPIC char main_topic[CODE_LENGTH+1]; uint8_t own_topic; const char* mqtt_sub_topics[MQTT_SUB_TOPIC_NUMBER] = { MQTT_CALEFACTOR_TSEL_TOPIC, MQTT_CALEFACTOR_TMP_TOPIC, MQTT_CALEFACTOR_STATUS_TOPIC }; int mqtt_sub_topics_int[MQTT_SUB_TOPIC_NUMBER] = { MQTT_CALEFACTOR_TSEL_TOPIC_ENUM, MQTT_CALEFACTOR_TMP_TOPIC_ENUM, MQTT_CALEFACTOR_STATUS_TOPIC_ENUM }; const char* mqtt_pub_topics[MQTT_PUB_TOPIC_NUMBER] = { MQTT_CALEFACTOR_TSEL_TOPIC, MQTT_CALEFACTOR_TMP_TOPIC, MQTT_CALEFACTOR_STATUS_TOPIC }; const char* mqtt_float_topics[MQTT_FLOAT_TOPIC_NUMBER] = { MQTT_CALEFACTOR_TSEL_TOPIC, MQTT_CALEFACTOR_TMP_TOPIC }; uint16_t tsel; uint16_t tmp = 2000; uint16_t cpower; uint16_t cstatus; uint16_t *mqtt_sub_var[MQTT_SUB_TOPIC_NUMBER] = { &tsel, &tmp, &cstatus }; const uint16_t *mqtt_pub_var[MQTT_PUB_TOPIC_NUMBER] = { &tsel, &tmp, &cstatus }; uint16_t *mqtt_alarm_var[MQTT_ALARM_VAR_NUMBER] = { &cstatus }; const uint16_t mqtt_alarm_val[MQTT_ALARM_VAR_NUMBER] = { MQTT_CALEFACTOR_STATUS_VALUE_ALARM }; const char* mqtt_alarm_name[MQTT_ALARM_VAR_NUMBER] = { MQTT_CALEFACTOR_STATUS_NAME_ALARM }; //Command config #define MAX_COMMAND_COUNTER 7 #define MAX_COMMAND_LENGHT 16 #define MAX_VALUE_LENGHT 16 char commands[MAX_COMMAND_COUNTER][MAX_COMMAND_LENGHT]; char values[MAX_COMMAND_COUNTER][MAX_VALUE_LENGHT];
c1ccc448198cdf9c80a5d8ef48a23416ed8a2c65
bf45df9d7d28a8563bf7ed9834c6942a9bf9b4d4
/src/yazik/testlib/yaz_test_macros.hpp
249fd6c40d9ba5b65530b3855bc3e9b3447aa444
[]
no_license
blockspacer/yazik
f6e612b967fbce9257f0173dd456e7b9fd8a34c5
c63116823c670f74606da38db84b77102751ac9c
refs/heads/master
2023-03-02T10:45:39.320608
2021-02-17T02:17:02
2021-02-17T02:17:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,228
hpp
yaz_test_macros.hpp
#pragma once #include <yazik/utility/result.hpp> #include <yazik/concurrency/future_result.hpp> #include <yazik/concurrency/scheduler.hpp> #include <yazik/utility/macro.hpp> #define CATCH_CONFIG_PREFIX_ALL #include <catch2/catch_test_macros.hpp> #define TEST_CASE CATCH_TEST_CASE #define REQUIRE CATCH_REQUIRE #define REQUIRE_FALSE CATCH_REQUIRE_FALSE #define _YAZ_R_TEST_CASE(ID, ...) \ ::yazik::Result<> ID(); \ TEST_CASE(__VA_ARGS__) { \ auto res = ID(); \ if (!res) \ CATCH_FAIL(res.error()); \ } \ ::yazik::Result<> ID() #define YAZ_R_TEST_CASE(...) _YAZ_R_TEST_CASE( YAZ_CONCAT(__TEST_CASE, __LINE__ ), __VA_ARGS__) #define _YAZ_F_TEST_CASE(ID, ...) \ ::yazik::Task<> ID(::yazik::concurrency::scheduler_ptr_t); \ TEST_CASE(__VA_ARGS__) { \ auto work = ::yazik::concurrency::create_asio_scheduler(); \ ::yazik::concurrency::mark_default_executor(work); \ auto res = work->run_until_done(ID(work)); \ if (!res) \ CATCH_FAIL(res.error()); \ } \ ::yazik::Task<> ID(::yazik::concurrency::scheduler_ptr_t __scheduler) #define YAZ_F_TEST_CASE(...) _YAZ_F_TEST_CASE( YAZ_CONCAT(__TEST_CASE, __LINE__ ), __VA_ARGS__)
f3a8478b6d266828a3bd7488c8b0dbe768af2972
28ed617c67ac84b98dd28d94f063a195c6a10b3e
/ldd/cage/internal/.svn/text-base/keeper_impl.h.svn-base
16b2826b57538a91276cb1681fa0a72dc58bdaac
[]
no_license
Strongc/EasyLib
b5ec5bae21b4a92b7deee646d1bfe3505aa2bafc
d8c406964ad21f0bfff99b2fe44134b32809f068
refs/heads/master
2021-01-22T01:28:48.631884
2015-12-29T11:46:53
2015-12-29T11:46:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,757
keeper_impl.h.svn-base
#ifndef LDD_CAGE_ZOOKEEPER_IMPL_H_ #define LDD_CAGE_ZOOKEEPER_IMPL_H_ #include <boost/noncopyable.hpp> #include <vector> #include <map> #include "ldd/cage/keeper.h" #include "functions.h" namespace ldd { namespace cage { typedef std::vector<NodeWatcher> NodeWatchers; typedef std::vector<ChildWatcher> ChildWatchers; typedef std::map<std::string, NodeWatchers> NodeWatchersMap; typedef std::map<std::string, ChildWatchers> ChildWatchersMap; class Keeper::Impl : boost::noncopyable { public: Impl(net::EventLoop* event_loop, const KeeperListener& listener); ~Impl(); bool IsOpen() const; bool IsUnrecoverable() const; int timeout() const; bool Open(const std::string& dest, int timeout); void Close(); void AddAuth(const std::string& scheme, const std::string& cert, const AddAuthCallback& callback); void Create(const std::string& path, const std::string& value, const std::vector<Acl>& acls, Mode::Type mode, const CreateCallback& callback); void Delete(const std::string& path, int32_t version, const DeleteCallback& callback); void Exists(const std::string& path, const NodeWatcher& watcher, const ExistsCallback& callback); void Get(const std::string& path, const NodeWatcher& watcher, const GetCallback& callback); void Set(const std::string& path, const std::string& value, int32_t version, const SetCallback& callback); void GetAcl(const std::string& path, const GetAclCallback& callback); void SetAcl(const std::string& path, const std::vector<Acl>& acls, int32_t version, const SetAclCallback& callback); void GetChildren(const std::string& path, const ChildWatcher& watcher, const GetChildrenCallback& callback); void GetChildrenWithStat(const std::string& path, const ChildWatcher& watcher, const GetChildrenWithStatCallback& callback); void Multi(const std::vector<Op*>& ops, const MultiCallback& callback); private: friend void WatchSession(zhandle_t*, int, int, const char*, void*); friend void WatchNode(zhandle_t*, int, int, const char*, void*); friend void WatchChild(zhandle_t*, int, int, const char*, void*); Status Interest(int* fd, int* interest, ldd::util::TimeDiff* timeout); Status Process(int events); void UpdateEvent(); void ClearEvent(); void HandleEvent(int events); mutable zhandle_t* zh_; net::EventLoop* event_loop_; net::FdEvent event_; KeeperListener listener_; NodeWatchersMap node_watcher_; ChildWatchersMap child_watcher_; }; } // namespace cage } // namespace ldd #endif // LDD_CAGE_ZOOKEEPER_IMPL_H_
e643587c17c1e49c6c2ae35710991c55142549f1
9ceb525db220cedb7020fee25b7949b9a751da74
/lab5.5_Parallelogram.cpp
4d1d3d0618982c2eee320256ee0880251319fe31
[]
no_license
mahatosourav00/cs141
5916209d6bdfbd3c39b282d0b6f3175e82facf78
f43247c1d49f28655f7dffcbcc600b581e9dda3d
refs/heads/master
2020-03-25T10:59:54.094212
2018-11-19T08:23:28
2018-11-19T08:23:28
143,714,897
0
0
null
null
null
null
UTF-8
C++
false
false
334
cpp
lab5.5_Parallelogram.cpp
#include<iostream> using namespace std; int main(){ //draw rhombus int h, w; cin>>h; cin>>w; cout<<"enter height and width of the rhombus"<<endl; for(int i=0; i<h; i++){ //draw spaces for(int j=0; j<(w-i); j++){ cout<<" "; } //draw stars for(int j=0; j<w; j++){ cout<<"*"; } cout<<endl; } //done return 0; }
bf49491b022bc1160451cc069f9a47d821846c0d
e942cb8a3b390a42967fbbb9239db7e01895405a
/C++Implementation/Treblebcross UVa 10561.cpp
3c416a7e96ad687b7229e810ae2e4983481f52b0
[]
no_license
TCtobychen/IntrotoAlgorithm
53cbd1b24d13b715d642b074d6cb219cca128729
36cf607edad1d2163e115b78b8dad8f7c7facfbc
refs/heads/master
2021-09-14T10:45:34.301997
2018-05-12T07:51:55
2018-05-12T07:51:55
112,214,038
0
0
null
null
null
null
UTF-8
C++
false
false
382
cpp
Treblebcross UVa 10561.cpp
// // Treblebcross UVa 10561.cpp // Learning C++ // // Created by 杨 on 2017/7/29. // Copyright © 2017年 杨. All rights reserved. // /*#include <iostream> using namespace std; int a[100]; int n; int main() { cin >> n; char c; for(int i=0;i<n;i++) { cin >> c; if(c=='.') a[i]=0; if(c=='X') a[i]=1; } }*/
4be384b1a189a7e11444e538e45a54969ebbc451
7c3d724d136a7e08e9ea78aa934daab85da1bc9b
/Øving8/Øving8/CourseCatalog.cpp
2bb202bf5a8be9b05a955da15f6bc3515be059b8
[]
no_license
TheLarsinator/NTNU
3836eaed64a506d81cc67fca0f29267d74671deb
d7155ec499ecf98f90c69e8c21b45a807480c125
refs/heads/master
2021-01-10T15:11:41.714500
2017-01-15T21:18:41
2017-01-15T21:18:41
52,882,016
0
0
null
null
null
null
UTF-8
C++
false
false
806
cpp
CourseCatalog.cpp
#include "stdafx.h" #include <iostream> #include <Windows.h> #include <cmath> #include <ctime> #include <string> #include <map> #include "CourseCatalog.h" CC::CC() { } string CC::get(string subject) { return catalog[subject]; } void CC::set(string subject, string value) { catalog[subject] = value; } void CC::eraseFromCatalog(string subject) { catalog[subject].erase(); } void CC::printCatalog() { map<string, string>::const_iterator iter; for (iter = catalog.begin(); iter != catalog.end(); iter++) { cout << iter->first << '\t' << iter->second << endl; } } ostream& operator << (ostream &out, CC &CC) { map<string, string>::const_iterator iter; for (iter = CC.catalog.begin(); iter != CC.catalog.end(); iter++) { out << iter->first << '\t' << iter->second << endl; } return out; }
af2a327ce2be5be542bb677dd65685412d008ecf
315450354c6ddeda9269ffa4c96750783963d629
/CMSSW_7_0_4/src/TotemRPValidation/RPAngleValidation/interface/RPAngleValidation.h
e9b8edee0d51bf5fe104b5915616eb56f9892324
[]
no_license
elizamelo/CMSTOTEMSim
e5928d49edb32cbfeae0aedfcf7bd3131211627e
b415e0ff0dad101be5e5de1def59c5894d7ca3e8
refs/heads/master
2021-05-01T01:31:38.139992
2017-09-12T17:07:12
2017-09-12T17:07:12
76,041,270
0
2
null
null
null
null
UTF-8
C++
false
false
2,195
h
RPAngleValidation.h
#ifndef TotemRPValidation_RPAngleValidation_RPAngleValidation_h #define TotemRPValidation_RPAngleValidation_RPAngleValidation_h #include <boost/shared_ptr.hpp> #include "FWCore/Framework/interface/EDAnalyzer.h" #include "TotemCondFormats/BeamOpticsParamsObjects/interface/BeamOpticsParams.h" #include "RecoTotemRP/RPRecoDataFormats/interface/RPFittedTrackCollection.h" #include "TH2D.h" namespace edm { class ParameterSet; class EventSetup; class Event; } struct PrimaryProton { HepMC::FourVector vertex; HepMC::FourVector momentum; double thetaX, thetaY; bool found; }; struct TrackHit { double x, y, z; }; class RPAngleValidation : public edm::EDAnalyzer { public: explicit RPAngleValidation(const edm::ParameterSet&); ~RPAngleValidation(); private: virtual void beginRun(edm::Run const&, edm::EventSetup const&); virtual void analyze(const edm::Event&, const edm::EventSetup&); virtual void endJob(); enum { rp_150_l, rp_220_l, rp_150_r, rp_220_r, NSTATIONS }; enum { near_top, near_bottom, near_horiz, far_horiz, far_top, far_bottom, NPOTS }; typedef std::map<RPId, TrackHit> rec_tracks_collection; typedef std::vector<int> station_rp_ids_type; bool FindProtons(const edm::Handle<edm::HepMCProduct> &HepMCEvt, int smeared); int SelectHits(const RPFittedTrackCollection &tracks, rec_tracks_collection & coll, const station_rp_ids_type& st_ids); int calcTrackTheta(std::vector<double> &theta, const rec_tracks_collection &coll, int arm); std::string StIdToName(int st_id); edm::ParameterSet conf_; BeamOpticsParams BOPar_; struct PrimaryProton prot_[2][2]; /// left, right : primary, secondary std::string OriginalHepMCProductLabel_; std::string OriginalHepMCModuleName_; std::string SmearedHepMCProductLabel_; std::string SmearedHepMCModuleName_; std::string hist_file_name_; station_rp_ids_type station_ids_[NSTATIONS]; /// station std::auto_ptr<TH2D> angle_dists_[2][NSTATIONS]; /// X, Y : station std::auto_ptr<TH1D> angle_dists_1d_[2][2][NSTATIONS]; /// IP, RP : X, Y : station int verbosity_; edm::InputTag rpFittedTrackCollectionLabel; }; #endif
40b673b6badfd5bcde7dce973dd71096e5489a2d
bb910965169bfbb1fd36753fd0209e77cabffb05
/examples/openmp/deque.cpp
0725bbfbf2bf48c777214eff74740a78c5f2dbba
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
stotko/stdgpu
8659aeacf82c807c1162e796d09a422c23a431bf
e085756a2cc5f99a6610301211ffc12b44aa2f65
refs/heads/master
2023-09-02T01:23:10.271531
2023-08-28T13:36:02
2023-08-28T13:56:17
202,712,923
1,012
75
Apache-2.0
2023-09-13T13:54:36
2019-08-16T11:04:33
C++
UTF-8
C++
false
false
2,893
cpp
deque.cpp
/* * Copyright 2020 Patrick Stotko * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <iostream> #include <thrust/copy.h> #include <thrust/reduce.h> #include <thrust/sequence.h> #include <stdgpu/deque.cuh> // stdgpu::deque #include <stdgpu/iterator.h> // device_begin, device_end #include <stdgpu/memory.h> // createDeviceArray, destroyDeviceArray #include <stdgpu/platform.h> // STDGPU_HOST_DEVICE struct is_odd { STDGPU_HOST_DEVICE bool operator()(const int x) const { return x % 2 == 1; } }; void insert_neighbors_with_duplicates(const int* d_input, const stdgpu::index_t n, stdgpu::deque<int>& deq) { #pragma omp parallel for for (stdgpu::index_t i = 0; i < n; ++i) { int num = d_input[i]; int num_neighborhood[3] = { num - 1, num, num + 1 }; is_odd odd; for (int num_neighbor : num_neighborhood) { if (odd(num_neighbor)) { deq.push_back(num_neighbor); } else { deq.push_front(num_neighbor); } } } } int main() { // // EXAMPLE DESCRIPTION // ------------------- // This example demonstrates how stdgpu::deque is used to compute a set of duplicated numbers. // Every number is contained 3 times, except for the first and last one. // Furthermore, even numbers are put into the front, whereas odd number are put into the back. // const stdgpu::index_t n = 100; int* d_input = createDeviceArray<int>(n); stdgpu::deque<int> deq = stdgpu::deque<int>::createDeviceObject(3 * n); thrust::sequence(stdgpu::device_begin(d_input), stdgpu::device_end(d_input), 1); // d_input : 1, 2, 3, ..., 100 insert_neighbors_with_duplicates(d_input, n, deq); // deq : 0, 1, 1, 2, 2, 2, 3, 3, 3, ..., 99, 99, 99, 100, 100, 101 auto range_deq = deq.device_range(); int sum = thrust::reduce(range_deq.begin(), range_deq.end(), 0, thrust::plus<int>()); const int sum_closed_form = 3 * (n * (n + 1) / 2); std::cout << "The set of duplicated numbers contains " << deq.size() << " elements (" << 3 * n << " expected) and the computed sum is " << sum << " (" << sum_closed_form << " expected)" << std::endl; destroyDeviceArray<int>(d_input); stdgpu::deque<int>::destroyDeviceObject(deq); }
cafca2847e9b73c5cc429f90bac1c77a98e4d9d9
f1b4399af130b02b13a4d071ff832ed28ede151c
/src/transport.cpp
75c86088c3db786294083c37d1dacc2591ff6c6c
[ "BSD-3-Clause" ]
permissive
KDE/kmail-account-wizard
220a1ab089a744cab1592c3620ccf6b7f8535370
81f01fa5957b5df6c90c49cd38230e3121a85bcb
refs/heads/master
2023-08-17T09:59:37.859362
2023-08-08T01:52:18
2023-08-08T01:52:18
66,907,965
5
1
null
null
null
null
UTF-8
C++
false
false
5,044
cpp
transport.cpp
/* SPDX-FileCopyrightText: 2009 Volker Krause <vkrause@kde.org> SPDX-License-Identifier: LGPL-2.0-or-later */ #include "transport.h" #include <MailTransport/TransportManager> #include <KLocalizedString> #define TABLE_SIZE x template<typename T> struct StringValueTable { const char *name; using value_type = T; value_type value; }; static const StringValueTable<MailTransport::Transport::EnumEncryption> encryptionEnum[] = {{"none", MailTransport::Transport::EnumEncryption::None}, {"ssl", MailTransport::Transport::EnumEncryption::SSL}, {"tls", MailTransport::Transport::EnumEncryption::TLS}}; static const int encryptionEnumSize = sizeof(encryptionEnum) / sizeof(*encryptionEnum); static const StringValueTable<MailTransport::Transport::EnumAuthenticationType> authenticationTypeEnum[] = { {"login", MailTransport::Transport::EnumAuthenticationType::LOGIN}, {"plain", MailTransport::Transport::EnumAuthenticationType::PLAIN}, {"cram-md5", MailTransport::Transport::EnumAuthenticationType::CRAM_MD5}, {"digest-md5", MailTransport::Transport::EnumAuthenticationType::DIGEST_MD5}, {"gssapi", MailTransport::Transport::EnumAuthenticationType::GSSAPI}, {"ntlm", MailTransport::Transport::EnumAuthenticationType::NTLM}, {"apop", MailTransport::Transport::EnumAuthenticationType::APOP}, {"clear", MailTransport::Transport::EnumAuthenticationType::CLEAR}, {"oauth2", MailTransport::Transport::EnumAuthenticationType::XOAUTH2}, {"anonymous", MailTransport::Transport::EnumAuthenticationType::ANONYMOUS}}; static const int authenticationTypeEnumSize = sizeof(authenticationTypeEnum) / sizeof(*authenticationTypeEnum); template<typename T> static typename T::value_type stringToValue(const T *table, const int tableSize, const QString &string, bool &valid) { const QString ref = string.toLower(); for (int i = 0; i < tableSize; ++i) { if (ref == QLatin1String(table[i].name)) { valid = true; return table[i].value; } } valid = false; return table[0].value; // TODO: error handling } Transport::Transport(const QString &type, QObject *parent) : SetupObject(parent) , m_encr(MailTransport::Transport::EnumEncryption::TLS) , m_auth(MailTransport::Transport::EnumAuthenticationType::PLAIN) { if (type == QLatin1String("smtp")) { m_port = 25; } } void Transport::create() { Q_EMIT info(i18n("Setting up mail transport account...")); MailTransport::Transport *mt = MailTransport::TransportManager::self()->createTransport(); mt->setName(m_name); mt->setHost(m_host); if (m_port > 0) { mt->setPort(m_port); } if (!m_user.isEmpty()) { mt->setUserName(m_user); mt->setRequiresAuthentication(true); } if (!m_password.isEmpty()) { mt->setStorePassword(true); mt->setPassword(m_password); } mt->setEncryption(m_encr); mt->setAuthenticationType(m_auth); m_transportId = mt->id(); mt->save(); Q_EMIT info(i18n("Mail transport uses '%1' encryption and '%2' authentication.", m_encrStr, m_authStr)); MailTransport::TransportManager::self()->addTransport(mt); MailTransport::TransportManager::self()->setDefaultTransport(mt->id()); if (m_editMode) { edit(); } Q_EMIT finished(i18n("Mail transport account set up.")); } void Transport::destroy() { MailTransport::TransportManager::self()->removeTransport(m_transportId); Q_EMIT info(i18n("Mail transport account deleted.")); } void Transport::edit() { MailTransport::Transport *mt = MailTransport::TransportManager::self()->transportById(m_transportId, false); if (!mt) { Q_EMIT error(i18n("Could not load config dialog for UID '%1'", m_transportId)); } else { MailTransport::TransportManager::self()->configureTransport(mt->identifier(), mt, nullptr); } } void Transport::setEditMode(const bool editMode) { m_editMode = editMode; } void Transport::setName(const QString &name) { m_name = name; } void Transport::setHost(const QString &host) { m_host = host; } void Transport::setPort(int port) { m_port = port; } void Transport::setUsername(const QString &user) { m_user = user; } void Transport::setPassword(const QString &password) { m_password = password; } void Transport::setEncryption(const QString &encryption) { bool valid; m_encr = stringToValue(encryptionEnum, encryptionEnumSize, encryption, valid); if (valid) { m_encrStr = encryption; } } void Transport::setAuthenticationType(const QString &authType) { bool valid; m_auth = stringToValue(authenticationTypeEnum, authenticationTypeEnumSize, authType, valid); if (valid) { m_authStr = authType; } } int Transport::transportId() const { return m_transportId; }
b4c3b1eeb1cac0ee4cdcf4ab0ad3d5eef1327866
8908e62a428ffaa2a1390f54f956b9f23eb83d94
/oil_volume_table.cpp
215616028672005aef650491eab99d1225c682c6
[]
no_license
Hello-lee-cell/anysafeplat_12
fe3d1a239e8de2ff51f077fdea0f96555fedeee4
9da9bba5bda53ca62bdd2c1445a8baded29e402c
refs/heads/master
2022-12-17T09:06:06.334863
2020-09-11T02:30:46
2020-09-11T02:30:46
294,568,292
0
0
null
2020-09-11T06:31:05
2020-09-11T02:00:32
C++
UTF-8
C++
false
false
4,854
cpp
oil_volume_table.cpp
#include"config.h" //罐长 280cm float OilTank_50[300] = { 0 ,0.0054,0.0381,0.0805,0.1305,0.1872,0.2497,0.3176,0.3903,0.4677,0.5493,0.6349,0.7244, 0.8174, 0.9140, 1.0139, 1.1170, 1.2231, 1.3323, 1.4442, 1.5590, 1.6764,1.7964,1.9190,2.0440,2.1713,2.3010,2.4330,2.5672,2.7035,2.8419,2.9823,3.1247, 3.2691, 3.4154, 3.5636, 3.7136, 3.8654, 4.0189, 4.1742, 4.3311, 4.4896,4.6498,4.8116,4.9749,5.1397,5.3060,5.4737,5.6429,5.8135,5.9855,6.1588,6.3335, 6.5094, 6.6867, 6.8651, 7.0449, 7.2258, 7.4079, 7.5912, 7.7756, 7.9611,8.1477,8.3354,8.5242,8.7140,8.9049,9.0967,9.2895,9.4833,9.6780,9.8737,10.0703,10.2678,10.4661,10.6653,10.8654,11.0662,11.2679,11.4704,11.6737, 11.8777,12.0825,12.2880,12.4942,12.7012,12.9088,13.1171,13.3260,13.5356,13.7458,13.9567,14.1681,14.3802,14.5928,14.8059,15.0196,15.2339,15.4486,15.6639,15.8797, 16.3126,16.5298,16.7474,16.9654,17.1839,17.4027,17.6220,17.8416,18.0616,18.2819,18.5026,18.7236,18.9449,19.1666,19.3885,19.6107,19.8331,20.0559,20.2788,20.5020, 20.8255,20.9491,21.1729,21.3969,21.4662,21.6211,21.8455,22.0700,22.2946,22.5194,22.7443,22.9692,23.1943,23.4195,23.6447,23.8700,24.0953,24.3207,24.5461,24.7715, 24.9969,25.2222,25.4476,25.6729,25.8982,26.1234,26.3486,26.5737,26.7987,27.0235,27.2483,27.4729,27.6974,27.9218,28.1460,28.3700,28.5938,28.8175,29.0409,29.2641, 29.4870,29.7098,29.9322,30.1544,30.3764,30.5980,30.8193,31.0403,31.2610,31.4813,31.7013,31.9210,32.1402,32.3590,32.5775,32.7955,33.0131,33.2303,33.4470,33.6632, 33.8790,34.0943,34.3090,34.5233,34.7370,34.9502,35.1628,35.3748,35.5862,35.7971,36.0073,36.2169,36.4258,36.6341,36.8418,37.0487,37.2549,37.4606,37.6652,37.8692, 38.0725,38.4767,38.4767,38.6776,38.8776,39.0768,39.2752,39.4726,39.6692,39.8649,40.0596,40.2534,40.4462,40.6381,40.8289,41.0187,41.2075,41.3952,41.5818,41.7674, 41.9518,42.1350,42.3171,42.4981,42.6778,42.8563,43.0335,43.2094,43.3841,43.5574,43.7294,43.9000,44.0692,44.2369,44.4032,44.5681,44.7314,44.8931,45.0533,45.2118, 45.3688,45.5240,45.6775,45.8293,45.9793,46.1275,46.2738,46.4182,46.5606,46.7011,46.8395,46.9758,47.1099,47.2719,47.3716,47.4990,47.6239,47.7465,47.8665,47.9839, 48.0987,48.2107,48.3198,48.4259,48.5290,48.6289,48.7255,48.8186,48.9080,48.9937,49.0753,49.1526,49.2254,49.2932,49.3558,49.4124,49.4625,49.5048,49.5375,49.5555 }; //罐长 260cm float OilTank_40[300] = { 0, 0.01539,0.04350,0.07987,0.12291,0.17169,0.22557,0.28411,0.34693,0.41375,0.48433,0.55846,0.63596,0.71669,0.80049,0.88725,0.97686,1.06921,1.16422,1.26179,1.36186, 1.46433,1.56915,1.67626,1.78558,1.89706,2.01066,2.12631,2.24397,2.36360,2.48514,2.60855,2.73380,2.86085,2.98965,3.12017,3.25237,3.38623,3.52171,3.65877,3.79738, 3.93753,4.07916,4.22227,4.36682,4.51277,4.66012,4.80883,4.95887,5.11022,5.26286,5.41676,5.57191,5.72827,5.88582,6.04455,6.20443,6.36545,6.52757,6.69078,6.85506, 7.02040,7.18676,7.35413,7.52250,7.69183,7.86213,8.03336,8.20551,8.37855,8.55249,8.72728,8.90293,9.07941,9.25670,9.43479,9.61366,9.79329,9.97368,10.15479,10.33663, 10.51916,10.70238,10.88626,11.07081,11.25598,11.44179,11.62820,11.81520,12.00278,12.19093,12.37962,12.56885,12.75859,12.94884,13.13958,13.33080,13.52247,13.71460,13.90715,14.10013, 14.29351,14.48728,14.68143,14.87594,15.07080,15.26599,15.46151,15.65733,15.85345,16.04985,16.24652,16.44343,16.64059,16.83798,17.03558,17.23337,17.43136,17.62951,17.82783,18.02629, 18.22488,18.42360,18.62242,18.82133,19.02032,19.21938,19.41849,19.61764,19.81682,20.01601,20.21407,20.41325,20.61240,20.81151,21.01057,21.20956,21.40847,21.60729,21.80601,22.00460, 22.20306,22.40138,22.59953,22.79752,22.99531,23.19291,23.39030,23.58745,23.78437,23.98104,24.17744,24.37356,24.56938,24.76490,24.96009,25.15495,25.34946,25.54361,25.73738,25.93076, 26.12374,26.31629,26.50842,26.70009,26.89131,27.08205,27.27230,27.46204,27.65127,27.83996,28.02811,28.21569,28.40269,28.58910,28.77490,28.96008,29.14462,29.32851,29.51173,29.69426, 29.87610,30.05721,30.23760,30.41723,30.59610,30.77419,30.95148,31.12796,31.30361,31.47840,31.65233,31.82538,31.99753,32.16876,32.33905,32.50839,32.67676,32.84413,33.01049,33.17582, 33.34011,33.50332,33.66544,33.82645,33.98634,34.14507,34.30262,34.45898,34.61413,34.76803,34.92067,35.07202,35.22206,35.37077,35.51811,35.66407,35.80862,35.95172,36.09336,36.23350, 36.37212,36.50918,36.64466,36.77852,36.91072,37.04124,37.17004,37.29709,37.42234,37.54575,37.66729,37.78692,37.90458,38.02023,38.13383,38.24531,38.35463,38.46174,38.56656,38.66903, 38.76909,38.86667,38.96167,39.05403,39.14364,39.23040,39.31420,39.39492,39.47243,39.54656,39.61714,39.68396,39.74678,39.80532,39.85920,39.90798,39.95102,39.98739,40.01550,40.03089 }; //罐长 240cm float OilTank_30[300] = { 0, };
4066203ef1efb03801eb5858ebfd1fc286e4c7cf
862c2227203b744bfc06cc912bdbe04972336fc7
/leetcode/medium/comb_sum_1.cpp
263831360eed11502f3f4b0560c5620794fad176
[]
no_license
sarckk/codeforces-solutions
54e558c90d08e22143125d688e4037eb5691f1bf
2d6bbe33bb97981b061ef4d0cee4cdc22cefd8be
refs/heads/master
2023-07-03T12:36:36.262593
2021-08-05T21:49:24
2021-08-05T21:49:24
374,132,833
0
0
null
null
null
null
UTF-8
C++
false
false
853
cpp
comb_sum_1.cpp
#include <bits/stdc++.h> using namespace std; class Solution { public: vector<vector<int>> combinationSum(vector<int>& candidates, int target) { vector<vector<int>> res; vector<int> current; if(!candidates.size()) return res; sort(candidates.begin(), candidates.end()); rec(candidates, target, current, res, 0); return res; } void rec(vector<int>& candidates, int target, vector<int>& current, vector<vector<int>>& res, int begin) { if(target < 0) return; if(target == 0) { res.push_back(current); return; } for(int i = begin; i < candidates.size(); i++) { current.push_back(candidates[i]); rec(candidates, target-candidates[i], current, res, i); current.pop_back(); } } };
6a556aa2fa1feaf9c2ef9b825abf63b2bffdaa05
9351f522eb6e1538430d0e1bcf05bba2a6531f35
/hellowCPP/3stage/SumNumber_11720.cpp
eaa3a34a357b6a1e8f172c47a2a9763b78faf470
[]
no_license
BoGyuPark/vscode_BOJ
98711488b560f2d3b930a70f2482ee273f15b078
bd7b707d7c7f269232618c96c682edd5a8611f70
refs/heads/master
2020-03-26T06:17:18.026452
2018-08-29T12:19:42
2018-08-29T12:19:42
144,597,979
0
0
null
null
null
null
UTF-8
C++
false
false
248
cpp
SumNumber_11720.cpp
//https://www.acmicpc.net/problem/11720 #include<iostream> using namespace std; main() { int N; cin>>N; int sum=0; char num[101]={0,}; cin>>num; for(int i=0; i<N; i++){ sum += num[i]-'0'; } cout<<sum<<endl; }
5328d1334244013893c077938ee67b0f630ce4b6
f015d2b8264dfd2b45349a7a421dbec5375d462f
/test/12.cpp
2f83bbc660d0cc449432a3590b520b98d31160d6
[]
no_license
Request2609/codeOfPractice
b8ab9f36a2e7ebd435645868f71ede0bd9875056
5226ff6616272f83423780209cb2dfe43c77527a
refs/heads/master
2021-07-12T17:25:28.637166
2020-09-20T14:44:20
2020-09-20T14:44:20
199,008,203
5
2
null
null
null
null
UTF-8
C++
false
false
1,473
cpp
12.cpp
#include <iostream> #include <vector> #include <map> using namespace std ; class Solution { public: int removeDuplicates(vector<int>& nums) { map<int, int>ls ; int len = nums.size() ; int l = 0 ; int r = l ; for(int i=0; i<len; i++) { //要是当前元素是重复元素,则记录当前元素后面的元素 if(ls.find(nums[i]) == ls.end()) { //使用l保存i的值 //元素第一次出现 ls[nums[i]] = 1 ; l = i+1 ; } else { //第一次,初始化r的值为i,第一个重复元素 if(r==0) { r = i+1 ; } while(r<len) { //要是r指向的元素不存在于ls中(也就是之前没出现过) if(ls.find(nums[r]) == ls.end()) { nums[i] = nums[r] ; i -- ; break ; } else { r++ ; } } if(r == len) break ; } } return l; } }; int main() { int c; vector<int>ls ; for(;;) { cin >> c ; if(c == -1) break ; ls.push_back(c) ; } Solution ss ; cout << ss.removeDuplicates(ls) << endl ; return 0; }
a2622366c510e4466578f16cc06997b812fc8f9b
4e40487eb963985c55a8b4a0518d0d4612e5291e
/reef-env/ROCm-OpenCL-Runtime/amdocl/cl_d3d10.cpp
0c0dcdd5b8b8736a5f2433517f640f1347912f45
[ "Apache-2.0", "MIT" ]
permissive
SJTU-IPADS/reef-artifacts
2858191efa1ce6423f2a912bfb9758af96e62ea7
8750974f2d6655525a2cc317bf2471914fe68dab
refs/heads/master
2023-04-06T16:48:31.807517
2022-05-27T05:57:37
2022-05-27T05:57:37
473,072,609
36
6
null
null
null
null
UTF-8
C++
false
false
48,186
cpp
cl_d3d10.cpp
/* Copyright (c) 2009-present Advanced Micro Devices, Inc. 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. */ #ifdef _WIN32 #include "top.hpp" #include "cl_common.hpp" #include "cl_d3d10_amd.hpp" #include "platform/command.hpp" #include <cstring> #include <utility> /*! \addtogroup API * @{ * * \addtogroup CL_D3D10_Interops * * This section discusses OpenCL functions that allow applications to use Direct3D 10 * resources (buffers/textures) as OpenCL memory objects. This allows efficient sharing of * data between OpenCL and Direct3D 10. The OpenCL API can be used to execute kernels that * read and/or write memory objects that are also the Direct3D resources. * An OpenCL image object can be created from a D3D10 texture object. An * OpenCL buffer object can be created from a D3D10 buffer object (index/vertex). * * @} * \addtogroup clGetDeviceIDsFromD3D10KHR * @{ */ RUNTIME_ENTRY(cl_int, clGetDeviceIDsFromD3D10KHR, (cl_platform_id platform, cl_d3d10_device_source_khr d3d_device_source, void* d3d_object, cl_d3d10_device_set_khr d3d_device_set, cl_uint num_entries, cl_device_id* devices, cl_uint* num_devices)) { cl_int errcode; ID3D10Device* d3d10_device = NULL; cl_device_id* gpu_devices; cl_uint num_gpu_devices = 0; bool create_d3d10Device = false; static const bool VALIDATE_ONLY = true; HMODULE d3d10Module = NULL; if (platform != NULL && platform != AMD_PLATFORM) { LogWarning("\"platrform\" is not a valid AMD platform"); return CL_INVALID_PLATFORM; } if (((num_entries > 0 || num_devices == NULL) && devices == NULL) || (num_entries == 0 && devices != NULL)) { return CL_INVALID_VALUE; } // Get GPU devices errcode = clGetDeviceIDs(NULL, CL_DEVICE_TYPE_GPU, 0, NULL, &num_gpu_devices); if (errcode != CL_SUCCESS && errcode != CL_DEVICE_NOT_FOUND) { return CL_INVALID_VALUE; } if (!num_gpu_devices) { *not_null(num_devices) = 0; return CL_DEVICE_NOT_FOUND; } switch (d3d_device_source) { case CL_D3D10_DEVICE_KHR: d3d10_device = static_cast<ID3D10Device*>(d3d_object); break; case CL_D3D10_DXGI_ADAPTER_KHR: { typedef HRESULT(WINAPI * LPD3D10CREATEDEVICE)(IDXGIAdapter*, D3D10_DRIVER_TYPE, HMODULE, UINT, UINT32, ID3D10Device**); static LPD3D10CREATEDEVICE dynamicD3D10CreateDevice = NULL; d3d10Module = LoadLibrary("D3D10.dll"); if (d3d10Module == NULL) { return CL_INVALID_PLATFORM; } dynamicD3D10CreateDevice = (LPD3D10CREATEDEVICE)GetProcAddress(d3d10Module, "D3D10CreateDevice"); IDXGIAdapter* dxgi_adapter = static_cast<IDXGIAdapter*>(d3d_object); HRESULT hr = dynamicD3D10CreateDevice(dxgi_adapter, D3D10_DRIVER_TYPE_HARDWARE, NULL, 0, D3D10_SDK_VERSION, &d3d10_device); if (SUCCEEDED(hr) && (NULL != d3d10_device)) { create_d3d10Device = true; } else { FreeLibrary(d3d10Module); return CL_INVALID_VALUE; } } break; default: LogWarning("\"d3d_device_source\" is invalid"); return CL_INVALID_VALUE; } switch (d3d_device_set) { case CL_PREFERRED_DEVICES_FOR_D3D10_KHR: case CL_ALL_DEVICES_FOR_D3D10_KHR: { gpu_devices = (cl_device_id*)alloca(num_gpu_devices * sizeof(cl_device_id)); errcode = clGetDeviceIDs(NULL, CL_DEVICE_TYPE_GPU, num_gpu_devices, gpu_devices, NULL); if (errcode != CL_SUCCESS) { break; } void* external_device[amd::Context::DeviceFlagIdx::LastDeviceFlagIdx] = {}; external_device[amd::Context::DeviceFlagIdx::D3D10DeviceKhrIdx] = d3d10_device; std::vector<amd::Device*> compatible_devices; for (cl_uint i = 0; i < num_gpu_devices; ++i) { cl_device_id device = gpu_devices[i]; if (is_valid(device) && as_amd(device)->bindExternalDevice(amd::Context::Flags::D3D10DeviceKhr, external_device, NULL, VALIDATE_ONLY)) { compatible_devices.push_back(as_amd(device)); } } if (compatible_devices.size() == 0) { *not_null(num_devices) = 0; errcode = CL_DEVICE_NOT_FOUND; break; } auto it = compatible_devices.cbegin(); cl_uint compatible_count = std::min(num_entries, (cl_uint)compatible_devices.size()); while (compatible_count--) { *devices++ = as_cl(*it++); --num_entries; } while (num_entries--) { *devices++ = (cl_device_id)0; } *not_null(num_devices) = (cl_uint)compatible_devices.size(); } break; default: LogWarning("\"d3d_device_set\" is invalid"); errcode = CL_INVALID_VALUE; } if (create_d3d10Device) { d3d10_device->Release(); FreeLibrary(d3d10Module); } return errcode; } RUNTIME_EXIT /*! @} * \addtogroup clCreateFromD3D10BufferKHR * @{ */ /*! \brief Creates an OpenCL buffer object from a Direct3D 10 resource. * * \param context is a valid OpenCL context. * * \param flags is a bit-field that is used to specify usage information. * Only CL_MEM_READ_ONLY, CL_MEM_WRITE_ONLY and CL_MEM_READ_WRITE values * can be used. * * \param pD3DResource is a valid pointer to a D3D10 resource of type ID3D10Buffer. * * \return valid non-zero OpenCL buffer object and \a errcode_ret is set * to CL_SUCCESS if the buffer object is created successfully. It returns a NULL * value with one of the following error values returned in \a errcode_ret: * - CL_INVALID_CONTEXT if \a context is not a valid context or if Direct3D 10 * interoperatbility has not been initialized between context and the ID3D10Device * from which pD3DResource was created. * - CL_INVALID_VALUE if values specified in \a clFlags are not valid. * - CL_INVALID_D3D_RESOURCE if \a pD3DResource is not of type ID3D10Buffer. * - CL_OUT_OF_HOST_MEMORY if there is a failure to allocate resources required * by the runtime. * * \version 1.0r33? */ RUNTIME_ENTRY_RET(cl_mem, clCreateFromD3D10BufferKHR, (cl_context context, cl_mem_flags flags, ID3D10Buffer* pD3DResource, cl_int* errcode_ret)) { cl_mem clMemObj = NULL; if (!is_valid(context)) { *not_null(errcode_ret) = CL_INVALID_CONTEXT; LogWarning("invalid parameter \"context\""); return clMemObj; } if (!flags) flags = CL_MEM_READ_WRITE; if (!(((flags & CL_MEM_READ_ONLY) == CL_MEM_READ_ONLY) || ((flags & CL_MEM_WRITE_ONLY) == CL_MEM_WRITE_ONLY) || ((flags & CL_MEM_READ_WRITE) == CL_MEM_READ_WRITE))) { *not_null(errcode_ret) = CL_INVALID_VALUE; LogWarning("invalid parameter \"flags\""); return clMemObj; } if (!pD3DResource) { *not_null(errcode_ret) = CL_INVALID_VALUE; LogWarning("parameter \"pD3DResource\" is a NULL pointer"); return clMemObj; } return ( amd::clCreateBufferFromD3D10ResourceAMD(*as_amd(context), flags, pD3DResource, errcode_ret)); } RUNTIME_EXIT /*! @} * \addtogroup clCreateImageFromD3D10Resource * @{ */ /*! \brief Create an OpenCL 2D or 3D image object from a D3D10 resource. * * \param context is a valid OpenCL context. * * \param flags is a bit-field that is used to specify usage information. * Only CL_MEM_READ_ONLY, CL_MEM_WRITE_ONLY and CL_MEM_READ_WRITE values * can be used. * * \param pD3DResource is a valid pointer to a D3D10 resource of type * ID3D10Texture2D, ID3D10Texture2D, or ID3D10Texture3D. * If pD3DResource is of type ID3D10Texture1D then the created image object * will be a 1D mipmapped image object. * If pD3DResource is of type ID3D10Texture2D and was not created with flag * D3D10_RESOURCE_MISC_TEXTURECUBE then the created image object will be a * 2D mipmapped image object. * If pD3DResource is of type ID3D10Texture2D and was created with flag * D3D10_RESOURCE_MISC_TEXTURECUBE then the created image object will be * a cubemap mipmapped image object. * errocde_ret returns CL_INVALID_D3D_RESOURCE if an OpenCL memory object has * already been created from pD3DResource in context. * If pD3DResource is of type ID3D10Texture3D then the created image object will * be a 3D mipmapped imageobject. * * \return valid non-zero OpenCL image object and \a errcode_ret is set * to CL_SUCCESS if the image object is created successfully. It returns a NULL * value with one of the following error values returned in \a errcode_ret: * - CL_INVALID_CONTEXT if \a context is not a valid context or if Direct3D 10 * interoperatbility has not been initialized between context and the ID3D10Device * from which pD3DResource was created. * - CL_INVALID_VALUE if values specified in \a flags are not valid. * - CL_INVALID_D3D_RESOURCE if \a pD3DResource is not of type ID3D10Texture1D, * ID3D10Texture2D, or ID3D10Texture3D. * - CL_INVALID_D3D_RESOURCE if an OpenCL memory object has already been created * from \a pD3DResource in context. * - CL_INVALID_IMAGE_FORMAT if the Direct3D 10 texture format does not map * to an appropriate OpenCL image format. * - CL_OUT_OF_HOST_MEMORY if there is a failure to allocate resources required * by the runtime. * * \version 1.0r48? */ RUNTIME_ENTRY_RET(cl_mem, clCreateImageFromD3D10Resource, (cl_context context, cl_mem_flags flags, ID3D10Resource* pD3DResource, UINT subresource, int* errcode_ret, UINT dimension)) { cl_mem clMemObj = NULL; if (!is_valid(context)) { *not_null(errcode_ret) = CL_INVALID_CONTEXT; LogWarning("invalid parameter \"context\""); return clMemObj; } if (!flags) flags = CL_MEM_READ_WRITE; if (!(((flags & CL_MEM_READ_ONLY) == CL_MEM_READ_ONLY) || ((flags & CL_MEM_WRITE_ONLY) == CL_MEM_WRITE_ONLY) || ((flags & CL_MEM_READ_WRITE) == CL_MEM_READ_WRITE))) { *not_null(errcode_ret) = CL_INVALID_VALUE; LogWarning("invalid parameter \"flags\""); return clMemObj; } if (!pD3DResource) { *not_null(errcode_ret) = CL_INVALID_VALUE; LogWarning("parameter \"pD3DResource\" is a NULL pointer"); return clMemObj; } // Verify context init'ed for interop ID3D10Device* pDev; pD3DResource->GetDevice(&pDev); if (pDev == NULL) { *not_null(errcode_ret) = CL_INVALID_D3D10_DEVICE_KHR; LogWarning("Cannot retrieve D3D10 device from D3D10 resource"); return (cl_mem)0; } pDev->Release(); if (!((*as_amd(context)).info().flags_ & amd::Context::D3D10DeviceKhr)) { *not_null(errcode_ret) = CL_INVALID_CONTEXT; LogWarning("\"amdContext\" is not created from D3D10 device"); return (cl_mem)0; } // Check for image support const std::vector<amd::Device*>& devices = as_amd(context)->devices(); bool supportPass = false; bool sizePass = false; for (const auto& it : devices) { if (it->info().imageSupport_) { supportPass = true; } } if (!supportPass) { *not_null(errcode_ret) = CL_INVALID_OPERATION; LogWarning("there are no devices in context to support images"); return (cl_mem)0; } switch (dimension) { #if 0 case 1: return(amd::clCreateImage1DFromD3D10ResourceAMD( *as_amd(context), flags, pD3DResource, subresource, errcode_ret)); #endif // 0 case 2: return (amd::clCreateImage2DFromD3D10ResourceAMD(*as_amd(context), flags, pD3DResource, subresource, errcode_ret)); case 3: return (amd::clCreateImage3DFromD3D10ResourceAMD(*as_amd(context), flags, pD3DResource, subresource, errcode_ret)); default: break; } *not_null(errcode_ret) = CL_INVALID_D3D10_RESOURCE_KHR; return (cl_mem)0; } RUNTIME_EXIT /*! @} * \addtogroup clCreateFromD3D10Texture2DKHR * @{ */ RUNTIME_ENTRY_RET(cl_mem, clCreateFromD3D10Texture2DKHR, (cl_context context, cl_mem_flags flags, ID3D10Texture2D* resource, UINT subresource, cl_int* errcode_ret)) { return clCreateImageFromD3D10Resource(context, flags, resource, subresource, errcode_ret, 2); } RUNTIME_EXIT /*! @} * \addtogroup clCreateFromD3D10Texture3DKHR * @{ */ RUNTIME_ENTRY_RET(cl_mem, clCreateFromD3D10Texture3DKHR, (cl_context context, cl_mem_flags flags, ID3D10Texture3D* resource, UINT subresource, cl_int* errcode_ret)) { return clCreateImageFromD3D10Resource(context, flags, resource, subresource, errcode_ret, 3); } RUNTIME_EXIT /*! @} * \addtogroup clEnqueueAcquireD3D10ObjectsKHR * @{ */ RUNTIME_ENTRY(cl_int, clEnqueueAcquireD3D10ObjectsKHR, (cl_command_queue command_queue, cl_uint num_objects, const cl_mem* mem_objects, cl_uint num_events_in_wait_list, const cl_event* event_wait_list, cl_event* event)) { return amd::clEnqueueAcquireExtObjectsAMD(command_queue, num_objects, mem_objects, num_events_in_wait_list, event_wait_list, event, CL_COMMAND_ACQUIRE_D3D10_OBJECTS_KHR); } RUNTIME_EXIT /*! @} * \addtogroup clEnqueueReleaseD3D10ObjectsKHR * @{ */ RUNTIME_ENTRY(cl_int, clEnqueueReleaseD3D10ObjectsKHR, (cl_command_queue command_queue, cl_uint num_objects, const cl_mem* mem_objects, cl_uint num_events_in_wait_list, const cl_event* event_wait_list, cl_event* event)) { return amd::clEnqueueReleaseExtObjectsAMD(command_queue, num_objects, mem_objects, num_events_in_wait_list, event_wait_list, event, CL_COMMAND_RELEASE_D3D10_OBJECTS_KHR); } RUNTIME_EXIT // // // namespace amd // // namespace amd { /*! @} * \addtogroup CL-D3D10 interop helper functions * @{ */ //******************************************************************* // // Internal implementation of CL API functions // //******************************************************************* // // clCreateBufferFromD3D10ResourceAMD // cl_mem clCreateBufferFromD3D10ResourceAMD(Context& amdContext, cl_mem_flags flags, ID3D10Resource* pD3DResource, int* errcode_ret) { // Verify pD3DResource is a buffer D3D10_RESOURCE_DIMENSION rType; pD3DResource->GetType(&rType); if (rType != D3D10_RESOURCE_DIMENSION_BUFFER) { *not_null(errcode_ret) = CL_INVALID_D3D10_RESOURCE_KHR; return (cl_mem)0; } D3D10Object obj; int errcode = D3D10Object::initD3D10Object(amdContext, pD3DResource, 0, obj); if (CL_SUCCESS != errcode) { *not_null(errcode_ret) = errcode; return (cl_mem)0; } BufferD3D10* pBufferD3D10 = new (amdContext) BufferD3D10(amdContext, flags, obj); if (!pBufferD3D10) { *not_null(errcode_ret) = CL_OUT_OF_HOST_MEMORY; return (cl_mem)0; } if (!pBufferD3D10->create()) { *not_null(errcode_ret) = CL_MEM_OBJECT_ALLOCATION_FAILURE; pBufferD3D10->release(); return (cl_mem)0; } *not_null(errcode_ret) = CL_SUCCESS; return as_cl<Memory>(pBufferD3D10); } #if 0 // There is no support for 1D images in the base imagee code // // clCreateImage1DFromD3D10ResourceAMD // cl_mem clCreateImage1DFromD3D10ResourceAMD( Context& amdContext, cl_mem_flags flags, ID3D10Resource* pD3DResource, UINT subresource, int* errcode_ret) { // Verify the resource is a 1D texture D3D10_RESOURCE_DIMENSION rType; pD3DResource->GetType(&rType); if(rType != D3D10_RESOURCE_DIMENSION_TEXTURE1D) { *not_null(errcode_ret) = CL_INVALID_D3D10_RESOURCE_KHR; return (cl_mem) 0; } D3D10Object obj; int errcode = D3D10Object::initD3D10Object(pD3DResource, subresource, obj); if(CL_SUCCESS != errcode) { *not_null(errcode_ret) = errcode; return (cl_mem) 0; } Image1DD3D10 *pImage1DD3D10 = new Image1DD3D10(amdContext, flags, obj); if(!pImage1DD3D10) { *not_null(errcode_ret) = CL_OUT_OF_HOST_MEMORY; return (cl_mem) 0; } if (!pImage1DD3D10->create()) { *not_null(errcode_ret) = CL_MEM_OBJECT_ALLOCATION_FAILURE; pImage1DD3D10->release(); return (cl_mem) 0; } *not_null(errcode_ret) = CL_SUCCESS; return as_cl<Memory>(pImage1DD3D10); } #endif // // clCreateImage2DFromD3D10ResourceAMD // cl_mem clCreateImage2DFromD3D10ResourceAMD(Context& amdContext, cl_mem_flags flags, ID3D10Resource* pD3DResource, UINT subresource, int* errcode_ret) { // Verify the resource is a 2D texture D3D10_RESOURCE_DIMENSION rType; pD3DResource->GetType(&rType); if (rType != D3D10_RESOURCE_DIMENSION_TEXTURE2D) { *not_null(errcode_ret) = CL_INVALID_D3D10_RESOURCE_KHR; return (cl_mem)0; } D3D10Object obj; int errcode = D3D10Object::initD3D10Object(amdContext, pD3DResource, subresource, obj); if (CL_SUCCESS != errcode) { *not_null(errcode_ret) = errcode; return (cl_mem)0; } Image2DD3D10* pImage2DD3D10 = new (amdContext) Image2DD3D10(amdContext, flags, obj); if (!pImage2DD3D10) { *not_null(errcode_ret) = CL_OUT_OF_HOST_MEMORY; return (cl_mem)0; } if (!pImage2DD3D10->create()) { *not_null(errcode_ret) = CL_MEM_OBJECT_ALLOCATION_FAILURE; pImage2DD3D10->release(); return (cl_mem)0; } *not_null(errcode_ret) = CL_SUCCESS; return as_cl<Memory>(pImage2DD3D10); } // // clCreateImage2DFromD3D10ResourceAMD // cl_mem clCreateImage3DFromD3D10ResourceAMD(Context& amdContext, cl_mem_flags flags, ID3D10Resource* pD3DResource, UINT subresource, int* errcode_ret) { // Verify the resource is a 2D texture D3D10_RESOURCE_DIMENSION rType; pD3DResource->GetType(&rType); if (rType != D3D10_RESOURCE_DIMENSION_TEXTURE3D) { *not_null(errcode_ret) = CL_INVALID_D3D10_RESOURCE_KHR; return (cl_mem)0; } D3D10Object obj; int errcode = D3D10Object::initD3D10Object(amdContext, pD3DResource, subresource, obj); if (CL_SUCCESS != errcode) { *not_null(errcode_ret) = errcode; return (cl_mem)0; } Image3DD3D10* pImage3DD3D10 = new (amdContext) Image3DD3D10(amdContext, flags, obj); if (!pImage3DD3D10) { *not_null(errcode_ret) = CL_OUT_OF_HOST_MEMORY; return (cl_mem)0; } if (!pImage3DD3D10->create()) { *not_null(errcode_ret) = CL_MEM_OBJECT_ALLOCATION_FAILURE; pImage3DD3D10->release(); return (cl_mem)0; } *not_null(errcode_ret) = CL_SUCCESS; return as_cl<Memory>(pImage3DD3D10); } // // Helper function SyncD3D10Objects // void SyncD3D10Objects(std::vector<amd::Memory*>& memObjects) { Memory*& mem = memObjects.front(); if (!mem) { LogWarning("\nNULL memory object\n"); return; } InteropObject* interop = mem->getInteropObj(); if (!interop) { LogWarning("\nNULL interop object\n"); return; } D3D10Object* d3d10Obj = interop->asD3D10Object(); if (!d3d10Obj) { LogWarning("\nNULL D3D10 object\n"); return; } ID3D10Query* query = d3d10Obj->getQuery(); if (!query) { LogWarning("\nNULL ID3D10Query\n"); return; } query->End(); BOOL data = FALSE; while (S_OK != query->GetData(&data, sizeof(BOOL), 0)) { } } // // Class D3D10Object implementation // size_t D3D10Object::getElementBytes(DXGI_FORMAT dxgiFmt) { size_t bytesPerPixel; switch (dxgiFmt) { case DXGI_FORMAT_R32G32B32A32_TYPELESS: case DXGI_FORMAT_R32G32B32A32_FLOAT: case DXGI_FORMAT_R32G32B32A32_UINT: case DXGI_FORMAT_R32G32B32A32_SINT: bytesPerPixel = 16; break; case DXGI_FORMAT_R32G32B32_TYPELESS: case DXGI_FORMAT_R32G32B32_FLOAT: case DXGI_FORMAT_R32G32B32_UINT: case DXGI_FORMAT_R32G32B32_SINT: bytesPerPixel = 12; break; case DXGI_FORMAT_R16G16B16A16_TYPELESS: case DXGI_FORMAT_R16G16B16A16_FLOAT: case DXGI_FORMAT_R16G16B16A16_UNORM: case DXGI_FORMAT_R16G16B16A16_UINT: case DXGI_FORMAT_R16G16B16A16_SNORM: case DXGI_FORMAT_R16G16B16A16_SINT: case DXGI_FORMAT_R32G32_TYPELESS: case DXGI_FORMAT_R32G32_FLOAT: case DXGI_FORMAT_R32G32_UINT: case DXGI_FORMAT_R32G32_SINT: case DXGI_FORMAT_R32G8X24_TYPELESS: case DXGI_FORMAT_D32_FLOAT_S8X24_UINT: case DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS: case DXGI_FORMAT_X32_TYPELESS_G8X24_UINT: bytesPerPixel = 8; break; case DXGI_FORMAT_R10G10B10A2_TYPELESS: case DXGI_FORMAT_R10G10B10A2_UNORM: case DXGI_FORMAT_R10G10B10A2_UINT: case DXGI_FORMAT_R11G11B10_FLOAT: case DXGI_FORMAT_R8G8B8A8_TYPELESS: case DXGI_FORMAT_R8G8B8A8_UNORM: case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB: case DXGI_FORMAT_R8G8B8A8_UINT: case DXGI_FORMAT_R8G8B8A8_SNORM: case DXGI_FORMAT_R8G8B8A8_SINT: case DXGI_FORMAT_R16G16_TYPELESS: case DXGI_FORMAT_R16G16_FLOAT: case DXGI_FORMAT_R16G16_UNORM: case DXGI_FORMAT_R16G16_UINT: case DXGI_FORMAT_R16G16_SNORM: case DXGI_FORMAT_R16G16_SINT: case DXGI_FORMAT_R32_TYPELESS: case DXGI_FORMAT_D32_FLOAT: case DXGI_FORMAT_R32_FLOAT: case DXGI_FORMAT_R32_UINT: case DXGI_FORMAT_R32_SINT: case DXGI_FORMAT_R24G8_TYPELESS: case DXGI_FORMAT_D24_UNORM_S8_UINT: case DXGI_FORMAT_R24_UNORM_X8_TYPELESS: case DXGI_FORMAT_X24_TYPELESS_G8_UINT: case DXGI_FORMAT_R9G9B9E5_SHAREDEXP: case DXGI_FORMAT_R8G8_B8G8_UNORM: case DXGI_FORMAT_G8R8_G8B8_UNORM: case DXGI_FORMAT_B8G8R8A8_UNORM: case DXGI_FORMAT_B8G8R8X8_UNORM: bytesPerPixel = 4; break; case DXGI_FORMAT_R8G8_TYPELESS: case DXGI_FORMAT_R8G8_UNORM: case DXGI_FORMAT_R8G8_UINT: case DXGI_FORMAT_R8G8_SNORM: case DXGI_FORMAT_R8G8_SINT: case DXGI_FORMAT_R16_TYPELESS: case DXGI_FORMAT_R16_FLOAT: case DXGI_FORMAT_D16_UNORM: case DXGI_FORMAT_R16_UNORM: case DXGI_FORMAT_R16_UINT: case DXGI_FORMAT_R16_SNORM: case DXGI_FORMAT_R16_SINT: case DXGI_FORMAT_B5G6R5_UNORM: case DXGI_FORMAT_B5G5R5A1_UNORM: bytesPerPixel = 2; break; case DXGI_FORMAT_R8_TYPELESS: case DXGI_FORMAT_R8_UNORM: case DXGI_FORMAT_R8_UINT: case DXGI_FORMAT_R8_SNORM: case DXGI_FORMAT_R8_SINT: case DXGI_FORMAT_A8_UNORM: case DXGI_FORMAT_R1_UNORM: bytesPerPixel = 1; break; case DXGI_FORMAT_BC1_TYPELESS: case DXGI_FORMAT_BC1_UNORM: case DXGI_FORMAT_BC1_UNORM_SRGB: case DXGI_FORMAT_BC2_TYPELESS: case DXGI_FORMAT_BC2_UNORM: case DXGI_FORMAT_BC2_UNORM_SRGB: case DXGI_FORMAT_BC3_TYPELESS: case DXGI_FORMAT_BC3_UNORM: case DXGI_FORMAT_BC3_UNORM_SRGB: case DXGI_FORMAT_BC4_TYPELESS: case DXGI_FORMAT_BC4_UNORM: case DXGI_FORMAT_BC4_SNORM: case DXGI_FORMAT_BC5_TYPELESS: case DXGI_FORMAT_BC5_UNORM: case DXGI_FORMAT_BC5_SNORM: // Less than 1 byte per pixel - needs special consideration bytesPerPixel = 0; break; default: bytesPerPixel = 0; _ASSERT(FALSE); break; } return bytesPerPixel; } cl_image_format D3D10Object::getCLFormatFromDXGI(DXGI_FORMAT dxgiFmt) { cl_image_format fmt; //! @todo [odintsov]: add real fmt conversion from DXGI to CL fmt.image_channel_order = 0; // CL_RGBA; fmt.image_channel_data_type = 0; // CL_UNSIGNED_INT8; switch (dxgiFmt) { case DXGI_FORMAT_R32G32B32A32_TYPELESS: fmt.image_channel_order = CL_RGBA; break; case DXGI_FORMAT_R32G32B32A32_FLOAT: fmt.image_channel_order = CL_RGBA; fmt.image_channel_data_type = CL_FLOAT; break; case DXGI_FORMAT_R32G32B32A32_UINT: fmt.image_channel_order = CL_RGBA; fmt.image_channel_data_type = CL_UNSIGNED_INT32; break; case DXGI_FORMAT_R32G32B32A32_SINT: fmt.image_channel_order = CL_RGBA; fmt.image_channel_data_type = CL_SIGNED_INT32; break; case DXGI_FORMAT_R32G32B32_TYPELESS: fmt.image_channel_order = CL_RGB; break; case DXGI_FORMAT_R32G32B32_FLOAT: fmt.image_channel_order = CL_RGB; fmt.image_channel_data_type = CL_FLOAT; break; case DXGI_FORMAT_R32G32B32_UINT: fmt.image_channel_order = CL_RGB; fmt.image_channel_data_type = CL_UNSIGNED_INT32; break; case DXGI_FORMAT_R32G32B32_SINT: fmt.image_channel_order = CL_RGB; fmt.image_channel_data_type = CL_SIGNED_INT32; break; case DXGI_FORMAT_R16G16B16A16_TYPELESS: fmt.image_channel_order = CL_RGBA; break; case DXGI_FORMAT_R16G16B16A16_FLOAT: fmt.image_channel_order = CL_RGBA; fmt.image_channel_data_type = CL_HALF_FLOAT; break; case DXGI_FORMAT_R16G16B16A16_UNORM: fmt.image_channel_order = CL_RGBA; fmt.image_channel_data_type = CL_UNORM_INT16; break; case DXGI_FORMAT_R16G16B16A16_UINT: fmt.image_channel_order = CL_RGBA; fmt.image_channel_data_type = CL_UNSIGNED_INT16; break; case DXGI_FORMAT_R16G16B16A16_SNORM: fmt.image_channel_order = CL_RGBA; fmt.image_channel_data_type = CL_SNORM_INT16; break; case DXGI_FORMAT_R16G16B16A16_SINT: fmt.image_channel_order = CL_RGBA; fmt.image_channel_data_type = CL_SIGNED_INT16; break; case DXGI_FORMAT_R32G32_TYPELESS: fmt.image_channel_order = CL_RG; break; case DXGI_FORMAT_R32G32_FLOAT: fmt.image_channel_order = CL_RG; fmt.image_channel_data_type = CL_FLOAT; break; case DXGI_FORMAT_R32G32_UINT: fmt.image_channel_order = CL_RG; fmt.image_channel_data_type = CL_UNSIGNED_INT32; break; case DXGI_FORMAT_R32G32_SINT: fmt.image_channel_order = CL_RG; fmt.image_channel_data_type = CL_SIGNED_INT32; break; case DXGI_FORMAT_R32G8X24_TYPELESS: break; case DXGI_FORMAT_D32_FLOAT_S8X24_UINT: break; case DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS: break; case DXGI_FORMAT_X32_TYPELESS_G8X24_UINT: break; case DXGI_FORMAT_R10G10B10A2_TYPELESS: fmt.image_channel_order = CL_RGBA; break; case DXGI_FORMAT_R10G10B10A2_UNORM: fmt.image_channel_order = CL_RGBA; break; case DXGI_FORMAT_R10G10B10A2_UINT: fmt.image_channel_order = CL_RGBA; break; case DXGI_FORMAT_R11G11B10_FLOAT: fmt.image_channel_order = CL_RGB; break; case DXGI_FORMAT_R8G8B8A8_TYPELESS: fmt.image_channel_order = CL_RGBA; break; case DXGI_FORMAT_R8G8B8A8_UNORM: fmt.image_channel_order = CL_RGBA; fmt.image_channel_data_type = CL_UNORM_INT8; break; case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB: fmt.image_channel_order = CL_RGBA; fmt.image_channel_data_type = CL_UNORM_INT8; break; case DXGI_FORMAT_R8G8B8A8_UINT: fmt.image_channel_order = CL_RGBA; fmt.image_channel_data_type = CL_UNSIGNED_INT8; break; case DXGI_FORMAT_R8G8B8A8_SNORM: fmt.image_channel_order = CL_RGBA; fmt.image_channel_data_type = CL_SNORM_INT8; break; case DXGI_FORMAT_R8G8B8A8_SINT: fmt.image_channel_order = CL_RGBA; fmt.image_channel_data_type = CL_SIGNED_INT8; break; case DXGI_FORMAT_R16G16_TYPELESS: fmt.image_channel_order = CL_RG; break; case DXGI_FORMAT_R16G16_FLOAT: fmt.image_channel_order = CL_RG; fmt.image_channel_data_type = CL_HALF_FLOAT; break; case DXGI_FORMAT_R16G16_UNORM: fmt.image_channel_order = CL_RG; fmt.image_channel_data_type = CL_UNORM_INT16; break; case DXGI_FORMAT_R16G16_UINT: fmt.image_channel_order = CL_RG; fmt.image_channel_data_type = CL_UNSIGNED_INT16; break; case DXGI_FORMAT_R16G16_SNORM: fmt.image_channel_order = CL_RG; fmt.image_channel_data_type = CL_SNORM_INT16; break; case DXGI_FORMAT_R16G16_SINT: fmt.image_channel_order = CL_RG; fmt.image_channel_data_type = CL_SIGNED_INT16; break; case DXGI_FORMAT_R32_TYPELESS: fmt.image_channel_order = CL_R; break; case DXGI_FORMAT_D32_FLOAT: break; case DXGI_FORMAT_R32_FLOAT: fmt.image_channel_order = CL_R; fmt.image_channel_data_type = CL_FLOAT; break; case DXGI_FORMAT_R32_UINT: fmt.image_channel_order = CL_R; fmt.image_channel_data_type = CL_UNSIGNED_INT32; break; case DXGI_FORMAT_R32_SINT: fmt.image_channel_order = CL_R; fmt.image_channel_data_type = CL_SIGNED_INT32; break; case DXGI_FORMAT_R24G8_TYPELESS: fmt.image_channel_order = CL_RG; break; case DXGI_FORMAT_D24_UNORM_S8_UINT: break; case DXGI_FORMAT_R24_UNORM_X8_TYPELESS: break; case DXGI_FORMAT_X24_TYPELESS_G8_UINT: break; case DXGI_FORMAT_R9G9B9E5_SHAREDEXP: break; case DXGI_FORMAT_R8G8_B8G8_UNORM: fmt.image_channel_data_type = CL_UNORM_INT8; break; case DXGI_FORMAT_G8R8_G8B8_UNORM: fmt.image_channel_data_type = CL_UNORM_INT8; break; case DXGI_FORMAT_B8G8R8A8_UNORM: fmt.image_channel_order = CL_BGRA; fmt.image_channel_data_type = CL_UNORM_INT8; break; case DXGI_FORMAT_B8G8R8X8_UNORM: fmt.image_channel_data_type = CL_UNORM_INT8; break; case DXGI_FORMAT_R8G8_TYPELESS: fmt.image_channel_order = CL_RG; break; case DXGI_FORMAT_R8G8_UNORM: fmt.image_channel_order = CL_RG; fmt.image_channel_data_type = CL_UNORM_INT8; break; case DXGI_FORMAT_R8G8_UINT: fmt.image_channel_order = CL_RG; fmt.image_channel_data_type = CL_UNSIGNED_INT8; break; case DXGI_FORMAT_R8G8_SNORM: fmt.image_channel_order = CL_RG; fmt.image_channel_data_type = CL_SNORM_INT8; break; case DXGI_FORMAT_R8G8_SINT: fmt.image_channel_order = CL_RG; fmt.image_channel_data_type = CL_SIGNED_INT8; break; case DXGI_FORMAT_R16_TYPELESS: fmt.image_channel_order = CL_R; break; case DXGI_FORMAT_R16_FLOAT: fmt.image_channel_order = CL_R; fmt.image_channel_data_type = CL_HALF_FLOAT; break; case DXGI_FORMAT_D16_UNORM: fmt.image_channel_data_type = CL_UNORM_INT16; break; case DXGI_FORMAT_R16_UNORM: fmt.image_channel_order = CL_R; fmt.image_channel_data_type = CL_UNORM_INT16; break; case DXGI_FORMAT_R16_UINT: fmt.image_channel_order = CL_R; fmt.image_channel_data_type = CL_UNSIGNED_INT16; break; case DXGI_FORMAT_R16_SNORM: fmt.image_channel_order = CL_R; fmt.image_channel_data_type = CL_SNORM_INT16; break; case DXGI_FORMAT_R16_SINT: fmt.image_channel_order = CL_R; fmt.image_channel_data_type = CL_SIGNED_INT16; break; case DXGI_FORMAT_B5G6R5_UNORM: fmt.image_channel_data_type = CL_UNORM_SHORT_565; break; case DXGI_FORMAT_B5G5R5A1_UNORM: fmt.image_channel_order = CL_BGRA; break; case DXGI_FORMAT_R8_TYPELESS: fmt.image_channel_order = CL_R; break; case DXGI_FORMAT_R8_UNORM: fmt.image_channel_order = CL_R; fmt.image_channel_data_type = CL_UNORM_INT8; break; case DXGI_FORMAT_R8_UINT: fmt.image_channel_order = CL_R; fmt.image_channel_data_type = CL_UNSIGNED_INT8; break; case DXGI_FORMAT_R8_SNORM: fmt.image_channel_order = CL_R; fmt.image_channel_data_type = CL_SNORM_INT8; break; case DXGI_FORMAT_R8_SINT: fmt.image_channel_order = CL_R; fmt.image_channel_data_type = CL_SIGNED_INT8; break; case DXGI_FORMAT_A8_UNORM: fmt.image_channel_order = CL_A; fmt.image_channel_data_type = CL_UNORM_INT8; break; case DXGI_FORMAT_R1_UNORM: fmt.image_channel_order = CL_R; break; case DXGI_FORMAT_BC1_TYPELESS: case DXGI_FORMAT_BC1_UNORM: case DXGI_FORMAT_BC1_UNORM_SRGB: case DXGI_FORMAT_BC2_TYPELESS: case DXGI_FORMAT_BC2_UNORM: case DXGI_FORMAT_BC2_UNORM_SRGB: case DXGI_FORMAT_BC3_TYPELESS: case DXGI_FORMAT_BC3_UNORM: case DXGI_FORMAT_BC3_UNORM_SRGB: case DXGI_FORMAT_BC4_TYPELESS: case DXGI_FORMAT_BC4_UNORM: case DXGI_FORMAT_BC4_SNORM: case DXGI_FORMAT_BC5_TYPELESS: case DXGI_FORMAT_BC5_UNORM: case DXGI_FORMAT_BC5_SNORM: break; default: _ASSERT(FALSE); break; } return fmt; } size_t D3D10Object::getResourceByteSize() { size_t bytes = 1; //! @todo [odintsov]: take into consideration the mip level?! switch (objDesc_.objDim_) { case D3D10_RESOURCE_DIMENSION_BUFFER: bytes = objDesc_.objSize_.ByteWidth; break; case D3D10_RESOURCE_DIMENSION_TEXTURE3D: bytes = objDesc_.objSize_.Depth; case D3D10_RESOURCE_DIMENSION_TEXTURE2D: bytes *= objDesc_.objSize_.Height; case D3D10_RESOURCE_DIMENSION_TEXTURE1D: bytes *= objDesc_.objSize_.Width * getElementBytes(); break; default: LogError("getResourceByteSize: unknown type of D3D10 resource"); bytes = 0; break; } return bytes; } int D3D10Object::initD3D10Object(const Context& amdContext, ID3D10Resource* pRes, UINT subres, D3D10Object& obj) { ID3D10Device* pDev; HRESULT hr; ScopedLock sl(resLock_); // Check if this ressource has already been used for interop for (const auto& it : resources_) { if (it.first == (void*)pRes && it.second == subres) { return CL_INVALID_D3D10_RESOURCE_KHR; } } (obj.pD3D10Res_ = pRes)->GetDevice(&pDev); if (!pDev) { return CL_INVALID_D3D10_DEVICE_KHR; } D3D10_QUERY_DESC desc = {D3D10_QUERY_EVENT, 0}; pDev->CreateQuery(&desc, &obj.pQuery_); #define SET_SHARED_FLAGS() \ { \ obj.pD3D10ResOrig_ = obj.pD3D10Res_; \ memcpy(&obj.objDescOrig_, &obj.objDesc_, sizeof(D3D10ObjDesc_t)); \ /* @todo - Check device type and select right usage for resource */ \ /* For now get only DPU path, CPU path for buffers */ \ /* will not worl on DEFAUL resources */ \ /*desc.Usage = D3D10_USAGE_STAGING;*/ \ desc.Usage = D3D10_USAGE_DEFAULT; \ desc.MiscFlags = D3D10_RESOURCE_MISC_SHARED; \ desc.CPUAccessFlags = 0; \ } #define STORE_SHARED_FLAGS(restype) \ { \ if (S_OK == hr && obj.pD3D10Res_) { \ obj.objDesc_.objFlags_.d3d10Usage_ = desc.Usage; \ obj.objDesc_.objFlags_.bindFlags_ = desc.BindFlags; \ obj.objDesc_.objFlags_.miscFlags_ = desc.MiscFlags; \ obj.objDesc_.objFlags_.cpuAccessFlags_ = desc.CPUAccessFlags; \ } else { \ LogError("\nCannot create shared " #restype "\n"); \ return CL_INVALID_D3D10_RESOURCE_KHR; \ } \ } #define SET_BINDING() \ { \ switch (desc.Format) { \ case DXGI_FORMAT_D32_FLOAT_S8X24_UINT: \ case DXGI_FORMAT_D32_FLOAT: \ case DXGI_FORMAT_D24_UNORM_S8_UINT: \ case DXGI_FORMAT_D16_UNORM: \ desc.BindFlags = D3D10_BIND_DEPTH_STENCIL; \ break; \ default: \ desc.BindFlags = D3D10_BIND_SHADER_RESOURCE | D3D10_BIND_RENDER_TARGET; \ break; \ } \ } pRes->GetType(&obj.objDesc_.objDim_); // Init defaults obj.objDesc_.objSize_.Height = 1; obj.objDesc_.objSize_.Depth = 1; obj.objDesc_.mipLevels_ = 1; obj.objDesc_.arraySize_ = 1; obj.objDesc_.dxgiFormat_ = DXGI_FORMAT_UNKNOWN; obj.objDesc_.dxgiSampleDesc_ = dxgiSampleDescDefault; switch (obj.objDesc_.objDim_) { case D3D10_RESOURCE_DIMENSION_BUFFER: // = 1, { D3D10_BUFFER_DESC desc; (reinterpret_cast<ID3D10Buffer*>(pRes))->GetDesc(&desc); obj.objDesc_.objSize_.ByteWidth = desc.ByteWidth; obj.objDesc_.objFlags_.d3d10Usage_ = desc.Usage; obj.objDesc_.objFlags_.bindFlags_ = desc.BindFlags; obj.objDesc_.objFlags_.cpuAccessFlags_ = desc.CPUAccessFlags; obj.objDesc_.objFlags_.miscFlags_ = desc.MiscFlags; // Handle D3D10Buffer without shared handle - create // a duplicate with shared handle to provide for CAL if (!(obj.objDesc_.objFlags_.miscFlags_ & D3D10_RESOURCE_MISC_SHARED)) { SET_SHARED_FLAGS(); desc.BindFlags = D3D10_BIND_SHADER_RESOURCE | D3D10_BIND_RENDER_TARGET; hr = pDev->CreateBuffer(&desc, NULL, (ID3D10Buffer**)&obj.pD3D10Res_); STORE_SHARED_FLAGS(ID3D10Buffer); } } break; case D3D10_RESOURCE_DIMENSION_TEXTURE1D: // = 2, { D3D10_TEXTURE1D_DESC desc; (reinterpret_cast<ID3D10Texture1D*>(pRes))->GetDesc(&desc); if (subres) { // Calculate correct size of the subresource UINT miplevel = subres; if (desc.ArraySize > 1) { miplevel = subres % desc.ArraySize; } if (miplevel >= desc.MipLevels) { LogWarning("\nMiplevel >= number of miplevels\n"); } if (subres >= desc.MipLevels * desc.ArraySize) { return CL_INVALID_VALUE; } desc.Width >>= miplevel; if (!desc.Width) { desc.Width = 1; } } obj.objDesc_.objSize_.Width = desc.Width; obj.objDesc_.mipLevels_ = desc.MipLevels; obj.objDesc_.arraySize_ = desc.ArraySize; obj.objDesc_.dxgiFormat_ = desc.Format; obj.objDesc_.objFlags_.d3d10Usage_ = desc.Usage; obj.objDesc_.objFlags_.bindFlags_ = desc.BindFlags; obj.objDesc_.objFlags_.cpuAccessFlags_ = desc.CPUAccessFlags; obj.objDesc_.objFlags_.miscFlags_ = desc.MiscFlags; // Handle D3D10Texture1D without shared handle - create // a duplicate with shared handle and provide it for CAL // Workaround for subresource > 0 in shared resource if (subres) obj.objDesc_.objFlags_.miscFlags_ &= ~(D3D10_RESOURCE_MISC_SHARED); if (!(obj.objDesc_.objFlags_.miscFlags_ & D3D10_RESOURCE_MISC_SHARED)) { SET_SHARED_FLAGS(); SET_BINDING(); obj.objDesc_.mipLevels_ = desc.MipLevels = 1; obj.objDesc_.arraySize_ = desc.ArraySize = 1; hr = pDev->CreateTexture1D(&desc, NULL, (ID3D10Texture1D**)&obj.pD3D10Res_); STORE_SHARED_FLAGS(ID3D10Texture1D); } } break; case D3D10_RESOURCE_DIMENSION_TEXTURE2D: // = 3, { D3D10_TEXTURE2D_DESC desc; (reinterpret_cast<ID3D10Texture2D*>(pRes))->GetDesc(&desc); if (subres) { // Calculate correct size of the subresource UINT miplevel = subres; if (desc.ArraySize > 1) { miplevel = subres % desc.MipLevels; } if (miplevel >= desc.MipLevels) { LogWarning("\nMiplevel >= number of miplevels\n"); } if (subres >= desc.MipLevels * desc.ArraySize) { return CL_INVALID_VALUE; } desc.Width >>= miplevel; if (!desc.Width) { desc.Width = 1; } desc.Height >>= miplevel; if (!desc.Height) { desc.Height = 1; } } obj.objDesc_.objSize_.Width = desc.Width; obj.objDesc_.objSize_.Height = desc.Height; obj.objDesc_.mipLevels_ = desc.MipLevels; obj.objDesc_.arraySize_ = desc.ArraySize; obj.objDesc_.dxgiFormat_ = desc.Format; obj.objDesc_.dxgiSampleDesc_ = desc.SampleDesc; obj.objDesc_.objFlags_.d3d10Usage_ = desc.Usage; obj.objDesc_.objFlags_.bindFlags_ = desc.BindFlags; obj.objDesc_.objFlags_.cpuAccessFlags_ = desc.CPUAccessFlags; obj.objDesc_.objFlags_.miscFlags_ = desc.MiscFlags; // Handle D3D10Texture2D without shared handle - create // a duplicate with shared handle and provide it for CAL // Workaround for subresource > 0 in shared resource if (subres) obj.objDesc_.objFlags_.miscFlags_ &= ~(D3D10_RESOURCE_MISC_SHARED); if (!(obj.objDesc_.objFlags_.miscFlags_ & D3D10_RESOURCE_MISC_SHARED)) { SET_SHARED_FLAGS(); SET_BINDING(); obj.objDesc_.mipLevels_ = desc.MipLevels = 1; obj.objDesc_.arraySize_ = desc.ArraySize = 1; hr = pDev->CreateTexture2D(&desc, NULL, (ID3D10Texture2D**)&obj.pD3D10Res_); STORE_SHARED_FLAGS(ID3D10Texture2D); } } break; case D3D10_RESOURCE_DIMENSION_TEXTURE3D: // = 4 { D3D10_TEXTURE3D_DESC desc; (reinterpret_cast<ID3D10Texture3D*>(pRes))->GetDesc(&desc); if (subres) { // Calculate correct size of the subresource UINT miplevel = subres; if (miplevel >= desc.MipLevels) { LogWarning("\nMiplevel >= number of miplevels\n"); } if (subres >= desc.MipLevels) { return CL_INVALID_VALUE; } desc.Width >>= miplevel; if (!desc.Width) { desc.Width = 1; } desc.Height >>= miplevel; if (!desc.Height) { desc.Height = 1; } desc.Depth >>= miplevel; if (!desc.Depth) { desc.Depth = 1; } } obj.objDesc_.objSize_.Width = desc.Width; obj.objDesc_.objSize_.Height = desc.Height; obj.objDesc_.objSize_.Depth = desc.Depth; obj.objDesc_.mipLevels_ = desc.MipLevels; obj.objDesc_.dxgiFormat_ = desc.Format; obj.objDesc_.objFlags_.d3d10Usage_ = desc.Usage; obj.objDesc_.objFlags_.bindFlags_ = desc.BindFlags; obj.objDesc_.objFlags_.cpuAccessFlags_ = desc.CPUAccessFlags; obj.objDesc_.objFlags_.miscFlags_ = desc.MiscFlags; // Handle D3D10Texture3D without shared handle - create // a duplicate with shared handle and provide it for CAL // Workaround for subresource > 0 in shared resource if (obj.objDesc_.mipLevels_ > 1) obj.objDesc_.objFlags_.miscFlags_ &= ~(D3D10_RESOURCE_MISC_SHARED); if (!(obj.objDesc_.objFlags_.miscFlags_ & D3D10_RESOURCE_MISC_SHARED)) { SET_SHARED_FLAGS(); SET_BINDING(); obj.objDesc_.mipLevels_ = desc.MipLevels = 1; hr = pDev->CreateTexture3D(&desc, NULL, (ID3D10Texture3D**)&obj.pD3D10Res_); STORE_SHARED_FLAGS(ID3D10Texture3D); } } break; default: LogError("unknown type of D3D10 resource"); return CL_INVALID_D3D10_RESOURCE_KHR; } obj.subRes_ = subres; pDev->Release(); // Check for CL format compatibilty if (obj.objDesc_.objDim_ != D3D10_RESOURCE_DIMENSION_BUFFER) { cl_image_format clFmt = obj.getCLFormatFromDXGI(obj.objDesc_.dxgiFormat_); amd::Image::Format imageFormat(clFmt); if (!imageFormat.isSupported(amdContext)) { return CL_INVALID_IMAGE_FORMAT_DESCRIPTOR; } } resources_.push_back({pRes, subres}); return CL_SUCCESS; } bool D3D10Object::copyOrigToShared() { // Don't copy if there is no orig if (NULL == getD3D10ResOrig()) return true; ID3D10Device* d3dDev; pD3D10Res_->GetDevice(&d3dDev); if (!d3dDev) { LogError("\nCannot get D3D10 device from D3D10 resource\n"); return false; } // Any usage source can be read by GPU d3dDev->CopySubresourceRegion(pD3D10Res_, 0, 0, 0, 0, pD3D10ResOrig_, subRes_, NULL); // Flush D3D queues and make sure D3D stuff is finished d3dDev->Flush(); pQuery_->End(); BOOL data = FALSE; while ((S_OK != pQuery_->GetData(&data, sizeof(BOOL), 0)) || (data != TRUE)) { } d3dDev->Release(); return true; } bool D3D10Object::copySharedToOrig() { // Don't copy if there is no orig if (NULL == getD3D10ResOrig()) return true; ID3D10Device* d3dDev; pD3D10Res_->GetDevice(&d3dDev); if (!d3dDev) { LogError("\nCannot get D3D10 device from D3D10 resource\n"); return false; } d3dDev->CopySubresourceRegion(pD3D10ResOrig_, subRes_, 0, 0, 0, pD3D10Res_, 0, NULL); d3dDev->Release(); return true; } std::vector<std::pair<void*, UINT>> D3D10Object::resources_; Monitor D3D10Object::resLock_; // // Class BufferD3D10 implementation // void BufferD3D10::initDeviceMemory() { deviceMemories_ = reinterpret_cast<DeviceMemory*>(reinterpret_cast<char*>(this) + sizeof(BufferD3D10)); memset(deviceMemories_, 0, context_().devices().size() * sizeof(DeviceMemory)); } // // Class Image1DD3D10 implementation // void Image1DD3D10::initDeviceMemory() { deviceMemories_ = reinterpret_cast<DeviceMemory*>(reinterpret_cast<char*>(this) + sizeof(Image1DD3D10)); memset(deviceMemories_, 0, context_().devices().size() * sizeof(DeviceMemory)); } // // Class Image2DD3D10 implementation // void Image2DD3D10::initDeviceMemory() { deviceMemories_ = reinterpret_cast<DeviceMemory*>(reinterpret_cast<char*>(this) + sizeof(Image2DD3D10)); memset(deviceMemories_, 0, context_().devices().size() * sizeof(DeviceMemory)); } // // Class Image3DD3D10 implementation // void Image3DD3D10::initDeviceMemory() { deviceMemories_ = reinterpret_cast<DeviceMemory*>(reinterpret_cast<char*>(this) + sizeof(Image3DD3D10)); memset(deviceMemories_, 0, context_().devices().size() * sizeof(DeviceMemory)); } } // namespace amd #endif //_WIN32
0c7f556c7255cd823ddca50216825455829c1ec1
2d5a7e8f3454b8577442a7d058768ea3086769ee
/example/ex23-master/examples/reductionExample.cpp
c6e2823897dd7c4c01df589508283953a0af292c
[]
no_license
LoveHRTF/ENGN-2912B
3946517c604e360f88c17cff93e353628c22fa6e
6650fbe5829a90c1ba790f0a625cdb07e76ebc4b
refs/heads/master
2020-07-31T00:33:15.036055
2019-09-23T18:12:27
2019-09-23T18:12:27
210,418,342
0
0
null
null
null
null
UTF-8
C++
false
false
421
cpp
reductionExample.cpp
#include <omp.h> #include <iostream> #include <string> // compile using: g++ reductionExample.cpp -fopenmp -o reductionExample int factorial (int number) { int fac = 1; #pragma omp parallel for reduction(* : fac) num_threads(2) for(int n = 2; n <= number; n++) { fac *= n; } return fac; } int main () { std::cout << "10!: " << factorial(10) << std::endl; return 0; }
eef0d6fb7f1afa9e23fccac701556687eff56d1f
a06d433b2d23a02e10b509722099b1c87f358e59
/4367 出现次数超过一半的数字/Latest Submission/main.cpp
1f3bca6ceae0bd76c0346dcba274ed212cf61239
[]
no_license
pangyzh/algorithm
31d53b2eb3a9a9791b428f3fd393fbace2943a08
b3406e832b720d9c4874a83c0095adb8d3319137
refs/heads/master
2020-04-30T09:16:15.559485
2019-03-20T13:40:20
2019-03-20T13:40:20
176,742,283
0
0
null
null
null
null
UTF-8
C++
false
false
492
cpp
main.cpp
#include<stdio.h> #include<string.h> int arr[100000]; int main() { int t; scanf("%d",&t); while(t--) { memset(arr,0,sizeof(arr)); int n; int count=0; char c; scanf("%d",&n); arr[n]++; count++; while((scanf("%c",&c))&&c!='\n') { scanf("%d",&n); arr[n]++; count++; } int flag=0; for(int i = 1;i < 100000;i++) { if(arr[i]!=0) if(arr[i]>count/2) { printf("%d\n",i); flag=1; break; } } if(flag==0) printf("0\n"); } }
c3ad7a786bd0aa40dcf3cc65133d1f6bf585f536
44227276cdce0d15ee0cdd19a9f38a37b9da33d7
/arcane/src/arcane/std/MetisWrapper.cc
eb166fa9c9c9ae26538139d8c018fd75a149779a
[ "Apache-2.0", "LGPL-2.1-or-later" ]
permissive
arcaneframework/framework
7d0050f0bbceb8cc43c60168ba74fff0d605e9a3
813cfb5eda537ce2073f32b1a9de6b08529c5ab6
refs/heads/main
2023-08-19T05:44:47.722046
2023-08-11T16:22:12
2023-08-11T16:22:12
357,932,008
31
21
Apache-2.0
2023-09-14T16:42:12
2021-04-14T14:21:07
C++
UTF-8
C++
false
false
15,496
cc
MetisWrapper.cc
// -*- tab-width: 2; indent-tabs-mode: nil; coding: utf-8-with-signature -*- //----------------------------------------------------------------------------- // Copyright 2000-2022 CEA (www.cea.fr) IFPEN (www.ifpenergiesnouvelles.com) // See the top-level COPYRIGHT file for details. // SPDX-License-Identifier: Apache-2.0 //----------------------------------------------------------------------------- /*---------------------------------------------------------------------------*/ /* MetisWrapper.cc (C) 2000-2019 */ /* */ /* Wrapper autour des appels de Parmetis. */ /* Calcule une somme de contrôle globale des entrées/sorties Metis. */ /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ #include "arcane/utils/ArrayView.h" #include "arcane/std/MetisGraph.h" #include "arcane/std/MetisGraphDigest.h" #include "arcane/std/MetisGraphGather.h" #include "arcane/std/MetisWrapper.h" #include <functional> /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ namespace Arcane { /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ using MetisCall = std::function<int(MPI_Comm& comm, MetisGraphView graph, ArrayView<idx_t> vtxdist)>; /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ namespace { /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ /*! * \brief Appelle Metis sans regroupement de graph. */ int _callMetis(MPI_Comm comm, ArrayView<idx_t> vtxdist, MetisGraphView my_graph, MetisCall& metis) { return metis(comm, my_graph, vtxdist); } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ /*! * \brief Appelle Metis en regroupant le graph sur 2 processeurs. */ int _callMetisWith2Processors(const idx_t ncon, const bool need_part, MPI_Comm comm, ConstArrayView<idx_t> vtxdist, MetisGraphView my_graph, MetisCall& metis) { int my_rank = -1; int nb_rank = -1; MPI_Comm_rank(comm, &my_rank); MPI_Comm_size(comm, &nb_rank); String half_comm_name = "first"; UniqueArray<idx_t> half_vtxdist(vtxdist.size()); int comm_0_size = nb_rank / 2 + nb_rank % 2; int comm_1_size = nb_rank / 2; int comm_0_io_rank = 0; int comm_1_io_rank = comm_0_size; MPI_Comm half_comm; for (int i = 0; i < nb_rank + 1; ++i) { half_vtxdist[i] = vtxdist[i]; } int color = 1; int key = my_rank; if (my_rank >= comm_0_size) { color = 2; half_comm_name = "second"; for (int i = 0; i < comm_1_size + 1; ++i) { half_vtxdist[i] = vtxdist[i + comm_0_size] - vtxdist[comm_0_size]; } } MetisGraph metis_graph; MetisGraphGather metis_gather; MPI_Comm_split(comm, color, key, &half_comm); metis_gather.gatherGraph(need_part, half_comm_name, half_comm, half_vtxdist, ncon, my_graph, metis_graph); color = MPI_UNDEFINED; if (my_rank == comm_0_io_rank || my_rank == comm_1_io_rank) { color = 1; } MPI_Comm metis_comm; MPI_Comm_split(comm, color, key, &metis_comm); UniqueArray<idx_t> metis_vtxdist(3); metis_vtxdist[0] = 0; metis_vtxdist[1] = vtxdist[comm_0_size]; metis_vtxdist[2] = vtxdist[vtxdist.size() - 1]; int ierr = 0; if (metis_comm != MPI_COMM_NULL) { MetisGraphView metis_graph_view(metis_graph); ierr = metis(metis_comm, metis_graph_view, metis_vtxdist); MPI_Comm_free(&metis_comm); } MPI_Bcast(&ierr, 1, MPI_INT, 0, half_comm); metis_gather.scatterPart(half_comm, half_vtxdist, metis_graph.part, my_graph.part); MPI_Comm_free(&half_comm); return ierr; } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ /*! * \brief Appelle Metis en regroupant le graph sur 1 seul processeur. * * \warning Cette méthode n'est pas compatible avec la routine AdaptiveRepart de ParMetis qui * est buggee lorsqu'il n'y a qu'un seul processeur. */ int _callMetisWith1Processor(const idx_t ncon, const bool need_part, MPI_Comm comm, ConstArrayView<idx_t> vtxdist, MetisGraphView my_graph, MetisCall& metis) { int my_rank = -1; int nb_rank = -1; MPI_Comm_rank(comm, &my_rank); MPI_Comm_size(comm, &nb_rank); MetisGraph metis_graph; MetisGraphGather metis_gather; metis_gather.gatherGraph(need_part, "maincomm", comm, vtxdist, ncon, my_graph, metis_graph); MPI_Comm metis_comm = MPI_COMM_SELF; UniqueArray<idx_t> metis_vtxdist(2); metis_vtxdist[0] = 0; metis_vtxdist[1] = vtxdist[vtxdist.size() - 1]; int ierr = 0; if (my_rank == 0) { MetisGraphView metis_graph_view(metis_graph); ierr = metis(metis_comm, metis_graph_view, metis_vtxdist); } MPI_Bcast(&ierr, 1, MPI_INT, 0, comm); metis_gather.scatterPart(comm, vtxdist, metis_graph.part, my_graph.part); return ierr; } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ int MetisWrapper:: callPartKway(ITraceMng* tm, const bool print_digest, const bool gather, idx_t *vtxdist, idx_t *xadj, idx_t *adjncy, idx_t *vwgt, idx_t *adjwgt, idx_t *wgtflag, idx_t *numflag, idx_t *ncon, idx_t *nparts, real_t *tpwgts, real_t *ubvec, idx_t *options, idx_t *edgecut, idx_t *part, MPI_Comm *comm) { int ierr = 0; int nb_rank = -1; int my_rank = -1; MPI_Comm_size(*comm, &nb_rank); MPI_Comm_rank(*comm, &my_rank); MetisCall partkway = [&](MPI_Comm& graph_comm, MetisGraphView graph, ArrayView<idx_t> graph_vtxdist) { // NOTE GG: il peut arriver que ces deux pointeurs soient nuls s'il n'y a pas // de voisins. Si tout le reste est cohérent cela ne pose pas de problèmes mais ParMetis // n'aime pas les tableaux vides donc si c'est le cas on met un 0. // TODO: il faudrait regarder en amont s'il ne vaudrait pas mieux mettre des valeurs // dans ces deux tableaux au cas où. idx_t null_idx = 0; idx_t* adjncy_data = graph.adjncy.data(); idx_t* adjwgt_data = graph.adjwgt.data(); if (!adjncy_data) adjncy_data = &null_idx; if (!adjwgt_data) adjwgt_data = &null_idx; return ParMETIS_V3_PartKway(graph_vtxdist.data(), graph.xadj.data(), adjncy_data, graph.vwgt.data(), adjwgt_data, wgtflag, numflag, ncon, nparts, tpwgts, ubvec, options, edgecut, graph.part.data(), &graph_comm); }; // Version séquentielle utilisant directement Metis // NOTE: Ce bout de code est le même que dans callAdaptativeRepart. // Il faudrait mutualiser les deux. MetisCall partkway_seq = [&](MPI_Comm& graph_comm, MetisGraphView graph, ArrayView<idx_t> graph_vtxdist) { ARCANE_UNUSED(graph_comm); idx_t options2[METIS_NOPTIONS]; METIS_SetDefaultOptions(options2); options2[METIS_OPTION_CTYPE] = METIS_CTYPE_SHEM; options2[METIS_OPTION_UFACTOR] = 30; // TODO: a récupérer depuis les options de parmetis options2[METIS_OPTION_NUMBERING] = 0; // 0 pour indiquer que les tableaux sont en C (indices commencent à 0) options2[METIS_OPTION_MINCONN] = 0; options2[METIS_OPTION_OBJTYPE] = METIS_OBJTYPE_VOL; options2[METIS_OPTION_SEED] = 25; // TODO: pouvoir changer la graine tm->pwarning() << "MetisWrapper: using user 'imbalance_factor' is not yet implemented. Using defaut value 30"; // Le nombre de sommets du graph est dans le premier indice de graph_vtxdist idx_t nvtxs = graph_vtxdist[1]; return METIS_PartGraphKway(&nvtxs /*graph_vtxdist.data()*/, ncon, graph.xadj.data(), graph.adjncy.data(), graph.vwgt.data(), graph.vsize.data(), graph.adjwgt.data(), nparts, tpwgts, ubvec, options2, edgecut, graph.part.data()); }; MetisGraphView my_graph; ArrayView<idx_t> offset(nb_rank + 1, vtxdist); my_graph.nb_vertices = offset[my_rank+1] - offset[my_rank]; my_graph.xadj = ArrayView<idx_t>(my_graph.nb_vertices + 1, xadj); idx_t adjncy_size = my_graph.xadj[my_graph.nb_vertices]; my_graph.adjncy = ArrayView<idx_t>(adjncy_size, adjncy); my_graph.vwgt = ArrayView<idx_t>(my_graph.nb_vertices * (*ncon), vwgt); my_graph.adjwgt = ArrayView<idx_t>(adjncy_size, adjwgt); my_graph.part = ArrayView<idx_t>(my_graph.nb_vertices, part); my_graph.have_vsize = false; my_graph.have_adjwgt = true; if (print_digest){ MetisGraphDigest d; String digest = d.computeInputDigest(*comm, false, 3, my_graph, vtxdist, wgtflag, numflag, ncon, nparts, tpwgts, ubvec, nullptr, options); if (my_rank == 0) { tm->info() << "signature des entrees Metis = " << digest; } } if (gather && nb_rank > 2) { // tm->info() << "Partionnement metis avec regroupement sur 1 processeur"; // ierr = callMetisWith1Processor(*ncon, false, *comm, offset, my_graph, partkway); // Normalement c'est plus rapide ... tm->info() << "Partionnement metis : regroupement " << nb_rank << " -> 2 processeurs"; ierr = _callMetisWith2Processors(*ncon, false, *comm, offset, my_graph, partkway); } else { tm->info() << "Partionnement metis : nb processeurs = " << nb_rank; ierr = _callMetis(*comm, offset, my_graph, (nb_rank==1) ? partkway_seq : partkway); } tm->info() << "End Partionnement metis"; if (print_digest){ MetisGraphDigest d; String digest = d.computeOutputDigest(*comm, my_graph, edgecut); if (my_rank == 0) { tm->info() << "signature des sorties Metis = " << digest; } } return ierr; } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ int MetisWrapper:: callAdaptiveRepart(ITraceMng* tm, const bool print_digest, const bool gather, idx_t *vtxdist, idx_t *xadj, idx_t *adjncy, idx_t *vwgt, idx_t *vsize, idx_t *adjwgt, idx_t *wgtflag, idx_t *numflag, idx_t *ncon, idx_t *nparts, real_t *tpwgts, real_t *ubvec, real_t *ipc2redist, idx_t *options, idx_t *edgecut, idx_t *part, MPI_Comm *comm) { int ierr = 0; int nb_rank = -1; int my_rank = -1; MPI_Comm_size(*comm, &nb_rank); MPI_Comm_rank(*comm, &my_rank); MetisCall repart_func = [&](MPI_Comm& graph_comm, MetisGraphView graph, ArrayView<idx_t> graph_vtxdist) { return ParMETIS_V3_AdaptiveRepart(graph_vtxdist.data(), graph.xadj.data(), graph.adjncy.data(), graph.vwgt.data(), graph.vsize.data(), graph.adjwgt.data(), wgtflag, numflag, ncon, nparts, tpwgts, ubvec, ipc2redist, options, edgecut, graph.part.data(), &graph_comm); }; // Version séquentielle utilisant directement Metis // NOTE: Ce bout de code est le même que dans callPartKWay // Il faudrait mutualiser les deux. MetisCall repart_seq_func = [&](MPI_Comm& graph_comm, MetisGraphView graph, ArrayView<idx_t> graph_vtxdist) { ARCANE_UNUSED(graph_comm); idx_t options2[METIS_NOPTIONS]; METIS_SetDefaultOptions(options2); options2[METIS_OPTION_CTYPE] = METIS_CTYPE_SHEM; options2[METIS_OPTION_UFACTOR] = 30; // TODO: a récupérer depuis les options de parmetis options2[METIS_OPTION_NUMBERING] = 0; // 0 pour indiquer que les tableaux sont en C (indices commencent à 0) options2[METIS_OPTION_MINCONN] = 0; options2[METIS_OPTION_OBJTYPE] = METIS_OBJTYPE_VOL; options2[METIS_OPTION_SEED] = 25; // TODO: pouvoir changer la graine tm->pwarning() << "MetisWrapper: using user 'imbalance_factor' is not yet implemented. Using defaut value 30"; // Le nombre de sommets du graph est dans le premier indice de graph_vtxdist idx_t nvtxs = graph_vtxdist[1]; return METIS_PartGraphKway(&nvtxs /*graph_vtxdist.data()*/, ncon, graph.xadj.data(), graph.adjncy.data(), graph.vwgt.data(), graph.vsize.data(), graph.adjwgt.data(), nparts, tpwgts, ubvec, options2, edgecut, graph.part.data()); }; MetisGraphView my_graph; ArrayView<idx_t> offset(nb_rank + 1, vtxdist); my_graph.nb_vertices = offset[my_rank+1] - offset[my_rank]; my_graph.xadj = ArrayView<idx_t>(my_graph.nb_vertices + 1, xadj); idx_t adjncy_size = my_graph.xadj[my_graph.nb_vertices]; my_graph.adjncy = ArrayView<idx_t>(adjncy_size, adjncy); my_graph.vwgt = ArrayView<idx_t>(my_graph.nb_vertices * (*ncon), vwgt); my_graph.vsize = ArrayView<idx_t>(my_graph.nb_vertices, vsize); my_graph.adjwgt = ArrayView<idx_t>(adjncy_size, adjwgt); my_graph.part = ArrayView<idx_t>(my_graph.nb_vertices, part); my_graph.have_vsize = true; my_graph.have_adjwgt = true; if (print_digest){ MetisGraphDigest d; String digest = d.computeInputDigest(*comm, true, 4, my_graph, vtxdist, wgtflag, numflag, ncon, nparts, tpwgts, ubvec, nullptr, options); if (my_rank == 0) { tm->info() << "signature des entrees Metis = " << digest; } } if (gather && nb_rank > 2) { tm->info() << "Partionnement metis : regroupement " << nb_rank << " -> 2 processeurs"; ierr = _callMetisWith2Processors(*ncon, true, *comm, offset, my_graph, repart_func); } else { tm->info() << "Partionnement metis : nb processeurs = " << nb_rank; ierr = _callMetis(*comm, offset, my_graph, (nb_rank==1) ? repart_seq_func : repart_func); } if (print_digest) { MetisGraphDigest d; String digest = d.computeOutputDigest(*comm, my_graph, edgecut); if (my_rank == 0) { tm->info() << "signature des sorties Metis = " << digest; } } return ierr; } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ } // End namespace Arcane /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/
221844ed024e5ee185b0e0c544a2dfb934b9d20d
30596203fbd1a52cdabb368c6ce8e5230d4f4a04
/ConcurrentAsyncQueueTests/ConcurrentAsyncQueuePush.cpp
ff2b1ccba547903bf1c3704f41ee1b4fe3cb09b6
[]
no_license
LeGnours/Cpp_HandsOn
5edde874d168a22b9b7c8491e2b5643e6b5bce66
f1de659d1fdcb7ae827ed57195a7227753c9d746
refs/heads/master
2020-03-16T03:42:55.036097
2018-05-09T22:45:29
2018-05-09T22:45:29
132,493,718
0
0
null
null
null
null
UTF-8
C++
false
false
1,597
cpp
ConcurrentAsyncQueuePush.cpp
#include "stdafx.h" #include "ConcurrentAsyncQueuePush.h" #include "ConcurrentAsyncQueueTestHelper.h" using namespace std::chrono_literals; INSTANTIATE_TEST_CASE_P(ConcurrentAsyncQueuePushParametized, ConcurrentAsyncQueuePush, testing::Combine(testing::Values(1, 3, 5, 7, 17, 23, 31), testing::Values(1, 3, 5, 7, 17, 23, 31))); TEST_P(ConcurrentAsyncQueuePush, AddCopyElements) { ASSERT_EQ(true, test_queue_->is_empty()); ASSERT_EQ(0, test_queue_->count()); for (auto i = 0; i < nb_threads_; ++i) { test_threads_result_.push_back(std::async(std::launch::async, [this, i] { return ConcurrentAsyncQueueTestHelper::add_copy_elements(*test_queue_, i, nb_values_to_add_); })); } auto result_async = true; for (auto &thread_result : test_threads_result_) { result_async &= thread_result.get(); } ASSERT_EQ(false, test_queue_->is_empty()); ASSERT_EQ(nb_threads_ * nb_values_to_add_, test_queue_->count()); ASSERT_EQ(true, result_async); } TEST_P(ConcurrentAsyncQueuePush, AddMoveElements) { ASSERT_EQ(true, test_queue_->is_empty()); ASSERT_EQ(0, test_queue_->count()); for (auto i = 0; i < nb_threads_; ++i) { test_threads_result_.push_back(std::async(std::launch::async, [this, i] { return ConcurrentAsyncQueueTestHelper::add_move_elements(*test_queue_, i, nb_values_to_add_); })); } auto result_async = true; for (auto &thread_result : test_threads_result_) { result_async &= thread_result.get(); } ASSERT_EQ(false, test_queue_->is_empty()); ASSERT_EQ(nb_threads_ * nb_values_to_add_, test_queue_->count()); ASSERT_EQ(true, result_async); }
be354e3ad1524dba07ea2d4d0639a3b7db8d2585
88a104c6f47802d19f1d8c8816c3b14601b46df8
/Source/ProceduralMeshUtility/Private/Line/Simplify/ThirdParty/Visvalingam/PMULineSimplifyVisvalingamHeap.h
6598f1109889aeb45b0ccd44dd82fa8c745baa1d
[ "MIT" ]
permissive
nwiswakarma/ProceduralMeshUtility
28f64648865be95a74a82ca95a24eba1df7ade16
5cd31874be74335ffb6df6f424364994a53edc32
refs/heads/master
2020-04-15T06:17:09.310057
2019-04-03T20:50:44
2019-04-03T20:50:44
164,455,098
3
2
null
null
null
null
UTF-8
C++
false
false
7,073
h
PMULineSimplifyVisvalingamHeap.h
// Copyright (c) 2013, Mathieu Courtemanche // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // The views and conclusions contained in the software and documentation are those // of the authors and should not be interpreted as representing official policies, // either expressed or implied, of the FreeBSD Project. // // Modified 2018 Nuraga Wiswakarma #pragma once #include "CoreMinimal.h" // Special Heap to store vertex data as we process the input linestring. // We need a min-heap with: // standard: top(), pop(), push(elem) // non-standard: remove(elem) anywhere in heap, // or alternatively, re-heapify a single element. // // This implementation uses a reheap() function and maintains a map to quickly // lookup a heap index given an element T. // template <typename T, typename Comparator = std::less<T> > class FPMULineSimplifyVisvalingamHeap { public: typedef TMap<T, SIZE_T> FNodeToHeapIndexMap; FPMULineSimplifyVisvalingamHeap(SIZE_T fixed_size) : m_data(new T[fixed_size]) , m_capacity(fixed_size) , m_size(0) , m_comp(Comparator()) { m_node_to_heap.Reserve(fixed_size); } ~FPMULineSimplifyVisvalingamHeap() { delete[] m_data; } void insert(T node) { check(m_size < m_capacity); // insert at left-most available leaf (i.e.: bottom) SIZE_T insert_idx = m_size; m_size++; m_data[insert_idx] = node; // bubble up until it's in the right place bubble_up(insert_idx); #ifdef PMU_LINE_SIMPLIFY_VIS_CHECK_HEAP_CONSISTENCY validate_heap_state(); #endif } const T top() const { check(!empty()); return m_data[NODE_TYPE_ROOT]; } T pop() { T res = top(); m_size--; clear_heap_index(res); if (!empty()) { // take the bottom element, stick it at the root and let it // bubble down to its right place. m_data[NODE_TYPE_ROOT] = m_data[m_size]; bubble_down(NODE_TYPE_ROOT); } #ifdef PMU_LINE_SIMPLIFY_VIS_CHECK_HEAP_CONSISTENCY validate_heap_state(); #endif return res; } bool empty() const { return m_size == 0; } /** reheap re-enforces the heap property for a node that was modified * externally. Logarithmic performance for a node anywhere in the tree. */ void reheap(T node) { SIZE_T heap_idx = get_heap_index(node); bubble_down(bubble_up(heap_idx)); #ifdef PMU_LINE_SIMPLIFY_VIS_CHECK_HEAP_CONSISTENCY validate_heap_state(); #endif } private: FPMULineSimplifyVisvalingamHeap(const FPMULineSimplifyVisvalingamHeap& other); FPMULineSimplifyVisvalingamHeap& operator=(const FPMULineSimplifyVisvalingamHeap& other); enum NodeType { NODE_TYPE_ROOT = 0, NODE_TYPE_INVALID = ~0 }; SIZE_T parent(SIZE_T n) const { if (n != NODE_TYPE_ROOT) { return (n-1)/2; } else { return NODE_TYPE_INVALID; } } SIZE_T left_child(SIZE_T n) const { return 2*n + 1; } SIZE_T bubble_up(SIZE_T n) { SIZE_T parent_idx = parent(n); while (n != NODE_TYPE_ROOT && parent_idx != NODE_TYPE_INVALID && m_comp(m_data[n], m_data[parent_idx])) { Swap(m_data[n], m_data[parent_idx]); // update parent which is now at heap index 'n' set_heap_index(m_data[n], n); n = parent_idx; parent_idx = parent(n); } set_heap_index(m_data[n], n); return n; } SIZE_T small_elem(SIZE_T n, SIZE_T a, SIZE_T b) const { SIZE_T smallest = n; if (a < m_size && m_comp(m_data[a], m_data[smallest])) { smallest = a; } if (b < m_size && m_comp(m_data[b], m_data[smallest])) { smallest = b; } return smallest; } SIZE_T bubble_down(SIZE_T n) { while (true) { SIZE_T left = left_child(n); SIZE_T right = 1+left; SIZE_T smallest = small_elem(n, left, right); if (smallest != n) { Swap(m_data[smallest], m_data[n]); // update 'smallest' which is now at 'n' set_heap_index(m_data[n], n); n = smallest; } else { set_heap_index(m_data[n], n); return n; } } } void set_heap_index(T node, SIZE_T n) { m_node_to_heap.Emplace(node, n); } void clear_heap_index(T node) { check(m_node_to_heap.Contains(node)); m_node_to_heap.Remove(node); } SIZE_T get_heap_index(T node) const { check(m_node_to_heap.Contains(node)); SIZE_T heap_idx = m_node_to_heap.FindChecked(node); check(m_data[heap_idx] == node); return heap_idx; } #ifdef PMU_LINE_SIMPLIFY_VIS_CHECK_HEAP_CONSISTENCY void validate_heap_state() const { check(m_node_to_heap.Num() == m_size); for (SIZE_T i = 0; i < m_size; ++i) { // ensure we cached the node properly check(i == get_heap_index(m_data[i])); // make sure heap property is preserved SIZE_T parent_index = parent(i); if (parent_index != NODE_TYPE_INVALID) { check(m_comp(m_data[parent_index], m_data[i])); } } } #endif private: T* m_data; SIZE_T m_capacity; SIZE_T m_size; const Comparator m_comp; FNodeToHeapIndexMap m_node_to_heap; };
41db9e1a9d6371198d1d5c1790e857d7e4bc5210
db0d88743c5b813a45d682e9f868d96cd62240d3
/ClassLoaderBytesGenerator/zip_file.cc
8cd61375a02efff8e42d7412b33fab4b1dbfc4f2
[]
no_license
Erouax/wape-launcher
42e6d3bb183fac62dbba5a027e4a0481532c399a
2e3a4991d1f1da453a7235534da8ad4d1992e7a6
refs/heads/master
2020-03-21T19:36:45.280224
2017-07-07T18:40:01
2017-07-07T18:40:01
138,959,647
1
0
null
2018-06-28T03:06:05
2018-06-28T03:06:05
null
UTF-8
C++
false
false
3,059
cc
zip_file.cc
#include "zip_file.h" #include <fstream> #include <cstring> #define NOMINMAX #include <Windows.h> #include "miniz.h" ZipFile::ZipFile() : archive_(new mz_zip_archive()) { Reset(); } ZipFile::ZipFile(const std::wstring& filename) : ZipFile() { Load(filename); } ZipFile::ZipFile(std::basic_istream<uint8_t>* stream) : ZipFile() { Load(stream); } ZipFile::ZipFile(const std::vector<uint8_t>& bytes) : ZipFile() { Load(bytes); } ZipFile::~ZipFile() { Reset(); } void ZipFile::Load(std::basic_istream<uint8_t>* stream) { Reset(); if (stream) { buffer_.assign(std::istreambuf_iterator<uint8_t>(*stream), std::istreambuf_iterator<uint8_t>()); } StartRead(); } void ZipFile::Load(const std::wstring& file) { filename_ = file; std::basic_ifstream<uint8_t> stream(file, std::ios::binary); Load(&stream); } void ZipFile::Load(const std::vector<uint8_t>& bytes) { Reset(); buffer_.assign(bytes.begin(), bytes.end()); StartRead(); } bool ZipFile::Good() const { return archive_->m_zip_mode != MZ_ZIP_MODE_INVALID; } void ZipFile::StartRead() { if (archive_->m_zip_mode == MZ_ZIP_MODE_READING) { return; } if (!mz_zip_reader_init_mem( archive_.get(), buffer_.data(), buffer_.size(), 0)) { Reset(); } } void ZipFile::Reset() { if (archive_->m_zip_mode == MZ_ZIP_MODE_READING) { mz_zip_reader_end(archive_.get()); } buffer_.clear(); buffer_.shrink_to_fit(); archive_->m_zip_mode = MZ_ZIP_MODE_INVALID; } size_t ZipFile::Count() const { return mz_zip_reader_get_num_files(archive_.get()); } bool ZipFile::ForEach(const std::function<bool(const ZipInfo&)>& cb) { for (size_t iii = 0; iii < Count(); iii++) { const auto info = GetInfo(static_cast<uint32_t>(iii)); if (info.file_index == kInvalidZipInfo) { return false; } if (!cb(info)) { break; } } return true; } bool ZipFile::Read(const ZipInfo& file, std::vector<uint8_t>* buf) { if (buf && !file.is_directory && file.file_index != kInvalidZipInfo) { auto size = size_t{ 0 }; auto data = static_cast<uint8_t*>(mz_zip_reader_extract_to_heap( archive_.get(), static_cast<mz_uint>(file.file_index), &size, 0)); if (data) { if (buf->capacity() < size) { buf->reserve(size); } std::copy(data, data + size, std::back_inserter(*buf)); mz_free(data); return true; } } return false; } std::vector<uint8_t> ZipFile::Read(const ZipInfo& file) { std::vector<uint8_t> buf; Read(file, &buf); return buf; } ZipInfo ZipFile::GetInfo(const uint32_t index) { mz_zip_archive_file_stat stat; if (!mz_zip_reader_file_stat(archive_.get(), static_cast<mz_uint>(index), &stat)) { return {}; } ZipInfo zip_info; zip_info.file_index = stat.m_file_index; zip_info.file_name = stat.m_filename; zip_info.is_directory = mz_zip_reader_is_file_a_directory( archive_.get(), stat.m_file_index); return zip_info; }
6b550613723eb935f1c6c76521fa00a0989a2dfb
a01dc7d5234c9dee4b237f2976f48e4d04e86c53
/source/Listener.cpp
a08cb60a05aa1ab1ade340fad536ff6eb241c54b
[ "MIT" ]
permissive
Johnsonys/AppServer
ebe8996eccb26747446f73f017feb4a14645c383
4c3eee0f99b38e46e676f8b0fc3012a929d4e4e2
refs/heads/master
2023-05-05T22:12:49.351266
2021-05-28T21:36:11
2021-05-28T21:36:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,828
cpp
Listener.cpp
#include "Listener.h" #include "LogData.h" #include "WebServer.h" #include "Cache.h" #include "LogClient.h" #include "WebServer.h" #include <jde/Str.h> #define var const auto #define _logClient Logging::LogClient::Instance() #define _webServer (*Web::MyServer::GetInstance()) #define _webLevelUint static_cast<uint>((Jde::ELogLevel)_webLevel) namespace Jde::ApplicationServer { //using Messages::EMessages; using Messages::Application; using Messages::Message; //namespace Server //{ shared_ptr<Listener> Listener::_pInstance{nullptr}; shared_ptr<Listener> Listener::Create( PortType port )noexcept(false) { ASSERT( _pInstance==nullptr ); try { return _pInstance = shared_ptr<Listener>( new Listener(port) ); } catch( const std::system_error& e ) { CRITICAL0( string(e.what()) ); THROW( Exception("Could not create listener: '{}'", e.what()) ); } } shared_ptr<Listener>& Listener::GetInstancePtr()noexcept { ASSERT( _pInstance!=nullptr ); return _pInstance; } Listener::Listener( PortType port )noexcept(false): IO::Sockets::ProtoServer{ port } { Accept(); RunAsyncHelper( "AppListener" );//_pThread = make_shared<Threading::InterruptibleThread>( [&](){Run();} ); INFO( "Accepting on port '{}'"sv, port ); } vector<google::protobuf::uint8> data( 4, 0 ); sp<IO::Sockets::ProtoSession> Listener::CreateSession( basio::ip::tcp::socket socket, IO::Sockets::SessionPK id )noexcept { //auto onDone = [&]( std::error_code ec, std::size_t length ) //{ // if( ec ) // ERR0( CodeException::ToString(ec) ); // else // DBG("length={}", length); //}; //basio::async_write( socket, basio::buffer(data.data(), data.size()), onDone ); return sp<Session>( new Session{socket, id} ); //return sp<Session>{}; } uint Listener::ForEachSession( std::function<void(const IO::Sockets::SessionPK&, const Session&)>& fncn )noexcept { std::function<void(const IO::Sockets::SessionPK&, const IO::Sockets::ProtoSession&)> fncn2 = [&fncn](const IO::Sockets::SessionPK& id, const IO::Sockets::ProtoSession& session ) { fncn( id, dynamic_cast<const Session&>(session) ); }; return _sessions.ForEach( fncn2 ); } sp<Session> Listener::FindSession( IO::Sockets::SessionPK id )noexcept { std::function<bool(const IO::Sockets::ProtoSession&)> fnctn = [id]( var& session ) { return dynamic_cast<const Session&>(session).ProcessId==id; }; auto pSession = _sessions.FindFirst( fnctn ); if( !pSession ) WARN( "Could not find session '{}'."sv, id ); return dynamic_pointer_cast<Session>( pSession ); } sp<Session> Listener::FindSessionByInstance( ApplicationInstancePK id )noexcept { std::function<bool(const IO::Sockets::ProtoSession&)> fnctn = [id]( var& session ) { return dynamic_cast<const Session&>(session).InstanceId==id; }; auto pSession = _sessions.FindFirst( fnctn ); if( !pSession ) WARN( "Could not find instance '{}'."sv, id ); return dynamic_pointer_cast<Session>( pSession ); } void Listener::SetLogLevel( ApplicationInstancePK instanceId, ELogLevel dbLevel, ELogLevel clientLevel )noexcept { if( instanceId==_logClient.InstanceId ) { GetDefaultLogger()->set_level( (spdlog::level::level_enum)clientLevel ); if( GetServerSink() ) GetServerSink()->SetLogLevel( dbLevel ); Web::MyServer::GetInstance()->UpdateStatus( *Web::MyServer::GetInstance() ); } else { auto pSession = FindSessionByInstance( instanceId ); if( pSession ) pSession->SetLogLevel( dbLevel, clientLevel ); } } void Listener::WebSubscribe( ApplicationPK applicationId, ELogLevel level )noexcept { if( applicationId==_logClient.ApplicationId ) _logClient.WebSubscribe( level ); else { auto pSession = FindApplication( applicationId ); if( pSession ) pSession->WebSubscribe( level ); } } sp<Session> Listener::FindApplication( ApplicationPK applicationId ) { std::function<bool(const IO::Sockets::ProtoSession&)> fnctn = [applicationId]( var& session ) { return dynamic_cast<const Session&>(session).ApplicationId==applicationId; }; return dynamic_pointer_cast<Session>( _sessions.FindFirst(fnctn) ); } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// Session::Session( basio::ip::tcp::socket& socket, IO::Sockets::SessionPK id )noexcept: IO::Sockets::TProtoSession<ToServer,FromServer>{ socket, id } { Start2();//0x7fffe0004760 } void Session::Start2()noexcept { auto pAck = new Logging::Proto::Acknowledgement(); pAck->set_instanceid( Id ); Logging::Proto::FromServer transmission; transmission.add_messages()->set_allocated_acknowledgement( pAck ); Write( transmission ); } void Session::SetLogLevel( ELogLevel dbLogLevel, ELogLevel fileLogLevel )noexcept { _dbLevel = dbLogLevel; _fileLogLevel = fileLogLevel; Logging::Proto::FromServer transmission; transmission.add_messages()->set_allocated_loglevels( AllocatedLogLevels() ); Write( transmission ); } Logging::Proto::LogLevels* Session::AllocatedLogLevels()noexcept { auto pValues = new Logging::Proto::LogLevels(); pValues->set_server( (Logging::Proto::ELogLevel)std::min((uint)_dbLevel, _webLevelUint) ); pValues->set_client( static_cast<Logging::Proto::ELogLevel>((Jde::ELogLevel)_fileLogLevel) ); return pValues; } void Session::WriteStrings()noexcept { Logging::Proto::FromServer transmission; var pStrings = Cache::GetApplicationStrings( ApplicationId ); if( pStrings ) { auto pValues = new Logging::Proto::Strings(); std::function<void(const uint32&, const string&)> fnctn = [&pValues](const uint32& id, const string&)->void{pValues->add_files(id);}; pStrings->FilesPtr->ForEach( fnctn ); std::function<void(const uint32&, const string&)> fnctn2 = [&pValues](const uint32& id, const string&)->void{pValues->add_functions(id);}; pStrings->FunctionsPtr->ForEach( fnctn2 ); std::function<void(const uint32&, const string&)> messageFnctn = [&pValues](const uint32& id, const string&)->void{pValues->add_messages(id);}; pStrings->MessagesPtr->ForEach( messageFnctn ); transmission.add_messages()->set_allocated_strings( pValues ); } else CRITICAL0( "!pStrings"sv ); transmission.add_messages()->set_allocated_loglevels( AllocatedLogLevels() ); Write( transmission ); } //send status update... void Session::SetStatus( Web::FromServer::Status& status )const noexcept { status.set_applicationid( (uint32)ApplicationId ); status.set_instanceid( (uint32)InstanceId ); status.set_hostname( HostName ); status.set_starttime( (uint32)Clock::to_time_t(StartTime) ); status.set_dbloglevel( (Web::FromServer::ELogLevel)DbLogLevel() ); status.set_fileloglevel( (Web::FromServer::ELogLevel)FileLogLevel() ); status.set_memory( Memory ); var statuses = Str::Split( Status, '\n' ); for( var& statusDescription : statuses ) status.add_values( statusDescription ); } void Session::OnDisconnect()noexcept { StartTime = TimePoint{}; auto pInstance = Web::MyServer::GetInstance(); if( pInstance ) pInstance->UpdateStatus( *this ); Listener::GetInstance().RemoveSession( Id ); } void Session::WebSubscribe( ELogLevel level )noexcept { var currentLevel = std::min( (uint)_dbLevel, static_cast<uint>((Jde::ELogLevel)_webLevel) ); _webLevel = level; if( currentLevel!=std::min((uint)_dbLevel, _webLevelUint) ) { Logging::Proto::FromServer transmission; transmission.add_messages()->set_allocated_loglevels( AllocatedLogLevels() ); Write( transmission ); } } void Session::WriteCustom( IO::Sockets::SessionPK webClientId, WebRequestId webRequestId, const string& message )noexcept { Logging::Proto::FromServer transmission; const RequestId requestId = ++_requestId; { lock_guard l{_customWebRequestsMutex}; _customWebRequests.emplace( requestId, make_tuple(webRequestId, webClientId) ); } auto pCustom = new Logging::Proto::CustomMessage(); pCustom->set_requestid( (uint32)requestId ); pCustom->set_message( message ); DBG( "({}) sending custom message to '{}' reqId='{}' from webClient='{}'('{}')"sv, InstanceId, Name, requestId, webClientId, webRequestId ); transmission.add_messages()->set_allocated_custom( pCustom ); Write( transmission ); } void Session::OnReceive( sp<Logging::Proto::ToServer> pTransmission )noexcept { try { if( !pTransmission->messages_size() ) THROW( Exception("!messages_size()") ); for( var& item : pTransmission->messages() ) { if( item.has_message() )//todo push multiple in one shot { if( !ApplicationId || !InstanceId ) { ERR( "sent message but have no instance."sv ); continue; } var& message = item.message(); const Jde::TimePoint time = TimePoint{} + std::chrono::seconds{ message.time().seconds() } + std::chrono::duration_cast<std::chrono::system_clock::duration>(std::chrono::nanoseconds{ message.time().nanos() }); var level = (uint)message.level(); vector<string> variables; for( auto i=0; i<message.variables_size(); ++i ) variables.push_back( message.variables(i) ); if( level>=(uint)_dbLevel ) Logging::Data::PushMessage( ApplicationId, InstanceId, time, (ELogLevel)message.level(), message.messageid(), message.fileid(), message.functionid(), message.linenumber(), message.userid(), message.threadid(), variables ); if( level>=_webLevelUint ) _webLevel = Web::MyServer::GetInstance()->PushMessage( 0, ApplicationId, InstanceId, time, (ELogLevel)message.level(), message.messageid(), message.fileid(), message.functionid(), message.linenumber(), message.userid(), message.threadid(), variables ); } else if( item.has_string() ) { var& strings = item.string(); if( ApplicationId && InstanceId ) Cache::Add( ApplicationId, strings.field(), strings.id(), strings.value() ); else ERR( "sent string but have no instance."sv ); } else if( item.has_status() ) { var& status = item.status(); Memory = status.memory(); ostringstream os; for( auto i=0; i<status.details_size(); ++i ) os << status.details(i) << endl; Status = os.str(); auto pInstance = Web::MyServer::GetInstance(); if( pInstance ) pInstance->UpdateStatus( *this ); } else if( item.has_custom() ) { DBG( "({})Received custom message, sending to web."sv, InstanceId ); CustomFunction<Logging::Proto::CustomMessage> fnctn = []( Web::MySession& webSession, uint a, const Logging::Proto::CustomMessage& b ){ webSession.WriteCustom((uint32)a, b.message()); }; SendCustomToWeb<Logging::Proto::CustomMessage>( item.custom(), fnctn ); // ‘const Jde::Logging::Proto::CustomMessage’) to type // ‘const Jde::ApplicationServer::Web::FromClient::Custom // var& custom = item.custom(); // uint clientId; // IO::Sockets::SessionPK sessionId; // { // lock_guard l{_customWebRequestsMutex}; // var pRequest = _customWebRequests.find( custom.requestid() ); // if( pRequest==_customWebRequests.end() ) // { // DBG( "Could not fine request {}", custom.requestid() ); // return; // } // clientId = get<0>( pRequest->second ); // sessionId = get<1>( pRequest->second ); // //_customWebRequests.erase( pRequest ); // } // var pSession = _webServer.Find( sessionId ); // if( pSession ) // pSession->WriteCustom( clientId, custom.message() ); // else // DBG( "Could not web session {}", sessionId ); } else if( item.has_complete() ) { CustomFunction<Logging::Proto::CustomComplete> fnctn = []( Web::MySession& webSession, uint a, const Logging::Proto::CustomComplete& ){ webSession.WriteComplete((uint32)a); }; SendCustomToWeb<Logging::Proto::CustomComplete>( item.complete(), fnctn, true ); } else if( item.has_instance() ) { var& instance = item.instance(); Name = instance.applicationname(); HostName = instance.hostname(); ProcessId = instance.processid(); StartTime = Clock::from_time_t( instance.starttime() ); try { var [applicationId,instanceId, dbLogLevel, fileLogLevel] = Logging::Data::AddInstance( Name, HostName, ProcessId ); DBG( "Adding applicaiton ({}){}@{}"sv, ProcessId, Name, HostName ); InstanceId = instanceId; ApplicationId = applicationId; _dbLevel = dbLogLevel; _fileLogLevel = fileLogLevel; Cache::Load( ApplicationId ); WriteStrings(); } catch( const Exception& e ) { ERR( "Could not create app instance - {}"sv, e.what() ); } break; } } } catch( const Exception& e )//parsing errors { ERR( "JdeException - {}"sv, e.what() ); } } }