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
dfadaacfdd32c5591d54d2f967b3d205da231b50
38b8ef65a66cdd60df8ff80b005b706d5119d63e
/Лаб4/StructuralPatterns.cpp
8ddfa67892ac1f26c97cfd63a8a3cf8fe2e054c5
[]
no_license
Svidruk/MAPZ
a7100fd9eb56b2ab4aa1de13e40b699904f7c373
fcf250e510f086f59199ec733a5d37fea38dd550
refs/heads/main
2023-05-06T10:26:16.680020
2021-05-28T12:06:31
2021-05-28T12:06:31
371,611,421
0
0
null
null
null
null
UTF-8
C++
false
false
863
cpp
StructuralPatterns.cpp
#include <iostream> #include "Facade.h" #include "Proxy.h" void setRules(Bot *b) { b->pushRule("Parsing header"); b->pushRule("Parsing body"); b->pushRule("Parsing ending"); } void setRules(abstractBot* b) { b->pushRule("Parsing header"); b->pushRule("Parsing body"); b->pushRule("Parsing ending"); } int main() { Bot* bot = new Bot(1,"someBot"); int i = 0; facade *f = new facade(); std::cout << "press 1: to reset params of current unattended bot\npress other: to create attended bot 2: \n"; std::cin >> i; switch (i) { case 1: setRules(bot); f->setExistingBot(bot); bot->runThread(); f->setNewParams(bot); bot->runThread(); break; default: abstractBot* ab = f->createAttended(); setRules(ab); ab->runThread(); //static_cast<AttendedBot*>(ab)->runThread(); delete ab; break; } delete bot; delete f; return 0; }
5b5a85dd3dc2ba99623bd35c14b418874f9192e5
1935926ec53604c936e53019c24bdd16e1ef1bbc
/vjudge/hdu_2700.cpp
8c54cb6976a205263bd3655ab13ea020af754812
[]
no_license
PrimisR/Training
345ec0b342ea2b515e1786c93d5a87602d6c3044
b4834cc29b13e604e7a95f231ac48f49987bebc7
refs/heads/master
2022-12-30T02:46:47.621210
2020-10-20T03:00:52
2020-10-20T03:00:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
641
cpp
hdu_2700.cpp
#include<stdio.h> #include<string.h> int main() { int length,i,count; char str[101] ; while(scanf("%s",str) != EOF && str[0] != '#'){ count = 0; length = strlen(str); for(i = 0; i<length-1;i++){ if(str[i]=='1'){ count++; } } if(count%2==0 && str[length-1] == 'e'){ str[length-1]='0'; }else if(count%2!=0 && str[length-1] == 'e'){ str[length-1]='1'; }else if(count%2==0 && str[length-1] == 'o'){ str[length-1]='1'; }else if(count%2!=0 && str[length-1] == 'o'){ str[length-1]='0'; } for(i = 0; i<length;i++){ printf("%c",str[i]); if(i == length-1){ printf("\n"); } } } return 0; }
b19e8beb10d4d88ac5f20d2b79947270276852bd
5b36c629df399989df0a7e2dd3a055008d57a2f8
/CP - Handbook/graphsRepresentation.cpp
36d215247dba20f80a42ffaab951fc1127b2dee1
[]
no_license
VelisariosF/Algorithms
2b3861e75f7d06ffdcbc69228c84e94e571be750
9c73cdcfcbe640fa2feb1d4edc22bba9544aa479
refs/heads/master
2022-12-24T14:48:40.115777
2020-09-26T07:34:38
2020-09-26T07:34:38
298,761,711
0
0
null
2020-09-26T07:30:36
2020-09-26T07:30:36
null
UTF-8
C++
false
false
1,500
cpp
graphsRepresentation.cpp
#include<cstdio> #include<vector> using namespace std; const int Nmax = 100; void matrix_display(int A[][Nmax], int N){ for(int i = 1; i <= N; i++) for(int j = 1; j <= N; j++) if(A[i][j] == 1) printf("%d %d\n", i, j); } void list_display(vector<int> A[Nmax], int N){ for(int i = 1; i <= N; i++){ vector<int>T = A[i]; printf("%d: ", i); for(int j = 0; j < (int)T.size(); j++) printf("%d ", T[j]); printf("\n"); } } void edge_display(vector<pair<int, int>>A, int M){ for(int i = 0; i < M; i++) printf("Edge: %d %d\n",A[i].first, A[i].second); } int main(){ int AMatrix[Nmax][Nmax] = {{0, 0, 0, 0, 0, 0}, {0, 0, 1, 0, 1, 0}, {0, 1, 0, 1, 0, 1}, {0, 0, 1, 0, 0, 1}, {0, 1, 0, 0, 0, 0}, {0, 0, 1, 1, 0, 0}}; int N = 5, M = 5; //matrix_display(AMatrix, N); vector<int> AList[N + 1]; for(int i = 1; i <= N; i++) for(int j = 1; j <= N; j++) if(AMatrix[i][j] == 1) AList[i].push_back(j); list_display(AList, N); vector<pair<int, int>>EList; EList.push_back(make_pair(1, 2)); EList.push_back(make_pair(1, 4)); EList.push_back(make_pair(2, 3)); EList.push_back(make_pair(2, 5)); EList.push_back(make_pair(3, 5)); edge_display(EList, M); return 0; }
58a97f9861c44a50d0fe539aae24b8a633d57ebc
ef331d33d8c5f9437547b9278c8b3e2833c0059b
/common/partition.hpp
259ad008d9e2ef3ac456525663c72940ee7ea537
[]
no_license
AlexanderKraynov/spbstu_cpp_labs
2d1bbf2eceadae6b1026be7dc1e90905751834ab
91f622b032ba32e0493147f919e9c716afbd7838
refs/heads/master
2021-01-05T07:39:52.200725
2020-02-16T17:44:50
2020-02-16T17:44:50
240,936,220
0
0
null
null
null
null
UTF-8
C++
false
false
316
hpp
partition.hpp
#ifndef A4_LABS_PARTITION_HPP #define A4_LABS_PARTITION_HPP #include "composite-shape.hpp" #include "matrix.hpp" #include "base-types.hpp" namespace kraynov { Matrix part(const Shape::array &, size_t); Matrix part(const CompositeShape &); bool intersect(const rectangle_t &, const rectangle_t &); } #endif
5f80fec4a5042aa43b89be1c66cc112db5cc934c
49db059c239549a8691fda362adf0654c5749fb1
/2010/rassokhin/task5/simpleudpchat.cpp
933c478f856378114d604090ae95f5bf6cccc6fd
[]
no_license
bondarevts/amse-qt
1a063f27c45a80897bb4751ae5c10f5d9d80de1b
2b9b76c7a5576bc1079fc037adcf039fed4dc848
refs/heads/master
2020-05-07T21:19:48.773724
2010-12-07T07:53:51
2010-12-07T07:53:51
35,804,478
0
0
null
null
null
null
UTF-8
C++
false
false
3,513
cpp
simpleudpchat.cpp
#include "simpleudpchat.h" #include <QtGui/QVBoxLayout> #include <QtGui/QHBoxLayout> #include <QtNetwork/QHostAddress> #include <QtGui/QMessageBox> #include <QtGui/QApplication> #include <QtGui/QIntValidator> #include <QtCore/QByteArray> #include <QtCore/QString> SimpleUDPChat::SimpleUDPChat(QWidget *parent) : QDialog(parent) { setWindowTitle("Simple UDP Chat"); constructObjects(); connectObjects(); } bool SimpleUDPChat::startUdpListener(int port) { if (udpSocket->isValid()) return false; if (!udpSocket->bind(QHostAddress::LocalHost, port)) { return false; } setWindowTitle("Simple UDP Chat at port " + QString::number(port)); messagesList->addItem("Started at port " + QString::number(port)); return true; } void SimpleUDPChat::constructObjects() { udpSocket = new QUdpSocket(this); QVBoxLayout * mainLayout = new QVBoxLayout(this); QHBoxLayout * addressLayout = new QHBoxLayout(); QHBoxLayout * messageLayout = new QHBoxLayout(); messagesList = new QListWidget(this); ipAddressText = new QLineEdit(this); portText = new QLineEdit(this); messageText = new QLineEdit(this); sendButton = new QPushButton(this); sendButton->setText(tr("Send")); ipAddressText->setText(tr("127.0.0.1")); portText->setValidator(new QIntValidator(1, 65535, this)); addressLayout->addWidget(ipAddressText); addressLayout->addWidget(portText); messageLayout->addWidget(messageText); messageLayout->addWidget(sendButton); mainLayout->addWidget(messagesList); mainLayout->addLayout(addressLayout); mainLayout->addLayout(messageLayout); } void SimpleUDPChat::connectObjects() { connect(sendButton, SIGNAL(clicked()), SLOT(sendMessage())); connect(udpSocket, SIGNAL(readyRead()),SLOT(readMessage())); } void SimpleUDPChat::sendMessage() { QString message = messageText->text(); QString mcopy = message; mcopy.replace(" ", ""); if (mcopy.length() == 0) { return; } QByteArray datagram; datagram.append(message); QHostAddress destination; if (!destination.setAddress(ipAddressText->text())) { QMessageBox::warning(0, "Simple UDP Chat","Cannot send message. May be address is invalid"); return; } bool portGetting; quint16 destinationPort = portText->text().toInt(&portGetting); if (!portGetting || destinationPort == 0) { QMessageBox::warning(0, "Simple UDP Chat","Cannot send message. May be port is invalid"); return; } qint64 sended = udpSocket->writeDatagram(datagram, destination, destinationPort); if (sended == -1) { QMessageBox::warning(0, "Simple UDP Chat","Cannot send message. Strange error occured"); return; } messagesList->addItem(tr("to ") + ipAddressText->text() + ":" + portText->text() + "|\t" + message); messageText->clear(); } void SimpleUDPChat::readMessage() { while (udpSocket->hasPendingDatagrams()) { QByteArray datagram; datagram.resize(udpSocket->pendingDatagramSize()); QHostAddress sender; quint16 senderPort; if( udpSocket->readDatagram(datagram.data(), datagram.size(), &sender, &senderPort) == -1) continue; QString toAdd = "from " + sender.toString() + ":" + QString::number(senderPort) + "|\t" + QString(datagram); messagesList->addItem(toAdd); } }
d7d56a7477e509c9b131282ff0f8f03013753875
2b23944ed854fe8d2b2e60f8c21abf6d1cfd42ac
/LightOJ/1078/7109186_AC_248ms_1088kB.cpp
6cb21433d9a0b61ecee2456c924664c364fe8c72
[]
no_license
weakmale/hhabb
9e28b1f2ed34be1ecede5b34dc2d2f62588a5528
649f0d2b5796ec10580428d16921879aa380e1f2
refs/heads/master
2021-01-01T20:19:08.062232
2017-07-30T17:23:21
2017-07-30T17:23:21
98,811,298
0
0
null
null
null
null
UTF-8
C++
false
false
329
cpp
7109186_AC_248ms_1088kB.cpp
#include "cstdio" typedef long long LL; int main(){ int T; scanf("%d",&T); int kcase=1; while(T--){ LL a,b; scanf("%lld %lld",&a,&b); LL mod=b%a; LL k=1; while(mod){ mod=(mod*10+b)%a; k++; } printf("Case %d: %lld\n",kcase++,k); } return 0; }
3d0a52389ebd312dd683fd545d9615da2827c6e3
bf817b914f2c423da15c330b2a60bdf9f32c798a
/10_10_class_practice/10_10_class_practice/oj2.cpp
91d235130ead84982991bd3e7fe3347b378370d8
[]
no_license
z397318716/C-Plus-Plus
2d074ea53f7f45534f72b3109c86c0612eb32bfe
6a7405386e60e1c2668fd8e92d7e4b4ab7903339
refs/heads/master
2021-12-10T22:16:34.871394
2021-09-27T01:55:23
2021-09-27T01:55:23
204,134,098
0
0
null
null
null
null
GB18030
C++
false
false
799
cpp
oj2.cpp
/* *根据逆波兰表示法,求表达式的值。 有效的运算符包括?+,?-,?*,?/?。每个运算对象可以是整数,也可以是另一个逆波兰表达式。 说明: 整数除法只保留整数部分。 给定逆波兰表达式总是有效的。换句话说,表达式总会得出有效数值且不存在除数为 0 的情况。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/evaluate-reverse-polish-notation 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 */ // 二叉树 后序 左右根 // vector 的成员函数 erase 效率太差 // 所以考虑将 vector<string> 中的数据 放入 栈中 // isdigit 函数判断字符是否是数字字符 // atoi 函数 将字符串转换成数字
5a6bf45ec6a0b5181e54fc7e61624d61fc48d807
b1174362d4357ba3ff5192ec84552357a351ac67
/FacialAuthAPI/FacialRecognitionTrainer.h
4c2ba1ada60d6406de6f975bd245dd7fb21cf56c
[]
no_license
Biimmy/OpenCV-2FA-API-POC
09536860a122febbd0ed9fc69f2e6a0d11359f15
a52655b3dff74f6443721369508fb53881e2c971
refs/heads/master
2020-04-17T10:31:44.247273
2019-01-19T03:59:22
2019-01-19T03:59:22
166,504,143
0
0
null
null
null
null
UTF-8
C++
false
false
440
h
FacialRecognitionTrainer.h
#include <iostream> #include "opencv2/core/core.hpp" using namespace std; using namespace cv; class FacialRecognitionTrainer { public: static void CreateTrainerCSV(Mat, int); static void ReadCSVTrainingSet(const string&, vector<Mat>&, vector<int>&, int); void TrainFromImageSet(); static vector<int> GetAvailableTrainingSets(); static void CreateNewTrainingSet(int, string); static vector<string> RetrieveIDMatch(); };
3a09f8fd3697004ed04f9249035d4cc88dad0e81
1303d0e1813721a0f224a1d018df26e976fea68f
/correlation/include/sfit_metropolis_blast.cc
29b653505326c2dec7bbc50d07a508bc9768023f
[]
no_license
shuxianghuafu/Research
05a388b8c5a3a7991f72a2d67d0eee67b7b77014
758fc1530cf60099d38882e1b5bba2e0e7002619
refs/heads/master
2021-09-01T09:49:14.007462
2017-12-26T08:55:28
2017-12-26T08:55:28
86,212,115
0
0
null
null
null
null
UTF-8
C++
false
false
1,134
cc
sfit_metropolis_blast.cc
#ifndef __INCLUDE_SFIT_METROPOLIS_3DGAUSSIAN_CC__ #define __INCLUDE_SFIT_METROPOLIS_3DGAUSSIAN_CC__ CCF2S_Metropolis_Blast::CCF2S_Metropolis_Blast(CSourceCalc *scset, C3DArray *cexpset, C3DArray *cerrorset, C3DArray *ctheory3Dset, CCHArray *ctheoryset, CCHArray *sourceset, CKernel *kernelset){ int i,j; ndim=3; // npars is different for different subclasses npars=4; // sourcecalc=scset; cexp3D=cexpset; cerror3D=cerrorset; ctheory=ctheoryset; ctheory3D=ctheory3Dset; source=sourceset; kernel=kernelset; Init(); // initialization of pars is also unique to given subclass par[0].Set("lambda",parameter::getD(sourcecalc->spars,"lambda",1), 0.05,0.0,1.5); par[1].Set("R",parameter::getD(sourcecalc->spars,"R",13), 0.5,5.0,20.0); par[2].Set("Tau",parameter::getD(sourcecalc->spars,"Tau",12), 0.5,5.0,20.0); par[3].Set("DelTau",parameter::getD(sourcecalc->spars,"DelTau",5), 0.5,0.0,20.0); for(i=0;i<npars;i++){ for(j=0;j<npars;j++){ Usigma[i][j]=0.0; if(i==j) Usigma[i][j]=par[i].error; } } } #endif
90b8ce2921b99e7a62cc7b72831d7604e8f1548c
caf88bb3b669f90721badd8ea25c344bfe15e988
/cpp/src/files.h
90a59faba26e6022df2ade9867d1f158a9c0807a
[ "MIT" ]
permissive
ev6r/ice_halo_sim
cfc386236e1bbfde094c02a3358c93282dcda6de
6a00cb9a1dad991983823fc3a9c86cbc72f4e2a8
refs/heads/master
2020-04-11T15:34:33.593900
2018-11-15T07:42:49
2018-11-15T07:42:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,591
h
files.h
#ifndef ICEHALOSIM_FILES_H #define ICEHALOSIM_FILES_H #include <vector> #define BOOST_FILESYSTEM_NO_DEPRECATED #include <boost/filesystem.hpp> namespace IceHalo { namespace Files { class File; bool exists(const char* filename); void listDataFiles(const char* dir, std::vector<File>& files); std::string pathJoin(const std::string& p1, const std::string& p2); namespace OpenMode { constexpr uint8_t READ = 0b0001; constexpr uint8_t WRITE = 0b0010; constexpr uint8_t APPEND = 0b0100; constexpr uint8_t BINARY = 0b1000; }; class File { public: explicit File(const char* filename); File(const char* path, const char* filename); ~File(); bool open(uint8_t mode = OpenMode::READ); bool close(); size_t getSize(); template<class T> size_t read(T* buffer, size_t n = 1); template<class T> size_t write(T data); template<class T> size_t write(const T* data, size_t n); private: std::FILE *file; bool fileOpened; boost::filesystem::path p; }; template<class T> size_t File::read(T* buffer, size_t n) { if (!fileOpened) { return 0; } auto count = std::fread(buffer, sizeof(T), n, file); return count; } template<class T> size_t File::write(T data) { if (!fileOpened) { return 0; } auto count = std::fwrite(&data, sizeof(T), 1, file); return count; } template<class T> size_t File::write(const T* data, size_t n) { if (!fileOpened) { return 0; } auto count = std::fwrite(data, sizeof(T), n, file); return count; } } } #endif
2c542fc8f748404699ee231fe6b7ab1d46e6638c
7473acc70a76ee9cbe954f93f5e4adc33d6f3d53
/valid_triangle_number.cpp
b0789d316c3d408ac38792f320f3a29e0f3f5dc5
[]
no_license
ChenBohan/Leetcode-02-JiuZhang-Algorithm-Advanced-Course
d11d2de9454dd33759f4f0bbd76e15dbf04015e7
91e9afcac92e5e16451fed0d225cf4394e059582
refs/heads/master
2022-04-05T02:43:14.723778
2020-02-26T03:02:19
2020-02-26T03:02:19
242,764,505
0
0
null
null
null
null
UTF-8
C++
false
false
583
cpp
valid_triangle_number.cpp
class Solution { public: int triangleNumber(vector<int>& nums) { int result = 0; sort(nums.begin(), nums.end()); for (size_t c = nums.size() - 1; c >=2; c--) { size_t a = 0; size_t b = c - 1; while (a != b) { if (nums[a] + nums[b] > nums[c]) { result += b - a; b--; } else { a++; } } } return result; } };
1b6c6a8a4da9a4be6b93e6f9a0f99cc110b02b40
52d3f8ad6ebb2098541a3ae25e9536002099387f
/Assignment 10/src/ofApp.cpp
2a44330402f0feccab83872f386a0aa00212be70
[]
no_license
VictoriaLXQian/OpenFrameWorks
cfaed293ecf57e55e82c44477bf8cd2bf7a5e03b
526e84f104be8830c457f3424063dac270a6a184
refs/heads/master
2020-04-19T14:22:28.704593
2019-09-16T02:02:03
2019-09-16T02:02:03
168,242,902
0
1
null
null
null
null
UTF-8
C++
false
false
2,728
cpp
ofApp.cpp
#include "ofApp.h" ofPoint orgin; //-------------------------------------------------------------- void drawTriangle(int numTriangles){ ofPushMatrix(); ofPushStyle(); // orgin = ofPoint (10,10); ofSetColor(102, 30+(25*numTriangles), 144); ofDrawTriangle(0-5*numTriangles, 0+8*numTriangles,0,0, 0+5*numTriangles, 0+8*numTriangles); ofTranslate(0+5*numTriangles, 0+8*numTriangles); ofRotateZDeg(4); if (--numTriangles>1) drawTriangle(numTriangles); ofPopStyle(); ofPopMatrix(); } void ofApp::setup(){ ofBackground(190,210,204); gui.setup(); gui.add(numberChange.setup("numTriangles", 5, 1, 20)); // orgin = ofPoint (ofGetScreenWidth()/2,ofGetScreenHeight()/2); } // setup only run once; it runs at the beginning. //-------------------------------------------------------------- void ofApp::update(){ } // everytime update runs before the draw. //-------------------------------------------------------------- void ofApp::draw(){ ofPushMatrix(); orgin = ofPoint (ofGetScreenWidth()/2,ofGetScreenHeight()/2); ofTranslate(orgin); for (int numTriangles=0; numTriangles <=360; numTriangles+=numberChange){ ofPushMatrix(); ofPushStyle(); ofRotateZDeg(numTriangles); drawTriangle(4); ofPopStyle(); ofPopMatrix(); } ofPopMatrix(); gui.draw(); } // draw is pure graphic, no heavy math, etc. //-------------------------------------------------------------- void ofApp::keyPressed(int key){ } //-------------------------------------------------------------- void ofApp::keyReleased(int key){ } //-------------------------------------------------------------- void ofApp::mouseMoved(int x, int y){ } //-------------------------------------------------------------- void ofApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseEntered(int x, int y){ } //-------------------------------------------------------------- void ofApp::mouseExited(int x, int y){ } //-------------------------------------------------------------- void ofApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void ofApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void ofApp::dragEvent(ofDragInfo dragInfo){ }
869136438c5584c862aa6ba49dfd30af2b3aa641
7af47432094f36a1de1e93e733973be139029b65
/stl_practice2.cpp
10286d4edf1106c0f68eaeb761601b455714e43a
[]
no_license
SakshiWadhwa/CPP
d52f93026460902e52e0304597a3a9d7124ebf3d
a40c0a360f935e43ab35f6354d9a691853609835
refs/heads/master
2021-04-29T14:28:08.803016
2018-02-16T17:07:40
2018-02-16T17:07:40
121,774,114
1
0
null
null
null
null
UTF-8
C++
false
false
4,333
cpp
stl_practice2.cpp
#include<iostream> #include<algorithm> #include<vector> using namespace std; //predicate for for_each void func(int n) { cout<<n<<" "; } int isUnique(){ static int count=0; return count++; } int IsOdd(int n) { return(n%2); } int IsEven(int n) { return(!(n%2)); } vector<int> v; vector<int> v1; int main(){ v.push_back(0); v.push_back(1); v.push_back(2); v.push_back(3); v.push_back(4); v.push_back(0); v.push_back(1); v.push_back(2); v.push_back(3); v.push_back(4); vector<int>::iterator it; it = unique(v.begin(),v.end()); v.resize(distance(v.begin(), it)); for_each(v.begin(),v.end(),func); cout<<endl; sort(v.begin(),v.end()); it = unique(v.begin(),v.end()); v.resize(distance(v.begin(), it)); for_each(v.begin(),v.end(),func); cout<<endl; //Note::see for yourself with unique-copy reverse(v.begin(),v.end()); //reverses the range for_each(v.begin(),v.end(),func); cout<<endl; //Note::see for yourself with reverse-copy rotate(v.begin(),v.begin()+2,v.end()); //rotate v.begin()to v.begin()+1 to end for_each(v.begin(),v.end(),func); cout<<endl; //Note::see for yourself with unique_copy random_shuffle(v.begin(),v.end()); //shuffles the elements of vector for_each(v.begin(),v.end(),func); cout<<endl; it=partition(v.begin(),v.end(),IsOdd); //partitions vector range on the basis of given elements for_each(it,v.end(),func); cout<<endl; it=stable_partition(v.begin(),v.end(),IsEven); //partitions vector range on the basis of given elements for_each(v.begin(),it,func); cout<<endl; partial_sort(v.begin(),v.begin()+2,v.end()); for_each(v.begin(),v.end(),func); cout<<endl; //Note::see for yourself with partial-sort_copy nth_element(v.begin(),v.begin()+3,v.end()); // puts the nth element i.e v.begin()+3 to its actual position for_each(v.begin(),v.end(),func); cout<<endl; v1.push_back(0); v1.push_back(1); v1.push_back(2); v1.push_back(3); v1.push_back(4); v1.push_back(0); v1.push_back(1); v1.push_back(2); v1.push_back(3); v1.push_back(4); sort(v1.begin(),v1.end()); it=upper_bound(v1.begin(),v1.end(),3); //return iterator to first element next than 3 cout<<*it<<endl; it=lower_bound(v1.begin(),v1.end(),3); //returns iterator to first occurrence of element equal to 3 cout<<*it<<endl; pair<vector<int>::iterator,vector<int>::iterator> p; p=equal_range(v1.begin(),v1.end(),3); //returns a pair of lower bound and upper bound iterators cout<<*p.first<<" "<<*p.second<<endl; bool x=binary_search(v1.begin(),v1.end(),3); //searches for 3 in a given range cout<<x<<endl; sort(v.begin(),v.end()); sort(v1.begin(),v1.end()); vector <int> result(15); vector <int> v3(20); // random_shuffle(v.begin(),v.end()); // random_shuffle(v1.begin(),v1.end()); merge(v.begin(),v.end(),v1.begin(),v1.end(),result.begin()); //merges two sorted vectors and stores it in result for_each(result.begin(),result.end(),func); cout<<endl; x=includes(result.begin(),result.end(),v.begin(),v.end()); //checks if v is present in result cout<<x<<endl; it=set_union(v.begin(),v.end(),result.begin(),result.end(),v3.begin()); // union of two vectors for_each(v3.begin(),v3.end(),func); cout<<endl; it=set_intersection(v.begin(),v.end(),result.begin(),result.end(),v3.begin()); // intersection of two vectors v3.resize(distance(v3.begin(),it)); for_each(v3.begin(),v3.end(),func); cout<<endl; v.push_back(50); it=set_difference(v.begin(),v.end(),result.begin(),result.end(),v3.begin()); // difference of two vectors v3.resize(distance(v3.begin(),it)); for_each(v3.begin(),v3.end(),func); cout<<endl; vector<int>v4(15); it=set_symmetric_difference(v.begin(),v.end(),result.begin(),result.end(),v4.begin()); // difference of two vectors for_each(v.begin(),v.end(),func); cout<<endl; for_each(result.begin(),result.end(),func); cout<<endl; v4.resize(distance(v4.begin(),it)); for_each(v4.begin(),v4.end(),func); cout<<endl; }
3d84f7088135fcec95f25297afd5c45393b6cd61
45c0c17bcf2ebe763917d106aacefe09ec8ca138
/medium/392. Is Subsequence.cpp
588cf2cde76826dfcc3d329f4348dce3ce00ac3b
[]
no_license
Juliiii/leetcode-everyday
8d1b11bd6aa63e6f430524f81e88f786146e12af
7bda1fc9ee9c58d3348ac0ce6176db7f43ede42e
refs/heads/master
2021-09-05T06:08:27.055385
2018-01-24T16:32:18
2018-01-24T16:32:18
107,296,151
1
0
null
null
null
null
UTF-8
C++
false
false
321
cpp
392. Is Subsequence.cpp
class Solution { public: bool isSubsequence(string s, string t) { int pointS, pointT; pointS = pointT = 0; while(pointS != s.length()) { if (pointT == t.length()) return false; if (s[pointS] == t[pointT]) { pointS++; pointT++; } else pointT++; } return true; } };
1f1ec9e9ef1dc557102b0061cf9285825fa3c502
4fa7351e3ea669a29940d0b97bcd4e52d813dc86
/Work/HW7/hw07.cpp
6cb953560484932ab3abdaec2fb726571c49b6e7
[]
no_license
MZI207/OOP18
ae006bcbd20e9a4af71a6b97719c6ed178d13428
a54ebf484f4cb6776fa8b21f3c27e9e29159019a
refs/heads/master
2020-04-21T09:20:10.601121
2019-02-06T17:48:45
2019-02-06T17:48:45
169,445,225
0
0
null
null
null
null
UTF-8
C++
false
false
4,811
cpp
hw07.cpp
//Mohammed Iqbal //mzi207 #include <string> #include <vector> #include <iostream> using namespace std; //Base class Noble class Noble { public: Noble(const string& name, int str = 0) :name(name), str(str) {} void battle(Noble& challenger) { int thisStr = str;//This Nobles str int cStr = challenger.str;//Challenger's str cout << name << " battles " << challenger.name << endl; if (thisStr == 0 && cStr == 0) { //If they are both dead cout << "Oh, NO! They're both dead! Yuck!" << endl; } else if (dead) { //If thisNoble is dead cout << "He's dead, " << challenger.name << endl; } else if (challenger.dead) { //If cNoble is dead cout << "He's dead, " << name << endl; } else if (thisStr > cStr) { // If thisNoble is stronger changeStr(cStr); challenger.changeStr(thisStr); challenger.dead = true; cout << name << " defeats " << challenger.name << endl; } else if (thisStr < cStr) { challenger.changeStr(thisStr); changeStr(cStr); dead = true; cout << challenger.name << " defeats " << name << endl; } else { //If they have equal strengths changeStr(0); challenger.changeStr(0); challenger.dead = true; dead = true; cout << "Mutual Annihilation: " << name << " and " << challenger.name << " die at each other's hands" << endl; } } string getName() const { return name; } protected: virtual void changeStr(int val) = 0; bool isDead() const { return dead; } void addStr(int val) { str += val; } void setStr(int val) { str = val; } int getStr() const { return str; } private: bool dead = false; string name; int str; }; class Warrior { public: Warrior(const string& name, int str):name(name), str(str) {} bool isDead() const { return !str; } void setStr(int val) { str = val; } int getStr() const { return str; } bool isHired() const { return boss; } void hire(Noble* nob) { boss = nob; } virtual void battleCry() const = 0; protected: string getName() const { return name; } Noble* getBoss() const { return boss; } private: Noble* boss = nullptr; string name; int str; }; //Archer class derived from Warrior class Archer : public Warrior { public: Archer(const string& name, int str) : Warrior(name, str) {} void battleCry() const { cout << "TWANG! " << getName() << " says: Take that in the name of my lord, " << getBoss()->getName() << endl; } private: }; //Swordsman class derived from Warrior class Swordsman : public Warrior { public: Swordsman(const string& name, int str) : Warrior(name, str) {} void battleCry() const { cout << "CLANG! " << getName() << " says: Take that in the name of my lord, " << getBoss()->getName() << endl; } private: }; //Wizard class derived from Warrior class Wizard : public Warrior { public: Wizard(const string& name, int str) :Warrior(name, str) {} void battleCry() const { cout << "POOF" << endl; } private: }; //Lords derived from Nobles class Lord :public Noble { public: Lord(const string& name) : Noble(name), warriors(0) {} //Hires a Warrior ONLY TO THE LORDS bool hires(Warrior& war) { if (!isDead() && !war.isDead() && !war.isHired()) { warriors.push_back(&war); war.hire(this); addStr(war.getStr()); return true; } return false; } void changeStr(int val) { for (size_t i = 0; i < warriors.size(); i++) { warriors[i]->battleCry(); } if (getStr() < val) {setStr(0); } else { double ratio = float(1) - (float(getStr()) / float(val)); for (size_t i = 0; i < warriors.size(); i++) { warriors[i]->setStr(warriors[i]->getStr() * ratio); } setStr(getStr() * ratio); } } private: vector<Warrior*> warriors; }; //PersonWithStrengthToFight derived from Nobles class PersonWithStrengthToFight : public Noble { public: PersonWithStrengthToFight(const string& name, int str): Noble(name, str){} void changeStr(int val) { if (getStr() < val) { setStr(0); } else { setStr(getStr() - val); } } private: }; int main() { Lord sam("Sam"); Archer samantha("Samantha", 200); sam.hires(samantha); Lord joe("Joe"); PersonWithStrengthToFight randy("Randolf the Elder", 250); joe.battle(randy); joe.battle(sam); Lord janet("Janet"); Swordsman hardy("TuckTuckTheHardy", 100); Swordsman stout("TuckTuckTheStout", 80); janet.hires(hardy); janet.hires(stout); PersonWithStrengthToFight barclay("Barclay the Bold", 300); janet.battle(barclay); janet.hires(samantha); Archer pethora("Pethora", 50); Archer thora("Thorapleth", 60); Wizard merlin("Merlin", 150); janet.hires(pethora); janet.hires(thora); sam.hires(merlin); janet.battle(barclay); sam.battle(barclay); joe.battle(barclay); return 0; }
627a96970455870f039dfc5ce39a92d3555795db
4da5010801c9ee4177d3fff86a43961173c688c2
/Plugins/TelegrammAPI/Source/TelegrammAPI/Public/TelegrammAPI.h
a6eaf21af932cc4c76e3b056232d75ce85c73967
[]
no_license
mrDoooser/TelegrammTest
91cd366b6a3b5eef8f9d57f7baea21324f488d62
ef9de099579803521f46c70d066c02e6cb959c7c
refs/heads/master
2020-09-25T00:50:04.340055
2019-12-10T13:07:52
2019-12-10T13:07:52
225,883,074
0
0
null
null
null
null
UTF-8
C++
false
false
597
h
TelegrammAPI.h
// Copyright 1998-2019 Epic Games, Inc. All Rights Reserved. #pragma once #include "CoreMinimal.h" #include "Modules/ModuleManager.h" //class ITelegrammAPIWindows; //#include <td/telegram/Client.h> //typedef TSharedPtr<ITelegrammAPIInterface, ESPMode::ThreadSafe> FTelegrammAPIInterfacePtr; class FTelegrammAPIModule : public IModuleInterface { public: /** IModuleInterface implementation */ virtual void StartupModule() override; virtual void ShutdownModule() override; virtual void PostLoadCallback() override; //protected: // FTelegrammAPIInterfacePtr TelegrammAPIInterface; };
8fa8e903a5e0d5f2ca89ff1ae7ddfae23bb31835
da1500e0d3040497614d5327d2461a22e934b4d8
/cobalt/renderer/test/png_utils/png_encode.cc
3b4d58b13d03f6c36d7a9e686cb7ccbd5831c521
[ "Apache-2.0", "BSD-3-Clause" ]
permissive
youtube/cobalt
34085fc93972ebe05b988b15410e99845efd1968
acefdaaadd3ef46f10f63d1acae2259e4024d383
refs/heads/main
2023-09-01T13:09:47.225174
2023-09-01T08:54:54
2023-09-01T08:54:54
50,049,789
169
80
BSD-3-Clause
2023-09-14T21:50:50
2016-01-20T18:11:34
null
UTF-8
C++
false
false
4,678
cc
png_encode.cc
// Copyright 2015 The Cobalt Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "cobalt/renderer/test/png_utils/png_encode.h" #include <memory> #include <utility> #include <vector> #include "base/files/file_starboard.h" #include "base/files/file_util.h" #include "base/logging.h" #include "base/trace_event/trace_event.h" #include "third_party/libpng/png.h" namespace cobalt { namespace renderer { namespace test { namespace png_utils { namespace { // Write PNG data to a vector to simplify memory management. typedef std::vector<png_byte> PNGByteVector; void PNGWriteFunction(png_structp png_ptr, png_bytep data, png_size_t length) { PNGByteVector* out_buffer = reinterpret_cast<PNGByteVector*>(png_get_io_ptr(png_ptr)); // Append the data to the array using pointers to the beginning and end of the // buffer as the first and last iterators. out_buffer->insert(out_buffer->end(), data, data + length); } } // namespace void EncodeRGBAToPNG(const base::FilePath& png_file_path, const uint8_t* pixel_data, int width, int height, int pitch_in_bytes) { // Write the PNG to an in-memory buffer and then write it to disk. TRACE_EVENT0("cobalt::renderer", "png_encode::EncodeRGBAToPNG()"); size_t size; std::unique_ptr<uint8[]> buffer = EncodeRGBAToBuffer(pixel_data, width, height, pitch_in_bytes, &size); if (!buffer || size == 0) { DLOG(ERROR) << "Failed to encode PNG."; return; } SbFile file = SbFileOpen(png_file_path.value().c_str(), kSbFileOpenAlways | kSbFileWrite, NULL, NULL); DCHECK_NE(file, kSbFileInvalid); int bytes_written = SbFileWrite(file, reinterpret_cast<char*>(buffer.get()), size); base::RecordFileWriteStat(bytes_written); SbFileClose(file); DLOG_IF(ERROR, bytes_written != size) << "Error writing PNG to file."; } // Encodes RGBA8 formatted pixel data to an in memory buffer. std::unique_ptr<uint8[]> EncodeRGBAToBuffer(const uint8_t* pixel_data, int width, int height, int pitch_in_bytes, size_t* out_size) { TRACE_EVENT0("cobalt::renderer", "png_encode::EncodeRGBAToBuffer()"); // Initialize png library and headers for writing. png_structp png = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); DCHECK(png); png_infop info = png_create_info_struct(png); DCHECK(info); // if error encountered png will call longjmp(), so we set up a setjmp() here // with a failed assert to indicate an error in one of the png functions. // yo libpng, 1980 called, they want their longjmp() back.... if (setjmp(png->jmpbuf)) { png_destroy_write_struct(&png, &info); NOTREACHED() << "libpng encountered an error during processing."; return std::unique_ptr<uint8[]>(); } // Structure into which png data will be written. PNGByteVector png_buffer; // Set the write callback. Don't set the flush function, since there's no // need for buffered IO when writing to memory. png_set_write_fn(png, &png_buffer, &PNGWriteFunction, NULL); // Stuff and then write png header. png_set_IHDR(png, info, width, height, 8, // 8 bits per color channel. PNG_COLOR_TYPE_RGBA, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT); png_write_info(png, info); // Write image bytes, row by row. png_bytep row = (png_bytep)pixel_data; for (int i = 0; i < height; ++i) { png_write_row(png, row); row += pitch_in_bytes; } png_write_end(png, NULL); png_destroy_write_struct(&png, &info); size_t num_bytes = png_buffer.size() * sizeof(PNGByteVector::value_type); *out_size = num_bytes; // Copy the memory from the buffer to a scoped_array to return to the caller. std::unique_ptr<uint8[]> out_buffer(new uint8[num_bytes]); memcpy(out_buffer.get(), &(png_buffer[0]), num_bytes); return std::move(out_buffer); } } // namespace png_utils } // namespace test } // namespace renderer } // namespace cobalt
4f5137d2e89eaeda2a49aa759fba3951da4bafa4
5902fa0857cd4f722a9663bbd61aa0895b9f8dea
/BMIG-5101-SequencesAsBioInformation/Blast/ncbi-blast-2.10.0+-src/c++/include/objects/homologene/HG_Gene.hpp
a59770b98bc85244d3d4ca0f049640ce23862876
[]
no_license
thegrapesofwrath/spring-2020
1b38d45fa44fcdc78dcecfb3b221107b97ceff9c
f90fcde64d83c04e55f9b421d20f274427cbe1c8
refs/heads/main
2023-01-23T13:35:05.394076
2020-12-08T21:40:42
2020-12-08T21:40:42
319,763,280
0
0
null
null
null
null
UTF-8
C++
false
false
129
hpp
HG_Gene.hpp
version https://git-lfs.github.com/spec/v1 oid sha256:91b5ff4b66d5b35370aa4484a17b44d935a7b7b2bde1cc9f6e3be3e19eb0013d size 2952
38ba3861593785bd2a28a1b25ed7d46f60f046fc
6f1cfd3513ea8bc5e38fa805884ca7d217b72086
/Lab 4 - ECS/ECS/Game.cpp
a2341709cbfd8a156fc320d7bef1cd8b7cbc30ba
[]
no_license
BrianONeill97/Games-Engineering-2
a081b7726ca349bfba958cad91ed862fa0f8023a
4c91529c852d414d349bdecdf9f3f69c3b86b66d
refs/heads/master
2022-03-29T16:37:12.978867
2020-01-05T15:30:33
2020-01-05T15:30:33
210,319,827
0
0
null
null
null
null
UTF-8
C++
false
false
2,082
cpp
Game.cpp
#include "Game.h" Game::Game() { } Game::~Game() { } void Game::init(const char* title, int xPos, int yPos, int width, int height, bool fullscreen) { int flags = 0; if (fullscreen == true) { flags = SDL_WINDOW_FULLSCREEN; } if (SDL_Init(SDL_INIT_EVERYTHING) == 0) { std::cout << " Subsystem initialised!!" << std::endl; window = SDL_CreateWindow(title, xPos, yPos, width, height, flags); if (window) { std::cout << "Window Created" << std::endl; } renderer = SDL_CreateRenderer(window, -1, 0 | SDL_RENDERER_PRESENTVSYNC); if (renderer) { SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255); std::cout << "Renderer Created" << std::endl; } isRunning = true; } else { isRunning = false; } //Dog dog->addComponents(ptr); dog->addComponents(ptrPos); //Cat cat->addComponents(ptr); cat->addComponents(ptrPos); //Player player->addComponents(ptr); player->addComponents(ptrPos); //Alien alien->addComponents(ptr); alien->addComponents(ptrPos); hs.addEntity(*dog,"Dog"); hs.addEntity(*cat, "Cat"); hs.addEntity(*player, "Player"); hs.addEntity(*alien, "Alien"); rs.addEntity(*dog, "Dog"); rs.addEntity(*cat, "Cat"); rs.addEntity(*player, "Player"); rs.addEntity(*alien, "Alien"); ai.addEntity(*dog, "Dog"); ai.addEntity(*cat, "Cat"); ai.addEntity(*player, "Player"); ai.addEntity(*alien, "Alien"); hs.init(); rs.init(); ai.init(); } /// handle user and system events/ input void Game::processEvents() { //Handles all the inputs } /// Update the game world void Game::update() { hs.update(); rs.update(); ai.update(); system("CLS"); } /// draw the frame and then sitch bufers void Game::render() { SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255); //Clears image after every frame SDL_RenderClear(renderer); //Draw here rs.draw(renderer); //Presents the new Images SDL_RenderPresent(renderer); } void Game::cleanUp() { SDL_DestroyWindow(window); SDL_DestroyRenderer(renderer); window = nullptr; renderer = nullptr; SDL_Quit(); std::cout << "Cleaned" << std::endl; }
861b69ab0c5e84d5d44642fa5b68e2521a85c268
9ff35738af78a2a93741f33eeb639d22db461c5f
/.build/Android-Debug/jni/app/Uno.UX.Template__NavButton.cpp
6ffbc542980e2edb6037facd4b4d020e47468e5a
[]
no_license
shingyho4/FuseProject-Minerals
aca37fbeb733974c1f97b1b0c954f4f660399154
643b15996e0fa540efca271b1d56cfd8736e7456
refs/heads/master
2016-09-06T11:19:06.904784
2015-06-15T09:28:09
2015-06-15T09:28:09
37,452,199
0
0
null
null
null
null
UTF-8
C++
false
false
2,143
cpp
Uno.UX.Template__NavButton.cpp
// This file was generated based on 'C:\ProgramData\Uno\Packages\UnoCore\0.1.0\Source\Uno\UX\$.uno'. // WARNING: Changes might be lost if you edit this file directly. #include <app/_.NavButton.h> #include <app/Uno.Type.h> #include <app/Uno.UX.Template__NavButton.h> namespace app { namespace Uno { namespace UX { Template__NavButton__uType* Template__NavButton__typeof() { static Template__NavButton__uType* type; if (::uEnterCriticalIfNull(&type)) { type = (Template__NavButton__uType*)::uAllocClassType(sizeof(Template__NavButton__uType), "Uno.UX.Template<NavButton>", ::uObject__typeof(), 1); type->__interface_0.__fp_Apply = (bool(*)(void*, ::uObject*))Template__NavButton__Apply; type->Implements[0] = ::app::Uno::UX::ITemplate__typeof(); type->InterfaceOffsets[0] = offsetof(Template__NavButton__uType, __interface_0); ::uRetainObject(type); ::uExitCritical(); } return type; } bool Template__NavButton__get_Cascade(Template__NavButton* __this) { return __this->_cascade; } void Template__NavButton__set_Cascade(Template__NavButton* __this, bool value) { __this->_cascade = value; } bool Template__NavButton__get_AffectSubtypes(Template__NavButton* __this) { return __this->_affectSubtypes; } void Template__NavButton__set_AffectSubtypes(Template__NavButton* __this, bool value) { __this->_affectSubtypes = value; } bool Template__NavButton__Apply(Template__NavButton* __this, ::uObject* obj) { if (__this->_affectSubtypes) { if (::uIs(obj, ::app::NavButton__typeof())) { __this->OnApply(::uCast< ::app::NavButton*>(obj, ::app::NavButton__typeof())); return __this->Cascade(); } } else { if (::app::Uno::Object::GetType(::uPtr< ::uObject*>(obj)) == (::uType*)::app::NavButton__typeof()) { __this->OnApply(::uCast< ::app::NavButton*>(obj, ::app::NavButton__typeof())); return __this->Cascade(); } } return true; } void Template__NavButton___ObjInit(Template__NavButton* __this) { __this->_cascade = true; } }}}
2a894401fb64cbecc28dbe789132f82f9c66016a
7f111287610f7a96d2e5a3f726c5d5ff5797163b
/test/test_cte_eval.cpp
1f76a8a4f1fe08ac9e73bfdb6fca3a269a015d70
[]
no_license
arviCV/PID_Controller_Project
7f5a9982f27c3d432ec10f68deb98af88782ec56
578b0a501906be20e5ff641c7ab94ededdc73142
refs/heads/master
2020-04-10T00:23:07.396310
2018-12-06T15:44:43
2018-12-06T15:44:43
160,683,868
0
0
null
null
null
null
UTF-8
C++
false
false
2,106
cpp
test_cte_eval.cpp
#include "catch.hpp" #include "../src/cte_eval.h" #include <iostream> #include <cmath> #include <vector> #include <random> using namespace std; TEST_CASE("CTE should be evaluated as IDEAL when error is constant small", "[cte_eval]") { CrosstrackErrorEvaluator cteEval(false); double deltaTime = 0.05; double cte = 0.01; for (int i = 0; i < 100; ++i) { REQUIRE(cteEval.Evaluate(deltaTime, cte) == CrosstrackErrorEvaluator::IDEAL); } } TEST_CASE("CTE should be evaluated as defective when error is constant large", "[cte_eval]") { CrosstrackErrorEvaluator cteEval(false); double deltaTime = 0.05; double cte = 1.0; for (int i = 0; i < 100; ++i) { REQUIRE(cteEval.Evaluate(deltaTime, cte) == CrosstrackErrorEvaluator::DEFECTIVE); } } TEST_CASE("CTE should be evaluated as defective when error is small but with large deviations", "[cte_eval]") { CrosstrackErrorEvaluator cteEval(false); double deltaTime = 0.05; for (int i = 0; i < 100; ++i) { double cte = i % 2 ? 0.35 : -0.35; CrosstrackErrorEvaluator::Performance performance = cteEval.Evaluate(deltaTime, cte); if (i > 10) { REQUIRE(performance == CrosstrackErrorEvaluator::DEFECTIVE); } } } TEST_CASE("CTE should be evaluated as defective until error becomes both constant and small", "[cte_eval]") { CrosstrackErrorEvaluator cteEval(false); double deltaTime = 0.05; for (int i = 0; i < 100; ++i) { // Large constant CTE. double largeConstantCte = 2.0; if (i > 5) { REQUIRE(cteEval.Evaluate(deltaTime, largeConstantCte) == CrosstrackErrorEvaluator::DEFECTIVE); } } for (int i = 0; i < 100; ++i) { // Small but deviating CTE. double smallDeviatingCte = i % 2 ? 0.26 : -0.26; REQUIRE(cteEval.Evaluate(deltaTime, smallDeviatingCte) == CrosstrackErrorEvaluator::DEFECTIVE); } double smallConstantCte = 0.1; for (int i = 0; i < 10; ++i) { // Give the algorithm some time to transition. (void)cteEval.Evaluate(deltaTime, smallConstantCte); } REQUIRE(cteEval.Evaluate(deltaTime, smallConstantCte) == CrosstrackErrorEvaluator::IDEAL); }
96d3192aad5214175becb216ea26d3bbb0e7ec70
d84b57c8e6ab67744800eede6fbd569af90df321
/practice/575C.cpp
99ae8e5be0a7945fa43afb8e4eca40afa7fd7edf
[]
no_license
vaibhavahuja/codes
bcb6b0f1bc56423e201158329373672d67ec5968
4b35c65769887f9d05aff2342187e1028de2fe6d
refs/heads/master
2023-02-10T11:37:01.812198
2020-12-29T18:20:43
2020-12-29T18:20:43
272,912,716
0
0
null
null
null
null
UTF-8
C++
false
false
1,659
cpp
575C.cpp
//robot breakout #include <bits/stdc++.h> using namespace std; #define vi vector<int> #define pii pair<int, int> #define vp vector<pii> #define vs vector<string> #define mii map<int, int> void show(auto a){ int i = 0; while(i < a.size()){ cout<<a[i].first<<" "<<a[i].second<<endl; i++; } cout<<endl; } pii interval(vp a){ pii ans(a[0].first, a[0].second); for(int i = 1; i < a.size(); i++){ pii b = ans; pii c = a[i]; if(b.first > c.second || c.first > b.second) return pii(-1e7, -1e7); else{ ans.first = max(b.first, c.first); ans.second = min(b.second, c.second); } } return ans; } int main(){ ios_base::sync_with_stdio(false); int q; cin>>q; while(q--){ int n; cin>>n; vi x(n), y(n); vi left(n), top(n), down(n), right(n); for(int i = 0; i < n; i++){ cin>>x[i]>>y[i]>>left[i]>>top[i]>>right[i]>>down[i]; } vp inx, iny; for(int i = 0; i < n; i++){ pii xx(x[i], x[i]); if(left[i] == 1) xx.first = -1e5; if(right[i] == 1) xx.second = +1e5; inx.push_back(xx); } for(int i = 0; i < n; i++){ pii yy(y[i], y[i]); if(down[i] == 1) yy.first = -1e5; if(top[i] == 1) yy.second = +1e5; iny.push_back(yy); } // cout<<"below is intervals of x L - R"<<endl; // show(inx); // cout<<"below is intervals of y D-T "<<endl; // show(iny); pii ansx = interval(inx); pii ansy = interval(iny); if(ansx == pii(-1e7, -1e7) || ansy == pii(-1e7, -1e7)) cout<<0<<endl; else{ cout<<1<<" "<<ansx.first<<" "<<ansy.first<<endl; } } // cout<<ansx.first<<" "<<ansx.second<<endl; // cout<<ansy.first<<" "<<ansy.second<<endl; }
e27abafedd3023de551110314cb9a94713fd3d33
959d59a0d1c644a6ae03441a433846351e1a84b0
/app/src/main/cpp/MovieController.hpp
a4247ef2b1fc0ac445c93135506dda1cca0ae7ad
[]
no_license
smedic/HRTest
5154f5254d3985334e39185b1117ecfd16d6fd1c
6da5f8e0267ee63d3ccf5aa14ef33dcd9f96505c
refs/heads/master
2023-01-11T16:26:57.572960
2020-11-09T00:19:51
2020-11-09T00:19:51
310,699,493
0
0
null
null
null
null
UTF-8
C++
false
false
3,889
hpp
MovieController.hpp
// // MovieController.hpp // Highrise // // Created by Jimmy Xu on 12/19/18. // Copyright © 2019 Highrise. All rights reserved. // #ifndef MovieController_hpp #define MovieController_hpp #include <string> #include <vector> #include <map> namespace movies { class Actor { public: std::string name; int age; std::string imageUrl; std::string biographyUrl; }; class Movie { public: int id; std::string name; int lastUpdated; float score; std::vector<Actor> actors; std::string description; std::string posterUrl; std::string trailerYouTubeId; }; class MovieController { private: std::vector<Movie *> _movies; public: MovieController() { //populate data for (int i = 0; i < 10; i++) { auto movie = new Movie(); movie->id = i; movie->name = "Top Gun " + std::to_string(i); movie->lastUpdated = i * 10000; movie->score = rand() % 10; if (i % 3 == 0) { movie->posterUrl = "https://www.wftv.com/resizer/5Y5lRAi-YHD_U09t7BW_G18JrK4=/1200x675/cloudfront-us-east-1.images.arcpublishing.com/cmg/KRZEOBULLVEKXPMUDRELO5XA7Q.jpg"; } else if (i % 3 == 1) { movie->posterUrl = "https://discoverbeaumont.com/wp-content/uploads/2019/06/TopGun_wenthumb.jpg"; } else { movie->posterUrl = "https://sothebys-md.brightspotcdn.com/b8/1c/41e05570498e97a6b26c472f5cfe/168l20895-bjb6b.jpg"; } movie->trailerYouTubeId = "xa_z57UatDY"; movie->description = "As students at the United States Navy's elite fighter weapons school compete to be best in the class, one daring young pilot learns a few things from a civilian instructor that are not taught in the classroom."; auto tomCruise = Actor(); tomCruise.name = "Tom Cruise"; tomCruise.age = 50; tomCruise.imageUrl = "https://pyxis.nymag.com/v1/imgs/4e5/1f7/a917c50e70a4c16bc35b9f0d8ce0352635-14-tom-cruise.rsquare.w700.jpg"; tomCruise.biographyUrl = "https://www.imdb.com/name/nm0000129"; movie->actors.push_back(tomCruise); auto valKilmer = Actor(); valKilmer.name = "Val Kilmer"; valKilmer.age = 46; valKilmer.imageUrl = "https://m.media-amazon.com/images/M/MV5BMTk3ODIzMDA5Ml5BMl5BanBnXkFtZTcwNDY0NTU4Ng@@._V1_UY317_CR4,0,214,317_AL_.jpg"; valKilmer.biographyUrl = "https://www.imdb.com/name/nm0000174"; movie->actors.push_back(valKilmer); auto timRobbins = Actor(); timRobbins.name = "Tim Robbins"; timRobbins.age = 55; timRobbins.imageUrl = "https://m.media-amazon.com/images/M/MV5BMTI1OTYxNzAxOF5BMl5BanBnXkFtZTYwNTE5ODI4._V1_UY317_CR16,0,214,317_AL_.jpg"; timRobbins.biographyUrl = "https://www.imdb.com/name/nm0000209"; movie->actors.push_back(timRobbins); auto jenniferConnelly = Actor(); jenniferConnelly.name = "Jennifer Connelly"; jenniferConnelly.age = 39; jenniferConnelly.imageUrl = "https://m.media-amazon.com/images/M/MV5BOTczNTgzODYyMF5BMl5BanBnXkFtZTcwNjk4ODk4Mw@@._V1_UY317_CR12,0,214,317_AL_.jpg"; jenniferConnelly.biographyUrl = "https://www.imdb.com/name/nm0000124"; movie->actors.push_back(jenniferConnelly); _movies.push_back(movie); } } //Returns list of movies std::vector<Movie *> getMovies() { return _movies; } }; } #endif /* MovieController_hpp */
40e039b7247ef6afdbc8a6dda9af0ebe4eb484bd
8a0bba7078a67642c86261e9eef5d58030c3df0a
/main.cpp
53d721ba0fe50fa4a826495bb6d304dbfda7c3a6
[]
no_license
cmazakas/Regulus
7a662ead7962af7a0303dcffdf7454061a071d1d
038f9895fb88bab671b8b1767df54614fe0f007a
refs/heads/master
2021-12-31T01:46:08.938323
2014-04-26T16:50:11
2014-04-26T16:50:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,416
cpp
main.cpp
/* Welcome to project Regulus! This is a poor man's version of Volker Springel's code Arepo and is quite the work in progress. But what is Arepo? Arepo is a physics simulator done using an unstructured mesh employing a Vornoi tessellation to solve flux equations. This is the ultimate goal of Regulus as well, only a free and open-source implementation which we all know means it's obviously a pale imitation. Contributors are always welcome, however. Or at least, I haven't been able to find a download link for Arepo... This is subject to change. As of now, the code is a Delaunay triangulator and, unfortunately, currently lacks the ability to receive user-defined point sets. Luckily, this is one of the areas of future development. For Regulus, I would currently love to add : 1. Voronoi Mesh Generation 2. User-defined Point Sets 3. Arbitrary Precision Support Also, there are various bug fixes and optimizations that still need to happen. Namely, when Regulus is run on more than one thread, the point set is split across buffers and the largest problem is that each individual mesh formed is disparate in the sense that they are not linked with each other. This is most likely to be the first bug fix to be addressed as it would be nice to have one giant mesh instead of four smaller ones. So for a complete mesh, run with "-np 1" only Things you will need to install Regulus : 1. Eigen 3.0 and higher 2. GMP 3. MPFR 4. C++11-compliant compiler I also have no idea if it'll Make on non-Unix based systems. But that's open-source for you, now isn't it? */ #include "structures.hpp" double get_wall_time(void); /* main loop */ int main(int argc, char **argv) { /* We choose to handle simple command line input */ int num_threads(0), box_length(0); try { if (argc == 5) { if (strcmp(argv[1], "-np") == 0 && strcmp(argv[3], "-bl") == 0) { sscanf(argv[2], "%d", &num_threads); sscanf(argv[4], "%d", &box_length); } else throw std::runtime_error("Incorrect arugments"); } else throw std::runtime_error("Incorrect number of arguments"); } catch(std::runtime_error &error) { std::cout << error.what() << std::endl; std::cout << "Use the form :: ./regulus -np X -bl Y \n"; return -1; } /* ... And we then build a point set to triangulate... */ unsigned long int num_points = std::pow(box_length, 3); std::vector<mesh> meshes; { std::vector<point> tmp_point_buff; tmp_point_buff.reserve(num_points); write_sorted_set(tmp_point_buff, num_points, box_length); auto m = num_points % num_threads; auto ppp = (num_points - m) / num_threads; for (int i = 0; i < num_threads; ++i) { unsigned long int num_per_tetra = 0; if (i != num_threads - 1) num_per_tetra = ppp; else num_per_tetra = ppp + m; meshes.emplace_back(num_per_tetra); /* Allocate root points */ auto tl = 3 * (box_length - 1); meshes[i].p_buffer.emplace_back(0, 0, 0); meshes[i].p_buffer.emplace_back(tl, 0, 0); meshes[i].p_buffer.emplace_back(0, tl, 0); meshes[i].p_buffer.emplace_back(0, 0, tl); meshes[i].p_position += 4; /* Allocate root tetrahedron */ new(meshes[i].t_position) tetra(&meshes[i].p_buffer[0], &meshes[i].p_buffer[1], &meshes[i].p_buffer[2], &meshes[i].p_buffer[3]); meshes[i].m_position = meshes[i].t_position; ++meshes[i].t_position; /* Copy partitioned points */ for (unsigned long int j = 0; j < num_per_tetra; ++j) { auto &cpy = tmp_point_buff[i*ppp + j]; meshes[i].p_buffer.emplace_back(cpy.x, cpy.y, cpy.z); } if (verbose >= 3) { std::cout << "\nthread : " << i << std::endl; for (auto it = meshes[i].p_buffer.begin(); it < meshes[i].p_buffer.end(); ++it) std::cout << *it << std::endl; } std::cout << std::endl; } } /* This is the crux of regulus We begin the triangulation */ double start_time = get_wall_time(); std::vector<std::thread> threads; for (int i = 0; i < num_threads; ++i) { threads.emplace_back([&meshes, i](void)->void { std::vector<std::pair<tetra*, unsigned int>> leaves; leaves.reserve(512); std::vector<tetra*> pile; pile.reserve(2048); point *p = meshes[i].p_buffer.data(); for (unsigned long int j = 5; j < meshes[i].p_buffer.size(); ++j) { if (verbose >= 1) std::cout << "\niterative index : " << j - 4 << std::endl; walk(leaves, p + j, meshes[i].m_position, &*(meshes[i].t_buffer.begin())); fracture(meshes[i], leaves, pile, p + j); delaunay(meshes[i], pile); leaves.clear(); pile.clear(); } }); } for (auto &t : threads) t.join(); unsigned long int tot_num_tetra = 0; for (auto &m : meshes) tot_num_tetra += m.num_tetra; double end_time = get_wall_time(); std::cout << "\nTotal number of tetrahedra triangulated : " << tot_num_tetra << std::endl; std::cout<< "\nTriangulated " << num_points << " points in " << end_time - start_time << " seconds" << std::endl; std::cout << num_points / ((end_time - start_time) * num_threads) << " points per second per thread" << std::endl; return 0; } /* Simple function found on the internet to return wall time (Unix only) */ double get_wall_time(void){ struct timeval time; if (gettimeofday(&time, nullptr)){ return 0; } return (double )time.tv_sec + (double )time.tv_usec * .000001; }
8e3a36466167469f3ead76d03cc72d8dc439efda
4593c780288a80a02d30df706a7326c380e5f7cf
/choirBoy.cpp
76a7a28f46f3f70d3b5ba35c6a082bd6e62d5d8e
[]
no_license
kcroo/ChurchOfTheDamned
e3f0527503ed45eaff4ead0ad85e54e5c3e4a442
eb355992ea91520606466cddf20b6f721d7c94e3
refs/heads/master
2020-06-19T21:07:12.893931
2020-01-03T01:35:20
2020-01-03T01:35:20
196,873,090
0
0
null
null
null
null
UTF-8
C++
false
false
1,801
cpp
choirBoy.cpp
/************************************************************************************************** Program Name: Final Project File: ChoirBoy.hpp Author: Kirsten Corrao Date: 03/14/2019 Description: this is the implementation file for ChoirBoy, which is a derived class of Character. ***************************************************************************************************/ #include "choirBoy.hpp" /********************************* constructor **************************************************** Uses the Character base class constructor to create a derived class object. Creates a weapon and armor in the Character's inventory and sets the Character's currentWeapon and currentArmor to them. ***************************************************************************************************/ ChoirBoy::ChoirBoy() : Character(5, "Zombie Choir Boy", "", 'Z', 12) // HP, type, name { inventory.add(std::make_unique<Treasure>("Satanic Hymnal", 2, 0, 0, 0, Type::weapon)); inventory.add(std::make_unique<Treasure>("Choir Robes", 0, 2, 0, 0, Type::armor)); currentWeapon = inventory.getTreasure(0); currentArmor = inventory.getTreasure(1); specialActions.push_back(std::make_unique<SpecialAction>(ActionType::attack, "Hymn of Beelzebub", "A disturbing hymn straight from hell causes 2-10 damage", 3, 2, 10, 0, 0, 0)); specialActions.push_back(std::make_unique<SpecialAction>(ActionType::attack, "Zombie Bite", "The Zombie child tears at the hero's flesh, causing 1-6 damage", 2, 1, 6, 0, 0, 0)); } /********************************* destructor ***************************************************** New inventory items deleted in Character destructor. ***************************************************************************************************/ ChoirBoy::~ChoirBoy() { }
4007f9e8782a11503c6d0fa51b4a34c05fff1c85
9628b555ffe0768020abcfbc3935005043601bc3
/Problem Solving/Diag-diff.cpp
07886054fdfa35b45d7253db536f806bcf3e02fb
[]
no_license
Dgeneration11/HackerRank
2e13ffd602467473252ca2b0868aaa4b729a3eca
3dd2fb35981079b7e6091dd0955a56746a67f4af
refs/heads/main
2023-09-06T04:53:34.278465
2021-10-31T06:45:38
2021-10-31T06:45:38
363,462,890
0
0
null
null
null
null
UTF-8
C++
false
false
526
cpp
Diag-diff.cpp
#include <bits/stdc++.h> using namespace std; int diagonalDifference(vector<vector<int>> a) { int d1 = 0, d2 = 0; int n = a.size() - 1; for (int i = 0; i < a.size(); i++) { d1 += a[i][i]; d2 += a[i][n - 1 - i]; } return abs(d1 - d2); } int main() { int n; cin>>n; vector<vector<int>> a(n); for(int i=0; i<n; i++){ for(int j=0; j<n; j++){ int x; cin>>x; a[i][j] = x; } } cout<<diagonalDifference(a); }
3984a2b9154a8267255eebd328bf923b92451f59
b476272aa4aac35df08d5eb8789170584bed1a3e
/src/tutorial.cxx
18b699eab3a790c970d4384f64c65287cdb06f65
[]
no_license
huangkenny/cmake_tutorial
4722380ff5646a2b4fe41a756294763e1044e1fe
89b2810c11bc9d5ce4499380279951ee4e8c3def
refs/heads/master
2020-07-23T21:09:48.247678
2016-08-26T21:09:47
2016-08-26T21:09:47
66,677,491
0
0
null
2016-09-26T16:23:40
2016-08-26T20:31:16
C++
UTF-8
C++
false
false
921
cxx
tutorial.cxx
// A simple program that computes the square root of a number #include <stdio.h> #include <stdlib.h> #include <math.h> #include "TutorialConfig.h" #ifdef USE_MYMATH #include "mymath.h" #endif int main (int argc, char *argv[]) { if (argc < 2) { fprintf(stdout, "%s Version %d.%d\n", argv[0], Tutorial_VERSION_MAJOR, Tutorial_VERSION_MINOR); fprintf(stdout,"Usage: %s number\n",argv[0]); return 1; } double inputValue = atof(argv[1]); #if defined (HAVE_LOG) && (HAVE_EXP) fprintf(stdout,"Using log and exp \n"); double outputValue = exp(log(inputValue)*0.5); #elif defined (USE_MYMATH) fprintf(stdout,"Using mysqrt\n"); double outputValue = mysqrt(inputValue); #else // fprintf(stdout,"Using sqrt\n"); double outputValue = sqrt(inputValue); #endif fprintf(stdout,"The square root of %g is %g\n", inputValue, outputValue); return 0; }
0e753aa5ffdca1371e531c6bdc86c382792e474f
f3eecbb3c325c808e26732ff362aabf808d6effb
/application_on_tr6/app_to_csv.cxx
cf8ce75a9a6a8fe65b16e2d18bd0be13a89834aa
[]
no_license
aman-upadhyay/FCP_ML
66117fee2940ef811b29457b006b617f67a13317
13ca6c3dd5c4f27d09e6d69be5c545b36e3c1cac
refs/heads/main
2023-02-01T09:12:37.483246
2020-12-18T11:03:46
2020-12-18T11:03:46
316,887,600
0
0
null
null
null
null
UTF-8
C++
false
false
14,424
cxx
app_to_csv.cxx
#include <iostream> #include <string> #include <fstream> #include <vector> #include <utility> // std::pair using namespace std; void write_csv(std::string filename, std::vector<std::pair<std::string, std::vector<int>>> dataset){ // Make a CSV file with one or more columns of integer values // Each column of data is represented by the pair <column name, column data> // as std::pair<std::string, std::vector<int>> // The dataset is represented as a vector of these columns // Note that all columns should be the same size // Create an output filestream object std::ofstream myFile(filename); // Send column names to the stream for(int j = 0; j < dataset.size(); ++j) { myFile << dataset.at(j).first; if(j != dataset.size() - 1) myFile << ","; // No comma at end of line } myFile << "\n"; // Send data to the stream for(int i = 0; i < dataset.at(0).second.size(); ++i) { for(int j = 0; j < dataset.size(); ++j) { myFile << dataset.at(j).second.at(i); if(j != dataset.size() - 1) myFile << ","; // No comma at end of line } myFile << "\n"; } // Close the file myFile.close(); } void app_to_csv(const char *fname="dataset/weights/lips_bdt_DNN.weights.xml"){ //load this function in root double h; //variable for soring response value, should be double float x[16]; // array to store value from application file double dummy[16]; int pid; std::vector<int> vec1; // label i.e if fcp then charge of the fcp or else gamma or muon std::vector<int> vec2; // result from prediction std::vector<int> vec3; // true label TMVA::Reader *reader = new TMVA::Reader("!Color:!Silent"); reader->AddVariable("Edep1",&x[1]); reader->AddVariable("Edep2",&x[2]); reader->AddVariable("Edep3",&x[3]); reader->AddVariable("Edep4",&x[4]); reader->AddVariable("Edep5",&x[5]); reader->AddVariable("Edep6",&x[6]); reader->AddVariable("Edep7",&x[7]); reader->AddVariable("Edep8",&x[8]); reader->AddVariable("Edep9",&x[9]); reader->AddVariable("Edep10",&x[10]); reader->AddVariable("Edep11",&x[11]); reader->AddVariable("Edep12",&x[12]); reader->AddVariable("Edep13",&x[13]); reader->AddVariable("Edep14",&x[14]); reader->AddVariable("Edep15",&x[15]); reader->BookMVA("DNN",fname); TFile fs("CDMSlite_LIP.root"); TTree *ts = (TTree*)fs.Get("tr1"); ts->SetBranchAddress("PID",&pid); ts->SetBranchAddress("Edep1",&dummy[1]); ts->SetBranchAddress("Edep2",&dummy[2]); ts->SetBranchAddress("Edep3",&dummy[3]); ts->SetBranchAddress("Edep4",&dummy[4]); ts->SetBranchAddress("Edep5",&dummy[5]); ts->SetBranchAddress("Edep6",&dummy[6]); ts->SetBranchAddress("Edep7",&dummy[7]); ts->SetBranchAddress("Edep8",&dummy[8]); ts->SetBranchAddress("Edep9",&dummy[9]); ts->SetBranchAddress("Edep10",&dummy[10]); ts->SetBranchAddress("Edep11",&dummy[11]); ts->SetBranchAddress("Edep12",&dummy[12]); ts->SetBranchAddress("Edep13",&dummy[13]); ts->SetBranchAddress("Edep14",&dummy[14]); ts->SetBranchAddress("Edep15",&dummy[15]); int nent = ts->GetEntries(); for(int e=0; e<nent; e++){ ts->GetEntry(e); if(pid==22||pid==-13){ if(dummy[1]>=0.001){x[1]=dummy[1];} else{x[1]=0;} if(dummy[2]>=0.001){x[2]=dummy[2];} else{x[2]=0;} if(dummy[3]>=0.001){x[3]=dummy[3];} else{x[3]=0;} if(dummy[4]>=0.001){x[4]=dummy[4];} else{x[4]=0;} if(dummy[5]>=0.001){x[5]=dummy[5];} else{x[5]=0;} if(dummy[6]>=0.001){x[6]=dummy[6];} else{x[6]=0;} if(dummy[7]>=0.001){x[7]=dummy[7];} else{x[7]=0;} if(dummy[8]>=0.001){x[8]=dummy[8];} else{x[8]=0;} if(dummy[9]>=0.001){x[9]=dummy[9];} else{x[9]=0;} if(dummy[10]>=0.001){x[10]=dummy[10];} else{x[10]=0;} if(dummy[11]>=0.001){x[11]=dummy[11];} else{x[11]=0;} if(dummy[12]>=0.001){x[12]=dummy[12];} else{x[12]=0;} if(dummy[13]>=0.001){x[13]=dummy[13];} else{x[13]=0;} if(dummy[14]>=0.0001){x[14]=dummy[14];} else{x[14]=0;} if(dummy[15]>=0.001){x[15]=dummy[15];} else{x[15]=0;} h=reader->EvaluateMVA("DNN"); if(h>=0.19){ vec1.push_back(pid); vec2.push_back(1); vec3.push_back(0);} else{ vec1.push_back(pid); vec2.push_back(0); vec3.push_back(0); } } } TFile fs2("CDMSlite_LIP_2.root"); TTree *ts2 = (TTree*)fs2.Get("tr1"); ts2->SetBranchAddress("PID",&pid); ts2->SetBranchAddress("Edep1",&dummy[1]); ts2->SetBranchAddress("Edep2",&dummy[2]); ts2->SetBranchAddress("Edep3",&dummy[3]); ts2->SetBranchAddress("Edep4",&dummy[4]); ts2->SetBranchAddress("Edep5",&dummy[5]); ts2->SetBranchAddress("Edep6",&dummy[6]); ts2->SetBranchAddress("Edep7",&dummy[7]); ts2->SetBranchAddress("Edep8",&dummy[8]); ts2->SetBranchAddress("Edep9",&dummy[9]); ts2->SetBranchAddress("Edep10",&dummy[10]); ts2->SetBranchAddress("Edep11",&dummy[11]); ts2->SetBranchAddress("Edep12",&dummy[12]); ts2->SetBranchAddress("Edep13",&dummy[13]); ts2->SetBranchAddress("Edep14",&dummy[14]); ts2->SetBranchAddress("Edep15",&dummy[15]); int nent2 = ts2->GetEntries(); for(int e=0; e<nent2; e++){ ts2->GetEntry(e); if(pid==-90){ if(dummy[1]>=0.001){x[1]=dummy[1];} else{x[1]=0;} if(dummy[2]>=0.001){x[2]=dummy[2];} else{x[2]=0;} if(dummy[3]>=0.001){x[3]=dummy[3];} else{x[3]=0;} if(dummy[4]>=0.001){x[4]=dummy[4];} else{x[4]=0;} if(dummy[5]>=0.001){x[5]=dummy[5];} else{x[5]=0;} if(dummy[6]>=0.001){x[6]=dummy[6];} else{x[6]=0;} if(dummy[7]>=0.001){x[7]=dummy[7];} else{x[7]=0;} if(dummy[8]>=0.001){x[8]=dummy[8];} else{x[8]=0;} if(dummy[9]>=0.001){x[9]=dummy[9];} else{x[9]=0;} if(dummy[10]>=0.001){x[10]=dummy[10];} else{x[10]=0;} if(dummy[11]>=0.001){x[11]=dummy[11];} else{x[11]=0;} if(dummy[12]>=0.001){x[12]=dummy[12];} else{x[12]=0;} if(dummy[13]>=0.001){x[13]=dummy[13];} else{x[13]=0;} if(dummy[14]>=0.0001){x[14]=dummy[14];} else{x[14]=0;} if(dummy[15]>=0.001){x[15]=dummy[15];} else{x[15]=0;} h=reader->EvaluateMVA("DNN"); if(h>=0.19){ vec1.push_back(2); vec2.push_back(1); vec3.push_back(1);} else{ vec1.push_back(2); vec2.push_back(0); vec3.push_back(1); } } } TFile fs5("CDMSlite_LIP_5.root"); TTree *ts5 = (TTree*)fs5.Get("tr1"); ts5->SetBranchAddress("PID",&pid); ts5->SetBranchAddress("Edep1",&dummy[1]); ts5->SetBranchAddress("Edep2",&dummy[2]); ts5->SetBranchAddress("Edep3",&dummy[3]); ts5->SetBranchAddress("Edep4",&dummy[4]); ts5->SetBranchAddress("Edep5",&dummy[5]); ts5->SetBranchAddress("Edep6",&dummy[6]); ts5->SetBranchAddress("Edep7",&dummy[7]); ts5->SetBranchAddress("Edep8",&dummy[8]); ts5->SetBranchAddress("Edep9",&dummy[9]); ts5->SetBranchAddress("Edep10",&dummy[10]); ts5->SetBranchAddress("Edep11",&dummy[11]); ts5->SetBranchAddress("Edep12",&dummy[12]); ts5->SetBranchAddress("Edep13",&dummy[13]); ts5->SetBranchAddress("Edep14",&dummy[14]); ts5->SetBranchAddress("Edep15",&dummy[15]); int nent5 = ts5->GetEntries(); for(int e=0; e<nent5; e++){ ts5->GetEntry(e); if(pid==-90){ if(dummy[1]>=0.001){x[1]=dummy[1];} else{x[1]=0;} if(dummy[2]>=0.001){x[2]=dummy[2];} else{x[2]=0;} if(dummy[3]>=0.001){x[3]=dummy[3];} else{x[3]=0;} if(dummy[4]>=0.001){x[4]=dummy[4];} else{x[4]=0;} if(dummy[5]>=0.001){x[5]=dummy[5];} else{x[5]=0;} if(dummy[6]>=0.001){x[6]=dummy[6];} else{x[6]=0;} if(dummy[7]>=0.001){x[7]=dummy[7];} else{x[7]=0;} if(dummy[8]>=0.001){x[8]=dummy[8];} else{x[8]=0;} if(dummy[9]>=0.001){x[9]=dummy[9];} else{x[9]=0;} if(dummy[10]>=0.001){x[10]=dummy[10];} else{x[10]=0;} if(dummy[11]>=0.001){x[11]=dummy[11];} else{x[11]=0;} if(dummy[12]>=0.001){x[12]=dummy[12];} else{x[12]=0;} if(dummy[13]>=0.001){x[13]=dummy[13];} else{x[13]=0;} if(dummy[14]>=0.0001){x[14]=dummy[14];} else{x[14]=0;} if(dummy[15]>=0.001){x[15]=dummy[15];} else{x[15]=0;} h=reader->EvaluateMVA("DNN"); if(h>=0.19){ vec1.push_back(5); vec2.push_back(1); vec3.push_back(1);} else{ vec1.push_back(5); vec2.push_back(0); vec3.push_back(1); } } } TFile fs10("CDMSlite_LIP_10.root"); TTree *ts10 = (TTree*)fs10.Get("tr1"); ts10->SetBranchAddress("PID",&pid); ts10->SetBranchAddress("Edep1",&dummy[1]); ts10->SetBranchAddress("Edep2",&dummy[2]); ts10->SetBranchAddress("Edep3",&dummy[3]); ts10->SetBranchAddress("Edep4",&dummy[4]); ts10->SetBranchAddress("Edep5",&dummy[5]); ts10->SetBranchAddress("Edep6",&dummy[6]); ts10->SetBranchAddress("Edep7",&dummy[7]); ts10->SetBranchAddress("Edep8",&dummy[8]); ts10->SetBranchAddress("Edep9",&dummy[9]); ts10->SetBranchAddress("Edep10",&dummy[10]); ts10->SetBranchAddress("Edep11",&dummy[11]); ts10->SetBranchAddress("Edep12",&dummy[12]); ts10->SetBranchAddress("Edep13",&dummy[13]); ts10->SetBranchAddress("Edep14",&dummy[14]); ts10->SetBranchAddress("Edep15",&dummy[15]); int nent10 = ts10->GetEntries(); for(int e=0; e<nent10; e++){ ts10->GetEntry(e); if(pid==-90){ if(dummy[1]>=0.001){x[1]=dummy[1];} else{x[1]=0;} if(dummy[2]>=0.001){x[2]=dummy[2];} else{x[2]=0;} if(dummy[3]>=0.001){x[3]=dummy[3];} else{x[3]=0;} if(dummy[4]>=0.001){x[4]=dummy[4];} else{x[4]=0;} if(dummy[5]>=0.001){x[5]=dummy[5];} else{x[5]=0;} if(dummy[6]>=0.001){x[6]=dummy[6];} else{x[6]=0;} if(dummy[7]>=0.001){x[7]=dummy[7];} else{x[7]=0;} if(dummy[8]>=0.001){x[8]=dummy[8];} else{x[8]=0;} if(dummy[9]>=0.001){x[9]=dummy[9];} else{x[9]=0;} if(dummy[10]>=0.001){x[10]=dummy[10];} else{x[10]=0;} if(dummy[11]>=0.001){x[11]=dummy[11];} else{x[11]=0;} if(dummy[12]>=0.001){x[12]=dummy[12];} else{x[12]=0;} if(dummy[13]>=0.001){x[13]=dummy[13];} else{x[13]=0;} if(dummy[14]>=0.0001){x[14]=dummy[14];} else{x[14]=0;} if(dummy[15]>=0.001){x[15]=dummy[15];} else{x[15]=0;} h=reader->EvaluateMVA("DNN"); if(h>=0.19){ vec1.push_back(10); vec2.push_back(1); vec3.push_back(1);} else{ vec1.push_back(10); vec2.push_back(0); vec3.push_back(1); } } } TFile fs100("CDMSlite_LIP_100.root"); TTree *ts100 = (TTree*)fs100.Get("tr1"); ts100->SetBranchAddress("PID",&pid); ts100->SetBranchAddress("Edep1",&dummy[1]); ts100->SetBranchAddress("Edep2",&dummy[2]); ts100->SetBranchAddress("Edep3",&dummy[3]); ts100->SetBranchAddress("Edep4",&dummy[4]); ts100->SetBranchAddress("Edep5",&dummy[5]); ts100->SetBranchAddress("Edep6",&dummy[6]); ts100->SetBranchAddress("Edep7",&dummy[7]); ts100->SetBranchAddress("Edep8",&dummy[8]); ts100->SetBranchAddress("Edep9",&dummy[9]); ts100->SetBranchAddress("Edep10",&dummy[10]); ts100->SetBranchAddress("Edep11",&dummy[11]); ts100->SetBranchAddress("Edep12",&dummy[12]); ts100->SetBranchAddress("Edep13",&dummy[13]); ts100->SetBranchAddress("Edep14",&dummy[14]); ts100->SetBranchAddress("Edep15",&dummy[15]); int nent100 = ts100->GetEntries(); for(int e=0; e<nent100; e++){ ts100->GetEntry(e); if(pid==-90){ if(dummy[1]>=0.001){x[1]=dummy[1];} else{x[1]=0;} if(dummy[2]>=0.001){x[2]=dummy[2];} else{x[2]=0;} if(dummy[3]>=0.001){x[3]=dummy[3];} else{x[3]=0;} if(dummy[4]>=0.001){x[4]=dummy[4];} else{x[4]=0;} if(dummy[5]>=0.001){x[5]=dummy[5];} else{x[5]=0;} if(dummy[6]>=0.001){x[6]=dummy[6];} else{x[6]=0;} if(dummy[7]>=0.001){x[7]=dummy[7];} else{x[7]=0;} if(dummy[8]>=0.001){x[8]=dummy[8];} else{x[8]=0;} if(dummy[9]>=0.001){x[9]=dummy[9];} else{x[9]=0;} if(dummy[10]>=0.001){x[10]=dummy[10];} else{x[10]=0;} if(dummy[11]>=0.001){x[11]=dummy[11];} else{x[11]=0;} if(dummy[12]>=0.001){x[12]=dummy[12];} else{x[12]=0;} if(dummy[13]>=0.001){x[13]=dummy[13];} else{x[13]=0;} if(dummy[14]>=0.0001){x[14]=dummy[14];} else{x[14]=0;} if(dummy[15]>=0.001){x[15]=dummy[15];} else{x[15]=0;} h=reader->EvaluateMVA("DNN"); if(h>=0.19){ vec1.push_back(100); vec2.push_back(1); vec3.push_back(1);} else{ vec1.push_back(100); vec2.push_back(0); vec3.push_back(1); } } } TFile fs1000("CDMSlite_LIP_1000.root"); TTree *ts1000 = (TTree*)fs1000.Get("tr1"); ts1000->SetBranchAddress("PID",&pid); ts1000->SetBranchAddress("Edep1",&dummy[1]); ts1000->SetBranchAddress("Edep2",&dummy[2]); ts1000->SetBranchAddress("Edep3",&dummy[3]); ts1000->SetBranchAddress("Edep4",&dummy[4]); ts1000->SetBranchAddress("Edep5",&dummy[5]); ts1000->SetBranchAddress("Edep6",&dummy[6]); ts1000->SetBranchAddress("Edep7",&dummy[7]); ts1000->SetBranchAddress("Edep8",&dummy[8]); ts1000->SetBranchAddress("Edep9",&dummy[9]); ts1000->SetBranchAddress("Edep10",&dummy[10]); ts1000->SetBranchAddress("Edep11",&dummy[11]); ts1000->SetBranchAddress("Edep12",&dummy[12]); ts1000->SetBranchAddress("Edep13",&dummy[13]); ts1000->SetBranchAddress("Edep14",&dummy[14]); ts1000->SetBranchAddress("Edep15",&dummy[15]); int nent1000 = ts1000->GetEntries(); for(int e=0; e<nent1000; e++){ ts1000->GetEntry(e); if(pid==-90){ if(dummy[1]>=0.001){x[1]=dummy[1];} else{x[1]=0;} if(dummy[2]>=0.001){x[2]=dummy[2];} else{x[2]=0;} if(dummy[3]>=0.001){x[3]=dummy[3];} else{x[3]=0;} if(dummy[4]>=0.001){x[4]=dummy[4];} else{x[4]=0;} if(dummy[5]>=0.001){x[5]=dummy[5];} else{x[5]=0;} if(dummy[6]>=0.001){x[6]=dummy[6];} else{x[6]=0;} if(dummy[7]>=0.001){x[7]=dummy[7];} else{x[7]=0;} if(dummy[8]>=0.001){x[8]=dummy[8];} else{x[8]=0;} if(dummy[9]>=0.001){x[9]=dummy[9];} else{x[9]=0;} if(dummy[10]>=0.001){x[10]=dummy[10];} else{x[10]=0;} if(dummy[11]>=0.001){x[11]=dummy[11];} else{x[11]=0;} if(dummy[12]>=0.001){x[12]=dummy[12];} else{x[12]=0;} if(dummy[13]>=0.001){x[13]=dummy[13];} else{x[13]=0;} if(dummy[14]>=0.0001){x[14]=dummy[14];} else{x[14]=0;} if(dummy[15]>=0.001){x[15]=dummy[15];} else{x[15]=0;} h=reader->EvaluateMVA("DNN"); if(h>=0.19){ vec1.push_back(1000); vec2.push_back(1); vec3.push_back(1);} else{ vec1.push_back(1000); vec2.push_back(0); vec3.push_back(1); } } } std::vector<std::pair<std::string, std::vector<int>>> vals = {{"Label", vec1}, {"Prediction", vec2}, {"True_label", vec3}}; // Write the vector to CSV write_csv("predicted_dataset.csv", vals); }
b5c1858253845fcf5851d9239bb5f9eee1006c37
6f20de1882b7cd088989851b27f8a5f805bbadd3
/example-BoneControl/src/ofApp.cpp
1f12539c24ac2456b5c21d1feac1cb5087d8e5ba
[ "MIT" ]
permissive
mgs/ofxFBX
c45e492be5f1b5e4268864f57765764fa8a204c3
5dc32c68fdc05452027c054000025d2cd56792b6
refs/heads/master
2022-04-05T23:07:08.803098
2020-02-21T21:20:09
2020-02-21T21:20:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,446
cpp
ofApp.cpp
#include "ofApp.h" //-------------------------------------------------------------- void ofApp::setup(){ ofDisableArbTex(); ofSetBackgroundColor(220); // uncomment this to convert scene to meters // //ofxFBXSource::Scene::FbxUnits = FbxSystemUnit::m; ofxFBXSource::Scene::Settings settings; settings.importAnimations = false; settings.filePath = "astroBoy_walk.fbx"; // settings.useKeyFrames = false; settings.printInfo = true; ofSetLogLevel(OF_LOG_VERBOSE); if(fbx.load(settings)){ cout << "ofApp :: loaded the scene OK" << endl; }else{ cout << "ofApp :: Error loading the scene" << endl; } cam.lookAt(ofVec3f(0, 0, 0)); cam.setDistance(20); cam.setFarClip(100); cam.setNearClip(.5f); #ifdef TARGET_OPENGLES cam.disableMouseInput(); #endif fbx.setAnimation(0); fbx.setPosition(0, -7, 0); //cout << fbx.getSkeletonInfo() << endl; bRenderNormals = false; bRenderMeshes = true; bDrawBones = false; } //-------------------------------------------------------------- void ofApp::update(){ light.setPosition(cos(ofGetElapsedTimef() * 2.) * 7, 4 + sin(ofGetElapsedTimef()) * 2.5, 10); ofVec3f target(ofMap(ofGetMouseX(), 0, ofGetWidth(), -10, 10, true), fbx.getPosition().y, fbx.getPosition().z + 10); fbx.lookAt(target); fbx.panDeg(180); fbx.getCurrentAnimation().setSpeed(ofMap(ofGetMouseY(), 100, ofGetHeight() - 100, 0.5, 2.5, true)); // fbx.update(); #ifndef TARGET_OPENGLES // change colors of the materials // for(int i = 0; i < fbx.getNumMeshes(); i++){ // cout << i << " - " << fbx.getMeshes()[i]->getName() << " num materials: " << fbx.getMeshes()[i]->getNumMaterials() << endl; if(fbx.getMeshes()[i] -> getNumMaterials() > 2){ auto mat = fbx.getMeshes()[i] -> getMaterials()[2]; mat->setDiffuseColor(ofFloatColor(sin(ofGetElapsedTimef() *4.) *0.5 + 0.5, 1, 1, 1)); mat->disableTextures(); } } #endif // moves the bones into place based on the animation // fbx.earlyUpdate(); // perform any bone manipulation here // shared_ptr <ofxFBXBone> bone = fbx.getBone("head"); if(bone){ bone->pointTo(light.getPosition(), ofVec3f(-1, 0, 0)); } // manipulates the mesh around the positioned bones // fbx.lateUpdate(); } //-------------------------------------------------------------- void ofApp::draw(){ ofSetColor(255, 255, 255); ofEnableDepthTest(); cam.begin(); { ofEnableLighting(); light.enable(); if(bRenderMeshes){ ofSetColor(255, 255, 255); fbx.draw(); } light.disable(); ofDisableLighting(); if(bDrawBones){ fbx.drawSkeletons(0.5); } if(bRenderNormals){ ofSetColor(255, 0, 255); fbx.drawMeshNormals(0.5, false); } ofNoFill(); ofSetColor(50, 50, 50); ofDrawBox(0, 0, 0, 14); ofFill(); ofSetColor(light.getDiffuseColor()); ofDrawSphere(light.getPosition(), 1); } cam.end(); ofDisableDepthTest(); int numBones = fbx.getNumBones(); ofSetColor(60, 60, 60); stringstream ds; ds << "Render normals (n): " << bRenderNormals << endl; ds << "Render meshes (m): " << bRenderMeshes << endl; ds << "Render " << numBones << " bones (b): " << bDrawBones << endl; if(fbx.areAnimationsEnabled()){ ds << "Toggle play/pause (spacebar): playing: " << fbx.getCurrentAnimation().isPlaying() << endl; ds << "Previous/Next animation (up/down): " << fbx.getCurrentAnimation().name << endl; } ds << "Scale is " << fbx.getScale() << endl; if(fbx.getNumPoses() > 0){ ds << "Pose: " << fbx.getCurrentPose()->getName() << " num poses: " << fbx.getNumPoses() << " enabled (p): " << fbx.arePosesEnabled() << endl; } ofDrawBitmapString(ds.str(), 50, 30); for(int i = 0; i < fbx.getNumAnimations(); i ++){ stringstream ss; ofxFBXAnimation & anim = fbx.getAnimation(i); if(i == fbx.getCurrentAnimationIndex()){ ss << "- "; } ss << "name: " << anim.name << " " << ofToString(anim.getPositionSeconds(), 3) << " | " << ofToString(anim.getDurationSeconds(), 3) << " frame: " << anim.getFrameNum() << " / " << anim.getTotalNumFrames() << endl; ofDrawBitmapString(ss.str(), 50, i * 30 + 450); } } #ifdef TARGET_OPENGLES //-------------------------------------------------------------- void ofApp::touchDown(ofTouchEventArgs & touch){ } //-------------------------------------------------------------- void ofApp::touchMoved(ofTouchEventArgs & touch){ } //-------------------------------------------------------------- void ofApp::touchUp(ofTouchEventArgs & touch){ } //-------------------------------------------------------------- void ofApp::touchDoubleTap(ofTouchEventArgs & touch){ if(bRenderMeshes){ bRenderMeshes = false; bDrawBones = true; }else{ bRenderMeshes = true; bDrawBones = false; } } //-------------------------------------------------------------- void ofApp::touchCancelled(ofTouchEventArgs & touch){ } #else //-------------------------------------------------------------- void ofApp::keyPressed(int key){ if(fbx.getNumAnimations() > 1){ if(key == OF_KEY_DOWN){ int newAnimIndex = fbx.getCurrentAnimationIndex() + 1; if(newAnimIndex > fbx.getNumAnimations() - 1){ newAnimIndex = 0; } fbx.setAnimation(newAnimIndex); } if(key == OF_KEY_UP){ int newAnimIndex = fbx.getCurrentAnimationIndex() - 1; if(newAnimIndex < 0){ newAnimIndex = fbx.getNumAnimations() - 1; } fbx.setAnimation(newAnimIndex); } } } //-------------------------------------------------------------- void ofApp::keyReleased(int key){ if(key == ' '){ fbx.getCurrentAnimation().togglePlayPause(); } if(key == 'n'){ bRenderNormals = !bRenderNormals; } if(key == 'm'){ bRenderMeshes = !bRenderMeshes; } if(key == 'b'){ bDrawBones = !bDrawBones; } } //-------------------------------------------------------------- void ofApp::mouseMoved(int x, int y){ } //-------------------------------------------------------------- void ofApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void ofApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void ofApp::dragEvent(ofDragInfo dragInfo){ } #endif
d9b9dbfcdaef37e0219645c87985853d56a82d4e
dbd9f69455082b9d6fc06ed72aa162b34dfdb618
/src/conflux/lu/layout.cpp
e97677829f875b336463639096dc95571c964833
[ "BSD-3-Clause" ]
permissive
kadircs/conflux
b2170c046e71519ba895349949d7f9e89cacdf29
0af54c50777ab738ca7d36376f06a609ccac50f5
refs/heads/master
2023-06-30T07:02:33.872339
2021-07-21T23:59:43
2021-07-21T23:59:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,017
cpp
layout.cpp
#include <conflux/lu/layout.hpp> #include <complex> #include <string> // helper functions int X2p(MPI_Comm comm3D, int pi, int pj, int pk) { int coords[] = {pi, pj, pk}; int rank; MPI_Cart_rank(comm3D, coords, &rank); return rank; } int X2p(MPI_Comm comm2D, int pi, int pj) { int coords[] = {pi, pj}; int rank; MPI_Cart_rank(comm2D, coords, &rank); return rank; } std::vector<int> line_split(int N, int v) { std::vector<int> splits; splits.reserve(N/v + 1); for (int i = 0; i < N/v; ++i) { splits.push_back(i * v); } splits.push_back(N); return splits; } template <typename T> costa::grid_layout<T> conflux::conflux_layout(T* data, int M, int N, int v, char ordering, int Px, int Py, int rank) { ordering = std::toupper(ordering); assert(ordering == 'R' || ordering == 'C'); int Nt = (int)(std::ceil((double)N / v)); int Mt = (int)(std::ceil((double)M / v)); int t = (int)(std::ceil((double)Nt / Py)) + 1ll; int tA11x = (int)(std::ceil((double)Mt / Px)); int tA11y = (int)(std::ceil((double)Nt / Py)); int Ml = tA11x * v; int Nl = tA11y * v; int lld = ordering == 'R' ? Nl : Ml; auto matrix = costa::block_cyclic_layout(M, N, v, v, 1, 1, M, N, Px, Py, 'R', 0, 0, data, lld, ordering, rank); return matrix; } template <typename T> costa::grid_layout<T> conflux::conflux_layout(T* data, int M, int N, int v, char ordering, MPI_Comm lu_comm) { ordering = std::toupper(ordering); assert(ordering == 'R' || ordering == 'C'); int dims[3]; int periods[3]; int coords[3]; MPI_Cart_get(lu_comm, 3, dims, periods, coords); int rank; MPI_Comm_rank(lu_comm, &rank); int pi = coords[0]; int pj = coords[1]; int pk = coords[2]; int Px = dims[0]; int Py = dims[1]; int Nt = (int)(std::ceil((double)N / v)); int Mt = (int)(std::ceil((double)M / v)); int t = (int)(std::ceil((double)Nt / Py)) + 1ll; int tA11x = (int)(std::ceil((double)Mt / Px)); int tA11y = (int)(std::ceil((double)Nt / Py)); int Ml = tA11x * v; int Nl = tA11y * v; // local blocks std::vector<costa::block_t> local_blocks; int n_local_blocks = tA11x * tA11y; local_blocks.reserve(n_local_blocks); for (int lti = 0; lti < tA11x; ++lti) { auto gti = lti * Px + pi; for (int ltj = 0; ltj < tA11y; ++ltj) { auto gtj = ltj * Py + pj; costa::block_t block; // pointer to the data of this tile block.data = &data[lti * v * Nl + ltj * v]; // leading dimension block.ld = ordering=='R' ? Nl : Ml; // global coordinates of this block block.row = gti; block.col = gtj; local_blocks.push_back(block); } } std::vector<int> row_splits = line_split(M, v); std::vector<int> col_splits = line_split(N, v); std::vector<int> owners(Mt*Nt); for (int i = 0; i < Mt; ++i) { for (int j = 0; j < Nt; ++j) { int ij = i * Nt + j; int pi = i % Px; int pj = j % Py; owners[ij] = X2p(lu_comm, pi, pj, 0); } } auto matrix = costa::custom_layout<T>( Mt, Nt, // num of global blocks &row_splits[0], &col_splits[0], // splits in the global matrix &owners[0], // ranks owning each tile n_local_blocks, // num of local blocks &local_blocks[0], // local blocks ordering // row-major ordering within blocks ); return matrix; } // template instantiation for conflux_layout template costa::grid_layout<double> conflux::conflux_layout( double* data, int M, int N, int v, char ordering, MPI_Comm lu_comm); template costa::grid_layout<float> conflux::conflux_layout( float* data, int M, int N, int v, char ordering, MPI_Comm lu_comm); template costa::grid_layout<std::complex<float>> conflux::conflux_layout( std::complex<float>* data, int M, int N, int v, char ordering, MPI_Comm lu_comm); template costa::grid_layout<std::complex<double>> conflux::conflux_layout( std::complex<double>* data, int M, int N, int v, char ordering, MPI_Comm lu_comm); // template instantiation for conflux_layout template costa::grid_layout<double> conflux::conflux_layout( double* data, int M, int N, int v, char ordering, int Px, int Py, int rank); template costa::grid_layout<float> conflux::conflux_layout( float* data, int M, int N, int v, char ordering, int Px, int Py, int rank); template costa::grid_layout<std::complex<float>> conflux::conflux_layout( std::complex<float>* data, int M, int N, int v, char ordering, int Px, int Py, int rank); template costa::grid_layout<std::complex<double>> conflux::conflux_layout( std::complex<double>* data, int M, int N, int v, char ordering, int Px, int Py, int rank);
0f23e5ee66bb185f03eecb17ac1fa113d13b3d5c
d3bc4da66fcf059cbd3d05c2817f6d94bc0cf9d4
/AllClassSplit/Box2dDemo/Sprite.h
a0a0b3689b69be550f9c796c197d82aab32e92f4
[]
no_license
stanimir/ABirds
9535d8aaa56fc8ddb6939d9d635d4998eedf40c1
b0ec8a06246286617769184ead41fa0d9656d798
refs/heads/master
2023-06-25T01:43:31.294793
2023-06-18T15:18:49
2023-06-18T15:37:48
107,548,727
0
1
null
2023-06-18T15:37:49
2017-10-19T13:18:06
C
UTF-8
C++
false
false
386
h
Sprite.h
#pragma once #include "SDL.h" #include "SDL_image.h" #include "Box2D\Box2D.h" #include <iostream> class Sprite { public: Sprite(SDL_Renderer* passed_renderer, std::string FilePath, int x, int y, int w, int h); ~Sprite(void); void Draw(); void Draw(b2Vec2 newPos); void Draw(b2Vec2 newPos, float angle); private: SDL_Texture* image; SDL_Rect rect; SDL_Renderer* renderer; };
f799a8561865b3de96640b8ac17b510674f9b16e
0eacbbafe4cc2466419a458547842aab7d34df89
/src/d2/Rectangle.cpp
0ee8c9b5c31caae5b3d3f841fa646d78fb9502ce
[ "MIT" ]
permissive
pcbaecker/ananasgfx
ff7b9e58dec37683310ac4ff440fd3225158f05a
0637554bf82b990713314a24e4a6ead299be949a
refs/heads/master
2020-04-18T07:49:35.027451
2019-03-26T06:41:25
2019-03-26T06:41:25
167,373,747
1
0
null
null
null
null
UTF-8
C++
false
false
1,034
cpp
Rectangle.cpp
#include <ananasgfx/d2/Rectangle.hpp> #include <ananasgfx/gfx/Window.hpp> namespace d2 { gfx::Shader *Rectangle::shader() noexcept { return this->pWindow->getRenderer()->getShader(gfx::ShaderType::SimpleColor); } void Rectangle::updateIndices() noexcept { this->mVertices.setNumberOfIndices(6); this->mVertices.setIndices(0, 0, 1, 2); this->mVertices.setIndices(1, 2, 3, 0); } void Rectangle::updateVertices() noexcept { this->mVertices.setSize(4); auto& position = this->mVertices.createBuffer(gfx::VertexType::Position, 3, 0); // Upper left position.set(0, -this->mAnchorPoint.x, -this->mAnchorPoint.y, 0.0f); // Upper right position.set(1, 1.0f - this->mAnchorPoint.x, -this->mAnchorPoint.y, 0.0f); // Lower right position.set(2, 1.0f - this->mAnchorPoint.x, 1.0f - this->mAnchorPoint.y, 0.0f); // Lower left position.set(3, -this->mAnchorPoint.x, 1.0f - this->mAnchorPoint.y, 0.0f); } }
13e4725cbaabf4e470243d6237c3c55638ba437e
8378b49fa0a5e5ad53d9932e4c5282c602bd8e91
/MapTool/MapTool/main.h
9ee8f0d8b395c6989045956285ad3a958458b4b0
[]
no_license
vNutElma/MapTool
aa7ec1da2d283baeefddc8e5fcd64b87c00a61d1
7a22116afc3a777ff0756234ddf0584bf68cd491
refs/heads/master
2021-07-08T06:23:50.760685
2017-10-08T09:22:05
2017-10-08T09:22:05
null
0
0
null
null
null
null
UHC
C++
false
false
2,830
h
main.h
#pragma once #include <dxgi.h> #include <d3d11.h> #include <d3dcompiler.h> #include <DirectXMath.h> #include <vector> #include <fstream> #include <windowsx.h> #include <DirectXCollision.h> #include "DirectXTex.h" #include "camera.h" #pragma comment(lib,"dxguid.lib") #pragma comment(lib,"d3dcompiler.lib") #pragma comment(lib,"dxgi.lib") #pragma comment(lib,"d3d11.lib") using namespace DirectX; HWND g_hWnd = NULL; IDXGISwapChain* g_pSwapChain = NULL; ID3D11Device* g_pd3dDevice = NULL; ID3D11DeviceContext* g_pImmediateContext = NULL; ID3D11RenderTargetView* g_pRenderTargetView = NULL; ID3D11VertexShader* g_pVertexShader = NULL; ID3D11InputLayout* g_pVertexLayout = NULL; ID3D11Buffer* g_pVertexBuffer = NULL; ID3D11PixelShader* g_pPixelShader = NULL; ID3D11PixelShader* g_pPixedPixelShader = NULL; ID3D11Buffer* g_pIndexBuffer = NULL; D3D_FEATURE_LEVEL g_featureLevel = D3D_FEATURE_LEVEL_11_0; XMMATRIX g_World; ID3D11Buffer* g_pConstantBuffer = NULL; // 상수 버퍼 ID3D11Texture2D* g_pDepthStencil = NULL; // 스텐실 버퍼 ID3D11DepthStencilView* g_pDepthStencilView = NULL; ID3D11DepthStencilState* g_LessEqualDSS = NULL; ID3D11RasterizerState* g_pSolidRS; ID3D11RasterizerState* g_pWireframeRS; ID3D11ShaderResourceView* g_pTextureRV = NULL; // 텍스쳐 ID3D11SamplerState* g_pSamplerLinear = NULL; ID3D11Buffer* g_pHeightMapVertexBuffer = NULL; ID3D11Buffer* g_pHeightMapIndexBuffer = NULL; Camera g_Camera; float m_MoveSpeed = 3.0f; float m_RotateSpeed = 0.2f; float m_LastMouseX = 0.0f; float m_LastMouseY = 0.0f; struct MyVertex { XMFLOAT3 pos; XMFLOAT4 color; XMFLOAT3 normal; XMFLOAT2 tex; }; struct ConstantBuffer { XMMATRIX wvp; XMMATRIX world; XMFLOAT4 lightDir; XMFLOAT4 lightColor; }; int vertexCount = 257; int numVertices = vertexCount * vertexCount; int indexSize = 0; int pickedTriangle = -1; UINT* indices; MyVertex* heightMapVertex; float m_clientWidth = 800.0f; float m_clientHeight = 600.0f; std::vector<int> _heightMap; std::vector<int> m_pickedTriangles; HINSTANCE g_hInst; LPCTSTR lpszClass = TEXT("MapTool"); XMFLOAT4 lightDirection = { XMFLOAT4(1.0f,1.0f,1.0f,1.0f), }; XMFLOAT4 lightColor = { XMFLOAT4(1.0f,1.0f,0.0f,1.0f), }; LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); void CreateDepthStencilTexture(); HRESULT InitDevice(); void CleanupDevice(); HRESULT CreateShader(); void InitMatrix(); void CreateConstantBuffer(); void CreateRenderState(); HRESULT LoadTexture(); void CreateHeightMapVB(); void CreateHeightMapIB(); void CalcMatrixForHeightMap(float deltaTime); void LoadHeightMap(); void Render(float deltaTime); void Pick(int x,int y); void ClearPickedTriangleVector(); void UpdateHeightMap(bool);
d2a1e1c4e1bf00d1e88e7d2c70b6f2c301971acd
3532661f801ff6b04ff75edfc8bede79ed3cbde0
/TrackerOnline/Fed9U/Fed9USoftware/Fed9UUtils/src/Fed9UDescription.cc
739b4f485d121e9dd7389c11b7b18e8706d5c3a2
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
cms-externals/tkonlinesw
64c5012cf59294a65eac603f8eceaa2afe490786
bca417d3f21e1cf1122fed85ce000322290896ba
refs/heads/master
2020-12-24T16:16:37.180286
2017-07-14T00:55:10
2017-07-14T00:55:10
30,595,656
0
0
null
null
null
null
UTF-8
C++
false
false
44,133
cc
Fed9UDescription.cc
#include <stdint.h> #include <inttypes.h> #include "Fed9UDescription.hh" #include "ICAssert.hh" #include "TypeDefs.hh" #include "Fed9ULogTemplate.hh" // <NAC date="26/06/2007"> needed to check that address table exists #include <fstream> // </NAC> #include <iostream> #include <cstdlib> // This version number must be incremented whenever // a change is made to the description storage format: /*#define DESCRIPTION_VERSION 6//This is in the header.*/ /*#define VERSION_TEXT(name) ("Fed9U" #name "Version" STRINGIZE(DESCRIPTION_VERSION))//This is in the header*/ namespace Fed9U { //<JEC date=27/9/2007> // std::string Fed9U::Fed9UDescription::_fed9UAddressTable = std::string("Fed9UAddressTable.dat"); //</JEC> using std::endl; Fed9UDescription::Fed9UDescription():_epromDescription(2) { memset ( &(_name[0]),0,200); memset ( &(_fakeEventFile[0]),0,200); //<JEC date=26/9/2007> changed _fed9UAddressTable to a char array memset ( &(_fed9UAddressTable[0]),0,200); //</JEC> // <NAC date="26/07/2007"> fixed to check ENV_CMS_TK_DAQ and to check that the file exists and throw if not char* tkDaqBaseDir = getenv ("ENV_TRACKER_DAQ"); char* fedBaseDir = getenv ("ENV_CMS_TK_FED9U_ROOT"); char* baseDir; if (tkDaqBaseDir != NULL) baseDir = tkDaqBaseDir; else baseDir = fedBaseDir; //std::cout << "ENV_TRACKER_DAQ " << tkDaqBaseDir << std::endl; //std::cout << "ENV_CMS_TK_FED9U_ROOT " << fedBaseDir << std::endl; //std::cout << "Looking for Fed9UAddressTable.dat in " << baseDir << std::endl; //<JEC date=26/9/2007> // if (baseDir != NULL) _fed9UAddressTable = std::string(baseDir)+std::string("/config/Fed9UAddressTable.dat"); if (baseDir != NULL) { std::string tmpStr = std::string(baseDir)+std::string("/config/Fed9UAddressTable.dat"); memcpy ( &(_fed9UAddressTable[0]),tmpStr.c_str(),(tmpStr.size()>200)?200:tmpStr.size()); } //</JEC> else { //<JEC date=26/9/2007> // _fed9UAddressTable = std::string("Fed9UAddressTable.dat"); std::string tmpStr = "Fed9UAddressTable.dat"; memcpy ( &(_fed9UAddressTable[0]),tmpStr.c_str(),(tmpStr.size()>200)?200:tmpStr.size()); //</JEC> std::stringstream msg; msg << "Could not find environmental variable ENV_TRACKER_DAQ or ENV_CMS_TK_FED9U_ROOT, defaulting fed HAL address table to Fed9UAddressTable.dat, in your local directory, if you do not have this file present, the fed software will not work!!!" << std::endl; Fed9UMessage<Fed9UErrorLevel>(FED9U_ERROR_LEVEL_UNEXPECTED_RECOVERED) << msg.str(); std::cout << msg.str(); //remove this. it is to ensure you see it when using libraries from outside Fed9U } std::stringstream msg; msg << "Using Address table " << _fed9UAddressTable << std::endl; Fed9UMessage<Fed9UDebugLevel>(FED9U_DEBUG_LEVEL_DETAILED) << msg.str(); std::cout << msg.str(); //remove this. it is to ensure you see it when using libraries from outside Fed9U //<JRF date="28/11/2007"> // The following code has been moved to within the Fed9UVMEBase class so that this exception is never raised when only dealing with descriptions and not using hardware //std::ifstream addressTableFile(_fed9UAddressTable); //ICUTILS_VERIFYX(addressTableFile,Fed9UDescriptionException)(_fed9UAddressTable)(tkDaqBaseDir)(fedBaseDir).msg("Failed to open Address table").error().code(Fed9UDescriptionException::ERROR_NO_ADDRESS_TABLE); // </JRF> // </NAC> this->loadDefaultDescription(); } Fed9UDescription::~Fed9UDescription() { } Fed9UDescription* Fed9UDescription::clone ( ) { Fed9UDescription* description = new Fed9UDescription ( *this ) ; return description; } /************************************************************************************************** * setters *************************************************************************************************/ Fed9UDescription & Fed9UDescription::setHalAddressTable(const std::string val) { //<JEC date=27/9/2007> // _fed9UAddressTable = val; // strcpy(_fed9UAddressTable,val.c_str()); char deft[22] = "Fed9UAddressTable.dat"; if (val.size() == 0) { memcpy ( &(_fed9UAddressTable[0]),&(deft[0]),22); } else { std::string temp; for(u32 i=0; i < val.size(); i++){ if (val[i] != ' ') temp.push_back(val[i]); } memcpy ( &(_fed9UAddressTable[0]),temp.c_str(),(temp.size()>200)?200:temp.size()); } //</JEC> return *this; } Fed9UDescription& Fed9UDescription::setBusAdaptorType(Fed9UHalBusAdaptor type) { ICUTILS_VERIFY(type == FED9U_HAL_BUS_ADAPTOR_SBS || type == FED9U_HAL_BUS_ADAPTOR_CAEN_PCI || type == FED9U_HAL_BUS_ADAPTOR_CAEN_USB || type == FED9U_HAL_BUS_ADAPTOR_VXI || type == FED9U_HAL_BUS_ADAPTOR_DUMMY )(type).error().msg("You have not set a good bus adaptor Type"); _busAdaptorType = type; return *this; } Fed9UDescription& Fed9UDescription::setFeFirmwareVersion(u32 version) { _feFirmwareVersion=version; return *this; } Fed9UDescription& Fed9UDescription::setBeFirmwareVersion(u32 version) { _beFirmwareVersion=version; return *this; } Fed9UDescription& Fed9UDescription::setVmeFirmwareVersion(u32 version) { _vmeFirmwareVersion=version; return *this; } Fed9UDescription& Fed9UDescription::setDelayFirmwareVersion(u32 version) { _delayFirmwareVersion=version; return *this; } Fed9UDescription& Fed9UDescription::setFedVersion(u32 version) { _fedVersion=version; return *this; } Fed9UDescription& Fed9UDescription::setEpromVersion(u32 version) { _epromVersion=version; return *this; } Fed9UHalBusAdaptor Fed9UDescription::getBusAdaptorType() const { ICUTILS_VERIFY(_busAdaptorType == FED9U_HAL_BUS_ADAPTOR_SBS || _busAdaptorType == FED9U_HAL_BUS_ADAPTOR_CAEN_PCI || _busAdaptorType == FED9U_HAL_BUS_ADAPTOR_CAEN_USB || _busAdaptorType == FED9U_HAL_BUS_ADAPTOR_VXI || _busAdaptorType == FED9U_HAL_BUS_ADAPTOR_DUMMY )(_busAdaptorType).error().msg("You have not set a good bus adaptor Type"); return _busAdaptorType; } u32 Fed9UDescription::getEpromVersion()const { return _epromVersion; } u32 Fed9UDescription::getFedVersion()const { return _fedVersion; } u32 Fed9UDescription::getFeFirmwareVersion()const { return _feFirmwareVersion; } u32 Fed9UDescription::getBeFirmwareVersion()const { return _beFirmwareVersion; } u32 Fed9UDescription::getVmeFirmwareVersion()const { return _vmeFirmwareVersion; } u32 Fed9UDescription::getDelayFirmwareVersion()const { return _delayFirmwareVersion; } Fed9UDescription& Fed9UDescription::setDelay(const Fed9UAddress& fedChannel, u16 coarseDelay, u16 fineDelay) { setFineDelay(fedChannel, fineDelay); setCoarseDelay(fedChannel, coarseDelay); return *this; } Fed9UDescription& Fed9UDescription::setFineDelay(const Fed9UAddress& fedChannel, u16 value) { ICUTILS_VERIFY(fedChannel.getFedFeUnit() != Fed9UAddress::BACKEND && fedChannel.getFedFeUnit() != Fed9UAddress::FEBROADCAST) (fedChannel.getFedFeUnit()).msg("Address out of range").error(); _feParams[fedChannel.getFedFeUnit()]._fineDelay[fedChannel.getFeUnitChannel()] = value; return *this; } Fed9UDescription& Fed9UDescription::setCoarseDelay(const Fed9UAddress& fedChannel, u16 value) { ICUTILS_VERIFY(fedChannel.getFedFeUnit() != Fed9UAddress::BACKEND && fedChannel.getFedFeUnit() != Fed9UAddress::FEBROADCAST) (fedChannel.getFedFeUnit()).msg("Address out of range").error(); _feParams[fedChannel.getFedFeUnit()]._coarseDelay[fedChannel.getFeUnitChannel()] = value; return *this; } Fed9UDescription& Fed9UDescription::setTrimDacOffset(const Fed9UAddress& fedChannel, u16 value) { ICUTILS_VERIFY(fedChannel.getFedFeUnit() != Fed9UAddress::BACKEND && fedChannel.getFedFeUnit() != Fed9UAddress::FEBROADCAST) (fedChannel.getFedFeUnit()).msg("Address out of range").error(); _feParams[fedChannel.getFedFeUnit()]._trimDacOffset[fedChannel.getFeUnitChannel()] = value; return *this; } Fed9UDescription& Fed9UDescription::setOptoRxOffset(const Fed9UAddress& fedFeUnit, u16 value) { ICUTILS_VERIFY(fedFeUnit.getFedFeUnit() != Fed9UAddress::BACKEND) (fedFeUnit.getFedFeUnit()).msg("Address out of range").error(); ICUTILS_VERIFY(value < 64)(value).msg("Value out of range 0 - 63").error(); if (fedFeUnit.getFedFeUnit() == Fed9UAddress::FEBROADCAST) doLoop(&Fed9UDescription::setOptoRxOffset, value); _feParams[fedFeUnit.getFedFeUnit()]._optoRxOffset = value; return *this; } Fed9UDescription& Fed9UDescription::setOptoRxInputOffset(const Fed9UAddress& fedFeUnit, u16 value) { ICUTILS_VERIFY(fedFeUnit.getFedFeUnit() != Fed9UAddress::BACKEND) (fedFeUnit.getFedFeUnit()).msg("Address out of range").error(); ICUTILS_VERIFY(value < 16)(value).msg("Value out of range 0 - 15").error(); if (fedFeUnit.getFedFeUnit() == Fed9UAddress::FEBROADCAST) doLoop(&Fed9UDescription::setOptoRxInputOffset, value); _feParams[fedFeUnit.getFedFeUnit()]._optoRxOffset = ( _feParams[fedFeUnit.getFedFeUnit()]._optoRxOffset & 0x30 ) | ( value & 0x0F ); return *this; } Fed9UDescription& Fed9UDescription::setOptoRxOutputOffset(const Fed9UAddress& fedFeUnit, u16 value) { ICUTILS_VERIFY(fedFeUnit.getFedFeUnit() != Fed9UAddress::BACKEND) (fedFeUnit.getFedFeUnit()).msg("Address out of range").error(); ICUTILS_VERIFY(value < 4)(value).msg("Value out of range 0 - 3").error(); if (fedFeUnit.getFedFeUnit() == Fed9UAddress::FEBROADCAST) doLoop(&Fed9UDescription::setOptoRxOutputOffset, value); _feParams[fedFeUnit.getFedFeUnit()]._optoRxOffset = ( _feParams[fedFeUnit.getFedFeUnit()]._optoRxOffset & 0x0F ) | ( (value << 4) & 0x30 ); return *this; } Fed9UDescription& Fed9UDescription::setOptoRxCapacitor(const Fed9UAddress& fedFeUnit, u16 value) { ICUTILS_VERIFY(fedFeUnit.getFedFeUnit() != Fed9UAddress::BACKEND) (fedFeUnit.getFedFeUnit()).msg("Address out of range").error(); if (fedFeUnit.getFedFeUnit() == Fed9UAddress::FEBROADCAST) doLoop(&Fed9UDescription::setOptoRxCapacitor, value); _feParams[fedFeUnit.getFedFeUnit()]._optoRxCapacitor = value; return *this; } Fed9UDescription& Fed9UDescription::setApvDisable(const Fed9UAddress& fedApv, bool disable) { ICUTILS_VERIFY(fedApv.getFedFeUnit() != Fed9UAddress::BACKEND && fedApv.getFedFeUnit() != Fed9UAddress::FEBROADCAST) (fedApv.getFedFeUnit()).msg("Address out of range").error(); _feParams[fedApv.getFedFeUnit()]._apvDisable[fedApv.getFeUnitApv()] = disable; return *this; } //<GR date=27/07/2006> Added APV fake event disable Fed9UDescription& Fed9UDescription::setApvFakeEventDisable(Fed9UAddress fedApv, bool disable) { ICUTILS_VERIFY(fedApv.getFedFeUnit() != Fed9UAddress::BACKEND && fedApv.getFedFeUnit() != Fed9UAddress::FEBROADCAST) (fedApv.getFedFeUnit()).msg("Address out of range").error(); _feParams[fedApv.getFedFeUnit()]._apvFakeEventDisable[fedApv.getFeUnitApv()] = disable; return *this; } //</GR> Fed9UDescription& Fed9UDescription::setMedianOverride(const Fed9UAddress& fedApv, u16 medianOverride) { ICUTILS_VERIFY(fedApv.getFedFeUnit() != Fed9UAddress::BACKEND && fedApv.getFedFeUnit() != Fed9UAddress::FEBROADCAST) (fedApv.getFedFeUnit()).msg("Address out of range").error(); _feParams[fedApv.getFedFeUnit()]._medianOverride[fedApv.getFeUnitApv()] = medianOverride; return *this; } Fed9UDescription& Fed9UDescription::setMedianOverrideDisable(const Fed9UAddress& fedFeUnit, bool medianOverrideDisable){ ICUTILS_VERIFY(fedFeUnit.getFedFeUnit() != Fed9UAddress::BACKEND) (fedFeUnit.getFedFeUnit()).msg("Address out of range").error(); if (fedFeUnit.getFedFeUnit() == Fed9UAddress::FEBROADCAST) doLoop(&Fed9UDescription::setMedianOverrideDisable, medianOverrideDisable); _feParams[fedFeUnit.getFedFeUnit()]._medianOverrideDisable = medianOverrideDisable; return *this; } Fed9UDescription& Fed9UDescription::setCmMedianOverride( Fed9UAddress fedFeUnit, bool medianOverrideDisable, std::vector<u16> medianOverride) { for (u8 i=0; i<APVS_PER_FEUNIT; i++){ ICUTILS_VERIFY(medianOverride[i] < 1024)(medianOverride[i]).msg("Median Override Value too high. Max = 1023").error(); setMedianOverride( fedFeUnit.setFeUnitChannel(i>>1).setChannelApv(i%2), medianOverride[i] ); } setMedianOverrideDisable ( fedFeUnit, medianOverrideDisable ); return *this; } Fed9UDescription& Fed9UDescription::setScopeLength(u16 numberOfWords) { _scopeLength = numberOfWords; return *this; } Fed9UDescription& Fed9UDescription::setAdcOffset(const Fed9UAddress& channel, u16 offset){ ICUTILS_VERIFY(channel.getFedFeUnit() != Fed9UAddress::BACKEND && channel.getFedFeUnit() != Fed9UAddress::FEBROADCAST) (channel.getFedFeUnit()).msg("Address out of range").error(); _feParams[channel.getFedFeUnit()]._trimDacOffset[channel.getFeUnitChannel()] = offset; return *this; } Fed9UDescription& Fed9UDescription::setTempControl(const Fed9UAddress& fedFpga, const Fed9UTempControl& tempControl) { if (fedFpga.getFedFpga() == Fed9UAddress::BACKEND) { _beTempControl = tempControl; } else if(fedFpga.getFedFpga() == Fed9UAddress::VME){ _vmeTempControl = tempControl; } else if(fedFpga.getFedFpga() == Fed9UAddress::FEBROADCAST){ doLoop(&Fed9UDescription::setTempControl, tempControl); } else { _feParams[fedFpga.getFedFpga()]._tempControl = tempControl; } return * this; } Fed9UDescription& Fed9UDescription::setFrameThreshold(const Fed9UAddress& channel, u16 channelThreshold) { ICUTILS_VERIFY(channel.getFedFeUnit() != Fed9UAddress::BACKEND && channel.getFedFeUnit() != Fed9UAddress::FEBROADCAST) (channel.getFedFeUnit()).msg("Address out of range").error(); Fed9UMessage<Fed9UDebugLevel>(FED9U_DEBUG_LEVEL_SUPER_DETAILED) << "We are about to set the threshold to :" << channelThreshold << std::endl; Fed9UMessage<Fed9UDebugLevel>(FED9U_DEBUG_LEVEL_SUPER_DETAILED) << "Value Set was!!! :" <<_feParams[channel.getFedFeUnit()]._channelThreshold[channel.getFeUnitChannel()] << std::endl; _feParams[channel.getFedFeUnit()]._channelThreshold[channel.getFeUnitChannel()] = (channelThreshold & 0xFFE0) + ( ((channelThreshold&0x1F) > 0xF) ? 0x20 : 0x0) ; // we have to force the value to be multiple of 32 use usual rounding Fed9UMessage<Fed9UDebugLevel>(FED9U_DEBUG_LEVEL_SUPER_DETAILED) << "Value Set was!!! :" <<_feParams[channel.getFedFeUnit()]._channelThreshold[channel.getFeUnitChannel()] << std::endl; return *this; } Fed9UDescription& Fed9UDescription::setFedBeUnit(u16 beUnit) { _beUnit=beUnit; return *this; } Fed9UDescription& Fed9UDescription::setTriggerSource(Fed9UTrigSource triggerSource) { _triggerSource = triggerSource; return *this; } Fed9UDescription& Fed9UDescription::setTestRegister(u32 apvFrameEnable) { _testRegister = apvFrameEnable; return *this; } Fed9UDescription& Fed9UDescription::setFedFeUnitDisable(const Fed9UAddress& fedFeUnit, bool fedFeUnitDisable) { ICUTILS_VERIFY(fedFeUnit.getFedFeUnit() != Fed9UAddress::BACKEND && fedFeUnit.getFedFeUnit() != Fed9UAddress::FEBROADCAST) (fedFeUnit.getFedFeUnit()).msg("Address out of range").error(); _feParams[fedFeUnit.getFedFeUnit()]._feUnitDisable = fedFeUnitDisable; return *this; } Fed9UDescription& Fed9UDescription::setFedBeFpgaDisable(bool fedDisable) { _fedDisable=fedDisable; return *this; } Fed9UDescription& Fed9UDescription::setFedId(u16 fedId) { _fedId = fedId; return *this; } Fed9UDescription& Fed9UDescription::setFedHardwareId(u32 fedHardId) { _fedHardwareId = fedHardId; return *this; } Fed9UDescription& Fed9UDescription::setBeFpgaReadRoute(Fed9UReadRoute readRoute) { _readRoute=readRoute; return *this; } Fed9UDescription& Fed9UDescription::setChannelBufferOccupancy(const Fed9UAddress& channel, u16 channelOccupancy) { ICUTILS_VERIFY(channel.getFedFeUnit() != Fed9UAddress::FEBROADCAST && channel.getFedFeUnit() != Fed9UAddress::BACKEND) (channel.getFedFeUnit()).msg("Address out of range").error(); _feParams[channel.getFedFeUnit()]._channelBufferOccupancy[channel.getFeUnitChannel()]=channelOccupancy; return *this; } Fed9UDescription& Fed9UDescription::setAdcControls(const Fed9UAddress& channel, bool dfsen, bool dfsval, bool s1, bool s2) { ICUTILS_VERIFY(channel.getFedFeUnit() != Fed9UAddress::FEBROADCAST && channel.getFedFeUnit() != Fed9UAddress::BACKEND) (channel.getFedFeUnit()).msg("Address out of range").error(); // note that setting the ADCControls for one channel will also set the same values for the channel pair in the following order // | vector location | channel pair | // | 0 | (0,3) | // | 1 | (1,2) | // | 2 | (4,7) | // | 3 | (5,6) | // | 4 | (8,11) | // | 5 | (9,10) | // use the following vector to do the mapping const u16 channelPairMap[12] = {0, 1, 1, 0, 2, 3, 3, 2, 4, 5, 5, 4}; _feParams[channel.getFedFeUnit()]._adcControls[channelPairMap[channel.getFeUnitChannel()]]=Fed9UAdcControls( dfsen, dfsval, s1, s2); return *this; } Fed9UDescription& Fed9UDescription::setAdcControls(const Fed9UAddress& channel, const Fed9UAdcControls& adcControls) { return setAdcControls(channel, adcControls._dfsen, adcControls._dfsval, adcControls._s1, adcControls._s2 ); } Fed9UDescription& Fed9UDescription::setDaqMode(Fed9UDaqMode fed9UDaqMode) { _fed9UDaqMode = fed9UDaqMode; return *this; } Fed9UDescription& Fed9UDescription::setDaqSuperMode(Fed9UDaqSuperMode fed9UDaqSuperMode) { _fed9UDaqSuperMode = fed9UDaqSuperMode; return *this; } Fed9UDescription& Fed9UDescription::setClock(Fed9UClockSource clockSelect) { _clockMode = clockSelect; return *this; } Fed9UDescription& Fed9UDescription::setTtcrx(const Fed9UTtcrxDescription& ttcrxDescription) { _ttcrxDescription = ttcrxDescription; return *this; } Fed9UDescription& Fed9UDescription::setEprom(const Fed9UEpromDescription& epromDescription) { _epromDescription = epromDescription; return *this; } Fed9UDescription& Fed9UDescription::setVoltageMonitor(const Fed9UVoltageControl& voltageController) { _voltageController = voltageController; return *this; } Fed9UDescription& Fed9UDescription::setComplement(const Fed9UAddress& channel, bool disable) { ICUTILS_VERIFY(channel.getFedFeUnit() != Fed9UAddress::FEBROADCAST && channel.getFedFeUnit() != Fed9UAddress::BACKEND) (channel.getFedFeUnit()).msg("Address out of range").error(); _feParams[channel.getFedFeUnit()]._complement[channel.getFeUnitChannel()] = disable; return *this; } Fed9UDescription& Fed9UDescription::setName(std::string name) { char deft[8]= {'d','e','f','a','u','l','t'}; if (name.size() == 0) { memcpy ( &(_name[0]),&(deft[0]),8); } else { std::string temp; for(u32 i=0; i < name.size(); i++){ if (name[i] != ' ') temp.push_back(name[i]); } memcpy ( &(_name[0]),temp.c_str(),(temp.size()>200)?200:temp.size()); //_name = temp.c_str(); } //std::cout << __PRETTY_FUNCTION__ << " name being set to " << name << " and the array holds" << _name << std::endl; return *this; } Fed9UDescription& Fed9UDescription::setCrateNumber(u16 crateNumber) { _crateNumber = crateNumber; return *this; } Fed9UDescription& Fed9UDescription::setVmeControllerDaisyChainId(u16 daisyChainId) { _vmeControllerDaisyChainId = daisyChainId; return *this; } Fed9UDescription& Fed9UDescription::setSlotNumber(u8 slotNumber) { _baseAddress = slotNumber << 16; return *this; } /******************************************************************************************** * getters ********************************************************************************************/ //<JEC date=26/9/2007> //const std::string & Fed9UDescription::getHalAddressTable() const { std::string Fed9UDescription::getHalAddressTable() const { // return _fed9UAddressTable; return std::string(_fed9UAddressTable); //</JEC> } u16 Fed9UDescription::getFineDelay(const Fed9UAddress& fedChannel) const { ICUTILS_VERIFY(fedChannel.getFedFeUnit() != Fed9UAddress::BACKEND && fedChannel.getFedFeUnit() != Fed9UAddress::FEBROADCAST) (fedChannel.getFedFeUnit()).msg("Address out of range").error(); return _feParams[fedChannel.getFedFeUnit()]._fineDelay[fedChannel.getFeUnitChannel()]; } u16 Fed9UDescription::getCoarseDelay(const Fed9UAddress& fedChannel) const { ICUTILS_VERIFY(fedChannel.getFedFeUnit() != Fed9UAddress::BACKEND && fedChannel.getFedFeUnit() != Fed9UAddress::FEBROADCAST) (fedChannel.getFedFeUnit()).msg("Address out of range").error(); return _feParams[fedChannel.getFedFeUnit()]._coarseDelay[fedChannel.getFeUnitChannel()]; } u16 Fed9UDescription::getTrimDacOffset(const Fed9UAddress& fedChannel) const { ICUTILS_VERIFY(fedChannel.getFedFeUnit() != Fed9UAddress::BACKEND && fedChannel.getFedFeUnit() != Fed9UAddress::FEBROADCAST) (fedChannel.getFedFeUnit()).msg("Address out of range").error(); return _feParams[fedChannel.getFedFeUnit()]._trimDacOffset[fedChannel.getFeUnitChannel()]; } u16 Fed9UDescription::getOptoRxOffset(const Fed9UAddress& fedFeUnit) const { ICUTILS_VERIFY(fedFeUnit.getFedFeUnit() != Fed9UAddress::BACKEND && fedFeUnit.getFedFeUnit() != Fed9UAddress::FEBROADCAST) (fedFeUnit.getFedFeUnit()).msg("Address out of range").error(); return _feParams[fedFeUnit.getFedFeUnit()]._optoRxOffset; } u16 Fed9UDescription::getOptoRxInputOffset(const Fed9UAddress& fedFeUnit) const { ICUTILS_VERIFY(fedFeUnit. getFedFeUnit() != Fed9UAddress::BACKEND && fedFeUnit.getFedFeUnit() != Fed9UAddress::FEBROADCAST) (fedFeUnit.getFedFeUnit()).msg("Address out of range").error(); return ( _feParams[fedFeUnit.getFedFeUnit()]._optoRxOffset & 0x0F ); } u16 Fed9UDescription::getOptoRxOutputOffset(const Fed9UAddress& fedFeUnit) const { ICUTILS_VERIFY(fedFeUnit.getFedFeUnit() != Fed9UAddress::BACKEND && fedFeUnit.getFedFeUnit() != Fed9UAddress::FEBROADCAST) (fedFeUnit.getFedFeUnit()).msg("Address out of range").error(); return ( ( _feParams[fedFeUnit.getFedFeUnit()]._optoRxOffset & 0x30 ) >> 4 ) ; } u16 Fed9UDescription::getOptoRxCapacitor(const Fed9UAddress& fedFeUnit) const { ICUTILS_VERIFY(fedFeUnit.getFedFeUnit() != Fed9UAddress::BACKEND && fedFeUnit.getFedFeUnit() != Fed9UAddress::FEBROADCAST) (fedFeUnit.getFedFeUnit()).msg("Address out of range").error(); return _feParams[fedFeUnit.getFedFeUnit()]._optoRxCapacitor; } bool Fed9UDescription::getApvDisable(const Fed9UAddress& fedApv) const { ICUTILS_VERIFY(fedApv.getFedFeUnit() != Fed9UAddress::BACKEND && fedApv.getFedFeUnit() != Fed9UAddress::FEBROADCAST) (fedApv.getFedFeUnit()).msg("Address out of range").error(); return _feParams[fedApv.getFedFeUnit()]._apvDisable[fedApv.getFeUnitApv()]; } //<GR date=27/07/2006> Added APV fake event disable bool Fed9UDescription::getApvFakeEventDisable(Fed9UAddress fedApv) const { ICUTILS_VERIFY(fedApv.getFedFeUnit() != Fed9UAddress::BACKEND && fedApv.getFedFeUnit() != Fed9UAddress::FEBROADCAST) (fedApv.getFedFeUnit()).msg("Address out of range").error(); return _feParams[fedApv.getFedFeUnit()]._apvFakeEventDisable[fedApv.getFeUnitApv()]; } //</GR> u32 Fed9UDescription::getAllApvDisables(const Fed9UAddress& fedFeUnit) const { ICUTILS_VERIFY(fedFeUnit.getFedFeUnit() != Fed9UAddress::BACKEND && fedFeUnit.getFedFeUnit() != Fed9UAddress::FEBROADCAST) (fedFeUnit.getFedFeUnit()).msg("Address out of range").error(); u32 apvDisables = 0; for (u8 i=0;i<APVS_PER_FEUNIT;i++){ apvDisables |= static_cast<u32>(_feParams[fedFeUnit.getFedFeUnit()]._apvDisable[i]) << ((APVS_PER_FEUNIT-1)-i); } return apvDisables&0xFFFFFF; } u16 Fed9UDescription::getFakeEventRandomSeed(const Fed9UAddress& fedChannelPair) const { return _feParams[fedChannelPair.getFedFeUnit()]._fakeEventRandomSeed[fedChannelPair.getFeUnitChannelPair()]; } u16 Fed9UDescription::getFakeEventRandomMask(const Fed9UAddress& fedChannelPair) const { return _feParams[fedChannelPair.getFedFeUnit()]._fakeEventRandomMask[fedChannelPair.getFeUnitChannelPair()]; } Fed9UDescription & Fed9UDescription::setFakeEventRandomSeed(Fed9UAddress& fedChannelPair, u16 value) { _feParams[fedChannelPair.getFedFeUnit()]._fakeEventRandomSeed[fedChannelPair.getFeUnitChannelPair()] = value; return * this; } Fed9UDescription & Fed9UDescription::setFakeEventRandomMask(Fed9UAddress& fedChannelPair, u16 value) { _feParams[fedChannelPair.getFedFeUnit()]._fakeEventRandomMask[fedChannelPair.getFeUnitChannelPair()] = value; return * this; } u16 Fed9UDescription::getMedianOverride(const Fed9UAddress& fedApv) const { ICUTILS_VERIFY(fedApv.getFedFeUnit() != Fed9UAddress::BACKEND && fedApv.getFedFeUnit() != Fed9UAddress::FEBROADCAST) (fedApv.getFedFeUnit()).msg("Address out of range").error(); return _feParams[fedApv.getFedFeUnit()]._medianOverride[fedApv.getFeUnitApv()]; } bool Fed9UDescription::getMedianOverrideDisable(const Fed9UAddress& fedFeUnit) const { ICUTILS_VERIFY(fedFeUnit.getFedFeUnit() != Fed9UAddress::BACKEND && fedFeUnit.getFedFeUnit() != Fed9UAddress::FEBROADCAST) (fedFeUnit.getFedFeUnit()).msg("Address out of range").error(); return _feParams[fedFeUnit.getFedFeUnit()]._medianOverrideDisable; } std::vector<u16> Fed9UDescription::getCmMedianOverride(Fed9UAddress fedFeUnit, bool& medianOverrideDisable) const { std::vector<u16> medianOverrides; medianOverrideDisable = getMedianOverrideDisable(fedFeUnit); for(u8 i = 0 ; i < APVS_PER_FEUNIT ; i++ ){ medianOverrides.push_back(getMedianOverride(fedFeUnit.setFeUnitChannel(i>>1).setChannelApv(i%2))); } return medianOverrides; } u16 Fed9UDescription::getScopeLength() const { return _scopeLength; } u16 Fed9UDescription::getAdcOffset(const Fed9UAddress& channel) const { ICUTILS_VERIFY(channel.getFedFeUnit() != Fed9UAddress::BACKEND && channel.getFedFeUnit() != Fed9UAddress::FEBROADCAST) (channel.getFedFeUnit()).msg("Address out of range").error(); return _feParams[channel.getFedFeUnit()]._trimDacOffset[channel.getFeUnitChannel()]; } u16 Fed9UDescription::getFrameThreshold(const Fed9UAddress& channel) const { ICUTILS_VERIFY(channel.getFedFeUnit() != Fed9UAddress::BACKEND && channel.getFedFeUnit() != Fed9UAddress::FEBROADCAST) (channel.getFedFeUnit()).msg("Address out of range").error(); return _feParams[channel.getFedFeUnit()]._channelThreshold[channel.getFeUnitChannel()]; } Fed9UTrigSource Fed9UDescription::getTriggerSource() const {return _triggerSource;} u32 Fed9UDescription::getTestRegister() const {return _testRegister;} bool Fed9UDescription::getFedFeUnitDisable(const Fed9UAddress& fedFeUnit) const { ICUTILS_VERIFY(fedFeUnit.getFedFeUnit() != Fed9UAddress::BACKEND && fedFeUnit.getFedFeUnit() != Fed9UAddress::FEBROADCAST) (fedFeUnit.getFedFeUnit()).msg("Address out of range").error(); return _feParams[fedFeUnit.getFedFeUnit()]._feUnitDisable; } u32 Fed9UDescription::getFedBeUnit() const { return _beUnit;} bool Fed9UDescription::getFedBeFpgaDisable() const {return _fedDisable;} u16 Fed9UDescription::getFedId() const {return _fedId;} u32 Fed9UDescription::getFedHardwareId() const {return _fedHardwareId;} Fed9UReadRoute Fed9UDescription::getBeFpgaReadRoute() const {return _readRoute;} u16 Fed9UDescription::getChannelBufferOccupancy(const Fed9UAddress& channel) const { ICUTILS_VERIFY(channel.getFedFeUnit() != Fed9UAddress::FEBROADCAST && channel.getFedFeUnit() != Fed9UAddress::BACKEND) (channel.getFedFeUnit()).msg("Address out of range").error(); return _feParams[channel.getFedFeUnit()]._channelBufferOccupancy[channel.getFeUnitChannel()]; } Fed9UAdcControls Fed9UDescription::getAdcControls(const Fed9UAddress& channel) const { ICUTILS_VERIFY(channel.getFedFeUnit() != Fed9UAddress::FEBROADCAST && channel.getFedFeUnit() != Fed9UAddress::BACKEND) (channel.getFedFeUnit()).msg("Address out of range").error(); // note here we get the value for a pair of channels, so we can get one value for two incoming addresses. // the way these addresses are mapped to the channel pair in the vector are as follows (note channel pair is with internal numbering here): // | vector location | channel pair | // | 0 | (0,3) | // | 1 | (1,2) | // | 2 | (4,7) | // | 3 | (5,6) | // | 4 | (8,11) | // | 5 | (9,10) | // use the following vector to do the mapping const u16 channelPairMap[12] = {0, 1, 1, 0, 2, 3, 3, 2, 4, 5, 5, 4}; return _feParams[channel.getFedFeUnit()]._adcControls[channelPairMap[channel.getFeUnitChannel()]]; } Fed9UDaqMode Fed9UDescription::getDaqMode() const{ return _fed9UDaqMode; } Fed9UDaqSuperMode Fed9UDescription::getDaqSuperMode() const{ return _fed9UDaqSuperMode; } Fed9UClockSource Fed9UDescription::getClock() const { return _clockMode; } Fed9UTempControl Fed9UDescription::getTempControl(const Fed9UAddress& fedFpga) const { ICUTILS_VERIFY(fedFpga.getFedFpga() != Fed9UAddress::FEBROADCAST)(fedFpga.getFedFpga()).msg("Address out of range").error(); if (fedFpga.getFedFpga() == Fed9UAddress::BACKEND ) { return _beTempControl; } else if (fedFpga.getFedFpga() == Fed9UAddress::VME ) { return _vmeTempControl; } else { return _feParams[fedFpga.getFedFpga()]._tempControl; } } bool Fed9UDescription::getComplement(const Fed9UAddress& channel) const { ICUTILS_VERIFY(channel.getFedFeUnit() != Fed9UAddress::BACKEND && channel.getFedFeUnit() != Fed9UAddress::FEBROADCAST) (channel.getFedFeUnit()).msg("Address out of range").error(); return _feParams[channel.getFedFeUnit()]._complement[channel.getFeUnitChannel()]; } Fed9UTtcrxDescription Fed9UDescription::getTtcrx() const { return _ttcrxDescription; } Fed9UEpromDescription Fed9UDescription::getEprom() const { return _epromDescription; } Fed9UVoltageControl Fed9UDescription::getVoltageMonitor() const { return _voltageController; } u16 Fed9UDescription::getCrateNumber() const { return _crateNumber; } u16 Fed9UDescription::getVmeControllerDaisyChainId() const { return _vmeControllerDaisyChainId; } u8 Fed9UDescription::getSlotNumber() const { return (_baseAddress >> 16) & 0xFF; } //<JEC date=08/12/2005> //Added eventType to description Fed9UDescription& Fed9UDescription::setDaqEventType(u16 eventType) { _eventType = eventType; return *this; } u16 Fed9UDescription::getDaqEventType(void) const { return _eventType; } //</JEC> //<JEC date=08/12/2005> //Added DaqFov to description Fed9UDescription& Fed9UDescription::setDaqFov(u16 fov) { _fov = fov; return *this; } u16 Fed9UDescription::getDaqFov(void) const { return _fov; } //</JEC> //<JEC date=09/01/2006> //Added tracker header type Fed9UHeaderFormat Fed9UDescription::getHeaderFormatType(void) const { return _headerType; } Fed9UDescription& Fed9UDescription::setHeaderFormatType(Fed9UHeaderFormat headerType) { _headerType = headerType; return *this; } //</JEC> //<JEC date=23/02/06> //Added BunchCrossingOffset to description Fed9UDescription& Fed9UDescription::setBunchCrossingOffset(u16 bxOffset) { _bxOffset = bxOffset; return *this; } u16 Fed9UDescription::getBunchCrossingOffset(void) const { return _bxOffset; } //</JEC> /************************************************************************************************ * methods for creating and loading and saving descriptions and subcomponents. ***********************************************************************************************/ void Fed9UDescription::loadDescription(std::istream & is) { // NOTE: if any changes are made to the description file, // the DESCRIPTION_VERSION define at the top of this file // must be incremented. static const std::string expectedVersion = VERSION_TEXT(Description); std::string actualVersion; is >> actualVersion; is >> _name; ICUTILS_VERIFY(actualVersion == expectedVersion)(actualVersion)(expectedVersion).error() .msg("Wrong version number in settings, they may need to be updated"); loadSettings(is); loadStrips(is); is >> _epromDescription; } void Fed9UDescription::loadSettings(std::istream& is) { // NOTE: if any changes are made to the description file, // the DESCRIPTION_VERSION define at the top of this file // must be incremented. static const std::string expectedVersion = VERSION_TEXT(Settings); std::string actualVersion; is >> actualVersion; ICUTILS_VERIFY(actualVersion == expectedVersion)(actualVersion)(expectedVersion).error() .msg("Wrong version number in description file, it may need to be updated"); is >> _busAdaptorType; is >> _feFirmwareVersion; is >> _beFirmwareVersion; is >> _vmeFirmwareVersion; is >> _fedVersion; is >> _epromVersion; is >> _baseAddress; is >> _fed9UDaqMode; is >> _fed9UDaqSuperMode; is >> _scopeLength; is >> _triggerSource; is >> _testRegister; is >> _beUnit; is >> _fedDisable; is >> _fedId; is >> _fedHardwareId; is >> _readRoute; is >> _clockMode; is >> _beTempControl; is >> _vmeTempControl; is >> _crateNumber; is >> _vmeControllerDaisyChainId; is >> _ttcrxDescription; is >> _voltageController; is >> _globalFineSkew; is >> _globalCoarseSkew; is >> _optoRXResistor; is >> _fakeEventFile; is >> _fakeEventTriggerDelay; is >> _eventType; is >> _fov; is >> _headerType; is >> _bxOffset; for(int i=0; i<8; i++) { is >> _feParams[i]; } // // global fine skew initialised here. temporary bodge to avoid .fed file conflicts... // should be overridden by the xml load. // _globalFineSkew=0; _globalCoarseSkew=0; } void Fed9UDescription::loadStrips(std::istream& is) { // NOTE: if any changes are made to the description file, // the DESCRIPTION_VERSION define at the top of this file // must be incremented. static const std::string expectedVersion = VERSION_TEXT(Strips); std::string actualVersion; is >> actualVersion; ICUTILS_VERIFY(actualVersion == expectedVersion)(actualVersion)(expectedVersion).error() .msg("Wrong version number in strips, they may need to be updated"); is >> _strips; } void Fed9UDescription::saveDescription(std::ostream & os) const { // NOTE: if any changes are made to the description file, // the DESCRIPTION_VERSION define at the top of this file // must be incremented. os << VERSION_TEXT(Description) << endl; os << _name << endl; saveSettings(os); saveStrips(os); os << _epromDescription << endl; } void Fed9UDescription::saveSettings(std::ostream& os) const { // NOTE: if any changes are made to the description file, // the DESCRIPTION_VERSION define at the top of this file // must be incremented. os << VERSION_TEXT(Settings) << endl; os << _busAdaptorType << endl; os << _feFirmwareVersion << endl; os << _beFirmwareVersion << endl; os << _vmeFirmwareVersion << endl; os << _fedVersion << endl; os << _epromVersion << endl; os << _baseAddress << endl; os << _fed9UDaqMode << endl; os << _fed9UDaqSuperMode << endl; os << _scopeLength << endl; os << _triggerSource << endl; os << _testRegister << endl; os << _beUnit << endl; os << _fedDisable << endl; os << _fedId << endl; os << _fedHardwareId << endl; os << _readRoute << endl; os << _clockMode << endl; os << _beTempControl << endl; os << _vmeTempControl << endl; os << _crateNumber << endl; os << _vmeControllerDaisyChainId << endl; os << _ttcrxDescription << endl; os << _voltageController << endl; os << _globalFineSkew << endl; os << _globalCoarseSkew << endl; os << _optoRXResistor << endl; os << _fakeEventFile << endl; os << _fakeEventTriggerDelay << endl; os << _eventType << endl; os << _fov << endl; os << _headerType << endl; os << _bxOffset << endl; for(int i=0; i<8; i++) { os << _feParams[i] << endl; } } void Fed9UDescription::saveStrips(std::ostream& os) const { // NOTE: if any changes are made to the description file, // the DESCRIPTION_VERSION define at the top of this file // must be incremented. os << VERSION_TEXT(Strips) << endl; os << _strips; } void Fed9UDescription::loadDefaultSettings() { _crateNumber = 0; _vmeControllerDaisyChainId = 0; //_name=std::string("default"); char deft[8]= {'d','e','f','a','u','l','t'}; memcpy ( &(_name[0]),&(deft[0]),8); _busAdaptorType=FED9U_HAL_BUS_ADAPTOR_CAEN_PCI; _feFirmwareVersion=0; _beFirmwareVersion=0; _vmeFirmwareVersion=0; _fedVersion=0; _epromVersion=2; _baseAddress=0; _fed9UDaqMode=FED9U_MODE_SCOPE; _fed9UDaqSuperMode=FED9U_SUPER_MODE_NORMAL; _scopeLength=32; _triggerSource=FED9U_TRIG_SOFTWARE; _testRegister=0; //_beFpgaMode=0; _beUnit=0; _fedDisable=true; _fedId=0; _fedHardwareId=0; _readRoute=FED9U_ROUTE_VME; _clockMode=FED9U_CLOCK_INTERNAL; _beTempControl = Fed9UTempControl(); _vmeTempControl = Fed9UTempControl(); _ttcrxDescription = Fed9UTtcrxDescription(); _voltageController = Fed9UVoltageControl(); _epromDescription = Fed9UEpromDescription(_epromVersion); _optoRXResistor = 60; char deft2[13]= {'f','a','k','e','E','v','e','n','t','.','f','e','v'}; memcpy ( &(_name[0]),&(deft2[0]),13); // _fakeEventFile = "fakeEvent.fev"; _fakeEventTriggerDelay = 0; _eventType = 0; _fov = 0; _headerType = FED9U_HEADER_APVERROR; _bxOffset = 1; for(int i=0; i<8; i++) { _feParams[i] = Fed9UFrontEndDescription(0x8, 0xf, 0x1f, 0x6); } // // global fine skew initialised here... // _globalFineSkew=0; _globalCoarseSkew=0; } void Fed9UDescription::loadDefaultStrips() { _strips.loadDefaultStrips(); } //<JF date=18/03/2004> //Add get required buffer size. u32 Fed9UDescription::getRequiredBufferSize() const { u32 estimate=0; // will return number of u32s in data buffer u32 daqHeader = 8; // number of bytes in daq Header u32 trackerSpecial = 8; //Number of bytes in tracker special header //Matthew Pearson Jan 05 u32 daqTrailer = 8; // number of bytes in daq Trailer u32 trackerHeader = 8 << 4; // number of bytes in tracker Header u32 rubbish = 4; // occasionally there is one extra 32 bit word of rubbish u32 noFEsEnabled=0; for( int i=0; i < FEUNITS_PER_FED; i++ ){ if(!_feParams[i]._feUnitDisable) noFEsEnabled++; } u32 payload = 0; if ( _fed9UDaqMode == FED9U_MODE_SCOPE ) payload= ( (( _scopeLength << 1 ) + 3) * 12 ); else payload= ( ((140 << 2)+3) * 12 ); payload = (payload + 7) & ~7; payload *= noFEsEnabled; // // create the estimate by summing the payload length with the length of the // header and the trailer // estimate = ( payload + daqHeader + trackerSpecial + daqTrailer + trackerHeader + rubbish) >> 2; //Matthew Pearson Jan 05 - modifed above line to take into account extra tracker special header word. return estimate; } // <NAC date="24/04/2007"> operator to compare descriptions bool operator == (const Fed9UDescription& l, const Fed9UDescription& r) { Fed9UAddress addr; if (l.getEpromVersion() != r.getEpromVersion()) return false; if (l.getBusAdaptorType() != r.getBusAdaptorType()) return false; if (l.getFedVersion() != r.getFedVersion()) return false; if (l.getFeFirmwareVersion() != r.getFeFirmwareVersion()) return false; if (l.getBeFirmwareVersion() != r.getBeFirmwareVersion()) return false; if (l.getVmeFirmwareVersion() != r.getVmeFirmwareVersion()) return false; if (l.getDelayFirmwareVersion() != r.getDelayFirmwareVersion()) return false; if (l.getBaseAddress() != r.getBaseAddress()) return false; if (l.getScopeLength() != r.getScopeLength()) return false; if (l.getTriggerSource() != r.getTriggerSource()) return false; if (l.getTestRegister() != r.getTestRegister()) return false; if (l.getFedBeUnit() != r.getFedBeUnit()) return false; if (l.getFedBeFpgaDisable() != r.getFedBeFpgaDisable()) return false; if (l.getFedId() != r.getFedId()) return false; if (l.getFedHardwareId() != r.getFedHardwareId()) return false; if (l.getBeFpgaReadRoute() != r.getBeFpgaReadRoute()) return false; if (l.getDaqMode() != r.getDaqMode()) return false; if (l.getDaqSuperMode() != r.getDaqSuperMode()) return false; if (l.getClock() != r.getClock()) return false; if (l.getCrateNumber() != r.getCrateNumber()) return false; if (l.getVmeControllerDaisyChainId() != r.getVmeControllerDaisyChainId()) return false; if (l.getSlotNumber() != r.getSlotNumber()) return false; //required? if (l.getName() != r.getName()) return false; if (l.getHalAddressTable() != r.getHalAddressTable()) return false; if (l.getGlobalFineSkew() != r.getGlobalFineSkew()) return false; if (l.getGlobalCoarseSkew() != r.getGlobalCoarseSkew()) return false; if (l.getOptoRXResistor() != r.getOptoRXResistor()) return false; if (l.getFakeEventFile() != r.getFakeEventFile()) return false; if (l.getFakeEventTriggerDelay() != r.getFakeEventTriggerDelay()) return false; if (l.getDaqEventType() != r.getDaqEventType()) return false; if (l.getDaqFov() != r.getDaqFov()) return false; if (l.getHeaderFormatType() != r.getHeaderFormatType()) return false; if (l.getBunchCrossingOffset() != r.getBunchCrossingOffset()) return false; addr.setFedFpga(Fed9UAddress::BACKEND); if (l.getTempControl(addr) != r.getTempControl(addr)) return false; addr.setFedFpga(Fed9UAddress::VME); if (l.getTempControl(addr) != r.getTempControl(addr)) return false; if (l.getTtcrx() != r.getTtcrx()) return false; if (l.getEprom() != r.getEprom()) return false; if (l.getVoltageMonitor() != r.getVoltageMonitor()) return false; for (int f=0; f<FEUNITS_PER_FED; f++) { addr.setFedFeUnit(f); if (l.getFrontEndDescription(addr) != r.getFrontEndDescription(addr)) return false; } if (l.getFedStrips() != r.getFedStrips()) return false; return true; } // </NAC> // <NAC date="25/04/2007> Fed9UFrontEndDescription Fed9UDescription::getFrontEndDescription(const Fed9UAddress& addr) const { return _feParams[addr.getFedFeUnit()]; } Fed9UDescription& Fed9UDescription::setFrontEndDescription(const Fed9UAddress& addr, const Fed9UFrontEndDescription& theNewFrontEndDescription) { _feParams[addr.getFedFeUnit()] = theNewFrontEndDescription; return *this; } // </NAC> } //</JF>
e0d0caabe913e9786937a99efe27f341f9d5d4b2
2b6870b691cae94505126ac50138500cb54d5673
/PatternsTutorial/CObservedComponent.cpp
ac04a7d8febd3c2a0fdab85fb3eace261d5dcc51
[]
no_license
esra33/CppPatternsTutorials
cfad694c99c47e4f5c79bdbabceeb45c17e7ab10
63e596e38802d5d5b9ecab331bcb855c2a6c8a15
refs/heads/master
2020-12-24T16:33:25.056258
2016-04-18T15:14:16
2016-04-18T15:14:16
14,672,194
0
0
null
null
null
null
UTF-8
C++
false
false
1,042
cpp
CObservedComponent.cpp
#include <cstring> #include "CObservedComponent.h" bool CObservedComponent::InformObservers(int currValue) { bool response = false; for(std::list<IObserver*>::iterator i = m_Observers.begin(), e = m_Observers.end(); i != e; ++i) { // check if any of the observers can respond response = (*i)->Update(currValue) || response; } return response; } CObservedComponent::CObservedComponent(int max) : m_MaxValue(max) { } CObservedComponent::~CObservedComponent() { m_Observers.clear(); } void CObservedComponent::Flush() { printf("0\n"); for(int i = 1; i < m_MaxValue; ++i) { if(!InformObservers(i)) { printf("%i", i); } printf("\n"); } } void CObservedComponent::AddObserver(IObserver* pObserver) { // check that the observer doesn't exist for(std::list<IObserver*>::iterator i = m_Observers.begin(), e = m_Observers.end(); i != e; ++i) { if((*i) == pObserver) return; } m_Observers.push_back(pObserver); } void CObservedComponent::RemoveObserver(IObserver* pObserver) { m_Observers.remove(pObserver); }
1ddf42da5890d74be8f73fb81538bfbb4b615e2c
1b074eb7ab6aa244e3fb0c4135920ebda801ca64
/ActividadIntegral6/main.cpp
479c6a7e18fbee4fc6ce236423a22830fbd5c81b
[]
no_license
Luis-ERP/DataStructuresCourseProjects
bb40ae23f1c114662b2dc37f965ade95001ba6d7
2e0c7fff42ad8937bc30a963eb8e314355eada68
refs/heads/master
2023-01-21T09:36:56.815691
2020-11-28T07:23:59
2020-11-28T07:23:59
297,229,566
0
1
null
null
null
null
UTF-8
C++
false
false
6,293
cpp
main.cpp
#include <iostream> #include <fstream> #include <string> #include <vector> #include "algorithms.h" #include "dlist.h" #include "bst.h" #include "trie.h" using namespace std; // Functions declaration DList<DList<string>> readData(DList<BST<string, DList<string>>> &bst_list, Trie* trie); void writeData(DList<DList<string>> data, string fileName); template<class T> void outputData(DList<DList<T>> data, int start, int end); template<class T> DList<DList<T>> sortData(DList<DList<T>>& data, int start, int end, int varIndex); void casosPrueba(); void search(string value, int varName, DList<BST<string, DList<string>>>& bstList); // Main int main() { int answer; // Define the trie tree Trie* trie = new Trie(); // Define the list of BST's DList<BST<string, DList<string>>> data_bst; BST<string, DList<string>> entity; BST<string, DList<string>> code; BST<string, DList<string>> year; BST<string, DList<string>> co2; data_bst.push_back(entity); data_bst.push_back(code); data_bst.push_back(year); data_bst.push_back(co2); // Define the table of data and read the document DList<DList<string>> data = readData(data_bst, trie); do { cout << "\nWelcome to the the CO2 emissions Worldwide database, please select an option\n"; cout << "0. Exit\n"; cout << "1. Output dataset\n"; cout << "2. Ordenar por variable (versión lenta)\n"; cout << "3. Buscar valor\n"; cout << "4. Checar si existe entidad\n"; cout << "5. Casos de prueba\n"; cout << "-> "; cin >> answer; cout << endl; switch(answer){ case 1: { int start; int end; cout << "Start row (min. 0) -> "; cin >> start; cout << "End row (max. 20853) -> "; cin >> end; outputData(data, start, end); break; } case 2: { string variableName; int index; cout << "Enter variable name\n"; cout << "0. Entity\n"; cout << "1. Code\n"; cout << "2. Year\n"; cout << "3. CO2 emissions\n-> "; cin >> index; int start; int end; cout << "Start row (min. 0) -> "; cin >> start; cout << "End row (max. 20853) -> "; cin >> end; DList<DList<string>> sortedData = sortData(data, start, end, index); writeData(sortedData, "co2_emission_sorted.csv"); outputData(sortedData, start, end); break; } case 3: { int variableName; string valueToSearch; int start; int end; cout << "Enter the column where to search\n"; cout << "0. Entity\n"; cout << "1. Code\n"; cout << "2. Year\n"; cout << "3. CO2 emissions\n-> "; cin >> variableName; cout << "Enter the value to search\n-> "; cin >> valueToSearch; search(valueToSearch, variableName, data_bst); break; } case 4: { string entity; cout << "Ingresa el nombre de la entidad a buscar\n->"; cin >> entity; string result = (trie->search(entity)) ? "' si existe." : "' no existe."; cout << "La entidad '" << entity << result << endl; break; } case 5: { cout << "## ORDENAR ##\n"; cout << "Caso1. [IN]: 2 0 10\n"; DList<DList<string>> sortedData1 = sortData(data, 0, 10, 2); writeData(sortedData1, "co2_emission_sorted_PRUEBA1.csv"); outputData(sortedData1, 0, sortedData1.size()); cout << "Caso2. [IN]: 2 2 8\n"; DList<DList<string>> sortedData2 = sortData(data, 2, 8, 2); writeData(sortedData2, "co2_emission_sorted_PRUEBA2.csv"); outputData(sortedData2, 0, sortedData2.size()); cout << "## BUSCAR ##\n"; cout << "Caso1. [IN]: 3 1 COL"; search("COL", 1, data_bst); cout << "Caso2. [IN]: 3 2 1961"; search("1961", 2, data_bst); cout << "## BUSCAR (Trie) ##\n"; cout << "Caso1. [IN]: 4 Cu\n"; string result = (trie->search("Cu")) ? "' si existe." : "' no existe."; cout << "La entidad '" << "Cu" << result << "\n\n\n"; cout << "Caso2. [IN]: 4 Cuba\n"; result = (trie->search("Cuba")) ? "' si existe." : "' no existe."; cout << "La entidad '" << "Cuba" << result << "\n\n\n"; break; } } } while (answer != 0); } // Read data DList<DList<string>> readData(DList<BST<string, DList<string>>> &bst_list, Trie* trie){ DList<DList<string>> data; // Read file ifstream file; file.open("co2_emission_shuffled2.csv"); int counter = 0; while(file.good()){ counter++; string str_entity; string str_code; string str_year; string str_co2; // Read line getline(file, str_entity, ','); if (str_entity != ""){ getline(file, str_code, ','); getline(file, str_year, ','); getline(file, str_co2, '\n'); // Append to the vector DList<string> row; row.push_back(str_entity); row.push_back(str_code); row.push_back(str_year); row.push_back(str_co2); DList<string>* row_ptr = data.push_back(row); // Append to the BST's bst_list[0].add(str_entity, row_ptr); // Entity bst_list[1].add(str_code, row_ptr); // Entity Code bst_list[2].add(str_year, row_ptr); // Year bst_list[3].add(str_co2, row_ptr); // CO2 Emissions // Append to Trie trie->insert(str_entity); } } file.close(); return data; } // Print vector template<class T> void outputData(DList<DList<T>> data, int start, int end){ cout << "\nENTITY CODE YEAR CO2-EMISSIONS\n"; for(int i=start; i<end; i++){ cout << data[i][0] << " "; cout << data[i][1] << " "; cout << data[i][2] << " "; cout << data [i][3] << endl; } cout << "\n\n"; } // Write data void writeData(DList<DList<string>> data, string fileName){ ofstream file; file.open(fileName); for (int i=0; i<data.size(); i++){ file << data[i][0] << "," << data[i][1] << "," << data[i][2] << "," << data[i][3] << endl; } file.close(); } // Sort template<class T> DList<DList<T>> sortData(DList<DList<T>>& data, int start, int end, int varIndex){ DList<DList<T>> rangedVector; for (int i=start; i<end; i++){ rangedVector.push_back(data[i]); } sort(rangedVector, varIndex); return rangedVector; } // Serarch void search(string value, int varName, DList<BST<string, DList<string>>>& bstList){ DList<string>* ptr = bstList[varName].search(value); DList<string> foundValue = *ptr; if (foundValue.size() == 0){ cout << "\nValue not found." << endl; } else { DList<DList<string>> data; data.push_back(foundValue); outputData(data, 0, data.size()); } }
efd057a7cf576711b63ddc45809eb790f8921e2d
4abd8793f2f2cb52fe02837c67e39dfef74b5715
/mukulguptamg7/day18/target sum pair.cpp
3e154e6fd19d965ab8f8c58f588fd4711996ca34
[]
no_license
Devang-25/100DaysOfCode
bdab847655490b4421454b4693cfcd6ddc3d4ff5
4e3d632be1ecd3b235c03ac593a4ea8ec9562e56
refs/heads/master
2021-05-25T12:50:19.956945
2020-04-06T17:49:02
2020-04-06T17:49:02
253,761,487
1
1
null
2020-12-18T18:33:29
2020-04-07T10:31:32
null
UTF-8
C++
false
false
532
cpp
target sum pair.cpp
#include<iostream> #include<algorithm> using namespace std; int main() { int n; cin>>n; int a[1001]; for(int i=0;i<n;i++) { cin>>a[i]; } sort(a,a+n); int target; cin>>target; int l=0; int r=n-1; while(l<r) { if((a[l]+a[r])==target) { cout<<a[l]<<" and "<<a[r]<<endl; l++; } if((a[l]+a[r])>target) { r--; } if((a[l]+a[r])<target) { l++; } } return 0; }
c28d037f6b37f2d1b98ac21f82033e41528784c2
03f037d0f6371856ede958f0c9d02771d5402baf
/graphics/VTK-7.0.0/Infovis/Core/vtkKCoreDecomposition.h
b7c7b034979507312bf1252d22fe5d8fbcb45513
[ "BSD-3-Clause" ]
permissive
hlzz/dotfiles
b22dc2dc5a9086353ed6dfeee884f7f0a9ddb1eb
0591f71230c919c827ba569099eb3b75897e163e
refs/heads/master
2021-01-10T10:06:31.018179
2016-09-27T08:13:18
2016-09-27T08:13:18
55,040,954
4
0
null
null
null
null
UTF-8
C++
false
false
3,977
h
vtkKCoreDecomposition.h
/*========================================================================= Program: Visualization Toolkit Module: vtkKCoreDecomposition.h Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ /*------------------------------------------------------------------------- Copyright 2008 Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain rights in this software. -------------------------------------------------------------------------*/ // .NAME vtkKCoreDecomposition - Compute the k-core decomposition of the input graph. // // .SECTION Description // The k-core decomposition is a graph partitioning strategy that is useful for // analyzing the structure of large networks. A k-core of a graph G is a maximal // connected subgraph of G in which all vertices have degree at least k. The k-core // membership for each vertex of the input graph is found on the vertex data of the // output graph as an array named 'KCoreDecompositionNumbers' by default. The algorithm // used to find the k-cores has O(number of graph edges) running time, and is described // in the following reference paper. // // An O(m) Algorithm for Cores Decomposition of Networks // V. Batagelj, M. Zaversnik, 2001 // // .SECTION Thanks // Thanks to Thomas Otahal from Sandia National Laboratories for providing this // implementation. #ifndef vtkKCoreDecomposition_h #define vtkKCoreDecomposition_h #include "vtkInfovisCoreModule.h" // For export macro #include "vtkGraphAlgorithm.h" class vtkIntArray; class VTKINFOVISCORE_EXPORT vtkKCoreDecomposition : public vtkGraphAlgorithm { public: static vtkKCoreDecomposition *New(); vtkTypeMacro(vtkKCoreDecomposition, vtkGraphAlgorithm); void PrintSelf(ostream& os, vtkIndent indent); // Description: // Set the output array name. If no output array name is // set then the name 'KCoreDecompositionNumbers' is used. vtkSetStringMacro(OutputArrayName); // Description: // Directed graphs only. Use only the in edges to // compute the vertex degree of a vertex. The default // is to use both in and out edges to compute vertex // degree. vtkSetMacro(UseInDegreeNeighbors, bool); vtkGetMacro(UseInDegreeNeighbors, bool); vtkBooleanMacro(UseInDegreeNeighbors, bool); // Description: // Directed graphs only. Use only the out edges to // compute the vertex degree of a vertex. The default // is to use both in and out edges to compute vertex // degree. vtkSetMacro(UseOutDegreeNeighbors, bool); vtkGetMacro(UseOutDegreeNeighbors, bool); vtkBooleanMacro(UseOutDegreeNeighbors, bool); // Description: // Check the input graph for self loops and parallel // edges. The k-core is not defined for graphs that // contain either of these. Default is on. vtkSetMacro(CheckInputGraph, bool); vtkGetMacro(CheckInputGraph, bool); vtkBooleanMacro(CheckInputGraph, bool); protected: vtkKCoreDecomposition(); ~vtkKCoreDecomposition(); int RequestData(vtkInformation *, vtkInformationVector **, vtkInformationVector *); private: char* OutputArrayName; bool UseInDegreeNeighbors; bool UseOutDegreeNeighbors; bool CheckInputGraph; // K-core partitioning implementation void Cores(vtkGraph* g, vtkIntArray* KCoreNumbers); vtkKCoreDecomposition(const vtkKCoreDecomposition&); // Not implemented. void operator=(const vtkKCoreDecomposition&); // Not implemented. }; #endif
f46cae6a72b11da803a1c81278b4f7630a2c7c5e
3e13bf6a8272fbfae9fc8b9727c62b8cd1c5b0f1
/loncare_DataStructures/Student.cpp
4f812569e0ed61c3e65be14c014952ecb6bcb1c1
[]
no_license
Codetalker777/loncare_DataStructures
09484b2fd9d988a4400574c387caa11349381969
d913ad8701e7c6962c74873c1905fddd69cc3a62
refs/heads/master
2020-03-12T19:09:18.926104
2018-04-24T01:28:35
2018-04-24T01:28:35
130,778,356
0
0
null
null
null
null
UTF-8
C++
false
false
298
cpp
Student.cpp
#include "stdafx.h" #include "Student.h" #include <string> using namespace std; // constrcutor Student::Student(int id, string name) { this->id = id; this->name = name; } //return id int Student::get_id() const { return id; } // return name string Student::get_name() const { return name; }
6ec273ba57d86f72fd0dcc920f4806703382ec85
22011d72195a5675fa09c29a5374cc25d99505be
/source/game/protocolclient.cpp
722929492318e4991130386436ee26dc521a60b6
[]
no_license
mockthebear/burr-tower
24844be9ea68dc82cc0f2c996233b39832ecca6f
079753077950b12e1702cf752348f46ddd466b54
refs/heads/master
2020-03-17T22:13:18.558485
2018-05-18T19:07:29
2018-05-18T19:07:29
133,994,112
0
0
null
null
null
null
UTF-8
C++
false
false
7,197
cpp
protocolclient.cpp
#include "protocolclient.hpp" #include "../socket/reliableudp.hpp" #include "burr.hpp" #include "tower.hpp" #include "enemy.hpp" #include "gamelevel.hpp" #include "seeds.hpp" void ProtocolClient::Update(NetworkState *s,float dt){ m_sock->Update(dt); updateCounter -= dt; if (updateCounter <= 0){ updateCounter = updateInterval; SocketMessage msg; msg.Clear(); PeerList Peers = m_sock->GetPeers(); currentState = s; for (auto &peer : Peers){ m_Pid = peer; while (m_sock->Receive(&msg,peer)){ ParsePacket(s,peer,&msg); } } ObjectMap mapp = GetState()->cmap.GetObjects(); SocketMessage reply; ReliableUdpClient::SetSendMode(ENET_PACKET_FLAG_RELIABLE); for (auto &objEntry : mapp){ if (objEntry.second->IsLocal()){ if (objEntry.second->NetworkClientUpdate(&reply)){ reply.Add<int>(objEntry.first); m_sock->Send(&reply,-1); reply.Clear(); } } } } } void ProtocolClient::ParsePacket(NetworkState *s,int peer,SocketMessage *msg){ uint8_t firstByte = msg->Get<uint8_t>(); switch (firstByte){ case 0x01: ParseFirstPacket(msg); break; case 0x02: CreateObject(msg); break; case 0x07: ParseStorageChange(msg);break; case 0x08: ParseChangeHealth(msg);break; case 0x09: ParseAttack(msg);break; case 0x0a: ParseDestroy(msg);break; case 0x0e: ParseProceed(msg); break; case 0x0f: ParseCancel(msg); break; case 0x10: ParseBearAttack(msg); break; case 0x22: ParseEffect(msg); break; case 0xA3: ParseBearMove(msg); break; case 0xBE: ParseCarry(msg); break; default: bear::out << "Unknow packet " << firstByte << "\n"; } } void ProtocolClient::ParseFirstPacket(SocketMessage *msg){ m_myPid = msg->Get<int>(); // My id uint32_t objectCount = msg->Get<uint32_t>(); for (uint32_t i=0;i<objectCount;i++){ if (!CreateObject(msg)){ continue; } } } void ProtocolClient::ParseCancel(SocketMessage *msg){ Order::Cancel(); } void ProtocolClient::ParseDestroy(SocketMessage *msg){ int objId = msg->Get<int>(); GameObject *obj = GetState()->cmap.GetCreatureById(objId); if (obj){ GetState()->cmap.DestroyObject(objId); obj->Kill(); }else{ bear::out << "Attept to destroy "<<objId << ". id not found\n"; } } void ProtocolClient::ParseBearAttack(SocketMessage *msg){ int id = msg->Get<int>(); Burr *bur = (Burr*)GetState()->cmap.GetCreatureById(id); if (bur){ bur->ForceAttack(); } } void ProtocolClient::ParseEffect(SocketMessage *msg){ int x = msg->Get<int>(); int y = msg->Get<int>(); int dmg = msg->Get<int>(); GameLevel::MakeEffect(Point(x,y),dmg); } void ProtocolClient::ParseAttack(SocketMessage *msg){ int objId = msg->Get<int>(); Point pos; pos.x = msg->Get<int>(); pos.y = msg->Get<int>(); GameObject *obj = GetState()->cmap.GetCreatureById(objId); if (obj && obj->Is(TYPEOF(Tower))){ static_cast<Tower*>(obj)->AttackFunction(pos); } } void ProtocolClient::ParseChangeHealth(SocketMessage *msg){ int objId = msg->Get<int>(); int health = msg->Get<int>(); GameObject *obj = GetState()->cmap.GetCreatureById(objId); if (obj && obj->Is(TYPEOF(Enemy))){ static_cast<Enemy*>(obj)->health = health; } } void ProtocolClient::ParseStorageChange(SocketMessage *msg){ int field = msg->Get<int>(); int val = msg->Get<int>(); bear::out << "changed storage to" << val << "\n"; GameLevel::GameStorage[field] = val; } void ProtocolClient::ParseProceed(SocketMessage *msg){ int objId = msg->Get<int>(); GameObject *obj = GetState()->cmap.GetCreatureById(objId); if (obj) Order::Proceed(obj); } void ProtocolClient::RequestTower(int x,int y,int type){ SocketMessage reply; reply.Add<uint8_t>(0x33); reply.Add<int>(x); reply.Add<int>(y); reply.Add<int>(type); ReliableUdpServer::SetSendMode(ENET_PACKET_FLAG_RELIABLE); m_sock->Send(&reply,-1); } bool ProtocolClient::CreateObject(SocketMessage *msg){ int objId = msg->Get<int>(); int objType = msg->Get<int>(); int objOwner = msg->Get<int>(); if (objType == 1){ int x = msg->Get<int>(); int y = msg->Get<int>(); std::string name = msg->GetString(); bear::out << "Created " << objId << " at " << x << ":"<<y<<" named "<<name<<"\n"; if (GetState()->MakeObjectWithId<Burr>(objId,x,y,objOwner == m_myPid,name)){ return true; }else{ bear::out << "Failed to create object!!!!!\n"; } }else if (objType == 2){ int x = msg->Get<int>(); int y = msg->Get<int>(); int typ = msg->Get<int>(); bear::out << "Created " << objId << " at " << x << ":"<<y<<"\n"; if (GetState()->MakeObjectWithId<Tower>(objId,x,y,typ)){ return true; }else{ bear::out << "Failed to create object!!!!!\n"; } }else if (objType == 3){ int pid = msg->Get<int>(); int maxhealth = msg->Get<int>(); int health = msg->Get<int>(); float spd = msg->Get<float>(); int lktp = msg->Get<int>(); int x = msg->Get<int>(); int y = msg->Get<int>(); if (GetState()->MakeObjectWithId<Enemy>(objId,pid,health,spd,lktp,false)){ Enemy *obj = static_cast<Enemy*>(GetState()->cmap.GetCreatureById(objId)); obj->box.x = x; obj->box.y = y; obj->maxHealth = maxhealth; return true; }else{ bear::out << "Failed to create object!!!!!\n"; } }else if (objType == 4){ int x = msg->Get<int>(); int y = msg->Get<int>(); int value = msg->Get<int>(); GetState()->MakeObjectWithId<Seeds>(objId,x,y,value); bear::out << "Made a seederino\n"; return true; } bear::out << "Unknow object id "<<objId<<" typed "<<objType<<"\n"; return false; } void ProtocolClient::ParseCarry(SocketMessage *msg){ int id = msg->Get<int>(); int val = msg->Get<int>(); Burr *obj = (Burr *)GetState()->cmap.GetCreatureById(id); bear::out << "client carry\n"; if (obj){ bear::out << "vav: "<<val<<"\n"; obj->MakeCarry(val); } } void ProtocolClient::ParseBearMove(SocketMessage *msg){ int count = msg->Get<int>(); for (int i=0;i<count;i++){ int id = msg->Get<int>(); int x = msg->Get<int>(); int y = msg->Get<int>(); NetworkObject *obj = GetState()->cmap.GetCreatureById(id); if (obj){ obj->InterpolationBox.x = x; obj->InterpolationBox.y = y; }else{ //bear::out << "Trying to move instance unknow "<<id<<"\n"; } } }
ca15ea7fe81b13f4c5673f011164f286e19be4a3
430b9f703e595cd2308836779c44c6c27ff0aae2
/architect/patten/3-6-mementor/Memento.h
d4eb1d0e716a487e1e80a43e533271b95ff061ec
[]
no_license
menfeng/studynote
66f847115d37243d8ab41fb19bbcf4edaa328889
e7a547f7dcc4b9ad6efafb4937d1ea56efc0d83a
refs/heads/master
2022-10-04T14:23:55.314697
2022-09-22T16:57:44
2022-09-22T16:57:44
70,991,302
0
1
null
null
null
null
UTF-8
C++
false
false
498
h
Memento.h
#ifndef _MEMENTO_H_ #define _MEMENTO_H_ #include <string> using namespace std; class Memento; class Originator { public: Originator(); ~Originator(); void SetState(const string& sdt); Memento* CreateMemento(); void SetMemento(Memento* men); void PrintState(); private: string _sdt; Memento* _mt; }; class Memento { private: friend class Originator; Memento(); ~Memento(); void SetState(const string& sdt); string GetState(); private: string _sdt; }; #endif //~_MEMENTO_H_
e4f9f56f7dda256d0d03af2296c743554c93de7f
279cb529e80f1c59fb1b001aeb77e2a43385f905
/db/fh.h
7d3ff0ac7dc138ece2b0474b6aabcfc823009c4f
[ "LicenseRef-scancode-generic-cla", "BSD-3-Clause" ]
permissive
m4734/leveldb
1c633ae0b07fdd5fd9762971cbc28a249fced75a
9a74b7a472c8b0059cc8063e9e3b6a325851f8e9
refs/heads/master
2022-12-01T09:41:09.107539
2020-08-13T07:21:09
2020-08-13T07:21:09
277,441,717
0
0
null
null
null
null
UTF-8
C++
false
false
454
h
fh.h
//cgmin db/fh.h #ifndef STORAGE_LEVELDB_DB_FH_H_ #define STORAGE_LEVELDB_DB_FH_H_ #include "leveldb/slice.h" #include "util/mutexlock.h" namespace leveldb { class FH //cgmin FH { public: FH(); ~FH(); unsigned int** fv; //byte int bs; // bucket size int fs; // function size port::Mutex mutex_; void add(const Slice& key); //key int get(const Slice& key); //key int hash(int fn,const Slice& key); }; } #endif
470ef5bec1c3542823348dd9fd2187dd358db4da
d9c388807aae8fd961e34ea4f6f5fd6c272003e5
/200615_C++/BJ/11866/tempCodeRunnerFile.cpp
42d227c5def45abb06ed8e13d27a62fc0022fba5
[]
no_license
aksel26/TIL
d2ccf59e58454fed6328432f9be773da6176d450
c962d7a2f42cc1632c85c841c0c03e069179f704
refs/heads/master
2023-03-08T10:06:10.723392
2022-07-29T12:25:33
2022-07-29T12:25:33
188,199,617
2
1
null
2023-03-06T20:50:08
2019-05-23T09:07:02
C++
UTF-8
C++
false
false
45
cpp
tempCodeRunnerFile.cpp
if (!q.empty()) cout << ", ";
8dd48db0259a3b37e4866df8317efa6a9437879e
c5718f09a6e4e7fe8ed375981bbab7693817302f
/Classes/Level/Objects/Crate.h
1b9d915567ac97bf7b298a7f4ae70859a5259ee8
[]
no_license
ryanmcbride/CrashTestMonkeys
3ef3d4917b8d829005fb9b5c991970e86d282be8
236317741c7e769cb43da56cd52ec2681d12aeff
refs/heads/master
2016-09-06T18:51:47.699575
2013-10-01T03:17:03
2013-10-01T03:17:03
10,875,817
0
1
null
null
null
null
UTF-8
C++
false
false
1,107
h
Crate.h
/* * Ramp.h * CTM * * Created by Ryan McBride on 2/26/11. * Copyright 2011 __MyCompanyName__. All rights reserved. * */ #ifndef __CRATE_H__ #define __CRATE_H__ #include "Box2D.h" #include "TrackObject.h" #include "TextureObject.h" class Crate : public TrackObject { public: enum Type { ORIGINAL=0, BEACH_BALL, MAX_TYPES }; Crate(b2World *world, cocos2d::CCNode *ccLayer, b2Vec2 *startPos, float scale = 1.0f); Crate(b2World *world, cocos2d::CCNode *ccLayer, b2Vec2 *startPos, Type type, int sort); virtual ~Crate(); virtual void CreateSelf(); virtual void DestroySelf(); virtual void Update(float xpos,float ypos){TrackObject::Update(xpos,ypos);Step(xpos);} void Step(float xpos); b2Body *GetBody(){return m_MainCollision;} bool HandleBeginContact(b2Fixture *fixtureA,b2Fixture *fixtureB); protected: b2World *m_world; cocos2d::CCNode *m_ccLayer; b2Body *m_MainCollision; TextureObject *m_Texture; TextureObject *m_TextureHighlight; b2Vec2 m_StartPos; float m_Scale; Type m_type; int m_beachBallTexNum; float m_HitDelay; int m_sort; }; #endif
f3581bc492e62a7574a622e297a01891607ae7d9
c242c9c74e7b81399f62d4188aa2590d0726f903
/include/FDQUI/GUI/Widget/OpenGLWidget.h
8e450bfea4c17853fae8e233fe48768192b4c847
[ "Apache-2.0" ]
permissive
benjamin-fukdawurld/FDQUI
75e1ff2340b506b70f90c6b8defe2bd4c52d77a6
95ecc0ebd1ca2ba38865974035bbe7fd1486e16f
refs/heads/master
2021-02-07T10:22:01.872716
2020-06-06T13:05:51
2020-06-06T13:08:44
244,014,201
0
0
null
null
null
null
UTF-8
C++
false
false
1,376
h
OpenGLWidget.h
#ifndef OPENGLWINDOW_H #define OPENGLWINDOW_H #include <FDGL/BaseOpenGLWindow.h> #include <FDGL/OpenGLShaderProgram.h> #include <FDGL/OpenGLVertexArray.h> #include <FDGL/OpenGLTexture.h> #include <FDGL/OpenGLBuffer.h> #include <QOpenGLWidget> #include <FDCore/TimeManager.h> #include <FD3D/SceneGraph/Scene.h> #include <FD3D/SceneGraph/SceneLoader.h> #include <functional> namespace FDQUI { class OpenGLWidget : public QOpenGLWidget, public FDGL::BaseOpenGLWindow { Q_OBJECT public: explicit OpenGLWidget(QWidget *parent = nullptr, Qt::WindowFlags f = Qt::WindowFlags()); ~OpenGLWidget() override; bool create(int width, int height, const std::string &title) override; void destroy() override; bool isOpen() const override; void swapBuffer() const override; std::string getTitle() const override; void setTitle(const std::string &title) override; int getWidth() const override; void setWidth(int w) override; int getHeight() const override; void setHeight(int h) override; protected: void initializeGL() override; void paintGL() override; void resizeGL(int w, int h) override; signals: public slots: }; } #endif // OPENGLWINDOW_H
6108a399c3b70809ba04f9c2ce8118d1a2d9df1c
d0fb46aecc3b69983e7f6244331a81dff42d9595
/cdn/src/model/DescribeCdnWafDomainResult.cc
7b11c46f95cf70381e93741b85a18f4ca10b778d
[ "Apache-2.0" ]
permissive
aliyun/aliyun-openapi-cpp-sdk
3d8d051d44ad00753a429817dd03957614c0c66a
e862bd03c844bcb7ccaa90571bceaa2802c7f135
refs/heads/master
2023-08-29T11:54:00.525102
2023-08-29T03:32:48
2023-08-29T03:32:48
115,379,460
104
82
NOASSERTION
2023-09-14T06:13:33
2017-12-26T02:53:27
C++
UTF-8
C++
false
false
2,519
cc
DescribeCdnWafDomainResult.cc
/* * Copyright 2009-2017 Alibaba Cloud All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <alibabacloud/cdn/model/DescribeCdnWafDomainResult.h> #include <json/json.h> using namespace AlibabaCloud::Cdn; using namespace AlibabaCloud::Cdn::Model; DescribeCdnWafDomainResult::DescribeCdnWafDomainResult() : ServiceResult() {} DescribeCdnWafDomainResult::DescribeCdnWafDomainResult(const std::string &payload) : ServiceResult() { parse(payload); } DescribeCdnWafDomainResult::~DescribeCdnWafDomainResult() {} void DescribeCdnWafDomainResult::parse(const std::string &payload) { Json::Reader reader; Json::Value value; reader.parse(payload, value); setRequestId(value["RequestId"].asString()); auto allOutPutDomainsNode = value["OutPutDomains"]["OutPutDomain"]; for (auto valueOutPutDomainsOutPutDomain : allOutPutDomainsNode) { OutPutDomain outPutDomainsObject; if(!valueOutPutDomainsOutPutDomain["AclStatus"].isNull()) outPutDomainsObject.aclStatus = valueOutPutDomainsOutPutDomain["AclStatus"].asString(); if(!valueOutPutDomainsOutPutDomain["Status"].isNull()) outPutDomainsObject.status = valueOutPutDomainsOutPutDomain["Status"].asString(); if(!valueOutPutDomainsOutPutDomain["Domain"].isNull()) outPutDomainsObject.domain = valueOutPutDomainsOutPutDomain["Domain"].asString(); if(!valueOutPutDomainsOutPutDomain["CcStatus"].isNull()) outPutDomainsObject.ccStatus = valueOutPutDomainsOutPutDomain["CcStatus"].asString(); if(!valueOutPutDomainsOutPutDomain["WafStatus"].isNull()) outPutDomainsObject.wafStatus = valueOutPutDomainsOutPutDomain["WafStatus"].asString(); outPutDomains_.push_back(outPutDomainsObject); } if(!value["TotalCount"].isNull()) totalCount_ = std::stoi(value["TotalCount"].asString()); } int DescribeCdnWafDomainResult::getTotalCount()const { return totalCount_; } std::vector<DescribeCdnWafDomainResult::OutPutDomain> DescribeCdnWafDomainResult::getOutPutDomains()const { return outPutDomains_; }
d5213463b08761756f65a0b807a5d141b0627c60
b8fcf4b302d8d40967554d765412f7128d0fbb2a
/AmFilters/ArpMonophobic.cpp
7af92ab4536530520e5bbb6f9e8c88c620c2aa60
[ "LicenseRef-scancode-public-domain" ]
permissive
HaikuArchives/Sequitur
42f9083980b23089d7930b0ac767f6e12ac71aa5
d7a863be31802132f7d5c76dc50e78e6f100ac13
refs/heads/master
2021-12-26T05:42:47.517340
2021-11-13T13:23:04
2021-11-13T13:23:04
15,569,777
4
5
null
2021-09-26T03:01:12
2014-01-01T20:38:47
C++
UTF-8
C++
false
false
3,216
cpp
ArpMonophobic.cpp
#include "ArpMonophobic.h" #include <cstdio> #include <cstdlib> #include "ArpKernel/ArpDebug.h" ArpMOD(); static AmStaticResources gRes; /***************************************************************************** * ARP-MONOPHOBIC-FILTER *****************************************************************************/ ArpMonophobicFilter::ArpMonophobicFilter( ArpMonophobicAddOn* addon, AmFilterHolderI* holder, const BMessage* settings) : AmFilterI(addon), mAddOn(addon), mHolder(holder), mAmount(1) { if (settings) PutConfiguration(settings); } ArpMonophobicFilter::~ArpMonophobicFilter() { } AmEvent* ArpMonophobicFilter::HandleEvent(AmEvent* event, const am_filter_params* params) { return event; } AmEvent* ArpMonophobicFilter::HandleToolEvent( AmEvent* event, const am_filter_params* params, const am_tool_filter_params* toolParams) { if (!event || !toolParams || !mHolder) return event; event->SetNextFilter(mHolder->FirstConnection() ); AmRange range(event->TimeRange() ); if (event->Type() == event->NOTEON_TYPE) { AmNoteOn* e = dynamic_cast<AmNoteOn*>(event); if (e) e->SetNote(NewNote(e->Note(), range, toolParams) ); } else if (event->Type() == event->NOTEOFF_TYPE) { AmNoteOff* e = dynamic_cast<AmNoteOff*>(event); if (e) e->SetNote(NewNote(e->Note(), range, toolParams) ); } return event; } status_t ArpMonophobicFilter::GetConfiguration(BMessage* values) const { status_t err = AmFilterI::GetConfiguration(values); if (err != B_OK) return err; return B_OK; } status_t ArpMonophobicFilter::PutConfiguration(const BMessage* values) { status_t err = AmFilterI::PutConfiguration(values); if (err != B_OK) return err; return B_OK; } status_t ArpMonophobicFilter::Configure(ArpVectorI<BView*>& panels) { BMessage config; return GetConfiguration(&config); } uint8 ArpMonophobicFilter::NewNote( uint8 oldNote, AmRange noteRange, const am_tool_filter_params* toolParams) { float offset = (toolParams->cur_y_value - toolParams->orig_y_value) * am_x_amount(toolParams, noteRange.start + ((noteRange.end - noteRange.start) / 2)); int32 newNote = int32(oldNote + offset); if (newNote < 0) newNote = 0; else if (newNote > 127) newNote = 127; return uint8(newNote); } /***************************************************************************** * ARP-MONOPHOBIC-ADD-ON *****************************************************************************/ void ArpMonophobicAddOn::LongDescription(BString& name, BString& str) const { AmFilterAddOn::LongDescription(name, str); str << "<P>I am only available in a tool pipeline. I cause all selected \n" "note events to follow the mouse as it is dragged up and down.</P>\n"; } void ArpMonophobicAddOn::GetVersion(int32* major, int32* minor) const { *major = 1; *minor = 0; } BBitmap* ArpMonophobicAddOn::Image(BPoint requestedSize) const { const BBitmap* bm = gRes.Resources().FindBitmap("Class Icon"); if (bm) return new BBitmap(bm); return NULL; } extern "C" _EXPORT AmFilterAddOn* make_nth_filter( int32 n, image_id /*you*/, const void* cookie, uint32 /*flags*/, ...) { if (n == 0) return new ArpMonophobicAddOn(cookie); return NULL; }
4ca0495f310dc8a3e32ec6a406bc4e0dcfc6deac
381d662693f8efd18356c12849d82860e29ef7f6
/jni/hapviz/gimport.cpp
e256847f5231d1d6adff45136e5db2a48779b581
[]
no_license
remoegli/HAPdroid
8e563b078fae871e8d9fa209be6ae1280bbacc5d
8db117915df2bd0ac9a59a08eaa5c6437e83271e
refs/heads/master
2016-08-04T16:55:15.912214
2012-06-25T20:59:33
2012-06-25T20:59:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
48,110
cpp
gimport.cpp
/** * \file gimport.cpp * \brief Binary traffic data import, and * inference of hpg (host profile graphlet) data from flow data. * * This file is subject to the terms and conditions defined in * files 'BSD.txt' and 'GPL.txt'. For a list of authors see file 'AUTHORS'. */ #include <iostream> #include <fstream> #include <sstream> #include <set> #include <string> #include <iterator> #include <cstdio> #include <cstdlib> #include <cstring> #include <assert.h> #include <time.h> #include <errno.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <arpa/inet.h> // Library functions, e.g. ntoh() // Protocol header definitions #include <netinet/in_systm.h> #include <sys/socket.h> #include <net/if.h> #include <netinet/in.h> #include <netinet/ip.h> // IPv4 header #include <netinet/ip6.h> // IPv6 header #include <netinet/tcp.h> // TCP header #include <netinet/udp.h> // UDP header #include <netinet/in.h> // IP protocol types #ifdef __linux__ #include <linux/if_ether.h> // Ethernet header, ethernet protocol types #else #include <netinet/if_ether.h> // Ethernet header, ethernet protocol types #endif // __linux__ #include "zfstream.h" #include "gimport.h" #include "heapsort.h" #include "hpg.h" #include "gutil.h" #include "ggraph.h" #include "HAPviewer.h" #include "cflow.h" #include "gfilter.h" #include "gimport_config.h" #include "android_log.h" using namespace std; #ifdef NDEBUG bool debug =false; bool debug2=false; bool debug3=false; bool debug4=false; bool debug5=false; bool debug6=false; #else bool debug = false; bool debug2 = false; bool debug3 = true; bool debug4 = true; bool debug5 = true; bool debug6 = true; #endif /** * Default constructor */ ChostMetadata::ChostMetadata() { IP = IPv6_addr(); flow_count = 0; prot_count = 0; packet_count = 0; index = 0; bytesForAllFlows = 0; } /** * Simple constructor: pick data from memory instead from input file. * * \param flowlist Source flowlist. * \param newprefs Preferences settings */ CImport::CImport(const CFlowList & flowlist, const prefs_t & newprefs) : full_flowlist(flowlist), active_flowlist(full_flowlist.begin(), full_flowlist.end()), prefs(newprefs) { next_host_idx = full_flowlist.begin(); use_reverse_index = true; hpg_filename = default_hpg_filename; // No input file name to derive hpg file name from next_host = 0; } /** * Constructor: initialize * * \param in_filename Name of data input file. * \param out_filename Name of data ouput file (*.hpg). * \param newprefs Preferences settings */ CImport::CImport(const std::string & in_filename, const std::string & out_filename, const prefs_t & newprefs) : prefs(newprefs) { // Store parameter for later use this->in_filename = in_filename; // prefs->show_prefs(); if (!acceptForImport(in_filename)) { string errtext = "Invalid file name: " + in_filename; LOGE(errtext.c_str()); } hpg_filename = out_filename; cout << "out_filename: " << out_filename << endl; // Initialize flow list next_host_idx = full_flowlist.begin(); // flowlist_allocated = false; use_reverse_index = true; next_host = 0; } /** * Prepare r_index for outside graphlets. * * By use of the r_index it is possible to construct graphlets from the outside * perspective. This is used by the IP-based graphlet search function (go to IP address). */ void CImport::prepare_reverse_index() { cout << "Preparing index for remote IP-based outside graphlet look-up.\n"; // Use 2 auxiliary arrays for sorting vector<IPv6_addr> IPs(full_flowlist.size()); remoteIP_index.resize(full_flowlist.size()); // Initialize sorting indices // IPs = localIP // r_index = index into all_flowlist for (unsigned int j = 0; j < full_flowlist.size(); j++) { IPs[j] = full_flowlist[j].remoteIP; remoteIP_index[j] = j; } // Now sort arrays such that IPs have ascending order // ({IP, index} pairs are preserved) heapSort(IPs, remoteIP_index); cout << "Done.\n"; } /** * Prepare all_flowlist. * This includes sorting by ascending order of localIP, * and qualifying uniflows exchanged between host pairs that * otherwise communicate bidirectionally. * */ void CImport::prepare_flowlist() { LOGD("preparing flowlist"); // (3) Fill final flowlist // *********************** // The final all_flowlist has to be sorted in ascending order of localIPs. // Additionally, uniflow qualification is performed, i.e. uniflows exchanged between // hosts which also exchange biflows, are marked as "potential productive uniflows" // a) Sort arrays such that IPs have ascending order sort(full_flowlist.begin(), full_flowlist.end()); // Not necessary on cflow lists but still leave it here as we got way too many unsorted examples active_flowlist.invalidate(); active_flowlist.setBegin(full_flowlist.begin()); active_flowlist.setEnd(full_flowlist.end()); // b) Perform uniflow qualification // -------------------------------- // As a result we know which uniflows are productive, i.e. involve // a host pair that also exchanges biflows. // Loop 1: // Go through flowlist and store each host pair in hash map "flowHmHostPair" // key = {IP1,IP2 }, value=biflow count FlowHashMapHostPair * flowHmHostPair = new FlowHashMapHostPair(); FlowHashMapHostPair::iterator FlowHashMapHostPairIterator; cout << "Preparing for qualification of uniflows." << endl; int host_pairs = 0; for (CFlowList::iterator flowiterator = full_flowlist.begin(); flowiterator != full_flowlist.end(); flowiterator++) { // Go through all flows // Show progress on console static int i = 0; if (((i++ % 100000) == 0) && (i > 0)) { cout << "."; cout.flush(); } int biflow_inc = ((flowiterator->flowtype & biflow) != 0) ? 1 : 0; FlowHashKeyHostPair hostPairKey((flowiterator->localIP), (flowiterator->remoteIP)); FlowHashMapHostPairIterator = flowHmHostPair->find(hostPairKey); if (FlowHashMapHostPairIterator == flowHmHostPair->end()) { // New host pair (*flowHmHostPair)[hostPairKey] = biflow_inc; host_pairs++; } else { // An entry exists FlowHashMapHostPairIterator->second = FlowHashMapHostPairIterator->second + biflow_inc; // Update entry by biflow count } } // Loop 2: // For each uniflow check if there has been at least one biflow between the involved host pair. // If yes then mark flow as flow type "unibiflow". int uniflow_count = 0; int unibiflow_count = 0; int uIP_error = 0; for (CFlowList::iterator flowiterator = full_flowlist.begin(); flowiterator < full_flowlist.end(); flowiterator++) { // Go through all flows // Show progress on console static int i = 0; if (((i++ % 100000) == 0) && (i > 0)) { cout << "."; cout.flush(); } if ((flowiterator->flowtype & uniflow) != 0) { uniflow_count++; FlowHashKeyHostPair hostPairKey((flowiterator->localIP), (flowiterator->remoteIP)); FlowHashMapHostPairIterator = flowHmHostPair->find(hostPairKey); if (FlowHashMapHostPairIterator != flowHmHostPair->end()) { // Host pair found if (FlowHashMapHostPairIterator->second > 0) { // There is at least one biflow between involved host pair: qualify flow flowiterator->flowtype |= unibiflow; unibiflow_count++; } } } } delete flowHmHostPair; cout << "Done (qualified a total of " << unibiflow_count << " of " << uniflow_count << " uniflows)"; cout << " out of a total of " << full_flowlist.size() << " flows. We have a total of " << host_pairs << " host pairs.\n"; if (uIP_error > 0) cerr << "\n\nERROR: found " << uIP_error << " unexpected new IP address(es) in " << __func__ << "()..\n\n"; if (false) { // was debug 2 char text[200]; for (unsigned int i = 0; i < full_flowlist.size(); i++) { util::record2String(full_flowlist[i], text); cout << text; } } // (4) Prepare r_index for outside graphlets // ***************************************** prepare_reverse_index(); } /** * Set active flowlist to section starting with a particular local IP address * and ending after all flows belonging to host_count hosts. * * \param IP IP address to be used for local IP (use 0 to specify first localIP found) * \param host_count Count of hosts relevant to set new flowlist end (-1: reset to full flowlist) * * \return bool TRUE if success, false if IP not found in flowlist */ bool CImport::set_localIP(IPv6_addr newLocalIP, int host_count) { if (host_count < 0) { // IP=0 is reserved to reset active flowlist to full flowlist active_flowlist.invalidate(); active_flowlist.setBegin(full_flowlist.begin()); active_flowlist.setEnd(full_flowlist.end()); return true; } // Search for first flow belonging to requested IP // (this flow will have final value of variable flowlistIterator_start) CFlowList::iterator flowlistIterator_start = full_flowlist.begin(); while (flowlistIterator_start != full_flowlist.end()) { if (flowlistIterator_start->localIP == newLocalIP) { break; } else { flowlistIterator_start++; } } // Check if requested IP has been found or not. if (flowlistIterator_start != full_flowlist.end()) { // We have found requested IP: // Now, search for first flow belonging to a host after we have // seen flows belonging to a total of "host_count" hosts. // (this flow will have final value of variable j) CFlowList::iterator flowlistIterator_end = flowlistIterator_start; IPv6_addr lastIP = flowlistIterator_end->localIP; unsigned int hc = 0; // Host iterator while (hc < (unsigned int) host_count && flowlistIterator_end != active_flowlist.end()) { if (flowlistIterator_end->localIP != lastIP) { lastIP = flowlistIterator_end->localIP; hc++; } else flowlistIterator_end++; } if (flowlistIterator_end - flowlistIterator_start <= 0) { cerr << "ERROR: no flows found for requested IP.\n"; return false; } else { // Found a valid sub-list: make it the new active flowlist active_flowlist.invalidate(); active_flowlist.setBegin(flowlistIterator_start); active_flowlist.setEnd(flowlistIterator_end); cout << "This should be the same: " << distance(flowlistIterator_start, flowlistIterator_end) << "==" << getActiveFlowlistSize() << endl; cout << "i=" << distance( CFlowList::const_iterator(full_flowlist.begin()), active_flowlist.begin()) << ", j=" << distance( CFlowList::const_iterator(full_flowlist.begin()), active_flowlist.end()) << ", flow_count=" << getActiveFlowlistSize() << endl; return true; } } else { cerr << "ERROR: IP not found.\n"; return false; } } /** * Transform flow data (from active_flowlist) of a single local hosts into host profile graphlet data. * * If configured then transformation also includes role summarization (configurable per role type). * * Precondition: the flow data stored in flowlist has to be sorted such that all flows belonging to the * same localIP are grouped together. This is essential to separate graphlets from each other. * * Result: output file containing graphlet database (= collection of graphlets described in binary form) * * Overview: * * (I) Initialize * (II) Role Identification * - for all flows identify candidates for client and server role * - prune client and server candidates involved in roles not meeting requirements * - for all flows identify candidates for p2p flows * - from all p2p candidate flows identify candidate p2p roles * - prune p2p candidates involved in roles not meeting requirements * - rate roles to be able to resolve conflicts in step III * - create sub-roles, used for desummarization * - convert multi summary node desummarization to role desummarization * (III) Transform flows & roles to binary "hpg" graphlets. For each localIP do * - Firstly, detect and resolve role conflicts * - Add all not summarized flows to graphlet * - Then, add client/server/p2p role summaries to graphlet(node desummarization is done here) */ void CImport::prepare_graphlet(CGraphlet * graphlet, CRoleMembership & roleMembership) { // (I) Initialize // ************** LOGD("initializing graphlet"); // Role identifiers needed for summarization: CClientRole clientRole(active_flowlist, prefs); CServerRole serverRole(active_flowlist, prefs); CP2pRole p2pRole(active_flowlist, prefs); clientRole.register_rM(roleMembership); serverRole.register_rM(roleMembership); p2pRole.register_rM(roleMembership); //for (uint32_t role_id=1;role_id<100000;role_id++) { // desummarizedRolesSet.insert(role_id); //} CFlowFilter filter(active_flowlist, prefs); // For filtering by flow type and protocol // Summarization by flow type // -------------------------- // Define a mask that defines which flowtypes can participate in roles int sum_flow_mask = 0; if (prefs.summarize_biflows) sum_flow_mask = biflow; if (prefs.summarize_uniflows) sum_flow_mask |= uniflow; // (II) Role Identification // ************************ // Client & server candidate role identification // ============================================= // Go through flow list to check for candidate client and server roles. LOGD("identifying roles"); for (unsigned int i = 0; i < getActiveFlowlistSize(); i++) { if (filter.filter_flow(i)) continue; //util::printFlow(active_flowlist[i]); if ((active_flowlist[i].flowtype & sum_flow_mask) != 0) { clientRole.add_candidate(i); if (prefs.summarize_srv_roles) serverRole.add_candidate(i); } } if (debug && prefs.summarize_srv_roles) { cout << " ** Found " << serverRole.get_role_count() << " potential server roles.\n"; } if (debug && prefs.summarize_clt_roles) { cout << " ** Found " << clientRole.get_role_count() << " potential client roles\n"; } //cout << "client & server pruning\n"; cout.flush(); if (debug2) { cout << "\nBefore client pruning:\n"; roleMembership.print_multi_members(); } // Client & server candidate role purging clientRole.prune_candidates(); if (debug2) { cout << "\nAfter client pruning:\n"; roleMembership.print_multi_members(); } if (debug2) { cout << "\nBefore server pruning:\n"; roleMembership.print_multi_members(); } if (prefs.summarize_srv_roles) serverRole.prune_candidates(); if (debug2) { cout << "\nAfter server pruning:\n"; roleMembership.print_multi_members(); cout << "First p2p role number: " << roleMembership.get_role_num() << endl; } vector<uint32_t>& flow_server_role = serverRole.get_flow_role(); if (prefs.summarize_multclt_roles) { clientRole.check_multiclient(flow_server_role, filter, prefs.summarize_srv_roles); } // P2P role summarization // ====================== // - Identification of p2p candidate flows // - P2P candidate flows purging/ P2p candidate role identification // - P2P role purging LOGD("p2p role summarization"); vector<uint32_t>& flow_client_role = clientRole.get_flow_role(); if (prefs.summarize_p2p_roles) { // Firstly, construct a list of potential p2p flows for (unsigned int i = 0; i < getActiveFlowlistSize(); i++) { if (filter.filter_flow(i)) continue; // Ignore already summarized flows if (flow_client_role[i] == 0 && flow_server_role[i] == 0) p2pRole.add_candidate(i); } if (debug) cout << " ** Found " << p2pRole.get_cand_flow_num() - 1 << " potential p2p flows.\n"; // Secondly, decide which p2p flows to reject p2pRole.prune_candidates(clientRole, serverRole, filter); } // Finalize roles // ************** LOGD("finalizing roles"); vector<uint32_t>& flow_p2p_role = p2pRole.get_flow_role(); vector<uint32_t> single_flow_rolenum(getActiveFlowlistSize()); for (unsigned int j = 0; j < getActiveFlowlistSize(); j++) { if (filter.filter_flow(j)) { single_flow_rolenum[j] = 0; continue; } if (flow_client_role[j] == 0 && flow_server_role[j] == 0 && flow_p2p_role[j] == 0) { single_flow_rolenum[j] = roleMembership.add_single_flow( active_flowlist[j].remoteIP, active_flowlist[j].dPkts); } else { single_flow_rolenum[j] = 0; } } p2pRole.cleanConsumedClientRoles(clientRole); roleMembership.fill_summaryNodeList(); clientRole.cleanConsumedClientRoles(); if (debug) { cout << "\nAfter p2p pruning:\n"; roleMembership.print_multi_members(); roleMembership.print_multisummary_rolecount(); } // rate all generated roles clientRole.rate_roles(full_flowlist); serverRole.rate_roles(full_flowlist); p2pRole.rate_roles(full_flowlist); // create sub-roles required for part. desummarization for all flow types serverRole.create_sub_roles(); // both client & multiclient clientRole.create_sub_roles(); p2pRole.create_sub_roles(); calculate_multi_summary_node_desummarizations(roleMembership); // (III) Process selected flows to graphlet data // *************************************************** // // a) Firstly, go through all flows not being member of a client role and store edge information. // b) Secondly, add client/server/p2p role summaries as needed to edge information. LOGD("processing flows to graphlet data"); // Remember new localIP for change testing IPv6_addr lastIP = active_flowlist[0].localIP; // Get 1. localIP uint32_t i = 0; uint32_t ambiguous_cs_roles_flows = 0; uint32_t ambiguous_cp2p_roles_flows = 0; uint32_t ambiguous_sp2p_roles_flows = 0; uint32_t filtered_flows = 0; uint32_t summarized_flows = 0; while (i < getActiveFlowlistSize()) { // // (IIIa) Fetch next flow and update current graphlet data // ****************************************************** // Check for ambiguous roles (i.e. flows being members > 1 role) // -----===== conflict resolution start =====----- // We resolve role conflicts by comparing the previously calculated role ratings. // The role with the higher rating keeps the flow, the other one loses it. if ((flow_client_role[i] != 0) && (flow_server_role[i] != 0) && prefs.summarize_clt_roles && prefs.summarize_srv_roles) { float clt_rating = clientRole.getRating(flow_client_role[i]); float srv_rating = serverRole.getRating(flow_server_role[i]); if (debug6) { cout << "INFO: ambiguous roles (client(" << flow_client_role[i] << "," << clt_rating << ")+server(" << flow_server_role[i] << "," << srv_rating << ")) for flow: " << i << endl; cout << ((clt_rating < srv_rating) ? "server" : "client") << " wins" << endl; } CRole::role_t* client_role = clientRole.getRole( flow_client_role[i]); CRole::role_t* srv_role = serverRole.getRole(flow_server_role[i]); if (client_role == NULL || srv_role == NULL) { // can't resolve cerr << "unable to resolve role conflict between client and server(" << i << ")" << endl; ambiguous_cs_roles_flows++; } else { // conflict resolution bool was_successful; // try to resolve conflict using role rating information. if not possible because of a limit(min number of flows per role), invalidate the role to free the flows if (srv_rating <= clt_rating) { was_successful = srv_role->removeFlow(i, active_flowlist, roleMembership); if (!was_successful) { was_successful = invalidate_role((*srv_role), flow_server_role, active_flowlist, roleMembership); } } else { was_successful = client_role->removeFlow(i, active_flowlist, roleMembership); if (!was_successful) { was_successful = invalidate_role((*client_role), flow_client_role, active_flowlist, roleMembership); } } if (!was_successful) { cerr << "role conflict resolution not successful" << endl; } else { if (debug6) { cout << "role conflict resolved" << endl; } } } } else if ((flow_client_role[i] != 0) && (flow_p2p_role[i] != 0) && prefs.summarize_clt_roles && prefs.summarize_p2p_roles) { float clt_rating = clientRole.getRating(flow_client_role[i]); float p2p_rating = p2pRole.getRating(flow_p2p_role[i]); if (debug6) { cout << "INFO: ambiguous roles (client(" << flow_client_role[i] << "," << clt_rating << ")+p2p(" << flow_p2p_role[i] << "," << p2p_rating << ")) for flow: " << i << endl; cout << ((clt_rating < p2p_rating) ? "p2p" : "client") << " wins" << endl; } CRole::role_t* client_role = clientRole.getRole( flow_client_role[i]); CRole::role_t* p2p_role = p2pRole.getRole(flow_p2p_role[i]); if (client_role == NULL || p2p_role == NULL) { // can't resolve cerr << "unable to resolve role conflict between client and p2p(" << i << ")" << endl; ambiguous_cp2p_roles_flows++; } else { // conflict resolution bool was_successful; // try to resolve conflict using role rating information. if not possible because of a limit(min number of flows per role), invalidate the role to free the flows if (p2p_rating <= clt_rating) { was_successful = p2p_role->removeFlow(i, active_flowlist, roleMembership); if (!was_successful) { was_successful = invalidate_role((*p2p_role), flow_p2p_role, active_flowlist, roleMembership); } } else { was_successful = client_role->removeFlow(i, active_flowlist, roleMembership); if (!was_successful) { was_successful = invalidate_role((*client_role), flow_client_role, active_flowlist, roleMembership); } } if (!was_successful) { cerr << "role conflict resolution not successful" << endl; } else { if (debug6) { cout << "role conflict resolved" << endl; } } } } else if ((flow_server_role[i] != 0) && (flow_p2p_role[i] != 0) && prefs.summarize_srv_roles && prefs.summarize_p2p_roles) { float srv_rating = serverRole.getRating(flow_server_role[i]); float p2p_rating = p2pRole.getRating(flow_p2p_role[i]); if (debug6) { cout << "INFO: ambiguous roles (server(" << flow_server_role[i] << "," << srv_rating << ")+p2p(" << flow_p2p_role[i] << "," << p2p_rating << ")) for flow: " << i << endl; cout << ((srv_rating < p2p_rating) ? "p2p" : "server") << " wins" << endl; } CRole::role_t* srv_role = serverRole.getRole(flow_server_role[i]); CRole::role_t* p2p_role = p2pRole.getRole(flow_p2p_role[i]); if (srv_role == NULL || p2p_role == NULL) { // can't resolve cerr << "unable to resolve role conflict between server and p2p(" << i << ")" << endl; ambiguous_sp2p_roles_flows++; } else { // conflict resolution bool was_successful; // try to resolve conflict using role rating information. if not possible because of a limit(min number of flows per role), invalidate the role to free the flows if (p2p_rating <= srv_rating) { was_successful = p2p_role->removeFlow(i, active_flowlist, roleMembership); if (!was_successful) { was_successful = invalidate_role((*p2p_role), flow_p2p_role, active_flowlist, roleMembership); } } else { was_successful = srv_role->removeFlow(i, active_flowlist, roleMembership); if (!was_successful) { was_successful = invalidate_role((*srv_role), flow_server_role, active_flowlist, roleMembership); } } if (!was_successful) { cerr << "role conflict resolution not successful" << endl; } else { if (debug6) { cout << "role conflict resolved" << endl; } } } } // -----===== conflict resolution end =====----- if (filter.filter_flow(i)) { filtered_flows++; } else if ((prefs.summarize_clt_roles && (flow_client_role[i] != 0)) || (prefs.summarize_srv_roles && (flow_server_role[i] != 0)) || (prefs.summarize_p2p_roles && (flow_p2p_role[i] != 0))) { // Do not process flows that are summarized (part of a role) summarized_flows++; } else { // Add current flow to graphlet: this is an unsummarized flow graphlet->add_single_flow(active_flowlist[i], single_flow_rolenum[i], i); } // Switch to next flow i++; } // (IIIb) Summarize pending roles // ============================== // LOGD("summarizing client roles"); if (prefs.summarize_clt_roles) { // Add client summary nodes to graphlet // Add client roles int c = 0; CRole::role_t * role = clientRole.get_next_role(); while (role != NULL) { if (role->role_num != 0) { // Role number 0 marks an invalidated role if (debug2) { cout << "Client role " << c++ << endl; } graphlet->add_generic_role( *(role->getUsedSubRole(desummarizedRolesSet, desummarizedMultiNodeRolesSet)), *role, lastIP, active_flowlist); } role = clientRole.get_next_role(); } } LOGD("summarizing multi-client roles"); if (prefs.summarize_multclt_roles) { // Add multi-client summary nodes to graphlet // Add multi-client roles int c = 0; CRole::role_t * role = clientRole.get_next_mrole(); while (role != NULL) { if (role->role_num != 0) { // Role number 0 marks an invalidated role if (debug2) { cout << "Multi-client role " << c++ << endl; } graphlet->add_generic_role( *(role->getUsedSubRole(desummarizedRolesSet, desummarizedMultiNodeRolesSet)), *role, lastIP, active_flowlist); } role = clientRole.get_next_mrole(); } } LOGD("summarizing server roles"); if (prefs.summarize_srv_roles) { // Add server summary nodes to graphlet // Add server roles int c = 0; CRole::role_t * role = serverRole.get_next_role(); while (role != NULL) { if (role->role_num != 0) { // Role number 0 marks an invalidated role if (debug2) { cout << "Server role " << c++ << endl; } LOGD("add summarized server role"); graphlet->add_generic_role( *(role->getUsedSubRole(desummarizedRolesSet, desummarizedMultiNodeRolesSet)), *role, lastIP, active_flowlist); } role = serverRole.get_next_role(); } } LOGD("summarizing p2p roles"); if (prefs.summarize_p2p_roles) { // Add p2p summary nodes to graphlet // Add p2p roles int c = 0; CRole::role_t * role = p2pRole.get_next_role(); while (role != NULL) { if (role->role_num != 0) { // Role number 0 marks an invalidated role if (debug2) { cout << "P2P role " << c++ << endl; } graphlet->add_generic_role( *(role->getUsedSubRole(desummarizedRolesSet, desummarizedMultiNodeRolesSet)), *role, lastIP, active_flowlist); } role = p2pRole.get_next_role(); } } if (ambiguous_cs_roles_flows > 0) cerr << "INFO: ambiguous roles (client+server) for " << ambiguous_cs_roles_flows << " flows.\n"; if (ambiguous_cp2p_roles_flows > 0) cerr << "INFO: ambiguous roles (client+p2p) for " << ambiguous_cp2p_roles_flows << " flows.\n"; if (ambiguous_sp2p_roles_flows > 0) cerr << "INFO: ambiguous roles (server+p2p) for " << ambiguous_sp2p_roles_flows << " flows.\n"; if (summarized_flows) cout << "Summarized flows: " << summarized_flows << endl; if (filtered_flows) cout << "Filtered flows: " << filtered_flows << " out of " << getActiveFlowlistSize() << " flows." << endl; if (debug) { desummarizedRoles::const_iterator dri; cout << "desummarized roles:\t"; for (dri = desummarizedRolesSet.begin(); dri != desummarizedRolesSet.end(); dri++) { cout << (*dri) << ","; } cout << endl; roleMembership.print_multi_members(); roleMembership.print_multisummary_rolecount(); if (hap4nfsen) { cout << nodeInfos->printNodeInfos() << endl; } } } /** * Create binary "hpg" output data from edge information collected in * prepae_graphlet. * * \exception std::string Errorstring * */ void CImport::cflow2hpg() { std::ofstream outfs; try { util::open_outfile(outfs, hpg_filename); } catch (string & e) { stringstream error; error << "Could not open output file: " << hpg_filename; throw error.str(); } CRoleMembership roleMembership; // Manages groups of hosts having same role membership set CGraphlet * graphlet = new CGraphlet(outfs, roleMembership); prepare_graphlet(graphlet, roleMembership); // Finalize current graphlet and prepare for a next one // ========================================================== // Next flow belongs to new localIP: thus, finalize current host graphlet. // graphlet->finalize_graphlet(0); if (hap4nfsen) { nodeInfos = graphlet->nodeInfos; } outfs.close(); delete graphlet; } /** * Invalidate a specific role. used in role conflict resolution * * \param role_to_be_invalidated Role to be desummarized * \param role_conflict_cector A set of desummarized roles * \param active_flowlist List containing all currently active flows * \param roleMembership Role membership object * * \return bool true, if role invalidation was sucessful */ bool CImport::invalidate_role(CRole::role_t& role_to_be_invalidated, vector<uint32_t>& role_conflict_vector, Subflowlist& active_flowlist, CRoleMembership& roleMembership) { // invalidate role if (debug6) { cout << "invalidating role:" << endl; role_to_be_invalidated.print_role(); } set<int> freed_flows = role_to_be_invalidated.invalidate(roleMembership); assert(freed_flows.size()>0); // remove references set<int>::const_iterator flow_id; for (set<int>::const_iterator flow_id = freed_flows.begin(); flow_id != freed_flows.end(); ++flow_id) { assert((*flow_id)>=0 && (*flow_id)<(int)role_conflict_vector.size()); role_conflict_vector[*flow_id] = 0; } assert(role_to_be_invalidated.flows==freed_flows.size()); return true; } /** * Returns all desummarized roles * * \return desummarizedRoles A set of desummarized roles */ const desummarizedRoles CImport::get_desummarized_roles() { return desummarizedRolesSet; } /** * Set the desummarized roles * * \param desummarizedRoles A set of desummarized roles */ void CImport::set_desummarized_roles(const desummarizedRoles & role_set) { desummarizedRolesSet.clear(); add_desummarized_roles(role_set); } /** * Adds roles to the desummarzied ones * * \param desummarizedRoles Desummarized roles to add */ void CImport::add_desummarized_roles(const desummarizedRoles & role_set) { desummarizedRolesSet.insert(role_set.begin(), role_set.end()); } /** * Delete all desummarizes roles */ void CImport::clear_desummarized_roles() { desummarizedRolesSet.clear(); desummarizedMultiNodeRolesSet.clear(); } /** * Calculates which multi-summary nodes have to be desummarized * * \param roleMembership Holds the membership of the cflows */ void CImport::calculate_multi_summary_node_desummarizations( CRoleMembership & roleMembership) { const uint32_t MULTI_SUM_NODE_MASK = 0x00f00000; // value is only 24 bit const uint32_t MULTI_SUM_NODE_SHIFT = 23; // 24 bit-1 bit set<int> multi_sum_node_ids; for (desummarizedRoles::const_iterator role_iter = desummarizedRolesSet.begin(); role_iter != desummarizedRolesSet.end(); ++role_iter) { roleNumber role = *role_iter; if (((role & MULTI_SUM_NODE_MASK) >> MULTI_SUM_NODE_SHIFT) == 1) { // role is a multi summary node id cout << "[1]" << role << endl; int multi_node_id = (((int) (ROLE_NR_BIT_MASK - role)) * -1) - 1; // must be a(signed) integer because multi sum ids use negative role numbers cout << "[2]" << multi_node_id << endl; multi_sum_node_ids.insert(multi_node_id); } } CRoleMembership::multiSummaryNodeHashMap* m_s_nodes = roleMembership.get_hm_multiSummaryNode(); for (CRoleMembership::multiSummaryNodeHashMap::const_iterator m_sum_iter = m_s_nodes->begin(); m_sum_iter != m_s_nodes->end(); ++m_sum_iter) { int multi_node_id = m_sum_iter->second->role_num; //cout << "candidate: " << multi_node_id << endl; set<int>::const_iterator mn_id_iter = multi_sum_node_ids.find( multi_node_id); if (mn_id_iter != multi_sum_node_ids.end()) { // multi-node should be desummarized if (debug6) { m_sum_iter->first.printkey(); } cout << "found!" << endl; const boost::array<uint16_t, 8> roles = m_sum_iter->first.getRoles(); cout << util::bin2hexstring(&roles, 16) << endl; for (boost::array<uint16_t, 8>::const_iterator role_iter = roles.begin(); role_iter != roles.end(); ++role_iter) { cout << "contains role: " << (*role_iter) << endl; desummarizedMultiNodeRolesSet.insert(*role_iter); // store values so they can later be used in getUsedSubRole } } } } /** * Get host metadata from "flowlist" and store it in "hostMetadata". */ void CImport::get_hostMetadata() { // Scan flow list and assemble for each localIP the metadata assert(getActiveFlowlistSize() > 0); IPv6_addr lastIP = active_flowlist[0].localIP; // Get 1. localIP int hostFlowIndex = 0; int host_flows = 0; set<uint8_t> proto_set; int maxnum_hosts = 1; for (unsigned int j = 0; j < getActiveFlowlistSize(); j++) { if (active_flowlist[j].localIP != lastIP) { maxnum_hosts++; lastIP = active_flowlist[j].localIP; } } cout << "Input file " << in_filename << " contains " << maxnum_hosts << " unique local hosts.\n"; hostMetadata.resize(maxnum_hosts); Subflowlist::const_iterator it = active_flowlist.begin(); int host_index = -1; while (it != active_flowlist.end()) { // Check if host data is complete if (it->localIP != hostMetadata[host_index].IP || it == active_flowlist.begin()) { host_index++; hostMetadata[host_index].IP = it->localIP; hostMetadata[host_index].graphlet_number = host_index; hostMetadata[host_index].uniflow_count = 0; hostMetadata[host_index].packet_count = 0; hostMetadata[host_index].bytesForAllFlows = 0; hostMetadata[host_index].prot_count = 0; hostMetadata[host_index].index = 0; host_flows = 0; proto_set.clear(); // Prepare for next host hostFlowIndex = distance(active_flowlist.begin(), it); // Remember new srcIP for change testing assert((unsigned int)host_index <= hostMetadata.size()); // // Show progress on console // if ((host_index % 10000) == 0) { // cout << "."; // cout.flush(); // } } if (it->flowtype & uniflow) hostMetadata[host_index].uniflow_count++; hostMetadata[host_index].packet_count += it->dPkts; hostMetadata[host_index].bytesForAllFlows += it->dOctets; proto_set.insert(it->prot); hostMetadata[host_index].prot_count = proto_set.size(); hostMetadata[host_index].index = hostFlowIndex; hostMetadata[host_index].flow_count = ++host_flows; it++; } next_host = 0; cout << "\nMetadata for " << host_index + 1 << " local hosts prepared.\n"; } /** * Return first host metadata (graphlet property) object. * * \return Reference to host property object * * \pre hostMetadata.size() > 0 * * \exception std::string Errormessage */ const ChostMetadata & CImport::get_first_host_metadata() { if (hostMetadata.size() > 0) { next_host = 1; return hostMetadata[0]; } throw "invalid access to an empty hostMetadata"; } /** * Return next host metadata (graphlet property) object. * Use get_first_host() to scan list from beginning. * * \return Reference to host property object * * \pre next_host < hostMetadata.size() - 1 * * \exception std::string Errormessage */ const ChostMetadata & CImport::get_next_host_metadata() { if (next_host < ((int) hostMetadata.size())) { return hostMetadata[next_host++]; } throw "invalid access behind the last element of hostMetadata"; } /** * Get a list of flows * * \param flIndex Index into flowlist * \param flow_count Number of flows * * \return Subflowlist Subflowlist which ranges from flIndex to flIndex + flow_count in full_flowlist * * \pre full_flowlist.size() >= flIndex + flow_count */ Subflowlist CImport::get_flow(unsigned int flIndex, unsigned int flow_count) const { assert(full_flowlist.size() >= flIndex + flow_count); return Subflowlist(full_flowlist.begin() + flIndex, full_flowlist.begin() + flIndex + flow_count); } /** * Get the flowlist belonging to a graphlet of a remote host (remoteIP). * Go through flow list and pick any flow containing remoteIP. To do this we need * a previously initialized array r_index that contains an index such that remoteIPs are * sorted in ascending order. All found flows are stored in a new temporary flowlist * allocated on the fly for the requested remoteIP. * * \param remoteIP IP address of a remote host * \return CFlowList flowlist */ const CFlowList CImport::get_outside_graphlet_flows(IPv6_addr remoteIP) { // Search for first flow belonging to graphlet unsigned int i = 0; for (; i < full_flowlist.size(); i++) { int ii = remoteIP_index[i]; if (full_flowlist[ii].remoteIP == remoteIP) break; } int flow_cnt = 0; unsigned int j = 0; if (i < full_flowlist.size()) { // Check if any flows found: i points to first such flow // Count the number of flows belonging to graphlet j = i + 1; // A flow has been found: look for more for (; j < full_flowlist.size(); j++) { int jj = remoteIP_index[j]; if (full_flowlist[jj].remoteIP != remoteIP) break; // Found all flows } flow_cnt = j - i; // j points to first flow not belonging to graphlet } CFlowList flows(flow_cnt); if (flows.size() > 0) { // Now we are going to allocate and fill the graphlet's temporary flowlist // flows = new cflow_t[flow_cnt + 1]; // flows[flow_cnt].remoteIP = util::getDummyIpV6(); // Use extra entry for finalization check for (unsigned int k = 0; k < flows.size(); k++) { // Copy flow records in sorted order cflow_t temp = full_flowlist[remoteIP_index[i + k]]; flows[k] = temp; // Make a copy and modify then direction-dependent fields // Exchange local <-> remote flows[k].localIP = temp.remoteIP; flows[k].remoteIP = temp.localIP; flows[k].localPort = temp.remotePort; flows[k].remotePort = temp.localPort; // Adjust flow direction if needed if ((temp.flowtype & uniflow) == uniflow) { ; // Do not modify transit flows } else if ((temp.flowtype & inflow) != 0) { temp.flowtype = (temp.flowtype & (~inflow)) | outflow; } else if ((temp.flowtype & outflow) != 0) { temp.flowtype = (temp.flowtype & (~outflow)) | inflow; } flows[k].flowtype = temp.flowtype; } if (debug2) { cout << "First 20 flows for this graphlet:\n"; for (int i = 0; i < 20; i++) { cout << flows[i] << endl; } } } return flows; } /** * Print current content of flowlist in human readable form to console. * * \param linecount Maximal count of flow to display (0: for all) */ void CImport::print_flowlist(unsigned int linecount) { if (getActiveFlowlistSize() == 0) { cout << "Empty flow list: nothing to print.\n"; } else { cout << "Flow list contains " << getActiveFlowlistSize() << " flows.\n"; unsigned int maxcount = (linecount < getActiveFlowlistSize()) && (linecount != 0) ? linecount : getActiveFlowlistSize(); copy(active_flowlist.begin(), active_flowlist.begin() + maxcount, ostream_iterator<cflow_t>(cout, "\n")); } } /** * Return the hpg filename in use * * \return std::string Name of the hpg filename used */ std::string CImport::get_hpg_filename() const { return hpg_filename; } /** * Return the input filename in use * * \return std::string Name of the file which will be read */ std::string CImport::get_in_filename() const { return in_filename; } /** * Returns the number of cflows in the full_flowlist * * \return int Number of elements in full_flowlist */ int CImport::get_flow_count() const { return full_flowlist.size(); } /** * Return true if there is a gfilter which can read the supplied file * * \param in_filename Filename to check * * \return bool True if there is a gfilter available for this filetype, false if not */ bool CImport::acceptForImport(const string & in_filename) { std::vector<GFilter *>::iterator importfilterIterator; if (inputfilters.empty()) initInputfilters(); for (importfilterIterator = inputfilters.begin(); importfilterIterator != inputfilters.end(); importfilterIterator++) { if ((*importfilterIterator)->acceptFileForReading(in_filename)) return true; } return false; } /** * Return true if there is a gfilter which can write to the supplied file * * \param in_filename Filename to check * * \return bool True if there is a gfilter available for this filetype, false if not */ bool CImport::acceptForExport(const string & out_filename) { std::vector<GFilter *>::iterator importfilterIterator; if (inputfilters.empty()) initInputfilters(); for (importfilterIterator = inputfilters.begin(); importfilterIterator != inputfilters.end(); importfilterIterator++) { if ((*importfilterIterator)->acceptFileForWriting(out_filename)) return true; } return false; } /** * Writes a flowlist to the given file * * \param in_filename Filename to write to * \param subflowlist Subflowlist to write to * * \exception std::string Errormessage */ void CImport::write_file(std::string out_filename, const Subflowlist & subflowlist, bool appendIfExisting) { std::vector<GFilter *>::iterator filterIterator; if (inputfilters.empty()) initInputfilters(); // for (filterIterator = inputfilters.begin(); // filterIterator != inputfilters.end(); filterIterator++) { // if ((*filterIterator)->acceptFileForWriting(out_filename)) { // try { // (*filterIterator)->write_file(out_filename, subflowlist, // appendIfExisting); // } catch (string & e) { // throw e; // } // return; // } // } throw "no usable exportfilter found"; } /** * Writes a flowlist to the given file * * \param in_filename Filename to write to * * \exception std::string Errormessage */ void CImport::write_file(std::string out_filename, const CFlowList & flowlist, bool appendIfExisting) { Subflowlist sublist(flowlist.begin(), flowlist.end()); write_file(out_filename, sublist, appendIfExisting); } /** * Return the name of the filetype of the give filename * * \param in_filename Filename to check * * \return std::string Filetype of given filename or "none" if no gfilter accepts the supplied filename */ std::string CImport::getFormatName(std::string & in_filename) { std::vector<GFilter *>::iterator importfilterIterator; if (inputfilters.empty()) initInputfilters(); for (importfilterIterator = inputfilters.begin(); importfilterIterator != inputfilters.end(); importfilterIterator++) { if ((*importfilterIterator)->acceptFileForReading(in_filename)) return (*importfilterIterator)->getFormatName(); } return "none"; } /** * Return the name of the filetypes supported * * \return vector<std::string> Vector of supported filetypes */ vector<std::string> CImport::getAllFormatNames() { std::vector<GFilter *>::iterator importfilterIterator; vector<string> allTypeNames; if (inputfilters.empty()) initInputfilters(); for (importfilterIterator = inputfilters.begin(); importfilterIterator != inputfilters.end(); importfilterIterator++) allTypeNames.push_back((*importfilterIterator)->getFormatName()); return allTypeNames; } /** * Return the human readable patterns of the filetypes supported * * \return vector<std::string> Vector of patterns of supported filetypes */ vector<std::string> CImport::getAllHumanReadablePatterns() { std::vector<GFilter *>::iterator importfilterIterator; vector<string> allTypeNames; if (inputfilters.empty()) initInputfilters(); for (importfilterIterator = inputfilters.begin(); importfilterIterator != inputfilters.end(); importfilterIterator++) allTypeNames.push_back( (*importfilterIterator)->getHumanReadablePattern()); return allTypeNames; } /** * Print all supported filetypes to an ostream * * \return std::ostream Reference to used ostream */ std::ostream & CImport::printAllTypeNames(std::ostream & os) { vector<string> allTypeNames = getAllFormatNames(); vector<string>::iterator it = allTypeNames.begin(); os << (it != allTypeNames.end() ? *it : ""); for (; it != allTypeNames.end(); ++it) os << *it << endl; return os; } /** * Return all supported filetypes as a string, separated with ", " * * \return std::ostream Reference to used ostream */ std::string CImport::getFormatNamesAsString() { vector<string> allTypeNames = getAllFormatNames(); string ret; vector<string>::iterator it = allTypeNames.begin(); ret += (it != allTypeNames.end() ? *it : ""); for (; it != allTypeNames.end(); ++it) { ret += ", "; ret += *it; } return ret; } /** * Reads the (previously) set filename into memory * * \param local_net Local network address * \param netmask Network mask for local network address * * \pre one of the installed GFilter supports the given file * * \exception string Errortext */ void CImport::read_file(const IPv6_addr & local_net, const IPv6_addr & netmask) { ifstream cflow_compressed_inputstream; uint32_t uncompressed_size = 0; try { util::open_infile(cflow_compressed_inputstream, in_filename); } catch (...) { string errormsg = "ERROR: check input file " + in_filename + " and try again."; throw errormsg; } cout << "getting uncompressed file size\n"; uncompressed_size = getUncompressedFileSize(cflow_compressed_inputstream); cout << "Check if this file can be a cflow_t-file\n"; if (uncompressed_size % sizeof(cflow4) != 0) { string errortext = in_filename; errortext += " does not look like a cflow file (wrong size)"; throw errortext; } //close the file for now cflow_compressed_inputstream.close(); unsigned int flowcount = uncompressed_size / (sizeof(struct cflow4)); cout << "opening gzifstream\n"; gzifstream infs; infs.open(in_filename.c_str(), std::ios_base::in); read_stream(infs, flowcount, local_net, netmask); infs.close(); } /** * Returns the number of bytes the uncompressed gz-file contains * * \param in_filename Filestream for which the size gets looked up * * \return Number of bytes */ uint32_t CImport::getUncompressedFileSize(ifstream & in_filestream) const { uint32_t isize = 0; // By default, GZIP can just store up to 4GiBytes of data long old_pos = in_filestream.tellg(); in_filestream.seekg(-4, ios::end); // read the (uncompressed) filesize in_filestream.read((char *) &isize, 4); // FIXME: big endian will freak out here in_filestream.seekg(old_pos); return isize; } void CImport::read_stream(std::istream & in_stream, unsigned int flowcount, const IPv6_addr & local_net, const IPv6_addr & netmask){ if (inputfilters.empty()) initInputfilters(); std::vector<GFilter *>::iterator importfilterIterator; for (importfilterIterator = inputfilters.begin(); importfilterIterator != inputfilters.end(); importfilterIterator++) { if ((*importfilterIterator)->acceptFileForReading(in_filename)) { cout << "File accepted for reading\n"; try { (*importfilterIterator)->read_stream(in_stream, full_flowlist, local_net, netmask, flowcount, false); } catch (string & e) { LOGE(e.c_str()); } catch (...) { LOGE("Unkown error while importing"); } prepare_flowlist(); return; } } LOGE("no usable importfilter found"); } /** * Disables the remote-IP lookup */ void CImport::set_no_reverse_index() { use_reverse_index = false; } /** * Return the active Subflowlist in use */ Subflowlist CImport::getActiveFlowlist() { return active_flowlist; } /** * Invalidate the active_flowlist */ void CImport::invalidate() { active_flowlist.invalidate(); } /** * Set the begin of the active_flowlist at a specific index of the full flowlist * * \param start Index of the full flowlist to become the start of the active_flowlist * * \pre full_flowlist.size() >= start */ void CImport::setBegin(unsigned int start) { assert(full_flowlist.size() >= start); active_flowlist.invalidateBegin(); active_flowlist.setBegin(full_flowlist.begin() + start); } /** * Set the end of the active_flowlist * * \param start Index of the full flowlist to become the end of the active_flowlist * * \pre full_flowlist.size() >= last */ void CImport::setEnd(unsigned int last) { assert(full_flowlist.size() >= last); active_flowlist.invalidateEnd(); active_flowlist.setEnd(full_flowlist.begin() + last); }
be95787f28b41ddf5abce0632877830061f6ea92
f2a07d63f3fd98aece5191c46b362cc0f74e7d82
/1005.cpp
758c97973070f50ba294c5565880c7cacde9d4c3
[]
no_license
chace20/PAT
7f6891100bff061ebb319ef988c66ad5c3144de4
dc94ef27466474ce81728b3a7f7656fe3bd1c95d
refs/heads/master
2021-06-13T20:35:09.889155
2017-03-07T06:52:31
2017-03-07T06:52:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
694
cpp
1005.cpp
// // Created by 周超 on 08/02/2017. // // 非负整数<=10^100,所以和范围为0~891 // 二维数组存储所需的字符串,也可以用string #include <cstdio> char str[110]; int sum = 0; char en[10][10] = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"}; int main() { scanf("%s", str); for (int i = 0; i < 110; ++i) { if (str[i] != 0) { sum += (str[i] - 48); } else break; } if (sum >= 100) printf("%s %s %s", en[sum/100], en[sum/10%10], en[sum%100]); else if (sum >= 10) printf("%s %s", en[sum/10], en[sum%10]); else printf("%s", en[sum]); return 0; }
d1f810af20c1f8715940309ae96680c448fc0e4f
93bb53787cb3e9fb32371bb0fdc4e9227edce60e
/infoarena/euclid/main.cpp
90103c554c2cc4b8056efcdb6a97f2913c987311
[]
no_license
lupvasile/contest-problems
b969f6e591d1b3feaebf5675b999642b1f2ade32
a484632c23d8b62b98d550446f697675b50e9dc6
refs/heads/master
2021-07-03T22:19:41.142998
2017-09-27T21:00:02
2017-09-27T21:00:02
105,061,972
1
0
null
null
null
null
UTF-8
C++
false
false
1,946
cpp
main.cpp
#include <iostream> #include <fstream> using namespace std; ifstream f("euclid.in"); ofstream g("euclid.out"); int gI(); #define nmax 410 #define cout g int t,n,m,h,w,i,j,maxx,k,l; int rmq[9][9][nmax][nmax]; int log[nmax]; int gcd(int d,int i) { /*int r; do { r=d%i; d=i; i=r; } while (r); return d; */ while(d!=i) { if(d<i) swap(d,i); d=d-i; } return d; } int query(int x,int y) { int a=gcd(rmq[log[h]][log[w]][x][y],rmq[log[h]][log[w]][x][y+w-(1<<log[w])]); int b=gcd(rmq[log[h]][log[w]][x+h-(1<<log[h])][y],rmq[log[h]][log[w]][x+h-(1<<log[h])][y+w-(1<<log[w])]); return gcd(a,b); } int main() { t=gI(); for(i=2; i<nmax; ++i) log[i]=log[i>>1]+1; for(int tt=1; tt<=t; ++tt) { maxx=0; n=gI(),m=gI(),h=gI(),w=gI(); for(i=1; i<=n; ++i) for(j=1; j<=m; ++j) rmq[0][0][i][j]=gI(); for(k=1; k<=log[h]; ++k) for(l=0; l<=log[w]; ++l) for(i=1; i+(1<<k)-1<=n; ++i) for(j=1; j+(1<<l)-1<=m; ++j) { if(l>0) rmq[k][l][i][j]=gcd(rmq[k][l-1][i][j],rmq[k][l-1][i][j+(1<<(l-1))]); else rmq[k][l][i][j]=gcd(rmq[k-1][l][i][j],rmq[k-1][l][i+(1<<(k-1))][j]); } for(i=1;i+h-1<=n;++i) ///coltul dreapta sus in i,j for(j=1;j+w-1<=m;++j) maxx=max(maxx,query(i,j)); cout<<"Case #"<<tt<<": "<<maxx<<'\n'; } return 0; } #define nbuf 3276800 char buf[nbuf]; int pbuf(nbuf); int gI() { int n=0; while (buf[pbuf]<'0' || buf[pbuf]>'9') { if(++pbuf>=nbuf) f.read(buf,nbuf),pbuf=0; } while (buf[pbuf]>='0' && buf[pbuf]<='9') { n=n*10+buf[pbuf]-'0'; if(++pbuf>=nbuf) f.read(buf,nbuf),pbuf=0; } return n; }
ccf2b3f7d2f0bd5ddeb46d62a7a060a547a7088f
81fd63472f233daf0ca8811efcc625730ed2378b
/CodechefCodes/ALTARAY.cpp
d2490c17c50c10a5d3b22d02c18f3d10d0473e86
[ "MIT" ]
permissive
debashish05/competitive_programming
044d0d85f946008548916c0511d7c65bd0cefe7a
e2c0a7a741ac988e4393eda3b5006d6b8c88a5a9
refs/heads/master
2021-11-29T18:52:10.069235
2021-11-17T20:20:47
2021-11-17T20:20:47
120,617,701
0
0
null
null
null
null
UTF-8
C++
false
false
1,116
cpp
ALTARAY.cpp
#include<bits/stdc++.h> #define ll long long int #define ull unsigned long long int #define loop(k) for(i=0;i<k;++i) #define loop2(k) for(j=0;j<k;++j) #define mod 1000000007 using namespace std; int main() { std::ios::sync_with_stdio(false); cin.tie(NULL); int t=1,i=0,j=0; cin>>t; while(t--){ int n; cin>>n; ll a[n]; loop(n)cin>>a[i]; //input int count=0,k; loop(n){ //value of count is saved now //dp //at starting count=0 //solution from i-1th index is count if(i && count!=1){ --count;cout<<count<<" ";continue; } else count=0; if(a[i]>0){ //first element is +ve count++;k=0; for(j=i+1;j<n;++j){ if(a[j]<0 && k==0)k=1; else if(a[j]>0 && k)k=0; else break; count++; } } else{ //first element is -ve count++;k=0; for(j=i+1;j<n;++j){ if(a[j]>0 && k==0)k=1; else if(a[j]<0 && k)k=0; else break; count++; } } cout<<count<<" "; } cout<<"\n"; } return 0; }
6be37ccb42274a229d9cb23a8188feeb272607e2
600c9ec551e0238520e75974f1c4d2198e7f487b
/BOJ/DP/10844_DP.cpp
2a6c4236d24f091f38c9b1f6f1618d327da3428a
[]
no_license
100winone/algorithm
f20b035208d309b48959daeace235e9e52c5ff2e
90483b779e979b970732c9c217cb9b4831bff164
refs/heads/master
2021-01-07T18:02:56.267051
2020-07-15T12:28:49
2020-07-15T12:28:49
241,776,396
1
0
null
null
null
null
UTF-8
C++
false
false
834
cpp
10844_DP.cpp
/*10844 쉬운 계단 수 DP 20200504 * 점화식 어려운편*/ #include <iostream> #define MAX 101 using namespace std; int n; long long res; long long dp[MAX][11]; using namespace std; int main(){ ios::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); cin >> n; for (int i = 1; i <= 9; ++i) { // 한 자리수는 한개 dp[1][i] = 1; } for (int i = 2; i <= n; ++i) { for (int j = 0; j < 10; ++j) { // 0에서 9로 끝나는 경우 if(j == 0) dp[i][j] = dp[i - 1][j + 1] % 1000000000; else if(j == 9) dp[i][j] = dp[i - 1][j - 1] % 1000000000; else dp[i][j] = dp[i - 1][j - 1] + dp[i - 1][j + 1] % 1000000000; } } for (int i = 0; i < 10; ++i) { res += dp[n][i]; } cout << res % 1000000000<< '\n'; return 0; }
d6e7594da98d58c6749bce4b55dea569d97a1729
b7ea2a903761648ba301e3e2dbf9683de25df56b
/src/api/track.cpp
d9b5928f84c470482d66dab22eb6413e6c01b4bf
[]
no_license
unity8-team/unity-scope-soundcloud
56b96bc1c363b46c54587c805a1c1be7162d00a3
81cbd1edba2b3f5114876eebe57804222e7e2c04
refs/heads/master
2021-01-19T14:13:55.046517
2016-03-24T11:28:22
2016-03-24T11:28:22
88,136,959
0
3
null
null
null
null
UTF-8
C++
false
false
4,412
cpp
track.cpp
/* * Copyright (C) 2014 Canonical, Ltd. * * This library is free software; you can redistribute it and/or modify it under * the terms of version 3 of the GNU Lesser General Public License as published * by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Author: Pete Woods <pete.woods@canonical.com> * Gary Wang <gary.wang@canonical.com> */ #include <boost/algorithm/string.hpp> #include <api/track.h> #include <json/json.h> namespace json = Json; using namespace api; using namespace std; Track::Track(const json::Value &data) : user_(data["user"]) { id_ = data["id"].asUInt(); title_ = data["title"].asString(); description_ = data["description"].asString(); label_name_ = data["label_name"].asString(); duration_ = data["duration"].asUInt(); license_ = data["license"].asString(); created_at_ = data["created_at"].asString(); std::vector<std::string> created_time; boost::split(created_time, created_at_, boost::is_any_of(" ")); created_at_ = created_time[0]; playback_count_ = data["playback_count"].asUInt(); favoritings_count_ = data["favoritings_count"].asUInt(); comment_count_ = data["comment_count"].asUInt(); repost_count_ = data["reposts_count"].asUInt(); likes_count_ = data["likes_count"].asUInt(); artwork_ = data["artwork_url"].asString(); waveform_ = data["waveform_url"].asString(); //when loading login user stream, server gives waveform //sample json file instread of image if (boost::algorithm::ends_with(waveform_, "json")) { boost::replace_all(waveform_, "json", "png"); boost::replace_all(waveform_, "is.", "1."); } streamable_ = data["streamable"].asBool(); downloadable_ = data["downloadable"].asBool(); permalink_url_ = data["permalink_url"].asString(); purchase_url_ = data["purchase_url"].asString(); stream_url_ = data["stream_url"].asString(); download_url_ = data["download_url"].asString(); video_url_ = data["video_url"].asString(); genre_ = data["genre"].asString(); original_format_ = data["original_format"].asString(); } const string & Track::title() const { return title_; } const unsigned int & Track::id() const { return id_; } const string & Track::artwork() const { return artwork_; } const string & Track::waveform() const { return waveform_; } const string & Track::description() const { return description_; } const std::string & Track::uri() const { return uri_; } const std::string & Track::label_name() const { return label_name_; } unsigned int Track::duration() const { return duration_; } const std::string & Track::license() const { return license_; } const std::string & Track::created_at() const { return created_at_; } bool Track::streamable() const { return streamable_; } bool Track::downloadable() const { return downloadable_; } const std::string & Track::permalink_url() const { return permalink_url_; } const std::string & Track::purchase_url() const { return purchase_url_; } const std::string & Track::stream_url() const { return stream_url_; } const std::string & Track::download_url() const { return download_url_; } const std::string & Track::video_url() const { return video_url_; } unsigned int Track::playback_count() const { return playback_count_; } unsigned int Track::favoritings_count() const { return favoritings_count_; } unsigned int Track::comment_count() const { return comment_count_; } unsigned int Track::repost_count() const { return repost_count_; } unsigned int Track::likes_count() const { return likes_count_; } const string & Track::genre() const { return genre_; } const string & Track::original_format() const { return original_format_; } const User & Track::user() const { return user_; } Resource::Kind Track::kind() const { return Resource::Kind::track; } std::string Track::kind_str() const { return "track"; }
c11b31d16de3a0f9f38013eb5bfe6231ae6014bf
5e502618dfdfa9e104aaf2ba8d6757737e5123d8
/PlanetAssignment/EGP300-proj1/DrawData.cpp
d4de7a37e728c1ffc6fe4dabf216ef57c8131498
[]
no_license
ccmccooey/Game_Physics
96d96f390222261f6155e851009ec88ea7e2efa3
8b0ae74b95c3973aa62e3182a7cc3df84e7383d2
refs/heads/master
2021-01-25T05:28:02.878845
2015-05-01T22:05:13
2015-05-01T22:05:13
29,218,246
1
0
null
null
null
null
UTF-8
C++
false
false
77
cpp
DrawData.cpp
#include "DrawData.h" DrawData::DrawData() { } DrawData::~DrawData() { }
b1eedde3fb8bbf4e1eb1359ac60ce410ca32c80a
8cf68f88e11cf8969d55410643295be81e672dc7
/OPCNETAPI/Subscription.h
9acb20880609818d4b90a792caaf0f48c1fd6a1d
[]
no_license
myfree88/OPCNETAPI
07ee061bbf520cc2da6fcceede5d25331aff2a2b
375187593d6e0539e3ee57f2628e26b539e007d1
refs/heads/master
2023-03-18T10:14:57.128688
2021-01-26T15:16:31
2021-01-26T15:16:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,006
h
Subscription.h
#pragma once #include "DADataCallback.h" #include "ItemDefinition.h" #include "ItemValueDefinition.h" #include "ComBase.h" #include "ComUtils.h" #include "DAReadResult.h" #include "DAResult.h" #include "DataSources.h" #include "Conversions.h" using namespace OPC; using namespace OPC::DA; class DADataCallback; namespace OPC { namespace DA { public value struct DataChangedEventArgs { public: System::UInt32 TransactionId; System::Collections::Generic::List<DAReadResult>^ Results; }; public delegate void DataChangedEventHandler(System::Object^ sender, DataChangedEventArgs e); public value struct ReadCompletedEventArgs { public: System::UInt32 TransactionId; System::Collections::Generic::List<DAReadResult>^ Results; }; public delegate void ReadCompletedEventHandler(System::Object^ sender, ReadCompletedEventArgs e); public value struct WriteCompletedEventArgs { public: System::UInt32 TransactionId; }; public delegate void WriteCompletedEventHandler(System::Object^ sender, WriteCompletedEventArgs e); public value struct CancelCompletedEventArgs { public: System::UInt32 TransactionId; }; public delegate void CancelCompletedEventHandler(System::Object^ sender, CancelCompletedEventArgs e); public ref class Subscription : public ComBase { private: IOPCSyncIO2* m_IOPCSyncIO; IOPCAsyncIO2* m_IOPCASyncIO; IOPCItemMgt* m_IOPCItemMgt; IOPCGroupStateMgt* m_IOPCGroupStateMgt; internal: HRESULT OnDataChangedFunc( DWORD dwTransid, OPCHANDLE hGroup, HRESULT hrMasterquality, HRESULT hrMastererror, DWORD dwCount, OPCHANDLE *phClientItems, VARIANT *pvValues, WORD *pwQualities, FILETIME *pftTimeStamps, HRESULT *pErrors); HRESULT OnReadCompletedFunc( DWORD dwTransid, OPCHANDLE hGroup, HRESULT hrMasterquality, HRESULT hrMastererror, DWORD dwCount, OPCHANDLE *phClientItems, VARIANT *pvValues, WORD *pwQualities, FILETIME *pftTimeStamps, HRESULT *pErrors); HRESULT OnWriteCompletedFunc( DWORD dwTransid, OPCHANDLE hGroup, HRESULT hrMastererr, DWORD dwCount, OPCHANDLE *pClienthandles, HRESULT *pErrors); HRESULT OnCancelCompleted( DWORD dwTransid, OPCHANDLE hGroup); DADataCallback* dataCallback; protected: System::UInt32 cCounter; bool active; System::String^ m_name; System::UInt32 m_clientHandle; System::UInt32 m_serverHandle; System::UInt32 m_UpdateRate; float m_DeadBand; System::Collections::Generic::Dictionary<System::UInt32, ItemDefinition^>^ items; System::Runtime::InteropServices::GCHandle handle; DataChangedEventHandler^ DataChangedHandler; ReadCompletedEventHandler^ ReadCompletedHandler; WriteCompletedEventHandler^ WriteCompletedHandler; CancelCompletedEventHandler^ CancelCompletedHandler; IOPCItemMgt* GetServer(); IOPCSyncIO2* GetSyncIO(); IOPCAsyncIO2* GetAsyncIO(); IOPCGroupStateMgt* GetGroupStateMgt(); void ChangeState(DWORD* updateRate, bool* status, float* deadband); internal: void SetName(System::String^ v) { m_name = v; } void SetClientHandle(System::UInt32 v) { m_clientHandle = v; } void SetServerHandle(System::UInt32 v) { m_serverHandle = v; } void SetUpdateRate(System::UInt32 v) { m_UpdateRate = v; } void SetDeadBand(float v) { m_DeadBand = v; } public: event DataChangedEventHandler^ DataChanged { void add(DataChangedEventHandler^ p) { DataChangedHandler += p; } void remove(DataChangedEventHandler^ p) { DataChangedHandler -= p; } } event ReadCompletedEventHandler^ ReadCompleted { void add(ReadCompletedEventHandler^ p) { ReadCompletedHandler += p; } void remove(ReadCompletedEventHandler^ p) { ReadCompletedHandler -= p; } } event WriteCompletedEventHandler^ WriteCompleted { void add(WriteCompletedEventHandler^ p) { WriteCompletedHandler += p; } void remove(WriteCompletedEventHandler^ p) { WriteCompletedHandler -= p; } } event CancelCompletedEventHandler^ CancelCompleted { void add(CancelCompletedEventHandler^ p) { CancelCompletedHandler += p; } void remove(CancelCompletedEventHandler^ p) { CancelCompletedHandler -= p; } } Subscription( System::String^ name, System::UInt32 cHandle, System::UInt32 sHandle, System::UInt32 uRate, float dBand, ComBase^ pParent, IUnknown* ppIn); ~Subscription(); property System::String^ Name { System::String^ get() { return m_name; } } property System::UInt32 ClientHandle { System::UInt32 get() { return m_clientHandle; } } property System::UInt32 ServerHandle { System::UInt32 get() { return m_serverHandle; } } property System::UInt32 UpdateRate { System::UInt32 get() { return m_UpdateRate; } } property float DeadBand { float get() { return m_DeadBand; } } void AddItemsAsync( System::Collections::Generic::IList<ItemDefinition^>^ definitionsToAdd, [System::Runtime::InteropServices::Optional] System::Nullable<int> timeout); void AddItems( System::Collections::Generic::IList<ItemDefinition^>^ definitionsToAdd); void RemoveItemsAsync( System::Collections::Generic::IList<ItemDefinition^>^ definitionsToRemove, [System::Runtime::InteropServices::Optional] System::Nullable<int> timeout); void RemoveItems( System::Collections::Generic::IList<ItemDefinition^>^ definitionsToRemove); System::Collections::Generic::IList<DAReadResult>^ Read(System::Collections::Generic::IList<ItemDefinition^>^ definitionsToRead, DataSources source); System::Collections::Generic::IList<DAResult^>^ ReadAsync( System::Collections::Generic::IList<ItemDefinition^>^ definitionsToRead, DataSources source, System::UInt32 transactionId, [System::Runtime::InteropServices::Out] System::UInt32% cancelId); System::Collections::Generic::IList<DAResult^>^ Write(System::Collections::Generic::IList<ItemValueDefinition^>^ pairItemValuesToWrite); System::Collections::Generic::IList<DAResult^>^ WriteAsync( System::Collections::Generic::IList<ItemValueDefinition^>^ pairItemValuesToWrite, System::UInt32 transactionId, [System::Runtime::InteropServices::Out] System::UInt32% cancelId); void Refresh( DataSources source, System::UInt32 transactionId, [System::Runtime::InteropServices::OutAttribute] System::UInt32% cancelId); void Cancel(System::UInt32); void Activate(); void DeActivate(); void ChangeState(System::UInt32 updateRate, bool status, float deadband); void Release(); }; inline OPC::DA::Subscription^ ptrToSubscription(void* ptr) { System::Runtime::InteropServices::GCHandle h = System::Runtime::InteropServices::GCHandle::FromIntPtr(System::IntPtr(ptr)); OPC::DA::Subscription^ s = (OPC::DA::Subscription^) h.Target; return s; } } }
af918bc28cd94683d54686124ab76896d85dde6d
2b2da3c294d188fa7c2795364ab26859e29ffb87
/OFSample-Windows/depends/dwinternal/framework2015/duifw/release/moc_duitextobject.cpp
88381d902d054344e88821c3f9c18cc462c993cb
[]
no_license
JocloudSDK/OFSample
1de97d416402b91276f9992197bc0c64961fb9bd
fa678d674b3886fa8e6a1c4a0ba6b712124e671a
refs/heads/master
2022-12-28T05:03:05.563734
2020-10-19T07:11:55
2020-10-19T07:11:55
294,078,053
4
2
null
null
null
null
UTF-8
C++
false
false
3,861
cpp
moc_duitextobject.cpp
/**************************************************************************** ** Meta object code from reading C++ file 'duitextobject.h' ** ** Created: Fri Aug 2 15:23:45 2019 ** by: The Qt Meta Object Compiler version 62 (Qt 4.7.1) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../widgets/richedit/customtextobject/duitextobject.h" #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'duitextobject.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 62 #error "This file was generated using the moc from 4.7.1. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE static const uint qt_meta_data_DuiTextObject[] = { // content: 5, // revision 0, // classname 0, 0, // classinfo 3, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 2, // signalCount // signals: signature, parameters, type, tag, flags 42, 15, 14, 14, 0x05, 93, 63, 14, 14, 0x05, // slots: signature, parameters, type, tag, flags 130, 14, 14, 14, 0x09, 0 // eod }; static const char qt_meta_stringdata_DuiTextObject[] = { "DuiTextObject\0\0objectName,textObjectIndex\0" "clicked(QString,int)\0ev,objectName,textObjectIndex\0" "mousePress(QMouseEvent*,QString,int)\0" "on_textEditCleared()\0" }; const QMetaObject DuiTextObject::staticMetaObject = { { &QObject::staticMetaObject, qt_meta_stringdata_DuiTextObject, qt_meta_data_DuiTextObject, 0 } }; #ifdef Q_NO_DATA_RELOCATION const QMetaObject &DuiTextObject::getStaticMetaObject() { return staticMetaObject; } #endif //Q_NO_DATA_RELOCATION const QMetaObject *DuiTextObject::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject; } void *DuiTextObject::qt_metacast(const char *_clname) { if (!_clname) return 0; if (!strcmp(_clname, qt_meta_stringdata_DuiTextObject)) return static_cast<void*>(const_cast< DuiTextObject*>(this)); if (!strcmp(_clname, "QTextObjectInterface")) return static_cast< QTextObjectInterface*>(const_cast< DuiTextObject*>(this)); if (!strcmp(_clname, "com.trolltech.Qt.QTextObjectInterface")) return static_cast< QTextObjectInterface*>(const_cast< DuiTextObject*>(this)); return QObject::qt_metacast(_clname); } int DuiTextObject::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QObject::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { switch (_id) { case 0: clicked((*reinterpret_cast< const QString(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2]))); break; case 1: mousePress((*reinterpret_cast< QMouseEvent*(*)>(_a[1])),(*reinterpret_cast< const QString(*)>(_a[2])),(*reinterpret_cast< int(*)>(_a[3]))); break; case 2: on_textEditCleared(); break; default: ; } _id -= 3; } return _id; } // SIGNAL 0 void DuiTextObject::clicked(const QString & _t1, int _t2) { void *_a[] = { 0, const_cast<void*>(reinterpret_cast<const void*>(&_t1)), const_cast<void*>(reinterpret_cast<const void*>(&_t2)) }; QMetaObject::activate(this, &staticMetaObject, 0, _a); } // SIGNAL 1 void DuiTextObject::mousePress(QMouseEvent * _t1, const QString & _t2, int _t3) { void *_a[] = { 0, const_cast<void*>(reinterpret_cast<const void*>(&_t1)), const_cast<void*>(reinterpret_cast<const void*>(&_t2)), const_cast<void*>(reinterpret_cast<const void*>(&_t3)) }; QMetaObject::activate(this, &staticMetaObject, 1, _a); } QT_END_MOC_NAMESPACE
56b13697f668e922a2bdab54f3e20e48cf17d965
46f7adba3177b65f1e9aa0a488310828b7eb5e86
/KinectFusionCommon/DepthSensor/igD3D/inl/igD2D1Device.inl
d5bd48c779b8184c06a90c1e4216468cbbfc0bb4
[]
no_license
yizhongzhang1989/DynamicFusion
27a42ec948770be12a8ad49584b7010e89a30610
1fa3a57caddbd05466609a17aa2af65eb2a9c657
refs/heads/master
2020-07-11T06:39:03.058029
2019-08-26T13:15:21
2019-08-26T13:15:21
204,468,100
2
0
null
2019-08-26T12:12:19
2019-08-26T12:12:18
null
UTF-8
C++
false
false
506
inl
igD2D1Device.inl
#pragma once //#include "igD2D1Device.h" namespace ig { namespace D2D1 { // Getters inline ID2D1Factory1* CDevice::FactoryPtr() const { return m_pFactory.Get(); } inline ID2D1Device* CDevice::Ptr() const { return m_pDevice.Get(); } //inline CDeviceContext& CDevice::ImmediateContext() { return m_ImmediateContext; } inline bool CDevice::IsValid() const { return m_pDevice != nullptr; } // Convert to ComPtr inline CDevice::operator ID2D1Device*() const { return m_pDevice.Get(); } } }
f82097233413d3c6989d190ac1d3e94dc86b0d7e
9a529eb0f3ee9c06f1898c22429c3e433382d371
/bsbutils/src/bsbutils.h
c5d56468057d6a2535b6dc96481b8d6cd145dc2a
[]
no_license
roberto-code/bsbutils
8f9b87bd570fdedcf32ee4b46240aed880ed5539
48bced083ceb944d2f222f98529f71cbac87f6db
refs/heads/master
2021-01-17T15:13:00.266572
2016-10-24T19:59:17
2016-10-24T19:59:17
71,826,833
0
0
null
null
null
null
UTF-8
C++
false
false
370
h
bsbutils.h
#ifndef _BSB_UTILS_H #define _BSB_UTILS_H #include <Rcpp.h> #include <vector> RcppExport SEXP rarefy( SEXP theMatrix, SEXP theSampleDepth, SEXP theSumSample, SEXP theSelSampleCall ); template <typename T> void selectionSample( const std::vector<T> theVector, const size_t theSize, std::vector<T> &theResultVector, size_t theExecutionNumber ); #endif
0eabf1800180ead6745d2f23a3860a6231c2947b
55a6e487bfb0f8a509d2822723bda8b37f0b5a74
/Plugins/KinectV2/Source/KinectV2/Private/KinectAnimInstance.cpp
d733bca7f00fd9a4447ae4b0baf171bb8ed3d259
[]
no_license
liamisbest/KinectDemoRoom
81238503305fda8f910dad0a2364c5622f27a7f6
2a626be825c716f855205fd2b6e5e471f0a8fa4f
refs/heads/develop
2021-07-12T03:57:54.823414
2017-10-14T00:11:56
2017-10-14T00:11:56
106,882,873
4
5
null
2017-10-13T23:39:59
2017-10-13T23:39:59
null
UTF-8
C++
false
false
6,096
cpp
KinectAnimInstance.cpp
#include "IKinectV2PluginPCH.h" #include "KinectAnimInstance.h" #include "AnimationRuntime.h" #include "AnimationUtils.h" UKinectAnimInstance::UKinectAnimInstance(const class FObjectInitializer& PCIP) : Super(PCIP), KinectOverrideEnabled(false), EvaluateAnimationGraph(true) { if (CurrentSkeleton) { //auto num = CurrentSkeleton->PreviewAttachedAssetContainer.Num(); } if (BoneAdjustments.Num() < 25) { BoneAdjustments.Empty(); BoneAdjustments.AddDefaulted(25); } if (BonesToRetarget.Num() < 25) { BonesToRetarget.Empty(); BonesToRetarget.AddZeroed(25); } if (KinectBoneRotators.Num() < 25) { KinectBoneRotators.Empty(); KinectBoneRotators.AddZeroed(25); } } //bool UKinectAnimInstance::NativeEvaluateAnimation(FPoseContext& Output) //{ /*if (RootNode != nullptr && EvaluateAnimationGraph) { //SCOPE_CYCLE_COUNTER(STAT_AnimGraphEvaluate); RootNode->Evaluate(Output); } else { Output.ResetToRefPose(); } if (!KinectOverrideEnabled) return true; USkeletalMeshComponent* OwningComponent = GetOwningComponent(); //Proof of concept if (OwningComponent) { ProccessSkeleton();*/ /* uint32 i = 0; for (auto BoneName : BonesToRetarget) { if (BoneName != NAME_None) { int32 BoneIndex = OwningComponent->GetBoneIndex(BoneName); if (BoneIndex >= 0) { FCSPose<FCompactPose> CSPose; CSPose.InitPose(Output.Pose); auto BoneTransform = CSPose.GetComponentSpaceTransform(FCompactPoseBoneIndex(BoneIndex)); //BoneTransform.SetToRelativeTransform(GetOwningComponent()->GetComponentToWorld()); BoneTransform.SetRotation(KinectBoneRotators[i].Quaternion()); TArray<FBoneTransform> BoneTransforms; BoneTransforms.Add(FBoneTransform(FCompactPoseBoneIndex(BoneIndex), BoneTransform)); CSPose.SafeSetCSBoneTransforms(BoneTransforms); // CSPose.SetComponentSpaceTransform(FCompactPoseBoneIndex(BoneIndex), BoneTransform); int32 ParentIndex = OwningComponent->GetBoneIndex(OwningComponent->GetParentBone(BoneName)); if (ParentIndex >= 0) { Output.Pose[FCompactPoseBoneIndex(BoneIndex)].SetFromMatrix(BoneTransform.ToMatrixWithScale()); //Output.Pose[FCompactPoseBoneIndex(BoneIndex)].SetToRelativeTransform(CSPose.GetComponentSpaceTransform(FCompactPoseBoneIndex(BoneIndex))); } Output.Pose[FCompactPoseBoneIndex(BoneIndex)] = CSPose.GetComponentSpaceTransform(FCompactPoseBoneIndex(BoneIndex)); } } ++i; } */ //} // return false; //} #pragma optimize ("",off) void UKinectAnimInstance::NativeInitializeAnimation() { AdjasmentMap.Empty(); BindMap.Empty(); USkeletalMeshComponent* OwningComponent = GetOwningComponent(); if (OwningComponent) { if (OwningComponent->SkeletalMesh) { int32 BoneNum = OwningComponent->SkeletalMesh->RefSkeleton.GetNum(); for (int32 i = 0; i < BoneNum; ++i) { auto BoneWorldTransform = OwningComponent->GetBoneTransform(i, OwningComponent->GetComponentToWorld()); BindMap.Add(i, BoneWorldTransform.Rotator()); AdjasmentMap.Add(i, (FRotationMatrix::MakeFromX(FVector(0.f, 0.f, 1.f)).Rotator() - BoneWorldTransform.GetRotation().Rotator().GetNormalized())); } for (auto BoneMapPair : OverLayMap){ auto BoneName = BoneMapPair.Key; if (BoneName != NAME_None) { } } } } } #pragma optimize ("",on) void UKinectAnimInstance::ProccessSkeleton() { uint32 i = 0; for (auto Bone : CurrBody.KinectBones) { if (BonesToRetarget[i] != NAME_None) { auto DeltaTranform = Bone.MirroredJointTransform.GetRelativeTransform(GetOwningComponent()->GetBoneTransform(0)); //AxisMeshes[Bone.JointTypeEnd]->SetRelativeLocation(PosableMesh->GetBoneLocationByName(RetargetBoneNames[Bone.JointTypeEnd], EBoneSpaces::ComponentSpace)); auto BoneBaseTransform = DeltaTranform*GetOwningComponent()->GetBoneTransform(0); FRotator PreAdjusmentRotator = BoneBaseTransform.Rotator(); FRotator PostBoneDirAdjustmentRotator = (BoneAdjustments[Bone.JointTypeEnd].BoneDirAdjustment.Quaternion()*PreAdjusmentRotator.Quaternion()).Rotator(); FRotator CompSpaceRotator = (PostBoneDirAdjustmentRotator.Quaternion()*BoneAdjustments[Bone.JointTypeEnd].BoneNormalAdjustment.Quaternion()).Rotator(); FVector Normal, Binormal, Dir; UKismetMathLibrary::BreakRotIntoAxes(CompSpaceRotator, Normal, Binormal, Dir); Dir *= BoneAdjustments[Bone.JointTypeEnd].bInvertDir ? -1 : 1; Normal *= BoneAdjustments[Bone.JointTypeEnd].bInvertNormal ? -1 : 1; FVector X, Y, Z; switch (BoneAdjustments[Bone.JointTypeEnd].BoneDirAxis) { case EAxis::X: X = Dir; break; case EAxis::Y: Y = Dir; break; case EAxis::Z: Z = Dir; break; default: ; } switch (BoneAdjustments[Bone.JointTypeEnd].BoneBinormalAxis) { case EAxis::X: X = Binormal; break; case EAxis::Y: Y = Binormal; break; case EAxis::Z: Z = Binormal; break; default: ; } switch (BoneAdjustments[Bone.JointTypeEnd].BoneNormalAxis) { case EAxis::X: X = Normal; break; case EAxis::Y: Y = Normal; break; case EAxis::Z: Z = Normal; break; default: ; } FRotator SwiveledRot = UKismetMathLibrary::MakeRotationFromAxes(X, Y, Z); SwiveledRot = (GetOwningComponent()->GetBoneTransform(0).Rotator().Quaternion()*SwiveledRot.Quaternion()).Rotator(); KinectBoneRotators[i] = SwiveledRot; } ++i; } } void UKinectAnimInstance::OnKinectBodyEvent(EAutoReceiveInput::Type KinectPlayer, const FBody& Skeleton) { CurrBody = Skeleton; ProccessSkeleton(); if (!CurrentSkeleton) return; } void UKinectAnimInstance::OverrideBoneRotationByName(FName BoneName, FRotator BoneRotation) { OverLayMap.Add(BoneName, BoneRotation); } void UKinectAnimInstance::SetOverrideEnabled(bool Enable) { KinectOverrideEnabled = Enable; } void UKinectAnimInstance::ResetOverride() { OverLayMap.Empty(); } void UKinectAnimInstance::RemoveBoneOverrideByName(FName BoneName) { OverLayMap.Remove(BoneName); }
d1d9989d4a18ce648ca29115ef23b116f4040b64
6d65eef1d8a698968f2c27833c384b4c272bcc0f
/SourceCode/auto_document.h
d971dfae16cfca8531f719e9d80898acf1e82c3c
[]
no_license
KodFreedom/AutoDocument
181c7b27477679e935323c6e0187ebc3dea0b937
49d83ca1b84a6fad310c760c32616c6f42d81bcb
refs/heads/master
2020-06-25T07:56:26.124764
2019-07-28T11:59:42
2019-07-28T11:59:42
199,251,655
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
1,056
h
auto_document.h
#pragma once #include <list> #include <string> using namespace std; namespace KodFreedom { class ClassInfo; class AutoDocument { public: AutoDocument() {} ~AutoDocument(); void Analyze(const string& file_path); private: struct LineInfo { list<string> log; list<string> comment; }; void Analyze(ifstream& file); bool FindClass(ifstream& file); bool GetLineUntil(ifstream& file, const list<string>& keywords, LineInfo& out_line_info); bool IsClass(ifstream& file, LineInfo& line_info); // クラス名前と継承を解析 void AnalyzeClassNameAndInherits(string& buffer); // 継承を解析 void AnalyzeInheritances(string& buffer); // .hからクラス解析 void AnalyzeClass(ifstream& file); size_t m_curly_bracket_counter = 0; // `{`の階層カウンター list<ClassInfo*> m_classes = {}; // headファイルに宣言されたクラス }; }
330ded8da5b568036ce137c916e0f2780c742167
8342f87cc7e048aa812910975c68babc6fb6c5d8
/engine/StdAfx.h
caea8438ea834bbaa0442456152e959e34585796
[]
no_license
espes/hoverrace
1955c00961af4bb4f5c846f20e65ec9312719c08
7d5fd39ba688e2c537f35f7c723dedced983a98c
refs/heads/master
2021-01-23T13:23:03.710443
2010-12-19T22:26:12
2010-12-19T22:26:12
2,005,364
0
1
null
null
null
null
UTF-8
C++
false
false
1,381
h
StdAfx.h
/* StdAfx.h Precompiled header for engine. */ #ifdef _WIN32 # define VC_EXTRALEAN // Exclude rarely-used stuff from Windows headers // Minimum Windows version: XP # define WINVER 0x0501 # define _CRT_SECURE_NO_DEPRECATE # define _SCL_SECURE_NO_DEPRECATE # include <windows.h> # include <typeinfo.h> # pragma warning(disable: 4251) # pragma warning(disable: 4275) # include <assert.h> # define ASSERT(e) assert(e) # include "../include/config-win32.h" #else # include "../include/compat/unix.h" # include "../config.h" # include <strings.h> #endif #include <limits.h> #include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> // Commonly-used STL headers. #include <algorithm> #include <exception> #include <list> #include <map> #include <set> #include <sstream> #include <string> #include <vector> #include <boost/filesystem/convenience.hpp> #include <boost/filesystem/path.hpp> #include <boost/foreach.hpp> #include <boost/format.hpp> #include <boost/lexical_cast.hpp> #include <boost/shared_ptr.hpp> #ifndef _WIN32 // Xlib.h must be included *after* boost/foreach.hpp as a workaround for // https://svn.boost.org/trac/boost/ticket/3000 # include <X11/Xlib.h> #endif // Don't use the min/max macros; use std::min and std::max from the STL. #ifdef min # undef min #endif #ifdef max # undef max #endif using std::min; using std::max;
386c46f991b04fe140ebf6fa4890bba0db2dcb9f
04a900f98c538b1c0b2f426ec74de0b89d069174
/srcs/Database/databaseskill.h
6462b93da41ada87c830d43f9789ead053f7c556
[]
no_license
ApourtArtt/AyugraBot
8f4585e99d749e21a6fe6323a77b46bf20224933
11522140fd055062860ceeee29b53b281ae05290
refs/heads/main
2023-02-03T16:40:18.994680
2020-12-18T23:24:54
2020-12-18T23:24:54
322,726,285
1
1
null
null
null
null
UTF-8
C++
false
false
1,552
h
databaseskill.h
#ifndef DATABASESKILL_H #define DATABASESKILL_H #include <QObject> #include <QString> #include <QFile> #include <QDir> #include <QMap> #include "srcs/Enum/skillenum.h" class SkillFromDb { public: SkillFromDb(){} SkillFromDb(int Id); SkillFromDb(QStringList data); QStringList getData() const; int getID() const; QString getName() const; QString getNameID() const; QString getImage() const; int getCooldown() const; QStringList getDescription() const; QStringList getDescriptionID() const; bool isDash() const; bool isCombo() const; int getCastID() const; SkillTarget getSkillTarget() const; SkillType getSkillType() const; int getRange() const; int getManaCost() const; int getAnimationTimeMs() const; protected: QStringList datas; int id; int imageId; QString nameZts, name; QStringList descZts, desc; int nbLineDesc; int castId; SkillTarget targetType; bool dash; bool combo; SkillType type; int range; int manaCost; int animationTime; int cooldown; private: void loadData(QStringList data); }; class DatabaseSkill { public: DatabaseSkill(); static bool loadSkill(); static QString getSkillTextFromZts(QString zts); static SkillFromDb getSkillFromId(int id); private: static bool loadSkillDat(); static bool load_code__SkillTxt(); static QStringList SkillDat; static QStringList _code__SkillTxt; static QMap<int, SkillFromDb> skills; }; #endif // DATABASESKILL_H
3c0428f81fb697ed84ce2f64b2749c138f7f9638
83ce359b5a54b160fb3754b49ad36bcc1d0bfdf3
/src/c_map.cpp
8c4170d59f6415b79d278b8400a4e14cd7d65794
[]
no_license
ameghbhavsar/apf_ros
dee2fe7a019835f410f3b29cc49f0ea13b51edeb
90deab48e966c406f836b8ecd3f9e0c8ade03754
refs/heads/master
2021-01-21T15:14:27.549346
2017-05-20T17:17:50
2017-05-20T17:17:50
91,816,392
0
0
null
null
null
null
UTF-8
C++
false
false
1,406
cpp
c_map.cpp
// // create_map.cpp // // // Created by muskaan on 15/05/17. // // #include <stdlib.h> #include <vector> #include "apf.h" using namespace std; void c_map::create_map(int mx,int my,vector <int> X,vector <int> Y,vector <int> SIGMA_X,vector <int> SIGMA_Y,vector <int> TYPE, double **map){ Field F; int n = X.size(); for(int j=0; j<n; j++){ if(TYPE[j] == 0){ F.rep_field(X[j],Y[j],SIGMA_X[j],SIGMA_Y[j],mx,my,map); }else if(TYPE[j] == 2){ F.att_field(X[j],Y[j],mx,my,map); } } } void c_map::filter_map(int mx,int my,vector <int> X,vector <int> Y,vector <int> SIGMA_X,vector <int> SIGMA_Y,vector <int> TYPE, double **map){ Field F; double **res = (double**)calloc(mx, sizeof(double*)); for(int i=0; i<mx; i++) res[i] = (double*)calloc(my, sizeof(double)); // double** res = new double*[mx]; // for(int i = 0; i < mx; ++i) // res[i] = new double[my]; int n = 3; for(int j=0; j<n; j++){ if(TYPE[j] == 0){ F.rep_field(X[j],Y[j],SIGMA_X[j],SIGMA_Y[j],mx,my,res); for(int x=0; x<mx; x++) for(int y=0; y<my; y++) map[x][y] += 2*res[x][y]; } } for(int i=0; i<mx; i++) free(res[i]); free(res); // for(int i = 0; i < mx; ++i) // delete [] res[i]; // delete [] res; return ; }
681849b9167e8552d49e274e7573b48938eee0e1
991ec9ac6fc47760ae9306d9e33d8935398ce25f
/src/yCrc32.cpp
07ff0c25e1ba7a46319f69cbf40e8804107f6e8c
[ "Zlib" ]
permissive
YeaSoft/yLib
7435925c4803313a10e1a3b79653638c08edc8d0
b60285b0eee133f48aa42cd0be287540f1f76cac
refs/heads/master
2021-01-01T04:22:54.665015
2017-07-13T21:41:02
2017-07-13T21:41:02
97,166,078
0
0
null
null
null
null
UTF-8
C++
false
false
8,290
cpp
yCrc32.cpp
/*============================================================================= * This is a part of the yLib Software Development Kit. * Copyright (C) 1998-2000 YEAsoft Int'l. * All rights reserved. *============================================================================= * Copyright (c) 1998-2000 YEAsoft Int'l (Leo Moll, Andrea Pennelli). * This software is provided 'as-is', without any express or implied warranty. * In no event will the authors be held liable for any damages arising from the * use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software in * a product, an acknowledgment in the product documentation would be * appreciated but is not required. * * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * * 3. This notice may not be removed or altered from any source distribution. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *============================================================================= * FILENAME : yCrc32.cpp * PURPOSE : Implementation of the CRC Calculation Class * SCOPE : yLib * HISTORY : ============================================================= * * $Log$ * Revision 1.3 2001/05/07 21:07:28 leopoldo * Improvements * * Revision 1.2 2000/09/04 12:07:43 leopoldo * Updated license to zlib/libpng * * Revision 1.1 2000/05/26 14:04:55 leo * Initial revision * *============================================================================*/ /*============================================================================= * @doc YLIB | yCrc32.h *============================================================================*/ #include "StdInc.hpp" /*============================================================================= * The polynomial table *============================================================================= * The following table was generated with the following program and is statically * provided for performance and multithreading purposes: * * int main (int argc, char **argv) * { * unsigned long m_dwPOLYNOMIAL = 0x04c11db7L; * unsigned long m_dwTable[256]; * * register int i, j; * register unsigned long crc_accum; * * for ( i = 0; i < 256; i++ ) { * crc_accum = ( (unsigned long) i << 24 ); * for ( j = 0; j < 8; j++ ) { * if ( crc_accum & 0x80000000L ) { * crc_accum = ( crc_accum << 1 ) ^ m_dwPOLYNOMIAL; * } * else { * crc_accum = ( crc_accum << 1 ); * } * } * m_dwTable[i] = crc_accum; * } * * for ( i = 0; i < 256; i++ ) { * printf ("0x%08x, ", m_dwTable[i]); * if ( !((i + 1) % 8) ) { * printf ("\n"); * } * } * printf ("\n"); * } * *============================================================================*/ DWORD YCrc32::m_dwTable[256] = { 0x00000000, 0x04c11db7, 0x09823b6e, 0x0d4326d9, 0x130476dc, 0x17c56b6b, 0x1a864db2, 0x1e475005, 0x2608edb8, 0x22c9f00f, 0x2f8ad6d6, 0x2b4bcb61, 0x350c9b64, 0x31cd86d3, 0x3c8ea00a, 0x384fbdbd, 0x4c11db70, 0x48d0c6c7, 0x4593e01e, 0x4152fda9, 0x5f15adac, 0x5bd4b01b, 0x569796c2, 0x52568b75, 0x6a1936c8, 0x6ed82b7f, 0x639b0da6, 0x675a1011, 0x791d4014, 0x7ddc5da3, 0x709f7b7a, 0x745e66cd, 0x9823b6e0, 0x9ce2ab57, 0x91a18d8e, 0x95609039, 0x8b27c03c, 0x8fe6dd8b, 0x82a5fb52, 0x8664e6e5, 0xbe2b5b58, 0xbaea46ef, 0xb7a96036, 0xb3687d81, 0xad2f2d84, 0xa9ee3033, 0xa4ad16ea, 0xa06c0b5d, 0xd4326d90, 0xd0f37027, 0xddb056fe, 0xd9714b49, 0xc7361b4c, 0xc3f706fb, 0xceb42022, 0xca753d95, 0xf23a8028, 0xf6fb9d9f, 0xfbb8bb46, 0xff79a6f1, 0xe13ef6f4, 0xe5ffeb43, 0xe8bccd9a, 0xec7dd02d, 0x34867077, 0x30476dc0, 0x3d044b19, 0x39c556ae, 0x278206ab, 0x23431b1c, 0x2e003dc5, 0x2ac12072, 0x128e9dcf, 0x164f8078, 0x1b0ca6a1, 0x1fcdbb16, 0x018aeb13, 0x054bf6a4, 0x0808d07d, 0x0cc9cdca, 0x7897ab07, 0x7c56b6b0, 0x71159069, 0x75d48dde, 0x6b93dddb, 0x6f52c06c, 0x6211e6b5, 0x66d0fb02, 0x5e9f46bf, 0x5a5e5b08, 0x571d7dd1, 0x53dc6066, 0x4d9b3063, 0x495a2dd4, 0x44190b0d, 0x40d816ba, 0xaca5c697, 0xa864db20, 0xa527fdf9, 0xa1e6e04e, 0xbfa1b04b, 0xbb60adfc, 0xb6238b25, 0xb2e29692, 0x8aad2b2f, 0x8e6c3698, 0x832f1041, 0x87ee0df6, 0x99a95df3, 0x9d684044, 0x902b669d, 0x94ea7b2a, 0xe0b41de7, 0xe4750050, 0xe9362689, 0xedf73b3e, 0xf3b06b3b, 0xf771768c, 0xfa325055, 0xfef34de2, 0xc6bcf05f, 0xc27dede8, 0xcf3ecb31, 0xcbffd686, 0xd5b88683, 0xd1799b34, 0xdc3abded, 0xd8fba05a, 0x690ce0ee, 0x6dcdfd59, 0x608edb80, 0x644fc637, 0x7a089632, 0x7ec98b85, 0x738aad5c, 0x774bb0eb, 0x4f040d56, 0x4bc510e1, 0x46863638, 0x42472b8f, 0x5c007b8a, 0x58c1663d, 0x558240e4, 0x51435d53, 0x251d3b9e, 0x21dc2629, 0x2c9f00f0, 0x285e1d47, 0x36194d42, 0x32d850f5, 0x3f9b762c, 0x3b5a6b9b, 0x0315d626, 0x07d4cb91, 0x0a97ed48, 0x0e56f0ff, 0x1011a0fa, 0x14d0bd4d, 0x19939b94, 0x1d528623, 0xf12f560e, 0xf5ee4bb9, 0xf8ad6d60, 0xfc6c70d7, 0xe22b20d2, 0xe6ea3d65, 0xeba91bbc, 0xef68060b, 0xd727bbb6, 0xd3e6a601, 0xdea580d8, 0xda649d6f, 0xc423cd6a, 0xc0e2d0dd, 0xcda1f604, 0xc960ebb3, 0xbd3e8d7e, 0xb9ff90c9, 0xb4bcb610, 0xb07daba7, 0xae3afba2, 0xaafbe615, 0xa7b8c0cc, 0xa379dd7b, 0x9b3660c6, 0x9ff77d71, 0x92b45ba8, 0x9675461f, 0x8832161a, 0x8cf30bad, 0x81b02d74, 0x857130c3, 0x5d8a9099, 0x594b8d2e, 0x5408abf7, 0x50c9b640, 0x4e8ee645, 0x4a4ffbf2, 0x470cdd2b, 0x43cdc09c, 0x7b827d21, 0x7f436096, 0x7200464f, 0x76c15bf8, 0x68860bfd, 0x6c47164a, 0x61043093, 0x65c52d24, 0x119b4be9, 0x155a565e, 0x18197087, 0x1cd86d30, 0x029f3d35, 0x065e2082, 0x0b1d065b, 0x0fdc1bec, 0x3793a651, 0x3352bbe6, 0x3e119d3f, 0x3ad08088, 0x2497d08d, 0x2056cd3a, 0x2d15ebe3, 0x29d4f654, 0xc5a92679, 0xc1683bce, 0xcc2b1d17, 0xc8ea00a0, 0xd6ad50a5, 0xd26c4d12, 0xdf2f6bcb, 0xdbee767c, 0xe3a1cbc1, 0xe760d676, 0xea23f0af, 0xeee2ed18, 0xf0a5bd1d, 0xf464a0aa, 0xf9278673, 0xfde69bc4, 0x89b8fd09, 0x8d79e0be, 0x803ac667, 0x84fbdbd0, 0x9abc8bd5, 0x9e7d9662, 0x933eb0bb, 0x97ffad0c, 0xafb010b1, 0xab710d06, 0xa6322bdf, 0xa2f33668, 0xbcb4666d, 0xb8757bda, 0xb5365d03, 0xb1f740b4 }; DWORD YCrc32::UpdateCrc (LPSTR lpBuffer, UINT cbSize, DWORD dwAccum /* = 0 */) { register int i; register DWORD j; for ( j = 0; j < cbSize; j++ ) { i = ( (int) ( dwAccum >> 24) ^ *lpBuffer++ ) & 0xff; dwAccum = ( dwAccum << 8 ) ^ m_dwTable[i]; } return dwAccum; } // @mfunc Returns the CRC of a file // @syntax <b>static DWORD GetFileCrc (HANDLE<n> hFile<b>);<n> // @syntax <b>static DWORD GetFileCrc (LPCTSTR<n> lpName<b>);<n> // @parm HANDLE | hFile | Handle to an open file with read permission // @parm LPCTSTR | lpName | Name of the file // @comm The handle based implementation of this method restores after // processing the filepointer to it's original position. // @rdesc The computed CRC of the file. If this value is 0, you should // use <b>::GetLastError()<n> to check if the file was successfully // scanned. // @xref <c YCrc32> DWORD YCrc32::GetFileCrc (HANDLE hFile) { LONG dwPosLow, dwPosHigh = 0; char szReadBuffer[4096]; DWORD dwRead; DWORD dwAccumulator = 0; dwPosLow = SetFilePointer (hFile, 0, &dwPosHigh, FILE_CURRENT); SetFilePointer (hFile, 0, NULL, FILE_BEGIN); while ( ReadFile (hFile, szReadBuffer, sizeof (szReadBuffer), &dwRead, NULL) && dwRead ) { dwAccumulator = UpdateCrc (szReadBuffer, dwRead, dwAccumulator); } SetFilePointer (hFile, dwPosLow, &dwPosHigh, FILE_BEGIN); return dwAccumulator; } DWORD YCrc32::GetFileCrc (LPCTSTR lpName) { DWORD dwRetVal; HANDLE hFile; hFile = CreateFile ( lpName, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, NULL ); if ( hFile == INVALID_HANDLE_VALUE ) { return 0; } dwRetVal = GetFileCrc (hFile); CloseHandle (hFile); return dwRetVal; } #ifndef YLB_ENABLE_INLINE #include <yCrc32.inl> #endif /// IDENTITY STUFF /// //LPCTSTR lpComment = _T("$Id$"); // // EoF ////////
6d873471ca35c58bce233245c0fd6f3037673924
3168181ab2ddc031da38ab5cb74c1285bf43bb7d
/pool/cpp_rush3/src/ncurses/IMonitorDisplay.hpp
2a24a8ed76a4748e72fc4bf4b141d7dcb4caf784
[]
no_license
Fluorz/TEK2
358438fa9d9d881197b63b9ed83bdbff55e07e1c
9234bfc468cb2f3b566e451af3dfc08a2fa114e0
refs/heads/master
2022-02-02T04:02:29.575991
2019-01-31T14:06:21
2019-01-31T14:06:21
120,175,695
1
3
null
2022-01-19T15:43:25
2018-02-04T10:40:02
C++
UTF-8
C++
false
false
288
hpp
IMonitorDisplay.hpp
// // EPITECH PROJECT, 2018 // IMonitorDisplay // File description: // // #ifndef IMONITORDISPLAY_HPP_ #define IMONITORDISPLAY_HPP_ #include <vector> #include "IMonitorModule.hpp" class IMonitorDisplay { public: virtual ~IMonitorDisplay(); virtual bool displayAll() = 0; }; #endif
d39276d2e6e9dd0ff4a7294c9b6902a1c6218cad
2e65def61753098295cc8fda3684ddc6dc62b099
/BitmapButton.h
8c4b813365a329e2020e2ac5e8c7aa65ea53cf64
[]
no_license
JohnnyXiaoYang/wickedwidgets
3bafd6dab9fa75028a80c0a158b8563e15f4c6c6
523b3875647dcd2015de4db8979e28460a126db2
refs/heads/master
2021-05-26T19:20:59.052458
2010-10-23T12:30:09
2010-10-23T12:30:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,792
h
BitmapButton.h
// BitmapButton.h : Declaration of the CBitmapButton #ifndef __BITMAPBUTTON_H_ #define __BITMAPBUTTON_H_ #include "resource.h" // main symbols #include <atlctl.h> #include "gdimonster.h" #include "WickedWidgetsCP.h" #include "ObjectTable.h" #include "tooltip.h" #define WM_REQUIRE_RELEASE WM_APP + 13 ///////////////////////////////////////////////////////////////////////////// // CBitmapButton class ATL_NO_VTABLE CBitmapButton : public CComObjectRootEx<CComSingleThreadModel>, public IDispatchImpl<IBitmapButton, &IID_IBitmapButton, &LIBID_WICKEDWIDGETSLib>, public CComControl<CBitmapButton>, public IPersistStreamInitImpl<CBitmapButton>, public IOleControlImpl<CBitmapButton>, public IOleObjectImpl<CBitmapButton>, public IOleInPlaceActiveObjectImpl<CBitmapButton>, public IViewObjectExImpl<CBitmapButton>, public IOleInPlaceObjectWindowlessImpl<CBitmapButton>, public IConnectionPointContainerImpl<CBitmapButton>, public IPersistStorageImpl<CBitmapButton>, public ISpecifyPropertyPagesImpl<CBitmapButton>, public IQuickActivateImpl<CBitmapButton>, public IDataObjectImpl<CBitmapButton>, public IProvideClassInfo2Impl<&CLSID_BitmapButtonBar, &DIID__IBitmapButtonEvents, &LIBID_WICKEDWIDGETSLib>, public IPropertyNotifySinkCP<CBitmapButton>, public CComCoClass<CBitmapButton, &CLSID_BitmapButtonBar>, public CProxy_IBitmapButtonEvents< CBitmapButton >, public CObjectTable<CBitmapButton> { public: STDMETHOD(AddTooltips)(/*[in]*/ BSTR strTips); STDMETHOD(get_ToggleButton)(/*[out, retval]*/ VARIANT_BOOL *pVal); STDMETHOD(put_ToggleButton)(/*[in]*/ VARIANT_BOOL newVal); STDMETHOD(get_LeftOffset)(/*[out, retval]*/ long *pVal); STDMETHOD(put_LeftOffset)(/*[in]*/ long newVal); STDMETHOD(get_HasHover)(/*[out, retval]*/ VARIANT_BOOL *pVal); STDMETHOD(put_HasHover)(/*[in]*/ VARIANT_BOOL newVal); STDMETHOD(get_ButtonCount)(/*[out, retval]*/ long *pVal); STDMETHOD(put_ButtonCount)(/*[in]*/ long newVal); STDMETHOD(get_ButtonWidth)(/*[out, retval]*/ long *pVal); STDMETHOD(put_ButtonWidth)(/*[in]*/ long newVal); STDMETHOD(get_ButtonHeight)(/*[out, retval]*/ long *pVal); STDMETHOD(put_ButtonHeight)(/*[in]*/ long newVal); STDMETHOD(put_Picture)(/*[in]*/ IPictureDisp* newVal); STDMETHOD(putref_Picture)(/*[in]*/ IPictureDisp* newVal); STDMETHOD(get_Picture)(/*[out, retval]*/ IPictureDisp **pVal); CBitmapButton() : m_hdc(NULL) { m_bWindowOnly = TRUE; m_nWidth = 0; m_nHeight = 0; m_nButtonCount = 5; m_nClickedButton = -1; m_hdcMem = NULL; m_nButtonWidth = 23; m_bHasHover = VARIANT_FALSE; m_lLeftOffset = 0; m_hWndNotify = NULL; m_bIsToggle = false; ZeroMemory(m_arrTooltipOffsets, sizeof(long) * 49); ZeroMemory(m_szTooltips, sizeof(wchar_t) * 1023); CreateNotifyWnd(); } void FinalRelease() { // _ASSERT(m_hWndNotify); if (m_hWndNotify) { RemoveFromClassTable((long)m_hWndNotify); ::DestroyWindow(m_hWndNotify); } } DECLARE_REGISTRY_RESOURCEID(IDR_BITMAPBUTTON) DECLARE_PROTECT_FINAL_CONSTRUCT() BEGIN_COM_MAP(CBitmapButton) COM_INTERFACE_ENTRY(IBitmapButton) COM_INTERFACE_ENTRY(IDispatch) COM_INTERFACE_ENTRY(IViewObjectEx) COM_INTERFACE_ENTRY(IViewObject2) COM_INTERFACE_ENTRY(IViewObject) COM_INTERFACE_ENTRY(IOleInPlaceObjectWindowless) COM_INTERFACE_ENTRY(IOleInPlaceObject) COM_INTERFACE_ENTRY2(IOleWindow, IOleInPlaceObjectWindowless) COM_INTERFACE_ENTRY(IOleInPlaceActiveObject) COM_INTERFACE_ENTRY(IOleControl) COM_INTERFACE_ENTRY(IOleObject) COM_INTERFACE_ENTRY(IPersistStreamInit) COM_INTERFACE_ENTRY2(IPersist, IPersistStreamInit) COM_INTERFACE_ENTRY(IConnectionPointContainer) COM_INTERFACE_ENTRY(ISpecifyPropertyPages) COM_INTERFACE_ENTRY(IQuickActivate) COM_INTERFACE_ENTRY(IPersistStorage) COM_INTERFACE_ENTRY(IDataObject) COM_INTERFACE_ENTRY(IProvideClassInfo) COM_INTERFACE_ENTRY(IProvideClassInfo2) COM_INTERFACE_ENTRY_IMPL(IConnectionPointContainer) END_COM_MAP() BEGIN_PROP_MAP(CBitmapButton) PROP_DATA_ENTRY("_cx", m_sizeExtent.cx, VT_UI4) PROP_DATA_ENTRY("_cy", m_sizeExtent.cy, VT_UI4) PROP_ENTRY("Picture", DISPID_BPICTURE, CLSID_NULL) PROP_ENTRY("ButtonCount", DISPID_BUTTONCOUNT, CLSID_NULL) PROP_ENTRY("ButtonWidth", DISPID_BUTTONWIDTH, CLSID_NULL) PROP_ENTRY("HasHover", DISPID_HASHOVER, CLSID_NULL) PROP_ENTRY("LeftOffset", DISPID_LEFTOFFSET, CLSID_NULL) PROP_ENTRY("IsToggle", DISPID_ISTOGGLE, CLSID_NULL) // Example entries // PROP_ENTRY("Property Description", dispid, clsid) // PROP_PAGE(CLSID_StockColorPage) END_PROP_MAP() BEGIN_CONNECTION_POINT_MAP(CBitmapButton) CONNECTION_POINT_ENTRY(IID_IPropertyNotifySink) CONNECTION_POINT_ENTRY(DIID__IBitmapButtonEvents) END_CONNECTION_POINT_MAP() BEGIN_MSG_MAP(CBitmapButton) CHAIN_MSG_MAP(CComControl<CBitmapButton>) DEFAULT_REFLECTION_HANDLER() MESSAGE_HANDLER(WM_LBUTTONDOWN, OnLButtonDown) MESSAGE_HANDLER(WM_LBUTTONUP, OnLButtonUP) MESSAGE_HANDLER(WM_MOUSEMOVE, OnMouseMove) END_MSG_MAP() // Handler prototypes: // LRESULT MessageHandler(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled); // LRESULT CommandHandler(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled); // LRESULT NotifyHandler(int idCtrl, LPNMHDR pnmh, BOOL& bHandled); // IViewObjectEx DECLARE_VIEW_STATUS(VIEWSTATUS_SOLIDBKGND | VIEWSTATUS_OPAQUE) // IBitmapButton protected: void LoadBitmap(bool bOnlySizeChanged = false); HRESULT OnDraw(ATL_DRAWINFO& di) { RECT& rc = *(RECT*)di.prcBounds; if (m_hdc == NULL) LoadBitmap(); if (m_hdc && m_hdcMem) { // Draw entire button bar onto window BitBlt(m_hdcMem, 0, 0, m_nWidth, m_nHeight, m_hdc, 0, 0, SRCCOPY); if (m_nClickedButton != -1) { // We draw the pressed bitmap BitBlt(m_hdcMem, m_rcClickedButton.left, m_rcClickedButton.top, m_nButtonWidth, m_nHeight, m_hdc, m_rcClickedButton.left, m_nHeight, SRCCOPY); } BitBlt(di.hdcDraw, 0, 0, m_nWidth, m_nHeight, m_hdcMem, 0, 0, SRCCOPY); } else if (m_picture) { OLE_XSIZE_HIMETRIC w; OLE_YSIZE_HIMETRIC h; m_picture->get_Width(&w); m_picture->get_Height(&h); m_picture->Render(di.hdcDraw, 0, 0, m_nWidth, -m_nHeight, 0, 0, w, h/2, NULL); } return S_OK; } LRESULT OnLButtonDown(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled) { DWORD xPos = LOWORD(lParam); // horizontal position of cursor DWORD yPos = HIWORD(lParam); // vertical position of cursor if (m_bIsToggle == FALSE || m_nClickedButton == -1) m_nClickedButton = ButtonHitTest(xPos, yPos, &m_rcClickedButton); else { // this is a toggle button, and we are clicking it to unpress it // m_nClickedButton = -1; m_bIsDown = true; } SetCapture(); RedrawWindow(NULL, NULL, RDW_INVALIDATE|RDW_UPDATENOW); return 0; } LRESULT OnLButtonUP(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled) { ReleaseCapture(); DWORD xPos = LOWORD(lParam); // horizontal position of cursor DWORD yPos = HIWORD(lParam); // vertical position of cursor int iIndex = ButtonHitTest(xPos, yPos); if (m_bIsToggle == FALSE) m_nClickedButton = -1; else if (m_bIsToggle == TRUE && iIndex != m_nClickedButton) { // we have dragged our cursor out of a button area // adn raised the mouse button. this means that our // click even will not be fire, so we don't toggle // the button state if (m_nClickedButton != -1 && m_bIsDown) m_nClickedButton = -1; } RedrawWindow(NULL, NULL, RDW_INVALIDATE|RDW_UPDATENOW); this->AddRef(); // in case it gets unloaded in Click. Atl bug try { if (iIndex != -1) { Fire_Click(iIndex); if (m_bIsToggle && m_nClickedButton != -1) { // we are in toggle mode, and we where previously // selected m_nClickedButton = -1; m_bIsDown = false; //RedrawWindow(NULL, NULL, RDW_INVALIDATE|RDW_UPDATENOW); } } } catch (...) { } ::PostMessage(m_hWndNotify, WM_REQUIRE_RELEASE, 0, 0); return 0; } LRESULT OnMouseMove(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled) { DWORD xPos = LOWORD(lParam); // horizontal position of cursor DWORD yPos = HIWORD(lParam); // vertical position of cursor int nIndex = -1; if ((nIndex = ButtonHitTest(xPos, yPos, NULL)) != -1) { POINT pt = {xPos, yPos}; wchar_t * pstr = &m_szTooltips[m_arrTooltipOffsets[nIndex]]; USES_CONVERSION; m_tooltip.CreateTooltip(pt, W2A(pstr), m_hWnd); m_tooltip.NotifyTooltip(uMsg, lParam, wParam); } return 0; } int ButtonHitTest(long x, long y, RECT * rcButton = NULL); BOOL CreateNotifyWnd(); static LRESULT CALLBACK NotifyWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam); private: long m_arrTooltipOffsets[50]; wchar_t m_szTooltips[1024]; CTooltip m_tooltip; bool m_bIsToggle; HWND m_hWndNotify; long m_lLeftOffset; bool m_bIsDown; VARIANT_BOOL m_bHasHover; CComPtr<IPictureDisp> m_pictureDisp; CComPtr<IPicture> m_picture; RECT m_rcClickedButton; HDC m_hdcMem; HDC m_hdc; long m_nWidth; long m_nHeight; long m_nButtonCount; long m_nClickedButton; long m_nButtonWidth; }; #endif //__BITMAPBUTTON_H_
5c5e08c64771b1d4fa7ac0913cd18f647c36753e
f86d1dab86efe0467de5db5904476129cba38529
/GameEngine/Math/src/Matrix33.cpp
eac82c3d38d1617b9fd5277a00d1223e80ab6ff1
[ "MIT" ]
permissive
Gnaag98/game-engine
d458d6548c072ebc2619ac3085b0a48a14728728
40e4d65953c17718accd0fe8129bf934873bb306
refs/heads/master
2020-05-27T16:24:31.748094
2019-06-16T12:45:43
2019-06-16T12:45:43
188,699,768
0
0
MIT
2019-05-29T14:05:22
2019-05-26T15:23:44
C++
UTF-8
C++
false
false
1,627
cpp
Matrix33.cpp
#include "Matrix33.h" #include <iostream> #include <iomanip> #include "Matrix22.h" Matrix33f::Matrix33f(const float m00, const float m01, const float m02, const float m10, const float m11, const float m12, const float m20, const float m21, const float m22) { m[0][0] = m00; m[0][1] = m01; m[0][2] = m02; m[1][0] = m10; m[1][1] = m11; m[1][2] = m12; m[2][0] = m20; m[2][1] = m21; m[2][2] = m22; } auto Matrix33f::operator[](int i) const -> const Row& { return m[i]; } auto Matrix33f::operator[](int i) -> Row& { return m[i]; } auto Matrix33f::det() const -> float { auto m11 = Matrix22f{ m[1][1], m[1][2], m[2][1], m[2][2] }; auto m12 = Matrix22f{ m[1][0], m[1][2], m[2][0], m[2][2] }; auto m13 = Matrix22f{ m[1][0], m[1][1], m[2][0], m[2][1] }; return m[0][0] * m11.det() - m[0][1] * m12.det() + m[0][2] * m13.det(); } auto operator<<(std::ostream& s, const Matrix33f& m) -> std::ostream& { auto old_flags = s.flags(); auto width = 9; s.precision(5); s.setf(std::ios_base::fixed); s << "|" << std::setw(width) << m[0][0] << " " << std::setw(width) << m[0][1] << " " << std::setw(width) << m[0][2] << " |\n" << "|" << std::setw(width) << m[1][0] << " " << std::setw(width) << m[1][1] << " " << std::setw(width) << m[1][2] << " |\n" << "|" << std::setw(width) << m[2][0] << " " << std::setw(width) << m[2][1] << " " << std::setw(width) << m[2][2] << " |"; s.flags(old_flags); return s; }
fac2291a7873cf09aa2b6349352277030a20548f
6a945029cfe7def34dc940e96569930141da6853
/SB16.cpp
9f0c21f3a06fdabda3fe40c48967f9261ebc3e1f
[]
no_license
amtsai96/os2016_group14
b408a0db48bacce078116a78e1254145c2349666
17840f19b3b081dc3f9d8bbeb17781efade003e6
refs/heads/master
2021-06-10T14:15:50.903073
2017-01-16T14:38:15
2017-01-16T14:38:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
14,305
cpp
SB16.cpp
#ifdef __APPLE__ #include <GLUT/glut.h> #else #include <windows.h> //#include <GL/glew.h> #include <GL/glut.h> #endif #include "RGBpixmap.h" #include <iostream> #include <semaphore.h> //#include <pthread.h> #include <unistd.h> #include <cstdlib> #include <random> #include <thread> //#include <semaphore.h> #include <mutex> #include <condition_variable> #include <dispatch/dispatch.h> #define NUM_BARBERS 4 #define NUM_CHAIRS 5 #define MEAN 5 #define TIME_RANGE 10 #define NUM_CUSTOMER 15 using namespace std; /* * The barber shop has m barbers with m barber chairs, * and n chairs (m < n) for waiting customers, if any, to sit in. * If there are no customers present, a barber sits down in a barber chair and falls asleep. * When a customer arrives, he has to wake up a sleeping barber. * If additional customers arrive while all barbers are cutting customers' hair, * they either sit down (if there are empty chairs) or leave the shop (if all chairs are full). * The thread synchronization problem is to program the barbers and the customers * without getting into race conditions. */ /* initial for GUI */ bool isBusy[NUM_BARBERS]; int cutting[NUM_BARBERS]; bool isSit[NUM_CHAIRS]; int seat[NUM_CHAIRS]; int comeCus[NUM_CUSTOMER]; //Set windows int screenWidth = 800 , screenHeight = 600; RGBApixmap bg; RGBApixmap barSleep,barBusy,chairPic,cusPic[20]; class Semaphore { public: Semaphore(int value=1): count{value}, wakeups{0} {} void wait(){ std::unique_lock<std::mutex> lock{mutex}; if (--count<0) { // count is not enough ? condition.wait(lock, [&]()->bool{ return wakeups>0;}); // suspend and wait ... --wakeups; // ok, me wakeup ! } } void signal(){ std::lock_guard<std::mutex> lock{mutex}; if(++count<=0) { // have some thread suspended ? ++wakeups; condition.notify_one(); // notify one ! } } private: int count; int wakeups; std::mutex mutex; std::condition_variable condition; }; Semaphore barbers(NUM_BARBERS); Semaphore customers(0); mutex Mutex,ioMutex,cusMutex,barMutex; struct customerData { int cusID; bool hasFinishedCutting; }; typedef struct chair { struct customerData *data; /*the customer who sits on the chair*/ /*If nobody sits on it, then customerData = null*/ int seqNumber;/*The chair's sequence number of all chairs*/ } Chair; Chair waitingChairs[NUM_CHAIRS]; /*Chairs for waiting area*/ int availableChairs = NUM_CHAIRS; /*Number of available waiting chairs*/ int totalServedCustomers = 0; /*number of customers that have been served by barbers*/ int nextID = 1; /* ID for customer */ int nextCut = 0; /* Point to the chair which next served customer sits on */ int nextSit = 0; /* Point to the chair which will be sat when next customer comes */ /* Global Time */ int cus_perTime[TIME_RANGE]; int currentTime = 0; /*For poisson distribution*/ float mean = MEAN; int timeRange = TIME_RANGE; //1 period will have how many time unit int num_customer = NUM_CUSTOMER; //number (for poisson distribution) to create customers int realNum_customer = 0; thread mainThread; void showWhoSitOnChair() { ioMutex.lock(); // Acquire access to waiting cout<<"Waiting Chairs:"; for(int i=0; i<NUM_CHAIRS; i++) { if(waitingChairs[i].data != nullptr){ isSit[i] = true; cout << waitingChairs[i].data->cusID << " "; } else{ isSit[i] = false; cout << "0 "; } } cout << endl; ioMutex.unlock(); // Release waiting } void cutHair(int barberID, Chair wChair) { cusMutex.lock(); ++totalServedCustomers; barMutex.unlock(); ioMutex.lock(); // Acquire access to waiting cout<<"total:"<<totalServedCustomers<<"/"<<realNum_customer<<endl; ioMutex.unlock(); // Release waiting cusMutex.unlock(); ioMutex.lock(); // Acquire access to waiting cout << "(B) Barber " << barberID <<" is cutting Customer No." << wChair.data->cusID << "'s hair !"<<endl; ioMutex.unlock(); // Release waiting waitingChairs[wChair.seqNumber].data = nullptr; for(long long i=0; i<0.5*NSEC_PER_SEC; i++); //Cut hair time ioMutex.lock(); // Acquire access to waiting cout << "(B)Barber " << barberID <<" just finished cutting Customer No." << wChair.data->cusID << "'s hair !" <<endl<<endl;; ioMutex.unlock(); // Release waiting wChair.data->hasFinishedCutting = true; } void *barberThread(void* arg) { int *pID = (int*)arg; ioMutex.lock(); // Acquire access to waiting cout << "This is Barber No." << *pID << endl; ioMutex.unlock(); // Release waiting while(1) { barMutex.lock(); cusMutex.lock(); if(totalServedCustomers < realNum_customer){ cusMutex.unlock(); customers.wait(); // Try to acquire a customer. //Go to sleep if no customers Mutex.lock(); // Acquire access to waiting //When a barber is waken -> wants to modify # of available chairs barbers.signal(); // The barber is now ready to cut hair int nowCut = nextCut; nextCut = (nextCut+1) % NUM_CHAIRS; availableChairs++; Mutex.unlock(); // Release waiting /* GUI change barber's mode */ isBusy[*pID-1] = true; cutting[*pID-1] = waitingChairs[nowCut].data->cusID; isSit[waitingChairs[nowCut].seqNumber] = false; glutPostRedisplay(); //////////////GUI cutHair(*pID, waitingChairs[nowCut]); //pick the customer which counter point isBusy[*pID-1] = false; //this_thread::sleep_for( chrono::milliseconds( 1000 )); glutPostRedisplay(); //////////////GUI } else{ barMutex.unlock(); cusMutex.unlock(); break; } } } void waitForHairCut(struct customerData *a) { while(a->hasFinishedCutting == false); } void *customerThread(void* arg) { struct customerData *data = (struct customerData*)arg; Mutex.lock(); // Acquire access to waiting if( availableChairs == 0 ) { ioMutex.lock(); // Acquire access to waiting cout << "There is no available chair. Customer No." << data->cusID << " is leaving!" << endl; comeCus[data->cusID-1] = false; ioMutex.unlock(); // Release waiting cusMutex.lock(); --realNum_customer; cusMutex.unlock(); Mutex.unlock(); //pthread_exit(0); } ioMutex.lock(); // Acquire access to waiting cout << "Customer No." << data->cusID << " is sitting on chair " << nextSit << "." << endl; comeCus[data->cusID-1] = false; seat[nextSit] = data->cusID; ioMutex.unlock(); // Release waiting waitingChairs[nextSit].data = data; nextSit = (nextSit+1) % NUM_CHAIRS; availableChairs--; showWhoSitOnChair(); //usleep(10000); glutPostRedisplay(); //////////////GUI customers.signal(); // Wake up a barber (if needed) Mutex.unlock(); // Release waiting barbers.wait(); // Go to sleep if number of available barbers is 0 waitForHairCut(data); ioMutex.lock(); // Acquire access to waiting cout << "(C)Customer No." << data->cusID <<" just finished his haircut!"<<endl; ioMutex.unlock(); // Release waiting } int *possionDistribution(float mean, int range, int num_period) { const int NUM_TIMES = num_period; default_random_engine generator; poisson_distribution<int> distribution(mean); int *frequenceArray = new int[range]; for(int i=0; i<range; i++) frequenceArray[i] = 0; for(int i=0; i<NUM_TIMES; ) { int number = distribution(generator); if(number < range){ frequenceArray[number]++; i++; } } realNum_customer = 0; for(int i=0; i<range; i++) { cusMutex.lock(); ioMutex.lock(); cout << i << " : " << frequenceArray[i] <<endl; ioMutex.unlock(); realNum_customer += frequenceArray[i]; cusMutex.unlock(); } ioMutex.lock(); cout << "Sum : " << realNum_customer << endl << endl; ioMutex.unlock(); return frequenceArray; } void createCustomers(int timeRange,int num_customer,float mean,int* cusArray, thread cus[NUM_CUSTOMER],thread bar[NUM_BARBERS]) { int barberID[NUM_BARBERS]; for(int i=0; i<NUM_BARBERS; i++) { barberID[i] = i+1; // fill the barID bar[i] = thread(&barberThread,(void*)&barberID[i]); } int cusTH = 0; //this is n-th customer. (0 represent the first customer) struct customerData cusData[num_customer]; for(currentTime=0; currentTime<timeRange; currentTime++) { ioMutex.lock(); cout<<"*****TIME:"<<currentTime<<endl; ioMutex.unlock(); // Release waiting for(int j=0; j<cusArray[currentTime]; j++) { cusData[cusTH].cusID = nextID; cusData[cusTH].hasFinishedCutting = false; ioMutex.lock(); cout <<endl<< "Create Customer No."<< cusData[cusTH].cusID <<".\t(now Time :"<< currentTime << ")"<<endl; comeCus[cusData[cusTH].cusID-1] = true; glutPostRedisplay(); //////////////GUI usleep(100000); // next time unit ioMutex.unlock(); // Release waiting cus[cusTH] = thread(&customerThread, (void*)&cusData[cusTH]); cusTH ++; nextID ++; usleep(10); // avoid create earlier but execute thread laterly } usleep(1000000); // next time unit } for(int i=0; i<num_customer; i++) { if (cus[i].get_id() != thread::id()) { cus[i].join(); } } for(int i=0; i<NUM_BARBERS; i++) { if (bar[i].get_id() != thread::id()) { bar[i].join(); } } cout<<endl<<"All customers finish their haircuts!"<<endl; } void runMain(){ /* mean = MEAN; timeRange = TIME_RANGE; num_customer = NUM_CUSTOMER; */ /* initial */ for(int i=0;i<NUM_BARBERS;i++){ cutting[i] = -1; isBusy[i] = false; } for(int i=0;i<NUM_CUSTOMER;i++){ comeCus[i] = false; } for(int i=0; i<NUM_CHAIRS; i++) // fill the number of tn of all waiting chair waitingChairs[i].seqNumber = i; int *cusArray = possionDistribution(mean, timeRange, num_customer); //Use p_s create thread bar[NUM_BARBERS]; thread cus[NUM_CUSTOMER]; createCustomers(timeRange,num_customer,mean,cusArray,cus,bar); } /***************************** OpenGL *********************************/ static void CheckError(int line) { GLenum err = glGetError(); if (err) { printf("GL Error %s (0x%x) at line %d\n", gluErrorString(err), (int) err, line); } } void reshape(int w, int h) { /* Save the new width and height */ screenWidth = w; screenHeight = h; /* Reset the viewport... */ glViewport(0, 0, screenWidth, screenHeight); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0.0, (GLfloat)screenWidth, 0.0, (GLfloat)screenHeight, -1.0, 1.0); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); } void display(void) { glClear(GL_COLOR_BUFFER_BIT); //draw background glRasterPos2i(0, 0); bg.blend(); /* chairs */ chairPic.blendTexRotate(30, 200,1,1); chairPic.blendTexRotate(180, 200,1,1); chairPic.blendTexRotate(330, 200,1,1); chairPic.blendTexRotate(480, 200,1,1); chairPic.blendTexRotate(630, 200,1,1); for(int i=0;i<NUM_BARBERS;i++){ if(isBusy[i]){ barBusy.blendTexRotate(50+150*i,screenHeight-150,1,1); cusPic[cutting[i]-1].blendTexRotate(50+150*i,screenHeight-150,0.95,0.95); } else barSleep.blendTexRotate(50+150*i,screenHeight-150,1,1); } /* barber 1 */ /*if(isBusy[0]){ barBusy.blendTexRotate(50, 450,1,1); cusPic[cutting[0]-1].blendTexRotate(50, 450,0.95,0.95); } else barSleep.blendTexRotate(50, 450,1,1); */ /* barber 2 */ /*if(isBusy[1]){ barBusy.blendTexRotate(200, 450,1,1); cusPic[cutting[1]-1].blendTexRotate(200, 450,0.95,0.95); } else barSleep.blendTexRotate(200, 450,1,1);*/ /* barber 3 */ /*if(isBusy[2]){ barBusy.blendTexRotate(350, 450,1,1); cusPic[cutting[2]-1].blendTexRotate(350, 450,0.95,0.95); } else barSleep.blendTexRotate(350, 450,1,1);*/ /* customers sit on the chairs */ if(isSit[0]){ cusPic[seat[0]-1].blendTexRotate(50, 220,0.95,0.95); } if(isSit[1]){ cusPic[seat[1]-1].blendTexRotate(200, 220,0.95,0.95); } if(isSit[2]){ cusPic[seat[2]-1].blendTexRotate(350, 220,0.95,0.95); } if(isSit[3]){ cusPic[seat[3]-1].blendTexRotate(500, 220,0.95,0.95); } if(isSit[4]){ cusPic[seat[4]-1].blendTexRotate(650, 220,0.95,0.95); } /* coming customers */ int count = 0; for(int i=0;i<NUM_CUSTOMER;i++){ if(comeCus[i]==true){ cusPic[i].blendTexRotate(50+150*count, 50,0.95,0.95); count++; } } CheckError(__LINE__); glutSwapBuffers(); } void keys(unsigned char key, int x, int y) { switch(key) { case 'Q': case 'q': if (mainThread.get_id() != thread::id()) { mainThread.join(); } exit(0); break; case ' ': mainThread = thread(runMain); break; case 'i': cout<<"Enter mean number (for poisson distribution):"; cin>>mean; cout<<"Enter the time range (sec) that you want to test:"; cin>>timeRange; cout<<"Enter number (for poisson distribution) to create customers:"; cin>>num_customer; break; } //switch(key) glutPostRedisplay(); } void init( void ) { glutDisplayFunc(display); glutReshapeFunc(reshape); glutKeyboardFunc(keys); glShadeModel(GL_SMOOTH); glClearColor( 1.0, 1.0, 1.0, 0.0 ); } int main( int argc, char** argv ) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB); glutInitWindowSize(screenWidth, screenHeight); glutInitWindowPosition(0, 0); glutCreateWindow("Barber Sleeping Problem"); init(); barSleep.readBMPFile("pic/barber_sleep.BMP"); barBusy.readBMPFile("pic/barber_busy.BMP"); chairPic.readBMPFile("pic/chair.BMP"); cusPic[0].readBMPFile("pic/cus_1.bmp"); cusPic[1].readBMPFile("pic/cus_2.bmp"); cusPic[2].readBMPFile("pic/cus_3.bmp"); cusPic[3].readBMPFile("pic/cus_4.bmp"); cusPic[4].readBMPFile("pic/cus_5.bmp"); cusPic[5].readBMPFile("pic/cus_6.bmp"); cusPic[6].readBMPFile("pic/cus_7.bmp"); cusPic[7].readBMPFile("pic/cus_8.bmp"); cusPic[8].readBMPFile("pic/cus_9.bmp"); cusPic[9].readBMPFile("pic/cus_10.bmp"); cusPic[10].readBMPFile("pic/cus_11.bmp"); cusPic[11].readBMPFile("pic/cus_12.bmp"); cusPic[12].readBMPFile("pic/cus_13.bmp"); cusPic[13].readBMPFile("pic/cus_14.bmp"); cusPic[14].readBMPFile("pic/cus_15.bmp"); cusPic[15].readBMPFile("pic/cus_16.bmp"); cusPic[16].readBMPFile("pic/cus_17.bmp"); cusPic[17].readBMPFile("pic/cus_18.bmp"); cusPic[18].readBMPFile("pic/cus_19.bmp"); cusPic[19].readBMPFile("pic/cus_20.bmp"); barSleep.setChromaKey(255, 255, 255); barBusy.setChromaKey(255, 255, 255); chairPic.setChromaKey(255, 255, 255); for (int i=0; i<20; i++) cusPic[i].setChromaKey(255, 255, 255); glutMainLoop(); return 0; }
24838a1a3358b565200f70c03de16d2fb55f836e
b2f9e161c4e4ecbd5c1ed0c81258cfc79dd4297e
/28.cpp
3f4e34a23965eb3ef072fdfcc349f6be470bf2e3
[]
no_license
chaitanyatekane/datastructureandalgorithms
0dfc2608db48d6886436fc350841f6ebfb192b99
3f6e01e1af0ae130f7f63d6d9067662dc1e81009
refs/heads/main
2023-03-21T09:28:39.082138
2021-03-16T16:04:01
2021-03-16T16:04:01
325,555,658
2
1
null
null
null
null
UTF-8
C++
false
false
467
cpp
28.cpp
// Print 0-1 pattern (pattern questions) /* n=5 1 0 1 1 0 1 0 1 0 1 1 0 1 0 1 */ #include<iostream> using namespace std; int main(){ int n; cout<<"Enter Value of n :- "; cin>>n; for(int i=1; i<=n; i++){ for(int j=1; j<=i; j++){ if((i+j)%2==0){ cout<<"1"<<" "; }else{ cout<<"0"<<" "; } } cout<<endl; } return 0; }
89071138ea38b48f5c18b4cc9f23c11bdb03d9e5
c06d73520e698ed6d9a74aa5113aca54b00ef26f
/InvertedFile/IFarray.h
17359282d617c65b69e79f6061e471506f9f9219
[]
no_license
bbuckey/cpp
47020a212368c38d3c81fa0a21d8ed71d381567c
6a72b784ca9ab9b984ebc4e088e8177eabd8b040
refs/heads/master
2021-01-20T11:14:23.441628
2014-01-28T01:57:52
2014-01-28T01:57:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,066
h
IFarray.h
#include <iostream> #include <fstream> #include <string> #include "IFnode.h" #include "IFdnode.h" #include "IFstops.h" using namespace std; const int max = 100; class ifarray { private: link * parray[max]; string karray[max][max]; link * marray[max]; int size; int msize; dlink * head_ptr; slink * s_ptr; public: ifarray(){size = 0; msize = max; head_ptr = NULL; s_ptr = NULL;} void set_size(int _size){size = _size;} int r_size(){ return size;} void setarray() { for(int i = 0; i < msize; ++i) { parray[i] = NULL; karray[i][i] = ""; marray[i] = NULL; } } void stop_insert(string entry) { slink * newbox = new slink; newbox->set_stopw(entry); newbox->set_slink(s_ptr); s_ptr = newbox; } void list_head_insert(link *& a,int entry) { link * newbox = new link; newbox->setdoc(entry); newbox->set_link(a); a = newbox; } void insert_muti(link *& a,int entry) { link * newbox = new link; newbox->setdoc(entry); newbox->set_link(a); a = newbox; } void insert_s(string x, int i) { karray[i][i] = x; list_head_insert(parray[i],0); insert_muti(marray[i],0); } void insert_d(int docn, int key) { if(parray[key]->rdocnum() == 0) { link * a = parray[key]; parray[key] = NULL; delete a; } list_head_insert(parray[key],docn); } void insert_mu(int docn, int key) { if(marray[key]->rdocnum() == 0) { link * a = marray[key]; marray[key] = NULL; delete a; } insert_muti(marray[key],docn); } bool checkdub(string x, int r) { if(r == 0) return false; for(int i = 0; i < r; ++i) { if( x == karray[i][i]) return true; } return false; } void checkif(string x, int p) { for(int i = 0; i < size; ++i) { if(karray[i][i] == "") ; else if(x == karray[i][i]) { insert_d(p,i); } } return ; } void head_insert(string a, int number /*int anumber*/) { dlink * newbox = new dlink; // newbox->set_darray(anumber); newbox->set_sdoc(a); newbox->set_dnum(number); newbox->set_dlink(head_ptr); head_ptr = newbox; } int docnumb(){ return head_ptr->r_dnum();} bool f_stopw(string x) { for(slink * p1 = s_ptr; p1 != NULL; p1=p1->re_next()) { if(x == p1->r_stopw()) return true; } return false; } void print(ofstream &outfile) { string s; for(int i = 0; i < size; ++i) { if(karray[i][i] == "") return; if(karray[i][i] == "*") {++i;} if(karray[i][i] != "*" && karray[i+1][i+1] != "*") { int x = 0; i = findingmuti(i); for(link * p1 = marray[i]; p1 != NULL; p1 = p1->rnext()) { int q = 0; q = p1->rdocnum(); outfile << q << " "; } } else if(karray[i][i] != "" && karray[i+1][i+1] == "*") { for(link * p1 = parray[i]; p1 != NULL; p1 = p1->rnext()) { int x = 0; x = p1->rdocnum(); outfile << x << " "; } } outfile << endl; outfile << "*" << endl; } } int findingmuti(int i) { if(karray[i][i] != "*" && karray[i+1][i+1] != "*") for(link * p1 = parray[i]; p1 != NULL; p1 = p1->rnext()) { for(link * p2 = parray[i+1]; p2 != NULL; p2 = p2->rnext()) { int x = 0; if( p1->rdocnum() == p2->rdocnum()) { x = p1->rdocnum(); insert_mu(x,i+1); } } } ++i; while(karray[i+1][i+1] != "*" && karray[i][i] != "*") { for(link * p3 = parray[i+1]; p3 != NULL; p3 = p3->rnext()) { for(link * p10 = marray[i]; p10 != NULL; p10 = p10->rnext()) { int x = 0; if( p10->rdocnum() == p3->rdocnum()) { x = p10->rdocnum(); insert_mu(x,i+1); } } } ++i; } return i; } void find_words() { for( dlink * p7 = head_ptr; p7 != NULL; p7 = p7->next_d()) { checkif(p7->r_doc(),p7->r_dnum()); } return; } };
5d78e3ce00ab623404c9a052c71d8c08ba949b59
653523b8be62f070a532932074f5fcfec514f9f4
/leetcode/June-17.cpp
12979cd3becedff524f0689263bf9cebd3b834c6
[]
no_license
nitya2602/competitive-coding
4b02c84f09c8a0bc48ff02ac7dac1a227e613cd2
c161da52ab2791add235836d6661edb1dbf37d6b
refs/heads/master
2023-07-01T03:39:54.968205
2021-08-07T07:34:59
2021-08-07T07:34:59
284,318,327
0
0
null
null
null
null
UTF-8
C++
false
false
2,274
cpp
June-17.cpp
class Solution { public: void solve(vector<vector<char>>& board) { if(board.size()>2) { //replace all O's with - for(int i=0; i<board.size(); i++) { for(int j=0; j<board[i].size(); j++) { if(board[i][j]=='O') board[i][j] = '-'; } } //for corners if(board[0][0]=='-') board[0][0] = 'O'; if(board[0][board[0].size()-1]=='-') board[0][board[0].size()-1] = 'O'; if(board[board.size()-1][0]=='-') board[board.size()-1][0] = 'O'; if(board[board.size()-1][board[0].size()-1]=='-') board[board.size()-1][board[0].size()-1] = 'O'; //first row for(int i=1; i<board[0].size()-1; i++) { if(board[0][i]=='-') { board[0][i] = 'O'; if(board[1][i]=='-') board[1][i] = 'O'; } } //last row for(int i=1; i<board[board.size()-1].size()-1; i++) { if(board[board.size()-1][i]=='-') { board[board.size()-1][i] = 'O'; if(board[board.size()-2][i]=='-') board[board.size()-2][i] = 'O'; } } //first column for(int i=1; i<board.size()-1; i++) { if(board[i][0]=='-') { board[i][0] = 'O'; if(board[i][1]=='-') board[i][1] = 'O'; } } //last column for(int i=1; i<board.size()-1; i++) { if(board[i][board[i].size()-1]=='-') { board[i][board[i].size()-1] = 'O'; if(board[i][board[i].size()-2]=='-') board[i][board[i].size()-2] = 'O'; } } //replace the remaining -'s with O for(int i=0; i<board.size(); i++) { for(int j=0; j<board[0].size(); j++) { if(board[i][j]=='-') board[i][j] = 'X'; } } } } };
f316121111bcdcbe7f94072b9eefcb13232347bd
c3ac894509c368160005144861aabf3ecc9b90ec
/[剑指 Offer 27]二叉树的镜像.cpp
3865fa23c142c9f4440111d6646bf823935ba1d5
[]
no_license
oxygenbytes/swordoffer
f43a64669a691291eb91b22c0867f1f74d6cd81c
53e0a2b50fea8d06b022f0848385804400db90b2
refs/heads/master
2023-03-08T11:43:56.514836
2021-02-19T02:16:46
2021-02-19T02:16:46
340,233,812
0
0
null
null
null
null
UTF-8
C++
false
false
1,366
cpp
[剑指 Offer 27]二叉树的镜像.cpp
/* --- title: "[剑指 Offer 27]二叉树的镜像" date: 2021-02-18 11:35:20 draft: false toc: true tags: - SwordOffer - Leetcode --- */ //请完成一个函数,输入一个二叉树,该函数输出它的镜像。 // // 例如输入: // // 4 // / \ // 2 7 // / \ / \ //1 3 6 9 //镜像输出: // // 4 // / \ // 7 2 // / \ / \ //9 6 3 1 // // // // 示例 1: // // 输入:root = [4,2,7,1,3,6,9] //输出:[4,7,2,9,6,3,1] // // // // // 限制: // // 0 <= 节点个数 <= 1000 // // 注意:本题与主站 226 题相同:https://leetcode-cn.com/problems/invert-binary-tree/ // Related Topics 树 // 👍 101 👎 0 /* * 剑指 Offer 27 二叉树的镜像 * 2021-02-18 11:35:20 * @author oxygenbytes */ #include "leetcode.h" //leetcode submit region begin(Prohibit modification and deletion) /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode* mirrorTree(TreeNode* root) { if(!root) return nullptr; auto l = root->left; auto r = root->right; root->right = mirrorTree(l); root->left = mirrorTree(r); return root; } }; //leetcode submit region end(Prohibit modification and deletion)
c9d913b3ea0598163347669f1894922086f253fe
0cc2a22f7134870f12508365ec42ebe01be775ee
/102321022_HW7.cpp
20fad49610b132326e814dc2cda2e212b1749f24
[]
no_license
SiewMengYeong/C-plus-plus-Exersice
1925b530e8e3b7af48dc68d28d00955be6efb03e
8f53a38a99fbfec0d3d53512d683cb3554cc0f32
refs/heads/master
2020-04-28T00:38:34.504036
2019-03-10T13:45:48
2019-03-10T13:45:48
174,823,430
0
0
null
null
null
null
UTF-8
C++
false
false
2,809
cpp
102321022_HW7.cpp
#include <iostream> using std::cout; using std::endl; using std::cin; int main() { int a; int b; cout << "Input your birth month and day, separated by a space -- "; cin >> a >> b; if (b<0 || b>31) { cout << "Please check your birth day." << endl; cout << "Input your birth month and day, separated by a space -- "; cin >> a >> b; } if (a == 1) { if (b < 20) cout << "Capricorn" << endl; else cout << "Aquarius" << endl; } if (a == 2) { if (b < 19) cout << "Aquarius" << endl; else cout << "Pisces" << endl; } if (a == 3) { if (b < 21) cout << "Pisces" << endl; else cout << "Aries" << endl; } if (a == 4) { if (b < 20) cout << "Aries" << endl; else cout << "Taurus" << endl; } if (a == 5) { if (b < 21) cout << "Taurus" << endl; else cout << "Gemini" << endl; } if (a == 6) { if (b < 22) cout << "Gemini" << endl; else cout << "Cancer" << endl; } if (a == 7) { if (b < 23) cout << "Cancer" << endl; else cout << "Leo" << endl; } if (a == 8) { if (b < 23) cout << "Leo" << endl; else cout << "Virgo" << endl; } if (a == 9) { if (b < 23) cout << "Virgo" << endl; else cout << "Libra" << endl; } if (a == 10) { if (b < 23) cout << "Libra" << endl; else cout << "Scorpio" << endl; } if (a == 11) { if (b < 22) cout << "Scorpio" << endl; else cout << "Sagittarius" << endl; } if (a == 12) { if (b < 22) cout << "Sagittarius" << endl; else cout << "Capricorn" << endl; } return 0; }
6593ae4f074ea498c374535e17734ebb661395a5
08b8cf38e1936e8cec27f84af0d3727321cec9c4
/data/crawl/git/old_hunk_2655.cpp
8a56edc1ffecc8f5dd5b2742eb46ea8daa699b2c
[]
no_license
ccdxc/logSurvey
eaf28e9c2d6307140b17986d5c05106d1fd8e943
6b80226e1667c1e0760ab39160893ee19b0e9fb1
refs/heads/master
2022-01-07T21:31:55.446839
2018-04-21T14:12:43
2018-04-21T14:12:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
166
cpp
old_hunk_2655.cpp
return 1; } /* * The LRU pack is the one with the oldest MRU window, preferring packs * with no used windows, or the oldest mtime if it has no windows allocated.
a45219d39a92c5f88f30281c4bf839106b52109a
a46d23b1c03be1edf8127db532170580ae919b22
/sip/test/DecodeMultiple.cxx
059327f47c8f602ca0d45bd2298a24c52e709e90
[ "BSD-2-Clause" ]
permissive
greearb/vocal-ct
0e2935aa43d6bddf1506ad904d0cf61484724438
8c99a61930cc7c4887515ade518ad01022011a4e
refs/heads/master
2023-08-19T05:26:24.583272
2023-08-12T00:08:06
2023-08-12T00:08:06
87,567,277
5
0
null
null
null
null
UTF-8
C++
false
false
5,720
cxx
DecodeMultiple.cxx
/* ==================================================================== * The Vovida Software License, Version 1.0 * * Copyright (c) 2000 Vovida Networks, Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The names "VOCAL", "Vovida Open Communication Application Library", * and "Vovida Open Communication Application Library (VOCAL)" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact vocal@vovida.org. * * 4. Products derived from this software may not be called "VOCAL", nor * may "VOCAL" appear in their name, without prior written * permission of Vovida Networks, Inc. * * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND * NON-INFRINGEMENT ARE DISCLAIMED. IN NO EVENT SHALL VOVIDA * NETWORKS, INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT DAMAGES * IN EXCESS OF $1,000, NOR FOR ANY 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. * * ==================================================================== * * This software consists of voluntary contributions made by Vovida * Networks, Inc. and many individuals on behalf of Vovida Networks, * Inc. For more information on Vovida Networks, Inc., please see * <http://www.vovida.org/>. * */ static const char* const DecodeMultiple_cxx_Version = "$Id: DecodeMultiple.cxx,v 1.1 2004/05/01 04:15:26 greear Exp $"; #include "SipMsg.hxx" #include "Data.hxx" #include "VThread.hxx" #include <vector> #include "InviteMsg.hxx" #include "SipUrl.hxx" #include "SipSdp.hxx" using namespace Vocal; #define MSG_COUNT 1 #if 0 char* msgtext[MSG_COUNT] = { "\ INVITE sip:5221@192.168.66.104:5060;user=phone SIP/2.0\r Via: SIP/2.0/UDP 192.168.66.103:5060;branch=1\r Via: SIP/2.0/UDP 192.168.66.2:5060\r From: UserAgent<sip:5220@192.168.66.2:5060;user=phone>;\r To: 5221<sip:5221@192.168.66.103:5060;user=phone>;\r Call-ID: 209747329338013@192.168.66.2\r CSeq: 1 INVITE\r Proxy-Authorization: Basic VovidaClassXswitch\r Subject: VovidaINVITE\r Record-Route: <sip:5221@192.168.66.103:5060>\r Contact: <sip:5220@192.168.66.2:5060;user=phone>\r Content-Type: application/sdp\r Content-Length: 165\r \r v=0\r o=- 528534705 528534705 IN IP4 192.168.66.2\r s=VOVIDA Session\r c=IN IP4 192.168.66.2\r t=964134816 0\r m=audio 23456 RTP/AVP 0\r a=rtpmap:0 PCMU/8000\r a=ptime:20\r \r", }; void* decodeIt(void* c) { int count = (int) c; Data data = msgtext[0]; for (int i = 0; i < count; i++) { Sptr < SipMsg > msg = SipMsg::decode(data); } return 0; } void* junk(void*) { while (1) { vector < int > x; for (int i = 0; i < 10; i++) { x.push_back(i); } int k; for (vector < int > ::iterator j = x.begin(); j != x.end(); j++) { k += *j; } } return 0; } void* copyPtr(void* c) { int count = (int) c; InviteMsg myInvite; for (int i = 0; i < count; i++) { Sptr < SipMsg > msg = copyPtrtoSptr(&myInvite); } return 0; } #endif static bool srandomCalled = false; template < class T > void* copyClass(void* c) { int count = (int) c; Data x = "192.168.106.144"; T original; for (int i = 0; i < count; i++) { // while( random() % 1000000 ); // T copy; // = original; Data localid; Data host; struct timeval tv; //generate a random number; gettimeofday(&tv, 0); // Data noise = "asoifhadsfhoiasdh ioh"; #if 0 if (!srandomCalled) { srandom((unsigned int)(tv.tv_usec ^ tv.tv_sec)); srandomCalled = true; } #endif // host = theSystem.gethostAddress(); host = hostName; int tmpCallId; // tmpCallId = random(); localid = Data(tmpCallId); localid += tv.tv_usec; } return 0; } template < class T > void testClass(int iterations) { VThread thread0; VThread thread1; thread0.spawn(&copyClass < T > , (void*)iterations); // sleep(1); // sleep(1); thread1.spawn(&copyClass < T > , (void*)iterations); thread0.join(); thread1.join(); } Data hostName; void init_hostname() { char buf[256]; strcpy(buf, "192.168.5.254"); hostName = buf; } int main(int argc, char** argv) { int iterations = 100000; init_hostname(); if (argc > 1) { iterations = atoi(argv[1]); } testClass < SipCallId > (iterations); return 0; }
81bfdb7ff9d585ffc544f9226f4611cc2c6187b8
3195762cf17324063677d0d053a8640386eb294e
/UAlbertaBot/Source/Config.cpp
eb711d9c628d28bcd5bc654b44d514f0d8e9b5f0
[ "MIT" ]
permissive
davechurchill/ualbertabot
02545fc822dbdaa21dc3eb7cb23dcfd4a7e73971
558899d8793456f4a6ec4196efbb5235552e24db
refs/heads/master
2023-05-25T16:37:20.975939
2022-03-01T19:22:32
2022-03-01T19:22:32
23,928,013
549
242
MIT
2023-05-19T09:19:30
2014-09-11T17:18:49
C++
UTF-8
C++
false
false
4,939
cpp
Config.cpp
#include "Config.h" #include "UABAssert.h" namespace Bot { } namespace Config { namespace ConfigFile { bool ConfigFileFound = false; bool ConfigFileParsed = false; std::string ConfigFileLocation = "UAlbertaBot_Config.txt"; } namespace Strategy { std::string ProtossStrategyName = "Protoss_ZealotRush"; std::string TerranStrategyName = "Terran_MarineRush"; std::string ZergStrategyName = "Zerg_3HatchMuta"; std::string StrategyName = "Protoss_ZealotRush"; std::string ReadDir = "bwapi-data/read/"; std::string WriteDir = "bwapi-data/write/"; bool GasStealWithScout = false; bool ScoutHarassEnemy = true; bool UseEnemySpecificStrategy = false; bool FoundEnemySpecificStrategy = false; } namespace Modules { // the default tournament bot modules bool UsingGameCommander = true; // toggle GameCommander, effectively UAlbertaBot bool UsingScoutManager = true; bool UsingCombatCommander = true; bool UsingBuildOrderSearch = true; // toggle use of Build Order Search, currently no backup bool UsingAutoObserver = false; bool UsingStrategyIO = false; // toggle the use of file io for strategy bool UsingUnitCommandManager = false; // handles all unit commands // extra things, don't enable unless you know what they are bool UsingBuildOrderDemo = false; } namespace BotInfo { std::string BotName = "UAlbertaBot"; std::string Authors = "Dave Churchill"; bool PrintInfoOnStart = false; } namespace BWAPIOptions { int SetLocalSpeed = 42; int SetFrameSkip = 0; bool EnableUserInput = true; bool EnableCompleteMapInformation = false; } namespace Tournament { int GameEndFrame = 86400; } namespace Debug { bool DrawGameInfo = true; bool DrawUnitHealthBars = true; bool DrawProductionInfo = true; bool DrawBuildOrderSearchInfo = false; bool DrawScoutInfo = false; bool DrawResourceInfo = false; bool DrawWorkerInfo = false; bool DrawModuleTimers = false; bool DrawReservedBuildingTiles = false; bool DrawCombatSimulationInfo = false; bool DrawBuildingInfo = false; bool DrawMouseCursorInfo = false; bool DrawEnemyUnitInfo = false; bool DrawBWTAInfo = false; bool DrawMapGrid = false; bool DrawUnitTargetInfo = false; bool DrawSquadInfo = false; bool DrawBOSSStateInfo = false; bool DrawWalkableSectors = false; bool DrawTileInfo = false; bool PrintModuleTimeout = false; std::string ErrorLogFilename = "UAB_ErrorLog.txt"; bool LogAssertToErrorFile = false; BWAPI::Color ColorLineTarget = BWAPI::Colors::White; BWAPI::Color ColorLineMineral = BWAPI::Colors::Cyan; BWAPI::Color ColorUnitNearEnemy = BWAPI::Colors::Red; BWAPI::Color ColorUnitNotNearEnemy = BWAPI::Colors::Green; } namespace Micro { bool UseSparcraftSimulation = true; bool KiteWithRangedUnits = true; std::set<BWAPI::UnitType> KiteLongerRangedUnits; bool WorkersDefendRush = false; int RetreatMeleeUnitShields = 0; int RetreatMeleeUnitHP = 0; int CombatRadius = 1000; // radius of combat to consider units for Micro Search int CombatRegroupRadius = 300; // radius of units around frontmost unit we consider in regroup calculation int UnitNearEnemyRadius = 600; // radius to consider a unit 'near' to an enemy unit } namespace Macro { int BOSSFrameLimit = 160; int BOSSTimePerFrame = 30; int WorkersPerRefinery = 3; int BuildingSpacing = 1; int PylonSpacing = 3; } namespace Tools { extern int MAP_GRID_SIZE = 320; // size of grid spacing in MapGrid } }
03a6be2c4637306e57772af8c7144553667ad411
3c305dfca2e726c4959f980a8c287cd5bdd7fc05
/Climbing_Stairs.cpp
01355c5ff81cd07b453aa1dd40580468286316ab
[]
no_license
huy312100/leetcode-solutions
2f17105fb40dea2a512ef5e59c855c1320a4ad5b
b4abae73e5351ce1c0d1a2bdfd29d9fd56a9dee1
refs/heads/master
2021-12-02T22:36:05.238588
2013-01-13T13:37:20
2013-01-13T13:37:20
422,103,718
1
0
null
null
null
null
UTF-8
C++
false
false
941
cpp
Climbing_Stairs.cpp
/* Climbing Stairs You are climbing a stair case. It takes n steps to reach to the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? */ /* //recursive version int cache[1000000]; int go(int n) { if (cache[n] != -1) return cache[n]; if (n == 0 || n == 1) return 1; cache[n] = go(n-1) + go(n-2); return cache[n]; } class Solution { public: int climbStairs(int n) { // Start typing your C/C++ solution below // DO NOT write int main() function memset(cache, -1, sizeof(cache)); return go(n); } }; */ class Solution { public: int climbStairs(int n) { // Start typing your C/C++ solution below // DO NOT write int main() function if (n == 0 || n == 1) return 1; int a = 1; int b = 1; int c; for (int i = 2; i <= n; i++) { c = a + b; a = b; b = c; } return c; } };
f3bb8c67b5e1f5a8dc8cf68f41ba1a58300a4e7f
d0daf29f2fb5ff8630694b129aaac51bcdbbd50e
/aoapc_uva/aoapc-code/ch06/UVA1103.cpp
62a6e4a97ff4da727238dcabc3a21bda63431430
[]
no_license
fengshen024/Algorithm
9ce95258ef8e4a20b298d0c476c0c67aa8e3e56e
4d5c99f5a91d4a8dfcededa9d2da4b375080fb4e
refs/heads/master
2021-01-26T02:47:25.033358
2020-02-21T15:06:51
2020-02-21T15:06:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,672
cpp
UVA1103.cpp
#include<bits/stdc++.h> using namespace std; int H, W, num=0; string img[205], img2[205], s; // 原图像,加一轮白边的图像 map<char, string> mp; // 16进制字符->4位的2进制字符串 char word[6] = {'W', 'A', 'K', 'J', 'S', 'D'}; // 象形字内部对应的白色块个数 void trans() { // 一位16进制字符[0,f]转为4位的二进制字符串 char c[] = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'}; for (int i = 0; i < 16; i ++) { bitset<4> bt(i); // 10->二进制数值->二进制字符串 mp[c[i]] = bt.to_string(); } } void dfs(int x, int y, char tag) { // tag='0':遍历img的一个黑色连通块,并拷贝到img2;tag='0':计算img2的白色连通块个数 if (tag == '0') img[x][y] = '0'; if (tag == '0') img2[x+1][y+1] = '1'; // 白色边框 else img2[x][y] = '1'; int xx, yy, h, w; for (int i = -1; i <= 1; i ++) { // 8个方向 for (int j = -1; j <= 1; j ++) { if (i == 0 && j == 0) continue; // 不写也行,自身已经被赋值为1了 xx = x + i; yy = y + j; h = (tag == '1') ? H+2 : H; w = (tag == '1') ? 4*W+2 : 4*W; // 边界控制 if (xx >= 0 && xx < h && yy >= 0 && yy < w) { if (tag == '0' && img[xx][yy] == '1' || tag == '1' && img2[xx][yy] == '0') dfs(xx, yy, tag); } } } } int main() { trans(); // 16转二进制字符串初始化 while (cin >>H >>W && (H != 0 && W != 0)) { for (int i = 0; i < H; i ++) { cin >>s; img[i].clear(); for (int j = 0; j < s.size(); j ++) img[i].append(mp[s[j]]); // 转为2进制 } vector<char> res; // 保存结果 for (int i = 0; i < H; i ++) { for (int j = 0; j < 4*W; j ++) { if (img[i][j] == '1') { // 发现一个黑色块 for (int k=0; k < H+2; k ++) img2[k] = string(4*W+2, '0'); // 初始化 dfs(i, j, '0'); // 拷贝连通块 int cnt=0; // 统计白色块个数 for (int i2 = 0; i2 < H+2; i2 ++) { // img2计算白色洞个数 for (int j2 = 0; j2 < 4*W+2; j2 ++) { // 注意长度和宽度 if (img2[i2][j2] == '0') {cnt++; dfs(i2, j2, '1');} } } res.push_back(word[cnt-1]); // 存储对应象形字符结果 } } } sort(res.begin(), res.end()); // 字典序排列 printf("Case %d: ", ++num); for (auto c : res) printf("%c", c); puts(""); } return 0; }
1047906035101fc407393c92d2d8fe93b895fc2f
0676032b18133a46adeace89196bc769a87500d1
/2019-2020第二学期训练/“Shopee杯” e起来编程暨武汉大学2020年大学生程序设计大赛/E.Engage the Medical Workers.cpp
4a4c617a271e0cc8d00bb1e8b671407d769109c5
[]
no_license
zhushaoben/training
ce47c19934f67fc21f4571f99973d16561ede195
530f2b5dc1a2d1e4a02c22f034e251160d0b42af
refs/heads/master
2021-07-11T22:32:54.227626
2020-10-30T12:49:24
2020-10-30T12:49:24
213,320,465
0
0
null
null
null
null
UTF-8
C++
false
false
1,304
cpp
E.Engage the Medical Workers.cpp
#include<bits/stdc++.h> using namespace std; const int N=1e3+5; inline char getc(void) { static char buf[1 << 18], *fs, *ft; return (fs == ft && (ft = (fs = buf) + fread(buf, 1, 1 << 18, stdin)), fs == ft) ? EOF : *fs++; } inline int read(void) { register int res = 0; register char tmp = getc(); register bool f = true; while(!isgraph(tmp)) tmp = getc(); if(tmp == '-') f = false, tmp = getc(); while(isdigit(tmp)) res = ((res + (res << 2)) << 1) + (tmp ^ 0x30), tmp = getc(); if(f) return res; return ~res + 1; } struct Edge{ int x,y,w,v; bool operator <(const Edge &b){ return w<b.w; } }a[N*N]; int ma1[N],ma2[N]; void work(){ int n=read(),x,s=0; for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ a[++s].w=read(); a[s].x=i+1;a[s].y=j+1; } } sort(a+1,a+s+1); int ans=0,l=1,w1=0; for(int i=1;i<=s;i++){ if(a[i].w!=a[l].w){ for(int j=l;j<i;j++)ma1[a[j].x]=max(ma1[a[j].x],w1),ma2[a[j].y]=max(ma2[a[j].y],w1); l=i,w1=0; } a[i].v=max(ma1[a[i].x],ma2[a[i].y])+1; w1=max(w1,a[i].v); } for(int j=l;j<=s;j++)ma1[a[j].x]=max(ma1[a[j].x],a[j].v),ma2[a[j].y]=max(ma2[a[j].y],a[j].v); for(int i=1;i<=n;i++)ans=max(ans,ma1[i]); printf("%d\n",ans); } int main(){ int T=1; // scanf("%d",&T); while(T--)work(); return 0; }
0083b6004c7a95fa12616398594694348f7a6205
9f5289c0bb0d3d7a91d1003a4ae7564576cb169e
/Source/SBansheeEditor/Include/BsGUITextureField.h
e5ee377dc54a561e81af8cf197c1da9213cc9414
[]
no_license
linuxaged/BansheeEngine
59fa82828ba0e38841ac280ea1878c9f1e9bf9bd
12cb86711cc98847709f702e11a577cc7c2f7913
refs/heads/master
2021-01-11T00:04:23.661733
2016-10-10T13:18:44
2016-10-10T13:18:44
70,758,880
3
3
null
2016-10-13T01:57:56
2016-10-13T01:57:55
null
UTF-8
C++
false
false
9,063
h
BsGUITextureField.h
//********************************** Banshee Engine (www.banshee3d.com) **************************************************// //**************** Copyright (c) 2016 Marko Pintera (marko.pintera@gmail.com). All rights reserved. **********************// #pragma once #include "BsScriptEditorPrerequisites.h" #include "BsGUIElementContainer.h" namespace BansheeEngine { /** @addtogroup SBansheeEditor * @{ */ /** * GUI object that displays a field in which a Texture can be dragged and dropped. The field accepts a Texture of a * specific type and displays an optional label. If texture is referenced its image is displayed in the field. */ class BS_SCR_BED_EXPORT GUITextureField : public GUIElementContainer { struct PrivatelyConstruct {}; public: /** Returns type name of the GUI element used for finding GUI element styles. */ static const String& getGUITypeName(); /** * Creates a new texture GUI editor field with a label. * * @param[in] labelContent Content to display in the editor field label. * @param[in] labelWidth Width of the label in pixels. * @param[in] options Options that allow you to control how is the element positioned and sized. This will * override any similar options set by style. * @param[in] style Optional style to use for the element. Style will be retrieved from GUISkin of the * GUIWidget the element is used on. If not specified default style is used. */ static GUITextureField* create(const GUIContent& labelContent, UINT32 labelWidth, const GUIOptions& options, const String& style = StringUtil::BLANK); /** * Creates a new texture GUI editor field with a label. * * @param[in] labelContent Content to display in the editor field label. * @param[in] options Options that allow you to control how is the element positioned and sized. This will * override any similar options set by style. * @param[in] style Optional style to use for the element. Style will be retrieved from GUISkin of the * GUIWidget the element is used on. If not specified default style is used. */ static GUITextureField* create(const GUIContent& labelContent, const GUIOptions& options, const String& style = StringUtil::BLANK); /** * Creates a new texture GUI editor field with a label. * * @param[in] labelText Text to display in the editor field label. * @param[in] labelWidth Width of the label in pixels. * @param[in] options Options that allow you to control how is the element positioned and sized. This will * override any similar options set by style. * @param[in] style Optional style to use for the element. Style will be retrieved from GUISkin of the * GUIWidget the element is used on. If not specified default style is used. */ static GUITextureField* create(const HString& labelText, UINT32 labelWidth, const GUIOptions& options, const String& style = StringUtil::BLANK); /** * Creates a new texture GUI editor field with a label. * * @param[in] labelText Text to display in the editor field label. * @param[in] options Options that allow you to control how is the element positioned and sized. This will * override any similar options set by style. * @param[in] style Optional style to use for the element. Style will be retrieved from GUISkin of the * GUIWidget the element is used on. If not specified default style is used. */ static GUITextureField* create(const HString& labelText, const GUIOptions& options, const String& style = StringUtil::BLANK); /** * Creates a new texture GUI editor field without a label. * * @param[in] options Options that allow you to control how is the element positioned and sized. This will * override any similar options set by style. * @param[in] style Optional style to use for the element. Style will be retrieved from GUISkin of the * GUIWidget the element is used on. If not specified default style is used. */ static GUITextureField* create(const GUIOptions& options, const String& style = StringUtil::BLANK); /** * Creates a new texture GUI editor field with a label. * * @param[in] labelContent Content to display in the editor field label. * @param[in] labelWidth Width of the label in pixels. * @param[in] style Optional style to use for the element. Style will be retrieved from GUISkin of the * GUIWidget the element is used on. If not specified default style is used. */ static GUITextureField* create(const GUIContent& labelContent, UINT32 labelWidth, const String& style = StringUtil::BLANK); /** * Creates a new texture GUI editor field with a label. * * @param[in] labelContent Content to display in the editor field label. * @param[in] style Optional style to use for the element. Style will be retrieved from GUISkin of the * GUIWidget the element is used on. If not specified default style is used. */ static GUITextureField* create(const GUIContent& labelContent, const String& style = StringUtil::BLANK); /** * Creates a new texture GUI editor field with a label. * * @param[in] labelText Text to display in the editor field label. * @param[in] labelWidth Width of the label in pixels. * @param[in] style Optional style to use for the element. Style will be retrieved from GUISkin of the * GUIWidget the element is used on. If not specified default style is used. */ static GUITextureField* create(const HString& labelText, UINT32 labelWidth, const String& style = StringUtil::BLANK); /** * Creates a new texture GUI editor field with a label. * * @param[in] labelText Text to display in the editor field label. * @param[in] style Optional style to use for the element. Style will be retrieved from GUISkin of the * GUIWidget the element is used on. If not specified default style is used. */ static GUITextureField* create(const HString& labelText, const String& style = StringUtil::BLANK); /** * Creates a new texture GUI editor field without a label. * * @param[in] style Optional style to use for the element. Style will be retrieved from GUISkin of the * GUIWidget the element is used on. If not specified default style is used. */ static GUITextureField* create(const String& style = StringUtil::BLANK); GUITextureField(const PrivatelyConstruct& dummy, const GUIContent& labelContent, UINT32 labelWidth, const String& style, const GUIDimensions& dimensions, bool withLabel); /** Returns the texture referenced by the field, if any. This will load the texture if it is not already loaded. */ HTexture getValue() const; /** Sets the texture referenced by the field. */ void setValue(const HTexture& value); /** Returns a weak reference to the texture referenced by the field, if any. */ WeakResourceHandle<Texture> getValueWeak() const; /** Sets a weak reference to the texture referenced by the field. */ void setValueWeak(const WeakResourceHandle<Texture>& value); /** Returns the texture referenced by the field. Returns empty string with no texture is referenced. */ String getUUID() const { return mUUID; } /** @copydoc GUIElement::setTint */ virtual void setTint(const Color& color) override; /** @copydoc GUIElement::_updateLayoutInternal */ void _updateLayoutInternal(const GUILayoutData& data) override; /** @copydoc GUIElement::_getOptimalSize */ Vector2I _getOptimalSize() const override; /** * Triggered whenever the referenced texture changes. Provides a weak handle to the resource, or empty handle if no * texture is referenced. */ Event<void(const WeakResourceHandle<Texture>&)> onValueChanged; private: virtual ~GUITextureField(); /** @copydoc GUIElement::styleUpdated */ void styleUpdated() override; /** * Sets the texture referenced by the field by finding the texture with the provided UUID. * * @param[in] uuid Unique resource identifier of the texture to show, or empty string if no texture. * @param[in] triggerEvent Determines should the onValueChanged() event be triggered if the new UUID is * different from the previous one. */ void setUUID(const String& uuid, bool triggerEvent = true); /** Triggered when a drag and drop operation finishes over this element. */ void dataDropped(void* data); /** Triggered when the drop button that displays the game object label is clicked. */ void onDropButtonClicked(); /** Triggered when the clear button is clicked. */ void onClearButtonClicked(); private: static const UINT32 DEFAULT_LABEL_WIDTH; GUILayout* mLayout; GUILabel* mLabel; GUIDropButton* mDropButton; GUIButton* mClearButton; String mUUID; }; /** @} */ }
b080ca2181165581141212fe41a6ab8dbb2022c6
daeea0f48a276073216f9bf8b2a7dfff67d06c36
/examples/ninth.cpp
accc5763fb4b38f319030fc33bb4c398a35fe870
[ "MIT" ]
permissive
milleniumbug/yet_another_process_library
e6dabe9ae1d490e59afe1abe8d1ddb114f3fd0e3
aff4d62047c03c12f786e7d816d44f4b792a2df6
refs/heads/master
2021-01-17T06:47:11.112000
2016-08-06T19:05:33
2016-08-06T19:05:33
57,042,610
0
0
null
null
null
null
UTF-8
C++
false
false
2,368
cpp
ninth.cpp
#include <iostream> #include <thread> #include <cassert> #include <sstream> #include <boost/algorithm/string/replace.hpp> #include <yet_another_process_library/process.hpp> boost::filesystem::path get_current_process_path(); boost::filesystem::path program_component(); std::string expected_data(); int main() { namespace yapl = yet_another_process_library; std::stringstream ss; auto path = get_current_process_path().parent_path()/program_component(); std::cout << path << "\n"; yapl::process p(path, yapl::make_ascii_args({ "first\"_arg", "second argument", "some ' special chars $@!~`\n", "last, for good measure", "and a quote \""}), [&](boost::string_ref s) { ss << s; ss.flush(); }, yapl::stderr_closed, yapl::stdin_closed); p.wait(); std::string expected = expected_data(); std::string actual = ss.str(); boost::algorithm::replace_all(actual, "\r\n", "\n"); assert(actual == expected); std::cout << actual; } #ifdef _WIN32 #include <windows.h> boost::filesystem::path get_current_process_path() { std::wstring w; w.resize(1024); auto size = GetModuleFileNameW(nullptr, &w[0], w.size()); if(size == 0 || size == w.size()) { // assuming the path is less than 1024 chars // and the function doesn't fail assert(false); } w.resize(size); return boost::filesystem::path(w); } boost::filesystem::path program_component() { return L"_arg_tester.exe"; } std::string expected_data() { return R"*****(_arg_tester.exe%ENDOFARGUMENT% first"_arg%ENDOFARGUMENT% second argument%ENDOFARGUMENT% some ' special chars $@!~` %ENDOFARGUMENT% last, for good measure%ENDOFARGUMENT% and a quote "%ENDOFARGUMENT% )*****"; } #else #include <unistd.h> boost::filesystem::path get_current_process_path() { std::string w; w.resize(1024); auto size = readlink("/proc/self/exe", &w[0], w.size()); if(size == 0 || size == w.size()) { // assuming the path is less than 1024 chars // and the function doesn't fail assert(false); } w.resize(size); return boost::filesystem::path(w); } boost::filesystem::path program_component() { return "_arg_tester"; } std::string expected_data() { return R"*****(_arg_tester%ENDOFARGUMENT% first"_arg%ENDOFARGUMENT% second argument%ENDOFARGUMENT% some ' special chars $@!~` %ENDOFARGUMENT% last, for good measure%ENDOFARGUMENT% and a quote "%ENDOFARGUMENT% )*****"; } #endif
61392cc2051cd8261563db0b38115594c011767d
1f183a2b4ced386f4917685b8c01cbafab021306
/ChaosEngine/src/Chaos/Debug/ImGuiProfiler.h
17a0900dc4b64b8e805a75d0ad6b1547738727a6
[ "Apache-2.0" ]
permissive
JJRWalker/ChaosEngine
379004396be5a6e51bef5f5969ad0299c00c865d
47efb82cf8fac75af50ae639b85423304c90a52f
refs/heads/master
2023-07-08T23:06:21.734779
2021-08-09T16:04:39
2021-08-09T16:04:39
238,705,660
3
0
null
null
null
null
UTF-8
C++
false
false
442
h
ImGuiProfiler.h
/* date = May 10th 2021 9:31 pm */ #ifndef _IM_GUI_PROFILER_H #define _IM_GUI_PROFILER_H #include "ImGuiLayer.h" namespace Chaos { class ImGuiProfiler : public ImGuiLayer { public: ImGuiProfiler(); ~ImGuiProfiler(); void OnAttach() override; void OnDetach() override; void OnUpdate(float deltaTime) override; void OnImGuiUpdate() override; private: bool m_showProfiler = false; }; } #endif //_IM_GUI_PROFILER_H
d1c91c58f595544e8de0df8526d6ed37b6d57925
3126862ea13962984a9161a9ebd2032a4fc455bc
/08_basic_object_oriented_programming/08_16_timing_your_code/main.cpp
3bb5905c654cd675d069862bdc4b9e052fda58bb
[]
no_license
nieyu/learncpp_com
f9a5d191e4e4c416efcceb216bac10f5246e17ea
f2e53f3cee75fc7f91dfd3c8a5a85d09ba5313e3
refs/heads/master
2023-01-05T16:45:07.526075
2020-11-04T13:59:56
2020-11-04T13:59:56
299,284,110
0
0
null
null
null
null
UTF-8
C++
false
false
1,301
cpp
main.cpp
// // main.cpp // 08_16_timing_your_code // // Created by nie yu on 2020/11/1. // #include <iostream> #include <array> #include <cstddef> #include <numeric> #include <algorithm> #include "Timer.hpp" const int g_arrayElements = 10000; void sortArray(std::array<int, g_arrayElements>& array) { for (std::size_t startIndex{ 0 }; startIndex < (g_arrayElements - 1); ++startIndex) { std::size_t smallestIndex{ startIndex }; for (std::size_t currentIndex{ startIndex + 1}; currentIndex < g_arrayElements; ++currentIndex) { if (array[currentIndex] < array[smallestIndex]) { smallestIndex = currentIndex; } } std::swap(array[startIndex], array[smallestIndex]); } } int main(int argc, const char * argv[]) { Timer t; long sum{ 0 }; for (int i{ 0 }; i < 1000000000; ++i) { sum += i; } std::cout << "1 + 2 + 3 + ... + 10000 = " << sum << '\n'; std::cout << t.elapsed() << '\n'; std::array<int, g_arrayElements> array; std::iota(array.rbegin(), array.rend(), 1); t.reset(); // sortArray(array); std::sort(array.begin(), array.end()); std::cout << t.elapsed() << '\n'; return 0; } //4999999950000000 //499999999500000000
fd6850aee85e9b48e29cce7381793fe0890f1151
7659d93d559e81e73c5d7dfc34ae84c28e180fec
/darkness-shared/src/platform/Directory.cpp
757a60859f5d9672ea47933938fdcdf9df077910
[]
no_license
Karmiska/Darkness
d6905017025dd5b2cf591533ffcc21bd13a824ae
a9e35281307e8aa8843213f92804f6d74d145754
refs/heads/master
2023-07-23T10:19:41.900249
2023-07-09T11:00:33
2023-07-09T11:00:33
109,767,787
8
1
null
null
null
null
UTF-8
C++
false
false
2,079
cpp
Directory.cpp
#include "platform/Directory.h" using namespace engine; using namespace std; #ifndef __APPLE__ #include <filesystem> using namespace std; namespace engine { Directory::Directory(const string& path) : m_path{ path } { } const engine::string& Directory::path() const { return m_path; } bool Directory::exists() const { return filesystem::exists(m_path.c_str()); } void Directory::create() const { if (!exists()) filesystem::create_directories(m_path.c_str()); } void Directory::remove(bool removeFiles) const { if (!removeFiles) filesystem::remove(m_path.c_str()); else filesystem::remove_all(m_path.c_str()); } vector<string> Directory::files() const { vector<string> result; for (const auto& file : filesystem::directory_iterator{ m_path.c_str() }) { if (filesystem::is_regular_file(file.status())) { result.emplace_back(reinterpret_cast<const char*>(file.path().filename().u8string().c_str())); } } return result; } engine::vector<engine::string> Directory::directories() const { vector<string> result; for (const auto& file : filesystem::directory_iterator{ m_path.c_str() }) { if (filesystem::is_directory(file.status())) { result.emplace_back(reinterpret_cast<const char*>(file.path().filename().u8string().c_str())); } } return result; } } #else namespace engine { Directory::Directory(const string& path) : m_path{ path } { ASSERT(false, "TODO: Need to implement Directory support for this platform"); } bool Directory::exists() const { return false; } void Directory::create() const { } void Directory::remove(bool removeFiles) const { } vector<string> Directory::files() const { return {}; } } #endif
70f3920152aef4b69196c97b16f65b4452061ee7
27a98bd5b3dd7ddf892b95e410b34cf664ac5708
/ex02/ClapTrap.hpp
8cbffdd531be636ff85c62d6ff024a7b505d8eb3
[]
no_license
dennis903/CPP_Module_03
a7fc1cde66c64200848b090591d43a7e25a82c28
020fb52ad13f0491f5bafc55a09772941068930d
refs/heads/master
2023-06-17T00:12:51.056054
2021-07-05T05:47:05
2021-07-05T05:47:05
381,965,502
0
0
null
null
null
null
UTF-8
C++
false
false
2,524
hpp
ClapTrap.hpp
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ClapTrap.hpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: hyeolee <hyeolee@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/07/04 20:05:41 by hyeolee #+# #+# */ /* Updated: 2021/07/05 14:01:48 by hyeolee ### ########.fr */ /* */ /* ************************************************************************** */ #ifndef CLAPTRAP_HPP # define CLAPTRAP_HPP # include <iostream> # include <string> # include <cstdlib> # include <ctime> class ClapTrap { protected: unsigned int Hit_points; unsigned int Max_hit_point; unsigned int Energy_points; unsigned int Max_energy_points; unsigned int Level; std::string Name; unsigned int Melee_attack_damage; unsigned int Ranged_attack_damage; unsigned int Armor_damage_reduction; public: ClapTrap(); ClapTrap(const std::string & name); ClapTrap(const ClapTrap &_ClapTrap); ~ClapTrap(); ClapTrap &operator = (const ClapTrap &_ClapTrap); void set_Hit_points(int Hit_points); void set_Max_hit_point(int Max_hit_point); void set_Energy_points(int Energy_points); void set_Max_energy_points(int Max_energy_points); void set_Level(int Level); void set_Name(std::string Name); void set_Melee_attack_damage(int Melee_attack_damage); void set_Ranged_attack_damage(int Range_attack_damage); void set_Armor_damage_reduction(int Armor_damage_reduction); unsigned int get_Hit_points() const; unsigned int get_Max_hit_point() const; unsigned int get_Energy_points() const; unsigned int get_Max_energy_points() const; unsigned int get_Level() const; std::string get_Name() const; unsigned int get_Melee_attack_damage() const; unsigned int get_Ranged_attack_damage() const; unsigned int get_Armor_damage_reduction() const; void rangedAttack(std::string const &target); void meleeAttack(std::string const &target); void takeDamage(unsigned int amount); void beRepaired(unsigned int amount); }; #endif
06eed3738989ffdca1c55c6e6bb7d3006ae4ac51
806f3d057e6f62a59df9d119d95530dc80698594
/lite/model_parser/flatbuffers/io_test.cc
d2d020a2f3860a62a1b74de872ab51cb268f033a
[ "Apache-2.0" ]
permissive
chenjiaoAngel/Paddle-Lite
5eb6ad4863bc7564d2117ae07758bae5626441f6
b91552b565e42d86ebf53e097347ed00eb2b4c73
refs/heads/old_develop
2022-08-06T00:32:54.678048
2020-12-03T12:20:08
2020-12-03T12:20:08
214,328,262
1
0
Apache-2.0
2021-03-19T09:12:08
2019-10-11T02:43:21
C++
UTF-8
C++
false
false
3,278
cc
io_test.cc
// Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "lite/model_parser/flatbuffers/io.h" #include <gtest/gtest.h> #include <functional> #include <string> #include <utility> #include <vector> namespace paddle { namespace lite { namespace fbs { namespace { template <typename T> void set_tensor(paddle::lite::Tensor* tensor, const std::vector<int64_t>& dims) { auto production = std::accumulate(begin(dims), end(dims), 1, std::multiplies<int64_t>()); tensor->Resize(dims); tensor->set_persistable(true); std::vector<T> data; data.resize(production); for (int i = 0; i < production; ++i) { data[i] = i / 2.f; } std::memcpy(tensor->mutable_data<T>(), data.data(), sizeof(T) * data.size()); } } // namespace #ifdef LITE_WITH_FLATBUFFERS_DESC TEST(CombinedParamsDesc, Scope) { /* --------- Save scope ---------- */ Scope scope; std::vector<std::string> params_name({"var_0", "var_1", "var_2"}); // variable 0 Variable* var_0 = scope.Var(params_name[0]); Tensor* tensor_0 = var_0->GetMutable<Tensor>(); set_tensor<float>(tensor_0, std::vector<int64_t>({3, 2})); // variable 1 Variable* var_1 = scope.Var(params_name[1]); Tensor* tensor_1 = var_1->GetMutable<Tensor>(); set_tensor<int8_t>(tensor_1, std::vector<int64_t>({10, 1})); // variable 3 Variable* var_2 = scope.Var(params_name[2]); Tensor* tensor_2 = var_2->GetMutable<Tensor>(); set_tensor<int16_t>(tensor_2, std::vector<int64_t>({16, 1})); // Set combined parameters fbs::CombinedParamsDesc combined_param; std::set<std::string> params_set(params_name.begin(), params_name.end()); SetCombinedParamsWithScope(scope, params_set, &combined_param); /* --------- Check scope ---------- */ auto check_params = [&](const CombinedParamsDescReadAPI& desc) { Scope scope_l; SetScopeWithCombinedParams(&scope_l, desc); // variable 0 Variable* var_l0 = scope_l.FindVar(params_name[0]); CHECK(var_l0); const Tensor& tensor_l0 = var_l0->Get<Tensor>(); CHECK(TensorCompareWith(*tensor_0, tensor_l0)); // variable 1 Variable* var_l1 = scope_l.FindVar(params_name[1]); CHECK(var_l1); const Tensor& tensor_l1 = var_l1->Get<Tensor>(); CHECK(TensorCompareWith(*tensor_1, tensor_l1)); // variable 2 Variable* var_l2 = scope_l.FindVar(params_name[2]); CHECK(var_l2); const Tensor& tensor_l2 = var_l2->Get<Tensor>(); CHECK(TensorCompareWith(*tensor_2, tensor_l2)); }; check_params(combined_param); /* --------- View scope ---------- */ check_params(CombinedParamsDescView(combined_param.data())); } #endif // LITE_WITH_FLATBUFFERS_DESC } // namespace fbs } // namespace lite } // namespace paddle
abfaf6fab0720329ee817dc7f62bbfa924c3bf37
67f38a31a770e029209fd3a78ef093c885c270e7
/light/light_base.cpp
19b091743a89dbfee980e23b9dd684a0950ffbcf
[]
no_license
Zackere/Sculptor
f95b6dfa56bcc51934fca8ff1efcc5f72c648e5e
ff699cce064b8d8ea2a2a6ace220d5e574a694b3
refs/heads/master
2020-12-08T07:43:07.045093
2020-03-02T12:09:32
2020-03-02T12:09:32
232,927,738
0
0
null
2020-01-26T02:40:58
2020-01-09T23:42:08
C++
UTF-8
C++
false
false
1,973
cpp
light_base.cpp
// Copyright 2020 Wojciech Replin. All rights reserved. #include "light_base.hpp" #include "../shaderProgram/shader_program_base.hpp" namespace Sculptor { std::map<std::string, std::set<unsigned>> LightBase::taken_ids_{}; LightBase::LightBase(glm::vec3 ambient, glm::vec3 diffuse, glm::vec3 specular, std::string light_class_name) : light_class_name_(light_class_name), ambient_(ambient), diffuse_(diffuse), specular_(specular) { for (auto id : taken_ids_[light_class_name_]) if (id == id_) ++id_; else break; taken_ids_[light_class_name_].insert(id_); } void LightBase::LoadIntoShader(ShaderProgramBase* shader) { shader->Use(); auto id_string = std::to_string(id_); glUniform3f(shader->GetUniformLocation( (light_class_name_ + "[" + id_string + "].ambient").c_str()), ambient_.x, ambient_.y, ambient_.z); glUniform3f(shader->GetUniformLocation( (light_class_name_ + "[" + id_string + "].diffuse").c_str()), diffuse_.x, diffuse_.y, diffuse_.z); glUniform3f(shader->GetUniformLocation( (light_class_name_ + "[" + id_string + "].specular").c_str()), specular_.x, specular_.y, specular_.z); Enable(shader); } void LightBase::UnloadFromShader(ShaderProgramBase* shader) { Disable(shader); } void LightBase::Enable(ShaderProgramBase* shader) { shader->Use(); glUniform1i(shader->GetUniformLocation( (light_class_name_ + '[' + std::to_string(id_) + "].enabled") .c_str()), true); } void LightBase::Disable(ShaderProgramBase* shader) { shader->Use(); glUniform1i(shader->GetUniformLocation( (light_class_name_ + '[' + std::to_string(id_) + "].enabled") .c_str()), false); } LightBase::~LightBase() = default; } // namespace Sculptor
9eac215064add0c651acc2a07e4a1e572de0a30d
4bd571785edca57aa4bda96a167ad0f37da1cc31
/cmd_console_tools.cpp
67d72f6b03bc1edc14be086c8c5128621ab69d19
[ "MIT" ]
permissive
yyjxx2010xyu/Junqi
1d0335a67766aeabc88d73eeb47122e3a2dbb93b
11ef5d412d13e6d4afac5e4db9f8913646f51dd5
refs/heads/master
2022-10-10T02:46:48.391342
2020-06-10T06:36:42
2020-06-10T06:36:42
260,510,218
1
2
null
2020-06-10T06:36:43
2020-05-01T16:48:18
C++
GB18030
C++
false
false
27,291
cpp
cmd_console_tools.cpp
/* 1852696 计算机3班 王泽鉴 */ #define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <iomanip> #include <tchar.h> #include <Windows.h> #include "cmd_console_tools.h" using namespace std; /* 静态全局,只在本源程序文件中有效(为防止同名,静态全局一般建议加__做为变量名开始) */ static const HANDLE __hout = GetStdHandle(STD_OUTPUT_HANDLE); //取标准输出设备对应的句柄 static const HANDLE __hin = GetStdHandle(STD_INPUT_HANDLE); //取标准输入设备对应的句柄 /*************************************************************************** 函数名称: 功 能:完成与system("cls")一样的功能,但效率高 输入参数: 返 回 值: 说 明:清除整个屏幕缓冲区,不仅仅是可见窗口区域(使用当前颜色) ***************************************************************************/ void cls(void) { COORD coord = { 0, 0 }; CONSOLE_SCREEN_BUFFER_INFO binfo; /* to get buffer info */ DWORD num; /* 取当前缓冲区信息 */ GetConsoleScreenBufferInfo(__hout, &binfo); /* 填充字符 */ FillConsoleOutputCharacter(__hout, (TCHAR) ' ', binfo.dwSize.X * binfo.dwSize.Y, coord, &num); /* 填充属性 */ FillConsoleOutputAttribute(__hout, binfo.wAttributes, binfo.dwSize.X * binfo.dwSize.Y, coord, &num); /* 光标回到(0,0) */ SetConsoleCursorPosition(__hout, coord); return; } /*************************************************************************** 函数名称: 功 能:设置指定的颜色 输入参数:const int bg_color :背景色(0-15) const int fg_color :前景色(0-15) 返 回 值: 说 明:颜色的取值由背景色+前景色组成,各16种 fg_color:0-7 黑 蓝 绿 青 红 粉 黄 白 8-15 亮黑 亮蓝 亮绿 亮青 亮红 亮粉 亮黄 亮白 bg_color:0-7 黑 蓝 绿 青 红 粉 黄 白 8-15 亮黑 亮蓝 亮绿 亮青 亮红 亮粉 亮黄 亮白 最终的颜色为 背景色*16+前景色 ***************************************************************************/ void setcolor(const int bg_color, const int fg_color) { SetConsoleTextAttribute(__hout, bg_color * 16 + fg_color); } /*************************************************************************** 函数名称: 功 能:返回最后一次setcolor的前景色和背景色 输入参数:int &bg_color :返回的背景色(0-15) int &fg_color :返回的前景色(0-15) 返 回 值: 说 明:形参中的&表示引用,第六章会讲到,引用形参的值可以返回给实参 ***************************************************************************/ void getcolor(int &bg_color, int &fg_color) { CONSOLE_SCREEN_BUFFER_INFO binfo; GetConsoleScreenBufferInfo(__hout, &binfo); bg_color = binfo.wAttributes / 16; fg_color = binfo.wAttributes % 16; } /*************************************************************************** 函数名称: 功 能:将光标移动到指定位置 输入参数:const int X :X轴坐标(列) const int Y :Y轴坐标(行) 返 回 值: 说 明:屏幕左上角坐标为(0,0),在cmd窗口的大小未被调整的情况下,Win10为: 横向x轴,对应列(0-119) 纵向y轴,对应行(0-29) ***************************************************************************/ void gotoxy(const int X, const int Y) { COORD coord; coord.X = X; coord.Y = Y; SetConsoleCursorPosition(__hout, coord); } /*************************************************************************** 函数名称: 功 能:取当前光标所在位置的坐标值 输入参数:int &x :取得的X轴坐标(列) int &y :取得的Y轴坐标(行) 返 回 值: 说 明:形参中的&表示引用,第六章会讲到,引用形参的值可以返回给实参 ***************************************************************************/ void getxy(int &x, int &y) { CONSOLE_SCREEN_BUFFER_INFO binfo; GetConsoleScreenBufferInfo(__hout, &binfo); x = binfo.dwCursorPosition.X; y = binfo.dwCursorPosition.Y; return; } /*************************************************************************** 函数名称: 功 能:设置光标状态(显示/不显示/全高/半高/横线等) 输入参数:const int option:要设置的光标状态 返 回 值: 说 明: ***************************************************************************/ void setcursor(const int options) { CONSOLE_CURSOR_INFO cursor_info; switch (options) { case CURSOR_VISIBLE_FULL: cursor_info.bVisible = 1; cursor_info.dwSize = 100; break; case CURSOR_VISIBLE_HALF: cursor_info.bVisible = 1; cursor_info.dwSize = 50; break; case CURSOR_INVISIBLE: cursor_info.bVisible = 0; cursor_info.dwSize = 1; break; case CURSOR_VISIBLE_NORMAL: default: //缺省显示光标,横线 cursor_info.bVisible = 1; cursor_info.dwSize = 25; break; } SetConsoleCursorInfo(__hout, &cursor_info); } /*************************************************************************** 函数名称: 功 能:在指定位置,用指定颜色,显示一个字符若干次 输入参数:const int X :X轴坐标(列) const int Y :Y轴坐标(行) const char ch :要输出的字符值 const int bg_color:背景色(缺省为COLOR_BLACK) const int fg_color:背景色(缺省为COLOR_WHITE) const int rpt :重复次数(缺省为1) 返 回 值: 说 明:X、Y的范围参见gotoxy函数的说明 ***************************************************************************/ void showch(const int X, const int Y, const char ch, const int bg_color, const int fg_color, const int rpt) { int i; gotoxy(X, Y); setcolor(bg_color, fg_color); /* 循环n次,打印字符ch */ for (i = 0; i < rpt; i++) putchar(ch); } /*************************************************************************** 函数名称: 功 能:在指定位置,用指定颜色,显示一个字符串 输入参数:const int X :X轴坐标(列) const int Y :Y轴坐标(行) const char *str :要输出的字符串 const int bg_color:背景色(缺省为COLOR_BLACK) const int fg_color:背景色(缺省为COLOR_WHITE) const int rpt :重复次数(缺省为1) const int max_len :-1(表示不限制长度,按strlen(str)*rpt的实际打印) 返 回 值: 说 明: ***************************************************************************/ void showstr(const int X, const int Y, const char *str, const int bg_color, const int fg_color, int rpt, int maxlen) { #if 0 const char *p; int i; gotoxy(X, Y); setcolor(bg_color, fg_color); for (i = 0; i<rpt; i++) //重复rpt次,每次输出字符串,适用于在画边框时输出若干个"═"等情况 for (p = str; p && *p; p++) putchar(*p); #else const char *p; int i, rpt_count = 0; gotoxy(X, Y); setcolor(bg_color, fg_color); /* 首先考虑str==NULL / str="" 的情况 1、如果maxlen是-1/0,则直接返回,什么都不打印 2、如果maxlen>0,则用maxlen个空格填充 */ if (str == NULL || str[0] == 0) { for (i = 0; i < maxlen; i++) //如果maxlen是-1、0,循环不执行,直接返回 putchar(' '); return; } /* 之行到此,是str非NULL/str!=""的情况(既strlen一定>0) */ if (rpt <= 0) rpt = 1; //防止错误参数 if (maxlen < 0) maxlen = (int)strlen(str) * rpt; //未给出maxlen则为原始长度 for (i = 0, p = str; i < maxlen; i++, p++) { //重复rpt次,每次输出字符串,适用于在画边框时输出若干个"═"等情况 if (*p == 0) { p = str; //如果p已经到\0,则回到头(此处已保证strlen(str)>0,即一定有内容) rpt_count++; } putchar(rpt_count < rpt ? *p : ' '); //如果超过了rpt次数则用空格填充 } #endif } /*************************************************************************** 函数名称: 功 能:在指定位置,用指定颜色,显示一个字符串 输入参数:const int X :X轴坐标(列) const int Y :Y轴坐标(行) const int num :要输出的int值 const int bg_color:背景色(缺省为COLOR_BLACK) const int fg_color:背景色(缺省为COLOR_WHITE) const int rpt :重复次数(缺省为1) 返 回 值: 说 明: ***************************************************************************/ void showint(const int X, const int Y, const int num, const int bg_color, const int fg_color, const int rpt) { int i; gotoxy(X, Y); setcolor(bg_color, fg_color); for (i = 0; i < rpt; i++) //重复rpt次,每次输出字符串,适用于在画边框时输出若干个"═"等情况 cout << num; } /*************************************************************************** 函数名称: 功 能:改变cmd窗口的大小及缓冲区的大小 输入参数:const int cols :新的列数 const int lines :新的行数 const int buffer_cols :新的缓冲区列数 const int buffer_lines :新的缓冲区行数 返 回 值: 说 明:必须先设置缓冲区,再设置窗口大小, 否则若窗口大小大于当前缓冲区(未设置前)则设置失败 ***************************************************************************/ void setconsoleborder(int set_cols, int set_lines, int set_buffer_cols, int set_buffer_lines) { /* 去当前系统允许的窗口的行列最大值 */ COORD max_coord; max_coord = GetLargestConsoleWindowSize(__hout); /* .X 和 .Y 分别是窗口的列和行的最大值 */ /* 处理设置窗口的行列的非法值 */ if (set_cols <= 0 || set_lines <= 0) return; if (set_cols > max_coord.X) set_cols = max_coord.X; if (set_lines > max_coord.Y) set_lines = max_coord.Y; /* 设置窗口的行列大小(从0开始,0 ~ lines-1, 0 ~ cols-1)*/ SMALL_RECT rect; rect.Top = 0; rect.Bottom = set_lines - 1; rect.Left = 0; rect.Right = set_cols - 1; /* 设置缓冲区的行列大小(缺省或小于窗口值则与窗口值一样) */ COORD cr; cr.X = (set_buffer_cols == -1 || set_buffer_cols < set_cols) ? set_cols : set_buffer_cols; //未给出或给出的值小于set_cols则用set_cols,未控制上限 cr.Y = (set_buffer_lines == -1 || set_buffer_lines < set_lines) ? set_lines : set_buffer_lines; //未给出或给出的值小于set_lines则用set_lines,未控制上限 /* 取当前窗口及缓冲区的大小(就是getconsoleborder) */ int cur_cols, cur_lines, cur_buffer_cols, cur_buffer_lines; CONSOLE_SCREEN_BUFFER_INFO binfo; GetConsoleScreenBufferInfo(__hout, &binfo); cur_cols = binfo.srWindow.Right - binfo.srWindow.Left + 1; //可见窗口的列数 cur_lines = binfo.srWindow.Bottom - binfo.srWindow.Top + 1; //可见窗口的行数 cur_buffer_cols = binfo.dwSize.X; //缓冲区的列数 cur_buffer_lines = binfo.dwSize.Y; //缓冲区的行数 cls(); /* 设置顺序(保证设置窗口大小时,现缓冲区的列值>窗口值) */ if (cr.X <= cur_buffer_cols) { if (cr.Y <= cur_buffer_lines) { SetConsoleWindowInfo(__hout, true, &rect);//设置窗口 SetConsoleScreenBufferSize(__hout, cr);//设置缓冲区 } else { //cr.Y > cur_buffer_lines,先要让缓冲区的行数变大 COORD tmpcr; tmpcr.X = cur_buffer_cols; tmpcr.Y = cr.Y; SetConsoleScreenBufferSize(__hout, tmpcr);//设置缓冲区 SetConsoleWindowInfo(__hout, true, &rect);//设置窗口 SetConsoleScreenBufferSize(__hout, cr);//设置缓冲区 } } else {//cr.X > cur_buffer_cols if (cr.Y >= cur_buffer_lines) { SetConsoleScreenBufferSize(__hout, cr);//设置缓冲区 SetConsoleWindowInfo(__hout, true, &rect);//设置窗口 } else { //cr.Y < cur_buffer_lines COORD tmpcr; tmpcr.X = cr.X; tmpcr.Y = cur_buffer_lines; SetConsoleScreenBufferSize(__hout, tmpcr);//设置缓冲区 SetConsoleWindowInfo(__hout, true, &rect);//设置窗口 SetConsoleScreenBufferSize(__hout, cr);//设置缓冲区 } } return; } /*************************************************************************** 函数名称: 功 能:取当前cmd窗口的大小设置 输入参数:int &cols :当前窗口的列数-返回值 int &lines :当前窗口的行数-返回值 int &buffer_cols :当前缓冲区的列数-返回值 int &buffer_lines :当前缓冲区的行数-返回值 返 回 值: 说 明: ***************************************************************************/ void getconsoleborder(int &cols, int &lines, int &buffer_cols, int &buffer_lines) { CONSOLE_SCREEN_BUFFER_INFO binfo; GetConsoleScreenBufferInfo(__hout, &binfo); cols = binfo.srWindow.Right - binfo.srWindow.Left + 1; //可见窗口的列数 lines = binfo.srWindow.Bottom - binfo.srWindow.Top + 1; //可见窗口的行数 buffer_cols = binfo.dwSize.X; //缓冲区的列数 buffer_lines = binfo.dwSize.Y; //缓冲区的行数 } /*************************************************************************** 函数名称: 功 能:取当前cmd窗口的标题 输入参数: 返 回 值: 说 明: ***************************************************************************/ void getconsoletitle(char *title, int maxbuflen) { GetConsoleTitleA(title, maxbuflen); //不检查是否越界、是否有空间 } /*************************************************************************** 函数名称: 功 能: 输入参数: 返 回 值: 说 明: ***************************************************************************/ void setconsoletitle(const char *title) { SetConsoleTitleA(title); } /*************************************************************************** 函数名称: 功 能:允许使用鼠标 输入参数:const HANDLE hin :cmd窗口输入句柄 返 回 值: 说 明:某些cmd窗口控制语句执行后,可能会取消鼠标支持,则调用本函数回再次加入 ***************************************************************************/ void enable_mouse(void) { DWORD Mode; GetConsoleMode(__hin, &Mode); /* 取得控制台原来的模式 */ SetConsoleMode(__hin, Mode | ENABLE_MOUSE_INPUT); //加入鼠标支持(可能原先已支持鼠标,再加也没错) } /*************************************************************************** 函数名称: 功 能:允许使用鼠标 输入参数:const HANDLE hin :cmd窗口输入句柄 返 回 值: 说 明:某些cmd窗口控制语句执行后,可能会取消鼠标支持,则调用本函数回再次加入 ***************************************************************************/ void disable_mouse(void) { DWORD Mode; GetConsoleMode(__hin, &Mode); /* 取得控制台原来的模式 */ SetConsoleMode(__hin, Mode&(~ENABLE_MOUSE_INPUT)); //去除鼠标支持(如果原先已不支持鼠标,再设也没错) } /*************************************************************************** 函数名称: 功 能:读鼠标按键 输入参数: 返 回 值: 说 明:下列说明来自鼠标定义文件 01.typedef struct _MOUSE_EVENT_RECORD //鼠标事件结构体 02.{ 03. COORD dwMousePosition; //当前鼠标在控制台窗口缓冲区的位置 04. DWORD dwButtonState; //鼠标按键的状态 05. DWORD dwControlKeyState; //控制键状态 06. DWORD dwEventFlags; //鼠标事件类型 07.} MOUSE_EVENT_RECORD; 08. 09.其中鼠标按键状态dwButtonState可能的值有 10.~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 11.FROM_LEFT_1ST_BUTTON_PRESSED 最左边的鼠标键被按下 一般来说就是鼠标左键 12.FROM_LEFT_2ND_BUTTON_PRESSED 左起第二个鼠标键被按下 一般来说是鼠标中键,就是滚轮键 13.FROM_LEFT_3RD_BUTTON_PRESSED 左起第三个鼠标键被按下 14.FROM_LEFT_4TH_BUTTON_PRESSED 左起第四个鼠标键被按下 15.RIGHTMOST_BUTTON_PRESSED 最右边的鼠标键被按下 一般来说是鼠标右键 16.~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 17.控制键状态dwControlKeyState与键盘事件的一样 18.~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 19.ENHANCED_KEY 扩展键被按下 20.LEFT_ALT_PRESSED 左Alt键被按下 21.LEFT_CTRL_PRESSED 左Ctrl键被按下 22.RIGHT_ALT_PRESSED 右Alt键被按下 23.RIGHT_CTRL_PRESSED 右Ctrl键被按下 24.NUMLOCK_ON 数字锁定被打开 25.SCROLLLOCK_ON 滚动锁定被打开 26.CAPSLOCK_ON 大写锁定被打开 27.SHIFT_PRESSED Shift键被按下 28.~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 29.鼠标事件类型dwEventFlags有以下几种 30.~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 31.DOUBLE_CLICK 双击,第一击只作为普通按键事件,第二击才作为双击事件 32.MOUSE_HWHEELED 水平鼠标滚轮移动 33.MOUSE_MOVED 鼠标移动 34.MOUSE_WHEELED 垂直鼠标滚轮移动 35.0 当鼠标有键被按下或者释放 ***************************************************************************/ int read_keyboard_and_mouse(int &MX, int &MY, int &MAction, int &keycode1, int &keycode2) { static int MX_old = -1, MY_old = -1, MAction_old = MOUSE_ONLY_MOVED; INPUT_RECORD InputRec; DWORD res; COORD crPos; while (1) { /* 从hin中读输入状态(包括鼠标、键盘等) */ ReadConsoleInput(__hin, &InputRec, 1, &res); /* 键盘事件(要优于鼠标事件,否则如果鼠标放在目标区,无法读键) */ if (InputRec.EventType == KEY_EVENT) { keycode1 = 0x00; keycode2 = 0x00; if (InputRec.Event.KeyEvent.bKeyDown) { // 只在按下时判断,弹起时不判断 /* 所有的虚拟键码可参考下列网址: https://baike.baidu.com/item/%E8%99%9A%E6%8B%9F%E9%94%AE%E7%A0%81/9884611?fr=aladdin 对应头文件:c:\Program Files (x86)\Windows Kits\10\Include\10.0.16299.0\um\WinUser.h (以VS2017 15.5.7版本,缺省路径) 目前只返回四个箭头键,其余的可以自行添加 */ switch (InputRec.Event.KeyEvent.wVirtualKeyCode) { case VK_UP: keycode1 = 0xe0; keycode2 = KB_ARROW_UP; //模拟 _getch()方式返回的两个键码,分别是224(0xE0)和72(0x48) break; case VK_DOWN: keycode1 = 0xe0; keycode2 = KB_ARROW_DOWN; //模拟 _getch()方式返回的两个键码,分别是224(0xE0)和80(0x50) break; case VK_LEFT: keycode1 = 0xe0; keycode2 = KB_ARROW_LEFT; //模拟 _getch()方式返回的两个键码,分别是224(0xE0)和75(0x4B) break; case VK_RIGHT: keycode1 = 0xe0; keycode2 = KB_ARROW_RIGHT; //模拟 _getch()方式返回的两个键码,分别是224(0xE0)和77(0x4D) break; default: break; } //end of switch /* 非箭头键直接返回ASCII形式(Fn、Insert、Delete等均未处理) */ if (keycode1 == 0) keycode1 = InputRec.Event.KeyEvent.uChar.AsciiChar; return CCT_KEYBOARD_EVENT; } //end of if (KEYDOWN) } // end of if (键盘事件) /* 鼠标事件 */ if (InputRec.EventType == MOUSE_EVENT) { /* 从返回中读鼠标指针当前的坐标 */ crPos = InputRec.Event.MouseEvent.dwMousePosition; MX = crPos.X; MY = crPos.Y; if (InputRec.Event.MouseEvent.dwEventFlags == MOUSE_MOVED) {//鼠标移动 /* 如果始终是MOUSE_MOVED事件且坐标不变,则不认为是MOUSE_MOVED */ if (MX_old == MX && MY_old == MY && MAction_old == MOUSE_ONLY_MOVED) continue; /* 位置变化则记录下来 */ MX_old = MX; MY_old = MY; MAction = MOUSE_ONLY_MOVED; MAction_old = MAction; return CCT_MOUSE_EVENT; } MAction_old = MOUSE_NO_ACTION; //置非MOUSE_ONLY_MOVED值即可 if (InputRec.Event.MouseEvent.dwEventFlags == MOUSE_WHEELED) { //滚轮移动 /* https://docs.microsoft.com/en-us/windows/console/mouse-event-record-str The vertical mouse wheel was moved. If the high word of the dwButtonState member contains a positive value, the wheel was rotated forward, away from the user. Otherwise, the wheel was rotated backward, toward the user. */ if (InputRec.Event.MouseEvent.dwButtonState & 0x80000000) //高位为1,负数 MAction = MOUSE_WHEEL_MOVED_DOWN; else MAction = MOUSE_WHEEL_MOVED_UP; return CCT_MOUSE_EVENT; } if (InputRec.Event.MouseEvent.dwButtonState == (FROM_LEFT_1ST_BUTTON_PRESSED | RIGHTMOST_BUTTON_PRESSED)) { //同时按下左右键 MAction = MOUSE_LEFTRIGHT_BUTTON_CLICK; return CCT_MOUSE_EVENT; } else if (InputRec.Event.MouseEvent.dwButtonState == FROM_LEFT_1ST_BUTTON_PRESSED) { //按下左键 if (InputRec.Event.MouseEvent.dwEventFlags == DOUBLE_CLICK) MAction = MOUSE_LEFT_BUTTON_DOUBLE_CLICK; else MAction = MOUSE_LEFT_BUTTON_CLICK; return CCT_MOUSE_EVENT; } else if (InputRec.Event.MouseEvent.dwButtonState == RIGHTMOST_BUTTON_PRESSED) { //按下右键 if (InputRec.Event.MouseEvent.dwEventFlags == DOUBLE_CLICK) MAction = MOUSE_RIGHT_BUTTON_DOUBLE_CLICK; else MAction = MOUSE_RIGHT_BUTTON_CLICK; return CCT_MOUSE_EVENT; } else if (InputRec.Event.MouseEvent.dwButtonState == FROM_LEFT_2ND_BUTTON_PRESSED) { //按下滚轮 MAction = MOUSE_WHEEL_CLICK; return CCT_MOUSE_EVENT; } else //忽略其它按键操作 continue; } // end of if(鼠标事件) } //end of while(1) return CCT_MOUSE_EVENT; //此句应该执行不到,为避免某些编译器报不完全分支错误,加 } typedef BOOL(WINAPI *PROCSETCONSOLEFONT)(HANDLE, DWORD); typedef BOOL(WINAPI *PROCGETCONSOLEFONTINFO)(HANDLE, BOOL, DWORD, PCONSOLE_FONT_INFO); typedef COORD(WINAPI *PROCGETCONSOLEFONTSIZE)(HANDLE, DWORD); typedef DWORD(WINAPI *PROCGETNUMBEROFCONSOLEFONTS)(); typedef BOOL(WINAPI *PROCGETCURRENTCONSOLEFONT)(HANDLE, BOOL, PCONSOLE_FONT_INFO); typedef BOOL(WINAPI *PROCSetBufferSize)(HANDLE hConsoleOutput, COORD dwSize); typedef HWND(WINAPI *PROCGETCONSOLEWINDOW)(); #if 0 PROCSETCONSOLEFONT SetConsoleFont; PROCGETCONSOLEFONTINFO GetConsoleFontInfo; PROCGETCONSOLEFONTSIZE GetConsoleFontSize; PROCGETNUMBEROFCONSOLEFONTS GetNumberOfConsoleFonts; PROCGETCURRENTCONSOLEFONT GetCurrentConsoleFont; #endif /*************************************************************************** 函数名称: 功 能: 输入参数: 返 回 值: 说 明: ***************************************************************************/ int getfontinfo(void) { HMODULE hKernel32 = GetModuleHandleA("kernel32"); PROCSETCONSOLEFONT SetConsoleFont = (PROCSETCONSOLEFONT)GetProcAddress(hKernel32, "SetConsoleFont"); PROCGETCONSOLEFONTINFO GetConsoleFontInfo = (PROCGETCONSOLEFONTINFO)GetProcAddress(hKernel32, "GetConsoleFontInfo"); PROCGETCONSOLEFONTSIZE GetConsoleFontSize = (PROCGETCONSOLEFONTSIZE)GetProcAddress(hKernel32, "GetConsoleFontSize"); PROCGETNUMBEROFCONSOLEFONTS GetNumberOfConsoleFonts = (PROCGETNUMBEROFCONSOLEFONTS)GetProcAddress(hKernel32, "GetNumberOfConsoleFonts"); PROCGETCURRENTCONSOLEFONT GetCurrentConsoleFont = (PROCGETCURRENTCONSOLEFONT)GetProcAddress(hKernel32, "GetCurrentConsoleFont"); // PROCSetBufferSize SetConsoleBufSize = (PROCSetBufferSize)GetProcAddress(hKernel32,"SetConsoleScreenBufferSize"); // PROCGETCONSOLEWINDOW GetConsoleWindow = (PROCGETCONSOLEWINDOW)GetProcAddress(hKernel32,"GetConsoleWindow"); CONSOLE_FONT_INFOEX infoex; char fontname[64]; CONSOLE_FONT_INFO cur_f; int nFontNum; /* 取当前字体的名称,cmd下目前是两种:Terminal(点阵字体)和新宋体*/ infoex.cbSize = sizeof(CONSOLE_FONT_INFOEX); GetCurrentConsoleFontEx(__hout, 1, &infoex); WideCharToMultiByte(CP_ACP, 0, infoex.FaceName, -1, fontname, sizeof(fontname), NULL, NULL); cout << "当前字体:" << fontname << endl; /* 打印当前字体的字号信息 */ nFontNum = GetNumberOfConsoleFonts(); cout << " 字 号 数 量 :" << nFontNum << endl; #if 0 CONSOLE_FONT_INFO *p_font, *pf; int i; p_font = new(nothrow) CONSOLE_FONT_INFO[nFontNum]; if (p_font == NULL) return -1; //取当前系统的全部字体信息,存储在p_font中,再依次打印 GetConsoleFontInfo(__hout, 0, nFontNum, p_font); //最后一个参数是CONSOLE_FONT_INFO型数组 for (i = 0, pf = p_font; i < nFontNum; i++, pf++) cout << " 序号:" << setw(2) << pf->nFont << " 最大宽度:" << setw(3) << pf->dwFontSize.X << " 最大高度:" << pf->dwFontSize.Y << endl; cout << endl; delete[] p_font; #endif /* 取当前的字号设置 */ GetCurrentConsoleFont(__hout, 0, &cur_f); cout << " 当前字号序号:" << cur_f.nFont << endl; cout << " 宽度:" << cur_f.dwFontSize.X << " pixels" << endl; cout << " 高度:" << cur_f.dwFontSize.Y << " pixels" << endl; return 0; } /*************************************************************************** 函数名称: 功 能:改变输出窗口的字号 输入参数: 返 回 值: 说 明: ***************************************************************************/ void setconsolefont(const int font_no) { HMODULE hKernel32 = GetModuleHandleA("kernel32"); PROCSETCONSOLEFONT SetConsoleFont = (PROCSETCONSOLEFONT)GetProcAddress(hKernel32, "SetConsoleFont"); /* font_no width high 0 3 5 1 4 6 2 5 8 3 6 8 4 8 8 5 16 8 6 5 12 7 6 12 8 7 12 9 8 12 10 16 12 11 8 16 12 12 16 13 8 18 14 10 18 15 10 20 */ SetConsoleFont(__hout, font_no); } /*************************************************************************** 函数名称: 功 能:改变输出窗口的字体及大小 输入参数: 返 回 值: 说 明:GBK编码的cmd窗口只支持"点阵字体"和"新宋体"两种, 给出fontname时,非"新宋体"全部做为缺省字体(Terminal-"点阵字体") ***************************************************************************/ void setfontsize(const char *fontname, const int high, const int width) { CONSOLE_FONT_INFOEX infoex = { 0 }; infoex.cbSize = sizeof(CONSOLE_FONT_INFOEX); infoex.dwFontSize.X = width; // 字体宽度,对于Truetype字体,不需要宽度,为0即可,对于点阵字体,如果宽度为0,则选指定高度存在的宽度 infoex.dwFontSize.Y = high; // 字体高度 infoex.FontWeight = FW_NORMAL; //具体见 wingdi.h MultiByteToWideChar(CP_ACP, 0, fontname, -1, infoex.FaceName, sizeof(infoex.FaceName)); // wcscpy(info.FaceName, fontname); //字体 SetCurrentConsoleFontEx(__hout, NULL, &infoex); return; }
23ae410eea820dd6633f7703c6c8bf5d5093f348
bb13b9ec638ba92dbe82a5e9ef6e7308f74c4b0e
/12.dp3-longestincreasesubsequence/beautifulpeoplebaobe/tempCodeRunnerFile.cpp
9a4bf3f8ed355f319903931643d10abd4158ec72
[]
no_license
phanthaiduong22/bigoorange
a1313fece7abed90627f5a99ff5efccec8425ac7
6cbbd22317ee153e5167e27d1e71605340493cfc
refs/heads/master
2020-06-19T04:24:05.251686
2019-08-30T02:28:36
2019-08-30T02:28:36
196,561,337
0
0
null
null
null
null
UTF-8
C++
false
false
31
cpp
tempCodeRunnerFile.cpp
0, 0)); for (int i = 1; i <
281355e4524670755511c7161c0511bce70cc6b6
b2b4d86530a82e120bc003e8e772df7c1de3bca0
/coa.cpp
533dbc764df41eb335c0ce8eb1f719bd0e346ee1
[]
no_license
gxq-is-a-lovely-girl/lesson
a62db02100d3feb6a4fa076fc776d6bb99080435
138b9d0ba25d8429250167bf36372bd204044e10
refs/heads/main
2023-06-30T15:13:43.986645
2021-07-27T23:55:00
2021-07-27T23:55:00
390,158,767
0
0
null
null
null
null
UTF-8
C++
false
false
381
cpp
coa.cpp
#include<iostream> #include<algorithm> using namespace std; struct hd{ int s; int e; }; bool tmp(hd a,hd b){ return a.e<b.e; } int main(){ int n; cin>>n; hd p[n]; for(int i=0;i<n;i++){ cin>>p[i].s>>p[i].e; } sort(p,p+n,tmp); int num=n,k=0; for(int i=1;i<n;i++){ if(p[i].s<=p[k].e){ num--; }else{ k=i; } } cout<<num; }
762e3691daa1e9c62a519c718474bbf7d2785731
64d597590b7f4e19ee72b254ac51b48913914c4d
/servidorActivo/main.cpp
383d4999292711972adcc496bad1b6d9a16ab038
[]
no_license
edusjor/Remote-Memory-P1
aa4f8ad378fabaa546bfcd45dfa451ff4c7f3775
32647d48666c95d9545054e1b9dcb5b9fbfda3ae
refs/heads/master
2021-05-16T07:06:45.882864
2017-10-12T16:47:03
2017-10-12T16:47:03
103,685,214
0
0
null
null
null
null
UTF-8
C++
false
false
213
cpp
main.cpp
#include <iostream> #include "Server.h" using namespace std; int main() { cout << "Running!" << endl; Server *s; s = new Server(); //Main loop s->aceptarEimprimir(); return 0; }
75edab16508a78ed2a365b4ecff428090d275116
e3763614acb2df74fbe4aac8f31b530450ad14b3
/Ejercicio30.cpp
85fe6e743dfc48e161d3eb1c7d9f289ce135d6ee
[]
no_license
damsil99/Practica-1
536298f9cd1a26172188f3cd226d063c39513578
f5133b42da528fca05ed64fd869c4f2d5f061a76
refs/heads/master
2021-04-27T07:36:40.822529
2018-03-09T03:28:48
2018-03-09T03:28:48
122,636,413
0
0
null
null
null
null
UTF-8
C++
false
false
634
cpp
Ejercicio30.cpp
#include<time.h> #include <iostream> using namespace std; int numero=0,random; int main() { srand(time (NULL)); random = rand()% 101; cout << "Ingrese numero entre 0 y 100" << endl; cin>>numero; while(numero!=random){ if(numero<random){ cout<<"El numero es mayor"<<endl; cout << "Ingrese numero entre 0 y 100" << endl; cin>>numero; } else{ cout<<"El numero es menor"<<endl; cout << "Ingrese numero" << endl; cin>>numero; } } cout<<"El numero es correcto"<<endl; return 0; }
8044060457308c376e0832cd5088e73197bb570b
af3a863fe19c84bc5f05b22dcdf591e6497e3120
/Main.cpp
761c670a4bcdec0560055fc375639ce0c9b4f49f
[]
no_license
pjvincent/MannequinGenerator
1bb1fdb64689df74ad934462b5a7f5b3cb26635c
f0e017dc6cd5a759d2290e63e59dc90b33aef2a6
refs/heads/master
2021-01-01T05:40:31.238265
2014-11-14T14:00:45
2014-11-14T14:00:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
877
cpp
Main.cpp
#include <QApplication> #include <QtOpenGL/QGLWidget> #include "MainWindow.h" int main(int argc, char *argv[]) { QApplication app(argc, argv); // QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8")); // QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8")); // QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8")); // Anti-aliasing ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// QGLFormat glf = QGLFormat::defaultFormat(); glf.setSampleBuffers(true); glf.setSamples(4); QGLFormat::setDefaultFormat(glf); // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// MainWindow window; window.showMaximized(); return app.exec(); }
50020b2d5073cf274b91f224172af1492cf89f4b
63422d2fd3b1ff6d2d8899ad625eecb86fc7c3db
/Practice/Dijkstra/HeapNode.h
57020efbb18822d26d37368fce9aeb2d0995fbe0
[]
no_license
brianxchen/practice
2ac1dc0e62f32ea796211c1e3bcfd51f5eb6b33e
e41002c8ca86310be699b94ad0775f1784786727
refs/heads/master
2023-07-06T19:44:03.995176
2021-08-14T06:20:29
2021-08-14T06:20:29
270,399,602
0
0
null
null
null
null
UTF-8
C++
false
false
173
h
HeapNode.h
#pragma once #include "../Common.h" class HeapNode { public: int cityID; int cost; HeapNode(int cityID, int cost) { this->cityID = cityID; this->cost = cost; } };
5159e628559f8d08792e0b6ec2b0ef65695eeb57
a3b4b52ef09fafcae26dbd26e70c91c52aa142cc
/Lecture-25/StringToggleCase.cpp
1f33f265c4f92ab726abe09341b9d658156ab74a
[]
no_license
Kartik-Mathur/StAndrews-CPP
8abb5295f9afe182352fee37570c677479435a02
da399aa0ef185faa1e538374786ca6af6bf2d6d3
refs/heads/master
2023-02-16T00:32:20.555518
2021-01-15T06:06:00
2021-01-15T06:06:00
296,238,047
12
12
null
null
null
null
UTF-8
C++
false
false
225
cpp
StringToggleCase.cpp
// StringToggleCase #include <iostream> using namespace std; int main(){ char a[1001]; // cin.getline(a,1001); cin>>a; for(int i = 0 ; a[i] != '\0' ; i++){ a[i] = (a[i]^' '); } cout<<a; cout<<endl; return 0; }
e524edbc59e0a1fc17733208b0b08a062a2c95d1
6084f7ee54823caa2df5277ae398e9c447e60bdf
/raytrace/Vector3.cpp
d46a64d62c9b99fba9dbc3429dca7a11600a67fd
[]
no_license
Fenrisulfr503/SimpleRayTrace
c5974de949ab80fb62d1fc4a853fb6a5c13da16a
9580fb5a26609532dd447924e7c4ba89301eed41
refs/heads/master
2022-07-13T05:45:01.249922
2020-05-13T17:02:13
2020-05-13T17:02:13
261,632,968
0
0
null
null
null
null
UTF-8
C++
false
false
1,935
cpp
Vector3.cpp
#include "Vector3.h" #include <math.h> Vector3& Vector3::operator=(const Vector3& rhs) { if(this != &rhs) { x = rhs.x; y = rhs.y; z = rhs.z; } return *this; } Vector3 Vector3::operator+(const Vector3& rhs)const { return Vector3( x + rhs.x, y + rhs.y, z + rhs.z); } Vector3 Vector3::operator-(const Vector3& rhs)const { return Vector3( x - rhs.x, y - rhs.y, z - rhs.z); } Vector3 Vector3::operator*(const Vector3& rhs)const { return Vector3( x * rhs.x, y * rhs.y, z * rhs.z); } Vector3 Vector3::operator/(const Vector3& rhs)const { return Vector3( x / rhs.x, y / rhs.y, z / rhs.z); } Vector3 Vector3::operator*(const float val)const { return Vector3( x * val, y * val, z * val); } Vector3 Vector3::operator/(const float val)const { return Vector3( x / val, y / val, z / val); } Vector3& Vector3::operator+=(const Vector3& rhs) { x += rhs.x; y += rhs.y; z+= rhs.z; return *this; } Vector3& Vector3::operator-=(const Vector3& rhs) { x -= rhs.x; y -= rhs.y; z -= rhs.z; return *this; } Vector3& Vector3::operator*=(const Vector3& rhs) { x *= rhs.x; y *= rhs.y; z*= rhs.z; return *this; } Vector3& Vector3::operator/=(const Vector3& rhs) { x /= rhs.x; y /= rhs.y; z /= rhs.z; return *this; } Vector3& Vector3::operator*=(const float val) { x *= val; y *=val; z *= val; return *this; } Vector3& Vector3::operator/=(const float val) { x /= val; y /=val; z /= val; return *this; } float Vector3::length()const { return float(sqrt(x*x + y*y + z*z)); } float dot(const Vector3& lhs, const Vector3& rhs) { return lhs.x * rhs.x + lhs.y * rhs.y + lhs.z * rhs.z; } Vector3 cross(const Vector3& lhs, const Vector3& rhs) { return Vector3 (lhs.y * rhs.z - lhs.z * rhs.y, lhs.z * rhs.x - lhs.x * rhs.z, lhs.x * rhs.y - lhs.y * rhs.x); } Vector3 Normilize(const Vector3& v) { return v / v.length(); }
86eaa161b4158da2563a4082f78248e07a2c6c5e
d6e65aa23ff8b2344dacac93fe00fcfcd64cc414
/cf_make_good.cpp
5c7836c799e49c2adb80b848a8b01b12a1b5f75c
[]
no_license
diwadd/sport
c4b0ec3547cde882c549fa7b89e0132fdaf0c8fb
220dfaf1329b4feea5b5ca490ffc17ef7fe76cae
refs/heads/master
2023-05-29T13:17:23.516230
2023-05-20T22:08:28
2023-05-20T22:08:28
223,636,723
0
0
null
null
null
null
UTF-8
C++
false
false
624
cpp
cf_make_good.cpp
#include <iostream> #include <cstdio> #include <vector> #include <string> using namespace std; typedef unsigned long long int ulli; int main() { const unsigned long long MOD7 = 1000000000+7; ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int t; cin >> t; for(int i = 0; i < t; i++) { int n; cin >> n; ulli s = 0; ulli x = 0; for(int j = 0; j < n; j++){ ulli aj; cin >> aj; s = s + aj; x = x ^ aj; } cout << "2" << endl; cout << x << " " << s + x << endl; } }
07f0b529e8764573c4f2118b844ce08629981e1d
5549c58314d99adbb756e0264918168445f000fc
/Android/example/example.cpp
ea5d352c0ddf66d314752005bd69fb61583b2f14
[ "MIT" ]
permissive
MJx0/KittyMemory
12a907134618a5f68d90299f5a1da05965b86f94
ac2f6cde44035d71f2489dd9724243e43127ee64
refs/heads/master
2022-11-08T22:37:37.297847
2022-11-01T09:50:25
2022-11-01T09:50:25
167,967,058
233
104
null
null
null
null
UTF-8
C++
false
false
6,004
cpp
example.cpp
#include <pthread.h> #include <vector> #include <KittyMemory/KittyMemory.h> #include <KittyMemory/MemoryPatch.h> #include <KittyMemory/KittyScanner.h> #include <KittyMemory/KittyUtils.h> using KittyMemory::ProcMap; using KittyScanner::RegisterNativeFn; // define kITTYMEMORY_DEBUG in cpp flags for KITTY_LOGI & KITTY_LOGE outputs // fancy struct for patches struct GlobalPatches { // let's assume we have patches for these functions for whatever game // boolean function MemoryPatch canShowInMinimap; // etc... }gPatches; ProcMap g_il2cppBaseMap; void *test_thread(void *) { KITTY_LOGI("======================= LOADED ======================"); // loop until our target library is found do { sleep(1); g_il2cppBaseMap = KittyMemory::getLibraryBaseMap("libil2cpp.so"); } while (!g_il2cppBaseMap.isValid()); KITTY_LOGI("il2cpp base: %p", (void*)(g_il2cppBaseMap.startAddress)); // wait more to make sure lib is fully loaded and ready sleep(1); KITTY_LOGI("==================== MEMORY PATCH ==================="); /* patch with direct bytes */ gPatches.canShowInMinimap = MemoryPatch(g_il2cppBaseMap, 0x6A6144, "\x01\x00\xA0\xE3\x1E\xFF\x2F\xE1", 8); // absolute address gPatches.canShowInMinimap = MemoryPatch(g_il2cppBaseMap.startAddress + 0x6A6144, "\x01\x00\xA0\xE3\x1E\xFF\x2F\xE1", 8); // also possible with hex & no need to specify len gPatches.canShowInMinimap = MemoryPatch::createWithHex(g_il2cppBaseMap, 0x6A6144, "0100A0E31EFF2FE1"); // spaces are fine too gPatches.canShowInMinimap = MemoryPatch::createWithHex(g_il2cppBaseMap, 0x6A6144, "01 00 A0 E3 1E FF 2F E1"); // absolute address gPatches.canShowInMinimap = MemoryPatch::createWithHex(g_il2cppBaseMap.startAddress + 0x6A6144, "01 00 A0 E3 1E FF 2F E1"); KITTY_LOGI("Patch Address: %p", (void *)gPatches.canShowInMinimap.get_TargetAddress()); KITTY_LOGI("Patch Size: %zu", gPatches.canShowInMinimap.get_PatchSize()); KITTY_LOGI("Current Bytes: %s", gPatches.canShowInMinimap.get_CurrBytes().c_str()); // modify & print bytes if (gPatches.canShowInMinimap.Modify()) { KITTY_LOGI("canShowInMinimap has been modified successfully"); KITTY_LOGI("Current Bytes: %s", gPatches.canShowInMinimap.get_CurrBytes().c_str()); } // restore & print bytes if (gPatches.canShowInMinimap.Restore()) { KITTY_LOGI("canShowInMinimap has been restored successfully"); KITTY_LOGI("Current Bytes: %s", gPatches.canShowInMinimap.get_CurrBytes().c_str()); } KITTY_LOGI("=============== FIND NATIVE REGISTERS ==============="); // get all maps of unity lib std::vector<ProcMap> unityMaps = KittyMemory::getMapsByName("libunity.so"); // finding register native functions RegisterNativeFn nativeInjectEvent = KittyScanner::findRegisterNativeFn(unityMaps, "nativeInjectEvent"); if(nativeInjectEvent.isValid()) { KITTY_LOGI("nativeInjectEvent = { %s, %s, %p }", nativeInjectEvent.name, nativeInjectEvent.signature, nativeInjectEvent.fnPtr); } RegisterNativeFn nativeUnitySendMessage = KittyScanner::findRegisterNativeFn(unityMaps, "nativeUnitySendMessage"); if(nativeUnitySendMessage.isValid()) { KITTY_LOGI("nativeUnitySendMessage = { %s, %s, %p }", nativeUnitySendMessage.name, nativeUnitySendMessage.signature, nativeUnitySendMessage.fnPtr); } RegisterNativeFn nativeRender = KittyScanner::findRegisterNativeFn(unityMaps, "nativeRender"); if(nativeRender.isValid()) { KITTY_LOGI("nativeInjectEvent = { %s, %s, %p }", nativeRender.name, nativeRender.signature, nativeRender.fnPtr); } KITTY_LOGI("==================== PATTERN SCAN ==================="); // scan for bytes with mask x and ? uintptr_t found_at = 0; std::vector<uintptr_t> found_at_list; // scan with direct bytes & get one result found_at = KittyScanner::findBytesFirst(g_il2cppBaseMap.startAddress, g_il2cppBaseMap.endAddress, "\x33\x44\x55\x66\x00\x77\x88\x00\x99", "xxxx??x?x"); KITTY_LOGI("found bytes at: %p", (void*)found_at); // scan with direct bytes & get all results found_at_list = KittyScanner::findBytesAll(g_il2cppBaseMap.startAddress, g_il2cppBaseMap.endAddress, "\x33\x44\x55\x66\x00\x77\x88\x00\x99", "xxxx??x?x"); KITTY_LOGI("found bytes results: %zu", found_at_list.size()); // scan with hex & get one result found_at = KittyScanner::findHexFirst(g_il2cppBaseMap.startAddress, g_il2cppBaseMap.endAddress, "33 44 55 66 00 77 88 00 99", "xxxx??x?x"); KITTY_LOGI("found hex at: %p", (void*)found_at); // scan with hex & get all results found_at_list = KittyScanner::findHexAll(g_il2cppBaseMap.startAddress, g_il2cppBaseMap.endAddress, "33 44 55 66 00 77 88 00 99", "xxxx??x?x"); KITTY_LOGI("found hex results: %zu", found_at_list.size()); // scan with data type & get one result uint32_t data = 0x99887766; found_at = KittyScanner::findDataFirst(g_il2cppBaseMap.startAddress, g_il2cppBaseMap.endAddress, &data, sizeof(data)); KITTY_LOGI("found data at: %p", (void*)found_at); // scan with data type & get all results found_at_list = KittyScanner::findDataAll(g_il2cppBaseMap.startAddress, g_il2cppBaseMap.endAddress, &data, sizeof(data)); KITTY_LOGI("found data results: %zu", found_at_list.size()); KITTY_LOGI("====================== HEX DUMP ====================="); // hex dump by default 8 rows with ASCII KITTY_LOGI("%s", KittyUtils::HexDump((void*)g_il2cppBaseMap.startAddress, 100).c_str()); KITTY_LOGI("====================================================="); // 16 rows, no ASCII KITTY_LOGI("%s", KittyUtils::HexDump<16, false>((void*)g_il2cppBaseMap.startAddress, 100).c_str()); return nullptr; } __attribute__((constructor)) void initializer() { pthread_t ptid; pthread_create(&ptid, nullptr, test_thread, nullptr); }
674aa8e01ea692d9eff81d9328c8aed7bb6aecc6
8f8ede2d240cafa0b17f135c553a2ae64e6ea1bd
/voice/voicerecog/test/voicerecoglib/dialogengine/suntec/mockfiles/VR_DECommon_mock.h
e64d28a14e72660f94215fb893c4fa2fcc5b8c9d
[]
no_license
hyCpp/MyDemo
176d86b720fbc9619807c2497fadb781f5dc4295
150c77ebe54fe7b7f60063e6488319d804a07d03
refs/heads/master
2020-03-18T05:33:37.338743
2019-03-10T04:21:01
2019-03-10T04:21:01
134,348,743
0
0
null
null
null
null
UTF-8
C++
false
false
1,763
h
VR_DECommon_mock.h
/** * Copyright @ 2015 - 2016 Suntec Software(Shanghai) Co., Ltd. * All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are NOT permitted except as agreed by * Suntec Software(Shanghai) Co., Ltd. * * 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. */ /** * @file VR_Configure_mock.h * @brief inteface for interpeter or asr engine to perfer command * * * @attention used for C++ only. */ #ifndef VR_DECOMMON_MOCK_H #define VR_DECOMMON_MOCK_H #ifndef __cplusplus # error ERROR: This file requires C++ compilation (use a .cpp suffix) #endif #include "gmock/gmock.h" #include "gtest/gtest.h" #include "VR_DECommonIF.h" /** * VR_Configure_mock * * The class is a mock class for VR_Configure. */ class VR_DECommon_mock : public VR_DECommonIF { public: MOCK_METHOD1(init, void(VR_ConfigureIF* configure)); MOCK_METHOD0(isGetFromData, bool()); MOCK_METHOD0(getProductCountry, std::string()); MOCK_METHOD0(getCountryType, DE_Country()); MOCK_METHOD2(getAsrSupportLanguage, bool(const std::string& lang, std::string& outLanguage)); MOCK_METHOD0(getVROverBeep, bool()); MOCK_METHOD1(setNaviModel, void(bool is)); MOCK_METHOD0(getNaviModel, bool()); MOCK_METHOD0(getHybridVRFlag, bool()); MOCK_METHOD0(isSupportVR, bool()); MOCK_METHOD0(getVRLanguage, std::string()); MOCK_METHOD0(notifyVRLanguageChange, void()); MOCK_METHOD0(getDataPath, const std::string()); MOCK_METHOD1(getTargetNice, int(const std::string& thName)); MOCK_CONST_METHOD0(getHeadUnitType, const std::string&()); }; #endif /* EOF */
2a8716a8b3e63933d79614ae568b5c1c231ecebe
b92db19311447d94a809e98a069b8e5dbf929a99
/code/esp32_code/esp32_code.ino
9b9fedc210f5fa54a1ebf24cf299d9bd3b8ca0f4
[]
no_license
imsuneth/CO326-Project
eb751fba204aa4f95fa43465f8825615a02c83dc
bc5d47b219c5ae3ff9d9805e1496fc01e0325e78
refs/heads/master
2022-12-27T09:57:26.102927
2020-10-11T12:20:34
2020-10-11T12:20:34
300,497,159
0
0
null
2020-10-05T15:00:25
2020-10-02T04:10:16
null
UTF-8
C++
false
false
4,073
ino
esp32_code.ino
#include <WiFi.h> #include <PubSubClient.h> #include <Ethernet.h> enum CLSTATE {GO = 1, STOP = 0}; int led_pins[16] = {16, 26, 15, 4, 25, 14, 27, 17, 5, 18, 23, 19, 13, 33, 21, 22}; int cl_status[8] = {0, 0, 0, 0, 0, 0, 0, 0}; String nodes_status = "online"; //WiFi const char* ssid = "Dialog 4G wish"; const char* password = "wishez1234"; //MQTT Broker IP address const char* mqtt_server = "192.168.1.2"; WiFiClient espClient; PubSubClient client(espClient); void setup_wifi() { delay(10); Serial.println(); Serial.print("Connecting to"); Serial.println(ssid); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(""); Serial.println("WiFi connected"); Serial.println("IP address: "); Serial.println(WiFi.localIP()); } void cl_go(int road, int lane) { digitalWrite(led_pins[4 * road + 2 * lane + 0], LOW); digitalWrite(led_pins[4 * road + 2 * lane + 1], HIGH); } void cl_stop(int road, int lane) { digitalWrite(led_pins[4 * road + 2 * lane + 0], HIGH); digitalWrite(led_pins[4 * road + 2 * lane + 1], LOW); } void cl_stop_all() { for (int i = 1; i < 16; i += 2) { digitalWrite(led_pins[i], LOW); digitalWrite(led_pins[i-1], HIGH); } // for (int i = 0; i < 16; i += 2) { // digitalWrite(led_pins[i], HIGH); // } } void cl_update() { for (int i = 0; i < 8; i++) { if (cl_status[i] == '1') { cl_go(i / 2, i % 2); } else if (cl_status[i] == '0') { cl_stop(i / 2, i % 2); } } } void callback(char* topic, byte* message, unsigned int length) { Serial.print("Message arrived on topic: "); Serial.print(topic); Serial.print(". Message: "); if (String(topic) == "esp32/cl_status") { for (int i = 0; i < length; i++) { Serial.print((char)message[i]); cl_status[i] = (char)message[i]; } Serial.println(); //Update color lights cl_update(); } if (String(topic) == "willTopic") { nodes_status = ""; for (int i = 0; i < length; i++) { Serial.print((char)message[i]); nodes_status += (char)message[i]; } Serial.println(); if (nodes_status == "offline") { time_based2(); } } } void reconnect() { // Loop until we're reconnected //while (!client.connected()) { Serial.print("Attempting MQTT connection..."); // Attempt to connect if (client.connect("ESP32Client")) { Serial.println("connected"); // Subscribe client.subscribe("esp32/cl_status"); client.subscribe("willTopic"); client.subscribe("time"); } else { Serial.print("failed, rc="); Serial.print(client.state()); Serial.println(" try again in 5 seconds"); // Wait 5 seconds before retrying delay(100); } //} } void time_based() { Serial.println("Time based controlling started!"); int road = 0; while (true) { Serial.print("Open road:"); Serial.println(road); //cl_stop_all(); cl_go(road, 0); cl_go(road, 1); reconnect(); delay(10); cl_stop(road, 0); cl_stop(road, 1); road = (road + 1) % 4; if (client.connected()) { break; } } } void time_based2() { Serial.println("Time based controlling started!"); int road = 0; while (true) { Serial.print("Open road:"); Serial.println(road); //cl_stop_all(); cl_go(road, 0); cl_go(road, 1); delay(5000); cl_stop(road, 0); cl_stop(road, 1); road = (road + 1) % 4; client.loop(); if (nodes_status == "online") { break; } } } void setup() { Serial.begin(115200); setup_wifi(); client.setServer(mqtt_server, 1883); client.setCallback(callback); // client.setKeepAlive(5); // client.setSocketTimeout(1); // set OUTPUTs for (int i = 0; i < 16; i++) { pinMode(led_pins[i], OUTPUT); } cl_stop_all(); if (!client.connected()) { reconnect(); } } void loop() { // put your main code here, to run repeatedly: if (!client.connected()) { //Switch to time based mode time_based(); } client.loop(); }