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
b8fa714dcd41dbba5ddf735637491ac9617a2889
f9a521941997b5d3cd058e834821f2367838dfb1
/Arrays_and_LinkedLists/Q2_Array.cpp
04d80718539f45fb66e6e3c0ba915f6488aac1fe
[]
no_license
hmd0404-nitk-eee/algorithms_and_problems
4835923c5138b588fbb574d19aadb91d7c385338
14de5e6ea0c3324469bdff606570c089897f01e1
refs/heads/master
2022-12-20T18:28:05.309838
2020-09-28T03:52:20
2020-09-28T03:52:20
291,418,596
0
0
null
null
null
null
UTF-8
C++
false
false
1,981
cpp
Q2_Array.cpp
/* CS202 Assignment Name: Harshal Dhake 191EE212 This program stores a lower triangular matrix efficiently (space wise). The formula to map 2D indexing to 1D index .i.e. Matrix to Array is, 2D index (i,j) = (sigma(n){n from 1 to n-1} + j) in 1D indexing */ #include <iostream> using namespace std; #define MAXSIZE 100 //Evaluates the sigma int sumTillNum(int num) { int sum = 0; for(int i = 0; i <= num; i++) { sum += i; } return sum; } int main() { int array[MAXSIZE], size, noOfElements; cout << "Enter the array size: "; cin >> size; /*if(size <= MAXSIZE) { array = new int[size]; } else { array = NULL; cout << "Too big array!"; return 0; }*/ noOfElements = (size * (size+1)) / 2; cout << "Enter the lower triangular matrix in rows: "; for(int i = 0; i < noOfElements; i++) { cin >> array[i]; } cout << "The addressing formula for mapping element a[i][j] in the lower triangle matrix stored by rows" << endl; cout << "in an array B[1....n(n+1)/2] with A[1][1] stored in B[1] is," << endl; cout << "Formula: To access element a[i][j], " << endl; cout << " n = i-1 " << endl; cout << " --------- " << endl; cout << " \\ " << endl; cout << " \\ " << endl; cout << " \\ |----- + j = index of array" << endl; cout << " / | |" << endl; cout << " / | |" << endl; cout << " / | |" << endl; cout << " --------- " << endl; cout << " n = 1 " << endl; cout << endl << "Using the above formula, the inputed matrix is: " << endl; int index = 0; for(int i = 0; i < size; i++) { for(int j = 0; j < size; j++) { if(j > i) { cout << "0 "; } else { index = sumTillNum(i) + j; cout << array[index] << " "; } } cout << endl; } cout << "\nThe relation for zero part of A is i < j if i is row counter and j is column counter" << endl; return 0; }
bd3e28c1bf84d00697f53009ed979f8f5b6df190
c05e553d9fb38cb28dabfeb594b6f2c7b0defd85
/CSI2372-master/Hand.h
da1db0f9439f3b3a0755c534ac6314106b447c3b
[]
no_license
matteo391/CSI2372
25d79128547e586352e95f82d0bd3a4cab12dab0
3f6d02be611841578f483af28d22827296742fea
refs/heads/master
2023-01-25T03:49:58.588025
2020-12-08T03:01:10
2020-12-08T03:01:10
318,626,750
0
0
null
2020-12-07T22:45:32
2020-12-04T20:22:04
C++
UTF-8
C++
false
false
252
h
Hand.h
#include <iostream> #include <list> #include "Card.h" class Hand { list<Card*> hand; public: Hand(istream&, const CardFactory*); Hand& operator+=(Card*); Card* play(); Card* top(); Card* operator[](int); //todo insertion operator };
d8887cf9df74c81d877bc87a7a64b52986fe5120
91f913acfd0d085ce71aceca3e55dcd7953e319a
/MDP_GRP11/MDP_GRP11.ino
61cd9c3e28b9a2b3addf873784db1c34f068a0dc
[]
no_license
nghaninn/MDP
3a8d27acf5f074c85a625960e97c945e2059fa54
a947ce0a1808ef172b60ea61fbbedf8fb1449487
refs/heads/master
2022-10-15T16:16:46.726079
2018-10-17T15:44:59
2018-10-17T15:44:59
149,653,378
0
0
null
null
null
null
UTF-8
C++
false
false
6,442
ino
MDP_GRP11.ino
#include <EnableInterrupt.h> #include "Calib.h" #include "Global.h" String commands = ""; String pre_command = ""; bool isFastestPath = false; Movement *move; Calib *cal; Motor *motor; Sensor *s; void setup() { Serial.begin(115200); enableInterrupt(Motor::M1A, motor1, RISING); enableInterrupt(Motor::M2A, motor2, RISING); move = new Movement(); cal = new Calib(); motor = new Motor(); s = new Sensor(); } void motor1() { motor->encoder1(); } void motor2() { motor->encoder2(); } void loop() { if (CALIB_SENSORS_PRINTVALUES) s->detectAll(); while (!readCommand(&commands)); // if (pre_command != commands) { // while (Serial.available()) { // Serial.read(); //flush out all command while execution; // } // pre_command = ""; // } if ((commands.charAt(0) == 'S' || commands.charAt(0) == 's')) { if (DEBUG) Serial.println(String(ALREADY_SENT_OUT_SENSOR)); if (ALREADY_SENT_OUT_SENSOR > 0) ALREADY_SENT_OUT_SENSOR = 0; else if (ALREADY_SENT_OUT_SENSOR > 0) ALREADY_SENT_OUT_SENSOR++; else ALREADY_SENT_OUT_SENSOR = 0; } else ALREADY_SENT_OUT_SENSOR = 0; executeCommand(commands); // while (Serial.available()) { // Serial.read(); //flush out all command while execution; // } pre_command = commands; commands = ""; } bool readCommand(String *readVal) { char tmp; while (Serial.available()) { tmp = Serial.read(); (*readVal) += tmp; if (tmp == '\n' || tmp == '\0') return true; // stop blocking } // block if nothing comes in return false; } /* L = left turn R = right turn C = calibrate U = u-turn S = sensor around M1 = move 1 M2 = move 2 M3 = move 3 ALGO - 1-LF 2-LB 3-FL 4-FR 5-FM 6-R - DELIMINATOR "," BLIND = 100 */ bool executeCommand(String command) { if (DEBUG) Serial.println("-Received Command: " + String(command) + " | " + String(ALREADY_SENT_OUT_SENSOR)); String sub_command; while ((sub_command = getSubString(&command, ',')).length()) { while (cal->isCalibrating); if (DEBUG) Serial.println("-Received Command: " + String(sub_command)); if (sub_command.charAt(0) == 'a') { sub_command.remove(0, 1); int value = sub_command.toInt() + 1; Serial.println("a" + String(value)); } else if (sub_command.charAt(0) == 'L' || sub_command.charAt(0) == 'l') { if (DEBUG) Serial.println("L"); move->rotateL(90); if (AUTO_SELF_CALIB && LEFT_CAL_COUNT > 2) cal->selfCalib(false); } else if (sub_command.charAt(0) == 'R' || sub_command.charAt(0) == 'r') { if (DEBUG) Serial.println("R"); move->rotate(90); if (AUTO_SELF_CALIB && LEFT_CAL_COUNT > 2) cal->selfCalib(false); } else if (sub_command.charAt(0) == 'C' || sub_command.charAt(0) == 'c') { if (DEBUG) Serial.println("C"); if (sub_command.charAt(1) == '1') { if (AUTO_SELF_CALIB && LEFT_CAL_COUNT > 2) cal->selfCalib(); } else if (sub_command.charAt(1) == '2') cal->calibFront(); else if (sub_command.charAt(1) == '3') cal->calibLeft(); else cal->calib(); } else if (sub_command.charAt(0) == 'U' || sub_command.charAt(0) == 'u') { if (DEBUG) Serial.println("U"); move->rotate(180); if (AUTO_SELF_CALIB && LEFT_CAL_COUNT > 2) cal->selfCalib(false); } else if ((sub_command.charAt(0) == 'S' || sub_command.charAt(0) == 's')) { if (DEBUG) Serial.println("S"); if (sub_command.charAt(1) == '1') { s->printAllSensorsRAW(); ALREADY_SENT_OUT_SENSOR++; } else if (sub_command.charAt(1) == '2') { s->detectAll(); ALREADY_SENT_OUT_SENSOR++; } else if (sub_command.charAt(1) == '9') { move->rotateL(90); cal->calib(); move->rotateR(90); cal->selfCalib(); s->printAllSensors(); ALREADY_SENT_OUT_SENSOR++; } else if (ALREADY_SENT_OUT_SENSOR == 0) { s->printAllSensors(); ALREADY_SENT_OUT_SENSOR++; } } else if (sub_command.charAt(0) == 'M' || sub_command.charAt(0) == 'm') { if (DEBUG) Serial.println("M"); if (sub_command.charAt(1) == '1') { if (sub_command.charAt(2) == '0') { move->move(10); } else if (sub_command.charAt(2) == '1') { move->move(11); } else if (sub_command.charAt(2) == '2') { move->move(12); } else if (sub_command.charAt(2) == '3') { move->move(13); } else if (sub_command.charAt(2) == '4') { move->move(14); } else if (sub_command.charAt(2) == '5') { move->move(15); } else if (sub_command.charAt(2) == '6') { move->move(16); } else if (sub_command.charAt(2) == '7') { move->move(17); } else if (sub_command.charAt(2) == '8') { move->move(18); } else { move->move(1); delay(50); } } else if (sub_command.charAt(1) == '2') { move->move(2); } else if (sub_command.charAt(1) == '3') { move->move(3); } else if (sub_command.charAt(1) == '4') { move->move(4); } else if (sub_command.charAt(1) == '5') { move->move(5); } else if (sub_command.charAt(1) == '6') { move->move(6); } else if (sub_command.charAt(1) == '7') { move->move(7); } else if (sub_command.charAt(1) == '8') { move->move(8); } else if (sub_command.charAt(1) == '9') { move->move(9); } else move->move(1); if (AUTO_SELF_CALIB) cal->selfCalib(); } else if (sub_command.charAt(0) == 'z') { move->newBatt(); } else if (sub_command.charAt(0) == 'M' || sub_command.charAt(0) == 'f') { //RUNNING FASTEST } } if(isFastestPath) { delay(100); } else delay(50); LEFT_CAL_COUNT++; if (ALREADY_SENT_OUT_SENSOR == 0 && !isFastestPath) { s->printAllSensors(); ALREADY_SENT_OUT_SENSOR++; } if (DEBUG) Serial.println(String(ALREADY_SENT_OUT_SENSOR)); } String getSubString(String * command, char separator) { if (!(*command).length()) return ""; String temp = ""; int i; for (i = 0; i <= (*command).length(); i++) { if ((*command).charAt(i) != separator) { temp += (*command).charAt(i); } else break; } (*command).remove(0, i + 1); return temp; }
e517c7b33cefa3a972625c0365e2268d74a44808
784ab6712362e46dbcccb6c75e64c7b01f0844cc
/src/gamecode/mkbkgd.inc
b86c729de3355bda072e67b6cbb6b060cadea857
[]
no_license
Zoltan45/mktrilogy
6e574e23c3be9192832e3e5fb16d78b398130cf3
77bc46385b303168ed51f2597ff420d36c6d236b
refs/heads/main
2023-06-04T22:26:29.635963
2021-06-28T01:01:11
2021-06-28T01:01:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,848
inc
mkbkgd.inc
/* set if background is active/loadavle (0=no, 1=yes) */ ACT_BG_SUB_STREET = 1 ACT_BG_ROOF = 1 ACT_BG_BANK = 1 ACT_BG_TOWER = 1 ACT_BG_SOUL = 1 ACT_BG_BELL = 1 ACT_BG_GRAVE = 1 ACT_BG_BRIDGE = 1 ACT_BG_TEMPLE = 1 ACT_BG_THRONE = 1 ACT_BG_LADDER = 1 ACT_BG_BIO = 1 ACT_BG_COIN = 1 ACT_BG_VS = 1 ACT_BG_BUYIN = 1 SCX = 100 /* GLOBAL EQUATES */ NULL_IRQSKYE = 444 END_LIST = 0 SKIP_BAKMOD = 1 FORCE_EXIT = -1 CENTER_X = -2 .extern bakmods .extern worldtlx .extern worldtlx1 .extern worldtlx2 .extern worldtlx3 .extern worldtlx4 .extern worldtlx5 .extern worldtlx6 .extern worldtlx7 .extern worldtlx8 .extern worldtly .extern worldtly1 .extern worldtly2 .extern worldtly3 .extern worldtly4 .extern worldtly5 .extern worldtly6 .extern worldtly7 .extern worldtly8 .extern scrollx .extern scrollx1 .extern scrollx2 .extern scrollx3 .extern scrollx4 .extern scrollx5 .extern scrollx6 .extern scrollx7 .extern scrollx8 .extern objlst .extern objlst2 .extern baklst0 .extern baklst1 .extern baklst2 .extern baklst3 .extern baklst4 .extern baklst5 .extern baklst6 .extern baklst7 .extern baklst8 .extern baklst9 .extern objlst_t .extern baklst1_t .extern baklst2_t .extern baklst3_t .extern baklst4_t .extern baklst5_t .extern baklst6_t .extern baklst7_t .extern baklst8_t .extern worldtlx8_t .extern worldtlx7_t .extern worldtlx6_t .extern worldtlx5_t .extern worldtlx4_t .extern worldtlx3_t .extern worldtlx2_t .extern worldtlx1_t .extern worldtlx_t .extern calla_return .extern skew_7 .extern skew_8 .extern floor_code .extern shadow_p1p2 .extern use_next_y .extern use_worldtly_t .extern check_only_t .extern use_worldtly
e03cd1a1e6cca226d26c63916ac856e9fa10c992
628734bd2841ca93808d2252c1e1952fbcb109be
/traverse_blend_vr/cpp/octomutils/src/mapUpdate.cpp
2f1faa7d003ae34aa87aed9dad78db803451665e
[]
no_license
BlenderCN-Org/H-MRI_Search_and_Rescue
303579cb0dd2c4a3b532723eaee49313a0fe2e42
db1ee048fd8bd7d19f8be2d092cd650be0c3df1c
refs/heads/master
2020-05-22T18:25:30.349917
2017-03-01T17:26:34
2017-03-01T17:26:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,736
cpp
mapUpdate.cpp
#include <fstream> #include <stdio.h> /* printf */ #include <string.h> /* strcat */ #include <stdlib.h> /* strtol */ #include <iostream> #include <bitset> #include <sys/time.h> #include <vector> #include <math.h> #include <time.h> #include<ctime> #include <sstream> #include <sys/types.h> #include <dirent.h> // readdir opendir closedir #include <unistd.h> // getopt #include <getopt.h> #define no_argument 0 #define required_argument 1 #define optional_argument 2 #define VERSION 1.0 #define NOBLEND 0 #define save_bt_file 0 // include octomap header #include <octomap/octomap.h> #include <octomap/OcTree.h> #include <octomap/AbstractOcTree.h> // own files #include "binaryoctree.h" #include "compareoctrees.h" #include "octomaptoblend.h" using namespace std; using namespace octomap; void readOcTreeFile(std::string path, BinaryOctree &bin_octree); void getSubTrees(BinaryOctree* bin_octree,vector<Subtree>& subtrees); std::vector<Subtree> compare(BinaryOctree* curr_bin_octree,std::vector<Subtree>* curr_sub_trees,BinaryOctree* prev_bin_octree,std::vector<Subtree>* prev_sub_trees); void buildSubtree(std::vector<Subtree> , BinaryOctree*, string ); CompareOcTrees _comp_trees; // compare subtree object, can also get subtrees form octree octomapToBlend *_omtb_complete = new octomapToBlend(); int main( int argc, char *argv[] ){ BinaryOctree prev_bin_octree; std::vector<Subtree> prev_sub_trees; // init the python stuff _omtb_complete->init(); std::string octree_path("/tmp/octomapToBlend/maps"); // preamble std::string fst_filename; //main endless loop while(true){ // check if there is a new octree to read BinaryOctree curr_bin_octree; readOcTreeFile(octree_path,curr_bin_octree); if(curr_bin_octree.getData()->size() > 0){ // make sure we don't use empty trees // get the subtrees of the current binary octree std::vector<Subtree> curr_sub_trees; getSubTrees(&curr_bin_octree,curr_sub_trees); // make a tempory copy of the current subtrees because compare might alter this vector std::vector<Subtree> to_save = curr_sub_trees; if(prev_sub_trees.size() > 0){ // can compare something // find the subtrees which have to be updated // this alters the current subtree vector and removes subtrees which can be found in prev_sub_trees // and are equal to their counterpart _comp_trees.compare(&prev_bin_octree,&prev_sub_trees,&curr_bin_octree,&curr_sub_trees); } if(curr_sub_trees.size() > 0){ cout << "build blend" << endl; // build the subtrees which have been updated cout << curr_sub_trees.size()<< " "<< curr_bin_octree.getData()->size() << endl; buildSubtree(curr_sub_trees,&curr_bin_octree,"/tmp/blender"); } // save the new tree state prev_bin_octree = curr_bin_octree; prev_sub_trees = to_save; } // just for debugging I added a sleep here sleep(1); } _omtb_complete->finalize(); } bool hasEnding (std::string const &fullString, std::string const &ending) { if (fullString.length() >= ending.length()) { return (0 == fullString.compare (fullString.length() - ending.length(), ending.length(), ending)); } else { return false; } } void readOcTreeFile(string path,BinaryOctree& bin_octree){ DIR* dirp; dirent* dp; // make the readOcTreeFile() blocking // wait for a file to be within the folder while(true){ dirp = opendir(path.c_str()); while ((dp = readdir(dirp)) != NULL){ cout << dp->d_name << endl; if (hasEnding(dp->d_name,".bt")) { std::cout << "found " << dp->d_name << std::endl; std::stringstream completefile; completefile << path << "/" << dp->d_name; std::ifstream bintree_file(completefile.str().c_str(), std::ios_base::in | std::ios_base::binary); // check if file is open if (!bintree_file.is_open()){ cerr << bintree_file << " could not be opened" << endl; break; } BinaryOctree bo(bintree_file); bin_octree = bo; (void)closedir(dirp); return; } } (void)closedir(dirp); // sleep to define the check intervall for new files std::cout << "waiting for file in " << path << std::endl; sleep(1); } // when we exit the function we need to make sure we close the dir (void)closedir(dirp); } void getSubTrees(BinaryOctree *bin_octree, vector<Subtree> &subtrees){ // only if there is actual data in the tree other wise this ould cause a seg fault further down below if(bin_octree->getData()->size() > 0){ subtrees = _comp_trees.getSubtrees_iter(bin_octree->getData(),bin_octree->getResolution()); } } void buildSubtree(std::vector<Subtree> subtrees, BinaryOctree* bin_octree,std::string output_path){ if(subtrees.size() < 1 || bin_octree->getData()->size() < 1){ return; } // prepare the conversion from my binary octree to octomap bin octree vector<bitset<8> >data_bit8 = *bin_octree->getData(); vector<unsigned char> data_uchar; data_uchar.reserve(data_bit8.size()); ///////////////////////////////// // BUILDING THE BLEND MESH FILES ///////////////////////////////// vector<Origin> subtree_origs; cout << "number of subtrees " << subtrees.end() - subtrees.begin() << endl; for(std::vector<Subtree >::iterator subT_it = subtrees.begin(); subT_it != subtrees.end(); ++subT_it){ int lb = (*subT_it).getSubTreePointer(); int ub = (*subT_it).getSubTreeEndPointer(); if( ub == 0 ){ ub = data_bit8.size(); } Origin* orig = (*subT_it).getOrigin(); subtree_origs.push_back((*orig)); // clear any old data out of the uchar vector data_uchar.clear(); // convert the binary octree to octomap octree readable (conversion from bitset 8 to u int8) for(std::vector<bitset<8> >::iterator data_bit8_it = data_bit8.begin()+lb; data_bit8_it != data_bit8.begin()+lb+(ub-lb); ++data_bit8_it) { data_uchar.push_back(static_cast<u_int8_t> ((*data_bit8_it).to_ulong() )); } std::stringstream datastream_uchar; datastream_uchar.write((const char*) &data_uchar[0] ,data_uchar.size()); // set the correct resolution for the octomap octree octomap::OcTree* octree = new octomap::OcTree(bin_octree->getResolution()); // read the uint 8 data to the octomap octree octree->readBinaryData(datastream_uchar); // generate the name for the subtree std::stringstream subtree_name; subtree_name << output_path << "map_" << subT_it - subtrees.begin() << "_X" << (*subT_it).getOrigin()->x << "Y" << (*subT_it).getOrigin()->y << "Z" << (*subT_it).getOrigin()->z; // if this flag is set the .bt file will be written to disk if(save_bt_file){ std::stringstream binary_tree_name; binary_tree_name << subtree_name << ".bt"; octree->writeBinary(binary_tree_name.str()); } // with this flag one can prevent the creation of a blend file if(!NOBLEND){ _omtb_complete->createMeshData(octree,16,subtree_name.str(),(*subT_it).getOrigin()); } } }
a6d136f2ad1cc871eea698f4bab4ed0c63bde674
3b85b8142ea0ed022d40a135fd174ffcef295a2f
/DlgGame.h
60a7c0ecff66fcffca9a518b9c5395971daa08d7
[ "MIT" ]
permissive
ximenpo/easy-wgloader
56e9f7e4f9674874c6003759af16d86cfe057f8f
48991a2d9d57e7fa08fef0f6d0c8ba3241241d3b
refs/heads/master
2020-05-22T06:36:31.422128
2017-05-18T09:19:39
2017-05-18T09:19:39
61,518,522
2
0
null
null
null
null
UTF-8
C++
false
false
1,907
h
DlgGame.h
#pragma once #include "atlwin.h" #include "easy-wgloader.h" class GameDialog : public CAxDialogImpl<GameDialog, CAxWindow>, public IDispEventImpl<IDC_WEB,GameDialog>, public IDispEventImpl<IDC_WEB_DUMMY,GameDialog> { public: GameDialog(void); ~GameDialog(void); protected: typedef GameDialog thisClass; typedef CAxDialogImpl<GameDialog, CAxWindow> superClass; private: void do_CloseWindow(); private: CAxWindow m_ctrlWeb; IWebBrowser2* m_pWeb; CAxWindow m_ctrlWebDummy; IWebBrowser2* m_pWebDummy; public: enum {IDD = IDD_GAME}; bool PreProcessKeyboardMessage(MSG* msg); public: BEGIN_MSG_MAP(thisClass) MESSAGE_HANDLER(WM_ERASEBKGND, OnEraseBkgnd) MESSAGE_HANDLER(WM_SIZE, OnSize) MESSAGE_HANDLER(WM_CLOSE, OnClose) MESSAGE_HANDLER(WM_INITDIALOG, OnInitDialog) MESSAGE_HANDLER(WM_DESTROY, OnDestroy) COMMAND_ID_HANDLER(IDCANCEL, OnCloseCmd) END_MSG_MAP() private: LRESULT OnCloseCmd(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/); LRESULT OnInitDialog(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled); LRESULT OnDestroy(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/); LRESULT OnEraseBkgnd(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/); LRESULT OnSize(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/); LRESULT OnClose(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/); public: BEGIN_SINK_MAP(GameDialog) SINK_ENTRY(IDC_WEB, 251, NewWindow2Web) SINK_ENTRY(IDC_WEB_DUMMY, 250, BeforeNavigate2WebDummy) END_SINK_MAP() void __stdcall NewWindow2Web(LPDISPATCH* ppDisp, BOOL* Cancel); void __stdcall BeforeNavigate2WebDummy(LPDISPATCH pDisp, VARIANT* URL, VARIANT* Flags, VARIANT* TargetFrameName, VARIANT* PostData, VARIANT* Headers, BOOL* Cancel); };
e179c90da5294bb386b0b8de8f9fab39ab2eca3c
346c17a1b3feba55e3c8a0513ae97a4282399c05
/src/uti_phgrm/NewOri/cNewO_Hom1Im.cpp
e70b4f95f4499b968e9b00f67c1bd7404c240748
[ "LicenseRef-scancode-cecill-b-en" ]
permissive
micmacIGN/micmac
af4ab545c3e1d9c04b4c83ac7e926a3ff7707df6
6e5721ddc65cb9b480e53b5914e2e2391d5ae722
refs/heads/master
2023-09-01T15:06:30.805394
2023-07-25T09:18:43
2023-08-30T11:35:30
74,707,998
603
156
NOASSERTION
2023-06-19T12:53:13
2016-11-24T22:09:54
C++
ISO-8859-1
C++
false
false
35,080
cpp
cNewO_Hom1Im.cpp
/*Header-MicMac-eLiSe-25/06/2007 MicMac : Multi Image Correspondances par Methodes Automatiques de Correlation eLiSe : ELements of an Image Software Environnement www.micmac.ign.fr Copyright : Institut Geographique National Author : Marc Pierrot Deseilligny Contributors : Gregoire Maillet, Didier Boldo. [1] M. Pierrot-Deseilligny, N. Paparoditis. "A multiresolution and optimization-based image matching approach: An application to surface reconstruction from SPOT5-HRS stereo imagery." In IAPRS vol XXXVI-1/W41 in ISPRS Workshop On Topographic Mapping From Space (With Special Emphasis on Small Satellites), Ankara, Turquie, 02-2006. [2] M. Pierrot-Deseilligny, "MicMac, un lociel de mise en correspondance d'images, adapte au contexte geograhique" to appears in Bulletin d'information de l'Institut Geographique National, 2007. Francais : MicMac est un logiciel de mise en correspondance d'image adapte au contexte de recherche en information geographique. Il s'appuie sur la bibliotheque de manipulation d'image eLiSe. Il est distibue sous la licences Cecill-B. Voir en bas de fichier et http://www.cecill.info. English : MicMac is an open source software specialized in image matching for research in geographic information. MicMac is built on the eLiSe image library. MicMac is governed by the "Cecill-B licence". See below and http://www.cecill.info. Header-MicMac-eLiSe-25/06/2007*/ #include "NewOri.h" #define HOM_NbMinPTs 5 class cOrHom_AttrSom; class cOrHom_AttrASym; class cOrHom_AttrArc; class cAppli_Hom1Im; typedef ElSom<cOrHom_AttrSom,cOrHom_AttrArc> tSomGT; typedef ElArc<cOrHom_AttrSom,cOrHom_AttrArc> tArcGT; typedef ElSomIterator<cOrHom_AttrSom,cOrHom_AttrArc> tItSGT; typedef ElArcIterator<cOrHom_AttrSom,cOrHom_AttrArc> tItAGT; typedef ElGraphe<cOrHom_AttrSom,cOrHom_AttrArc> tGrGT; typedef ElSubGraphe<cOrHom_AttrSom,cOrHom_AttrArc> tSubGrGT; double PropPond(std::vector<Pt2df> & aV,double aProp,int * aKMed=0); /************************************************/ /* */ /* cOrHom_AttrSom */ /* */ /************************************************/ class cOneSolSim { public : cOneSolSim(tSomGT * aSom,const ElRotation3D & aRot,int aNbPts,double aDist) : mRot (aRot), mNbPts (aNbPts), mDist (aDist), mSom (aSom) { } ElRotation3D mRot; int mNbPts; double mDist; tSomGT *mSom; }; class cOrHom_AttrSom { public : void OneSensEqHomRig(double aPds,const std::vector<int> & aVInd,const Pt2dr & aP1, const Pt2dr & aP2,const std::vector<cElHomographie> & aVH1To2,const cElHomographie &aH1To2Init,double aEps); cOrHom_AttrSom(int aNum,const std::string & aName,cAppli_Hom1Im &); cOrHom_AttrSom(); const std::string & Name() const {return mName;} cAppli_Hom1Im & Appli() {return *mAppli;} void AddSol(const cOneSolSim & aSol); void ExportGps(); int NbPtsMax() const {return mNbPtsMax;} double DistPMax() const {return mDistPMax;} // Zone Homographie void AddObsLin2Var(int aKV1,double aCoef1,int aKV2,double aCoef2,double aVal,double aPds,bool CoordLoc); void AddObsGround(double aPds,bool CoordLoc); void AddObsFixAffinite(bool CoordLoc); void AddObsFixSimil(bool CoordLoc); void AddEqH12(tArcGT & anArc, double aPds,bool ModeAff,bool CoordLoc); L2SysSurResol & Sys(); Pt2dr SetSol(double * aSolGlob,bool CoordLoc); Pt3dr & GPS() {return mGPS;} const cElHomographie & CurHom() {return mCurHom;} // Homographie courante avec une variation Epsilon du parametre K cElHomographie HomogPerturb(int aKParam,double aEpsil); Pt3dr TestSol(tArcGT & anArc); void SaveSolHom(int aKEtape); private : void AddOnePEq12(bool IsX,const Pt2dr & aP1,cOrHom_AttrSom & aS2,const Pt2dr & aP2,double aPds,bool ModeAff); void AddObsFix(int aKVal,double aVal,double aPds,bool CoordLoc); void Save(const std::string & aNameOri,const ElRotation3D &); std::string mName; cAppli_Hom1Im * mAppli; cNewO_OneIm * mI; Pt3dr mGPS; int mNbPtsMax; double mDistPMax; std::vector<cOneSolSim> mVSol; // Zone de param pour homographie // L'homographie inconnue est t.q. Hom(I,I) = (X,Y) I,J "pixel", X,Y Terrain int mNum; int mN0Hom; int mN1Hom; double mCurParH[8]; cElHomographie mCurHom; }; class cOrHom_AttrArcSym { public : cOrHom_AttrArcSym(const cXml_Ori2Im &); const cXml_Ori2Im & Xml() const {return mXmlO;} cElHomographie Hom(bool Dir); const double & PdsFin() const {return mPdsFin;} // Module pour que Somme = NbSom const double & PdsRes() const {return mPdsRes;} // Module par les residus const double & PdsNb() const {return mPdsNb;} // Poids qui tient compte du nombre const double & ResH() const {return mResH;} void SetStdPds(double aRStd); void SetMulFin(double aRStd); const std::vector<Pt2dr> & VP1() {return mVP1;} const std::vector<Pt2dr> & VP2() {return mVP2;} private : cXml_Ori2Im mXmlO; double mPdsNb; double mPdsRes; double mPdsFin; double mResH; cElHomographie mHom12; std::vector<Pt2dr> mVP1; std::vector<Pt2dr> mVP2; }; class cOrHom_AttrArc { public : cOrHom_AttrArc(cOrHom_AttrArcSym * ,bool Direct); void GetDistribGaus(std::vector<Pt2dr> & aVPts,int aN); bool Direct() const {return mDirect;} cOrHom_AttrArcSym & ASym() {return *mASym;} private : cOrHom_AttrArcSym * mASym; bool mDirect; cElHomographie mHom; }; class cSubGraphe_NO_Hom : public tSubGrGT { public : bool inA(tArcGT & anArc) {return anArc.attr().Direct();} }; class cAppli_Hom1Im : public cCommonMartiniAppli { public : cAppli_Hom1Im(int argc,char ** argv,bool ModePrelim,bool aModeGps); tGrGT & Gr() {return mGr;} bool ModeGps() const {return mModeGps;} cNewO_NameManager * NM() {return mNM;} std::string GpsOut() {return mGpsOut;} L2SysSurResol & Sys(); Pt2dr ToW(const Pt2dr &aPIm) const { return (aPIm-mGpsMin) * mScaleW; } void DrawSeg(const Pt2dr & aP1,const Pt2dr & aP2, int aCoul); void WClear(); void WClik(); private: tSomGT * AddAnIm(int aNum,const std::string & aName); tSomGT * GetAnIm(const std::string & aName,bool SVP); tArcGT * AddArc(tSomGT * aS1,tSomGT * aS2); bool mModePrelim; bool mModeGps; std::string mPat; std::string mNameC; cElemAppliSetFile mEASF; std::map<std::string,tSomGT *> mMapS; std::vector<tSomGT *> mVecS; tSomGT * mSomC; tGrGT mGr; cSubGraphe_NO_Hom mSubAS; // tSubGrGT mSubAS; cNewO_NameManager * mNM; std::string mGpsOut; int mNbInc; L2SysSurResol * mSys; double mResiduStd; Pt2dr mGpsMin; Pt2dr mGpsMax; double mScaleW; Pt2dr mSzW; double mMulRab; // Pour mode visuel uniquement int mNbEtape; bool mModeVert; #if (ELISE_X11) Video_Win * mW; #endif Pt3dr mCdgGPS; double mMulGps; }; /************************************************/ /* */ /* cOrHom_AttrSom */ /* */ /************************************************/ cOrHom_AttrSom::cOrHom_AttrSom(int aNum,const std::string & aName,cAppli_Hom1Im & anAppli) : mName (aName), mAppli (&anAppli), mI (new cNewO_OneIm (*anAppli.NM(),aName)), mNbPtsMax (-1), mNum (aNum), mN0Hom (mNum * 8), mN1Hom (mN0Hom + 8), mCurHom (cElHomographie::Id()) { if (mAppli->ModeGps()) { mGPS = mAppli->GpsVal(mI); } } cElHomographie HomogrFromCoords(double * aParam) { cElComposHomographie aHX(aParam[0],aParam[1],aParam[2]); cElComposHomographie aHY(aParam[3],aParam[4],aParam[5]); cElComposHomographie aHZ(aParam[6],aParam[7],1.0); return cElHomographie(aHX,aHY,aHZ); } cElHomographie cOrHom_AttrSom::HomogPerturb(int aKParam,double aEpsil) { double aParam[8] ; for (int aK=0 ; aK<8 ; aK++) aParam[aK]= mCurParH[aK]; aParam[ aKParam] += aEpsil; return HomogrFromCoords(aParam); } Pt2dr cOrHom_AttrSom::SetSol(double * aSolGlob,bool CoordLoc) { for (int aN= mN0Hom ; aN<mN1Hom ; aN++) { if (CoordLoc) { // std::cout << "CccCc: " << mCurParH[aN-mN0Hom] << " "<< aSolGlob[aN] << "\n"; // mCurParH[aN-mN0Hom] += aSolGlob[aN] * 0.1; mCurParH[aN-mN0Hom] += aSolGlob[aN] ; } else mCurParH[aN-mN0Hom] = aSolGlob[aN]; } /* cElComposHomographie aHX(mCurParH[0],mCurParH[1],mCurParH[2]); cElComposHomographie aHY(mCurParH[3],mCurParH[4],mCurParH[5]); cElComposHomographie aHZ(mCurParH[6],mCurParH[7],1.0); mCurHom = cElHomographie(aHX,aHY,aHZ); */ mCurHom = HomogrFromCoords(mCurParH); Pt2dr aG2(mGPS.x,mGPS.y); Pt2dr aRes = aG2-mCurHom(Pt2dr(0,0)); return aRes; } cOrHom_AttrSom::cOrHom_AttrSom() : mAppli (0), mCurHom (cElHomographie::Id()) { } void cOrHom_AttrSom::AddSol(const cOneSolSim & aSol) { if (aSol.mNbPts > mNbPtsMax) { mNbPtsMax = aSol.mNbPts; mDistPMax = aSol.mDist; } mVSol.push_back(aSol); } void cOrHom_AttrSom::ExportGps() { double aScoreMax= -1; cOneSolSim * aBestSol0 =nullptr; for (auto & aSol : mVSol) { double aScore = aSol.mNbPts ;// * aSol.mDist; if (aScore> aScoreMax) { aScoreMax = aScore; aBestSol0 = & aSol; } } ELISE_ASSERT(aBestSol0!=nullptr,"cOrHom_AttrSom::ExportGps"); std::cout << "Sol for : " << mName << " => " << aBestSol0->mSom->attr().Name() << "\n"; Save(mAppli->GpsOut(),aBestSol0->mRot); } void cOrHom_AttrSom::Save(const std::string & aPrefixOri,const ElRotation3D & aRot) { CamStenope * aCal = mAppli->NM()->CalibrationCamera(mName); std::string aNameCal = mAppli->NM()->ICNM()->StdNameCalib(aPrefixOri,mName); if (! ELISE_fp::exist_file(aNameCal)) { ELISE_fp::MkDirSvp(DirOfFile(aNameCal)); cCalibrationInternConique aCIC = aCal->ExportCalibInterne2XmlStruct(aCal->Sz()); MakeFileXML(aCIC,aNameCal); } aCal->SetOrientation(aRot.inv()); cOrientationConique anOC = aCal->StdExportCalibGlob(); anOC.Interne().SetNoInit(); anOC.FileInterne().SetVal(aNameCal); std::string aNameOri = mAppli->NM()->ICNM()->NameOriStenope(aPrefixOri,mName); MakeFileXML(anOC,aNameOri); /* anOC.Interne().SetNoInit(); */ // std::cout << aCal << " " << aCal->Focale() << aNameOri << "\n"; } void cOrHom_AttrSom::SaveSolHom(int aKEtape) { CamStenope * aCal = mAppli->NM()->CalibrationCamera(mName); Pt2dr aSz = Pt2dr(aCal->Sz()); double aStep = 0.3; std::vector<double> aPAF; CamStenopeIdeale aCamI(true,1.0,Pt2dr(0,0),aPAF); std::list<Pt2dr> aLIm; std::list<Pt3dr> aLTer; for (double aPx=0.1 ; aPx<= 0.901 ; aPx += aStep) { for (double aPy=0.1 ; aPy<= 0.901 ; aPy += aStep) { Pt2dr aPIm = aSz.mcbyc(Pt2dr(aPx,aPy)); Pt2dr aPDir = aCal->F2toPtDirRayonL3(aPIm); aLIm.push_back(aPDir); Pt2dr aPTer = mCurHom(aPDir); aLTer.push_back(Pt3dr(aPTer.x,aPTer.y,0.0)); } } double aEcart; ElRotation3D aR= aCamI.CombinatoireOFPA(true,1000,aLTer,aLIm,&aEcart); CamStenopeIdeale aCamII(true,1.0,Pt2dr(0,0),aPAF); aCamI.SetOrientation(aR); aCamII.SetOrientation(aR.inv()); { Box2dr aBox(Pt2dr(0,0),aSz); Pt2dr aCorn[4]; aBox.Corners(aCorn); for (int aK=0 ; aK< 4 ; aK++) { Pt2dr aPDir = aCal->F2toPtDirRayonL3(aCorn[aK]); Pt2dr aP2Ter = mCurHom(aPDir); aCorn[aK] = aP2Ter; } for (int aK=0 ; aK< 4 ; aK++) { int aCoul = (aEcart<100) ? P8COL::blue : P8COL::red; mAppli->DrawSeg(aCorn[aK],aCorn[(aK+1)%4], aCoul); } } { double aD = 0; double aDI = 0; int aNb = 0; for (double aPx=0.1 ; aPx<= 0.901 ; aPx += aStep) { for (double aPy=0.1 ; aPy<= 0.901 ; aPy += aStep) { Pt2dr aPIm = aSz.mcbyc(Pt2dr(aPx,aPy)); Pt2dr aPDir = aCal->F2toPtDirRayonL3(aPIm); Pt2dr aP2Ter = mCurHom(aPDir); Pt3dr aPTer(aP2Ter.x,aP2Ter.y,0); aD += euclid(aPDir-aCamI.R3toF2(aPTer)); aDI += euclid(aPDir-aCamII.R3toF2(aPTer)); aNb++; } } } } L2SysSurResol & cOrHom_AttrSom::Sys() { return mAppli->Sys(); } /* Homographie a0 I + a1 J + a2 a3 I + a4 J + a5 X = ---------------- Y = ---------------- a6 I + a7 J +1 a6 I + a7 J +1 */ void cOrHom_AttrSom::AddObsFix(int aKVal,double aVal,double aPds,bool CoordLoc) { std::vector<int> aVInd; aVInd.push_back(mN0Hom+aKVal); double aCoeff = 1.0; if (CoordLoc) aVal -= mCurParH[aKVal]; Sys().GSSR_AddNewEquation_Indexe(0,0,0,aVInd,aPds,&aCoeff,aVal,NullPCVU); } void cOrHom_AttrSom::AddObsLin2Var(int aKV1,double aCoef1,int aKV2,double aCoef2,double aVal,double aPds,bool CoordLoc) { std::vector<int> aVInd; std::vector<double> aVCoeff; aVInd.push_back(mN0Hom+aKV1); aVCoeff.push_back(aCoef1); aVCoeff.push_back(aCoef2); aVInd.push_back(mN0Hom+aKV2); if (CoordLoc) { aVal -= mCurParH[aKV1] *aCoef1 + mCurParH[aKV2] *aCoef2 ; } Sys().GSSR_AddNewEquation_Indexe(0,0,0,aVInd,aPds,&(aVCoeff[0]),aVal,NullPCVU); } void cOrHom_AttrSom::AddObsGround(double aPds,bool CoordLoc) { /* On fait l'appoximition que le faisceau partant de (0,0) est vertical mGPS.x = a2/1 mGPS.y = a5/1 */ AddObsFix(2,mGPS.x,aPds,CoordLoc); AddObsFix(5,mGPS.y,aPds,CoordLoc); } void cOrHom_AttrSom::AddObsFixAffinite(bool CoordLoc) { AddObsFix(6,0,1.0,CoordLoc); AddObsFix(7,0,1.0,CoordLoc); } void cOrHom_AttrSom::AddObsFixSimil(bool CoordLoc) { // X = a0 I + a1 J + a2 Y= a3 I + a4 J + a5 // ==> a0-a4=0 a1+ a3 = 0 AddObsLin2Var(0,1.0,4,-1.0,0.0,1e4,CoordLoc); AddObsLin2Var(1,1.0,3,+1.0,0.0,1e4,CoordLoc); } Pt3dr cOrHom_AttrSom::TestSol(tArcGT & anArc) { cOrHom_AttrSom & aS2 = anArc.s2().attr(); cOrHom_AttrArcSym & aA12 = anArc.attr().ASym(); const std::vector<Pt2dr> & aVP1 = aA12.VP1(); const std::vector<Pt2dr> & aVP2 = aA12.VP2(); int aNbPts = aVP1.size(); cElHomographie aH1 = CurHom(); cElHomographie aH1I = aH1.Inverse(); // const cElHomographie & aH2 = aS2.CurHom().Inverse(); cElHomographie aH2 = aS2.CurHom(); cElHomographie aH2I = aH2.Inverse(); cElHomographie aH1To2 = aH2I * aH1; cElHomographie aH2To1 = aH1I * aH2; double aS=0; double aSI1=0; double aSI2=0; for (int aKp=0 ; aKp<aNbPts ; aKp++) { aS += euclid(aH1(aVP1[aKp]) - aH2(aVP2[aKp])); aSI1 += euclid(aH1To2(aVP1[aKp]) - aVP2[aKp]); aSI2 += euclid(aH2To1(aVP2[aKp]) - aVP1[aKp]); } return Pt3dr(aS,aSI1,aSI2) / aNbPts; } // PB void cOrHom_AttrSom::AddEqH12(tArcGT & anArc, double aPdsGlob,bool ModeAff,bool CoordLoc) { cOrHom_AttrSom & aS1 = *this; cOrHom_AttrSom & aS2 = anArc.s2().attr(); cOrHom_AttrArcSym & aA12 = anArc.attr().ASym(); const std::vector<Pt2dr> & aVP1 = aA12.VP1(); const std::vector<Pt2dr> & aVP2 = aA12.VP2(); int aNbPts = aVP1.size(); double aPds = (aPdsGlob * aA12.PdsFin()) / aNbPts; if (ModeAff) { ELISE_ASSERT(!CoordLoc,"Coord loc in affine mod"); for (int aKp=0 ; aKp<aNbPts ; aKp++) { for (int aKx=0 ; aKx<2 ; aKx++) AddOnePEq12((aKx==0),aVP1[aKp],aS2,aVP2[aKp],aPds,ModeAff); } return; } // Si ce n'est pas un mode lineaire, on aborde une linearisation par // differences finies ELISE_ASSERT(CoordLoc,"No Coord loc in homogr mod"); double aEpsil = 1e-4; cElHomographie aH1To2Init = aS2.CurHom().Inverse() * aS1.CurHom(); cElHomographie aH2To1Init = aS1.CurHom().Inverse() * aS2.CurHom(); std::vector<int> aVInd; std::vector<cElHomographie> aVH1To2; // H1 to 2 en fonction des 16 perturbation possibles de parametre std::vector<cElHomographie> aVH2To1; // 16 parametres : 8 pour chaque homographie for (int aKPTot=0 ; aKPTot<16 ; aKPTot++) { // H1_0 H1_1 ... H1_7 H2_0 H2_1 ... H2_7 int aKPLoc = aKPTot % 8; cElHomographie aH1 = aS1.CurHom(); cElHomographie aH2 = aS2.CurHom(); if (aKPTot<8) { aH1 = aS1.HomogPerturb(aKPLoc,aEpsil); aVInd.push_back(aS1.mN0Hom+aKPLoc); } else { aH2 = aS2.HomogPerturb(aKPLoc,aEpsil); aVInd.push_back(aS2.mN0Hom+aKPLoc); } aVH1To2.push_back(aH2.Inverse() * aH1); aVH2To1.push_back(aH1.Inverse() * aH2); } for (int aKPts=0 ; aKPts<aNbPts ; aKPts++) { Pt2dr aP1 = aVP1[aKPts]; Pt2dr aP2 = aVP2[aKPts]; OneSensEqHomRig(aPds,aVInd,aP1,aP2,aVH1To2,aH1To2Init,aEpsil); OneSensEqHomRig(aPds,aVInd,aP2,aP1,aVH2To1,aH2To1Init,aEpsil); } } void cOrHom_AttrSom::OneSensEqHomRig(double aPds,const std::vector<int> & aVInd,const Pt2dr & aP1, const Pt2dr & aP2,const std::vector<cElHomographie> & aVH1To2,const cElHomographie &aH1To2Init,double aEps) { // aH1To2Init[aP1] = aP2; double aCoeff_X[16]; double aCoeff_Y[16]; Pt2dr aPTh2 = aH1To2Init(aP1); Pt2dr aVal = aP2 - aPTh2 ; for (int aK=0 ; aK< 16 ; aK++) { Pt2dr aDif2 = (aVH1To2[aK](aP1) -aPTh2) / aEps; aCoeff_X[aK] = aDif2.x; aCoeff_Y[aK] = aDif2.y; } Sys().GSSR_AddNewEquation_Indexe(0,0,0,aVInd,aPds,aCoeff_X,aVal.x,NullPCVU); Sys().GSSR_AddNewEquation_Indexe(0,0,0,aVInd,aPds,aCoeff_Y,aVal.y,NullPCVU); } void cOrHom_AttrSom::AddOnePEq12(bool IsX,const Pt2dr & aP1,cOrHom_AttrSom & aS2,const Pt2dr & aP2,double aPds,bool ModeAff) { // a0 I + a1 J + a2 a3 I + a4 J + a5 int Ind1 = mN0Hom + (IsX ? 0 : 3); int Ind2 = aS2.mN0Hom + (IsX ? 0 : 3); if (!ModeAff) { ELISE_ASSERT(false,"cOrHom_AttrSom::AddOnePEq12"); } double aCoeff[6]; std::vector<int> aVInd; double aVal=0; aCoeff[0] = aP1.x; aVInd.push_back(Ind1+0); aCoeff[1] = aP1.y; aVInd.push_back(Ind1+1); aCoeff[2] = 1.0; aVInd.push_back(Ind1+2); aCoeff[3] = -aP2.x; aVInd.push_back(Ind2+0); aCoeff[4] = -aP2.y; aVInd.push_back(Ind2+1); aCoeff[5] = - 1.0; aVInd.push_back(Ind2+2); Sys().GSSR_AddNewEquation_Indexe(0,0,0,aVInd,aPds,aCoeff,aVal,NullPCVU); } /************************************************/ /* */ /* cOrHom_AttrArc */ /* */ /************************************************/ void cOrHom_AttrArcSym::SetStdPds(double aRStd) { mPdsRes = mPdsNb / (1 + ElSquare(mResH/aRStd)); } void cOrHom_AttrArcSym::SetMulFin(double aMul) { mPdsFin = mPdsRes * aMul; } cOrHom_AttrArcSym::cOrHom_AttrArcSym(const cXml_Ori2Im & aXml) : mXmlO (aXml), mHom12 (mXmlO.Geom().Val().HomWithR().Hom()) { int aNbP = mXmlO.NbPts(); double aRedund = ElMax(0.0,(aNbP-5) / double(aNbP)); mPdsNb = aNbP * pow(aRedund,3.0); // Total arbitraire l'exposant mResH = aXml.Geom().Val().HomWithR().ResiduHom(); cGenGaus2D aGC(aXml.Geom().Val().Elips2().Val()); aGC.GetDistribGaus(mVP1,2,2); for (const auto & aP1 : mVP1) mVP2.push_back(mHom12(aP1)); } cElHomographie cOrHom_AttrArcSym::Hom(bool aDir) { cElHomographie aRes = mHom12; if (! aDir) aRes = aRes.Inverse(); return aRes; } // cGenGaus2D(const cXml_Elips2D & anEl ); // ================================= cOrHom_AttrArc::cOrHom_AttrArc(cOrHom_AttrArcSym * anAsym ,bool Direct) : mASym(anAsym), mDirect (Direct), mHom (anAsym->Hom(Direct)) { } void cOrHom_AttrArc::GetDistribGaus(std::vector<Pt2dr> & aVPts,int aN) { } /* */ /************************************************/ /* */ /* cAppli_Hom1Im */ /* */ /************************************************/ L2SysSurResol & cAppli_Hom1Im::Sys() { ELISE_ASSERT(mSys!=0,"No Sys in cAppli_Hom1Im"); return *mSys; } void cAppli_Hom1Im::DrawSeg(const Pt2dr & aP1,const Pt2dr & aP2, int aCoul) { #if (ELISE_X11) if (!mW) return; mW->draw_seg(ToW(aP1),ToW(aP2),mW->pdisc()(aCoul)); #endif } void cAppli_Hom1Im::WClear() { #if (ELISE_X11) if (!mW) return; mW->clear(); #endif } void cAppli_Hom1Im::WClik() { #if (ELISE_X11) if (!mW) return; mW->clik_in(); #endif } tArcGT * cAppli_Hom1Im::AddArc(tSomGT * aS1,tSomGT * aS2) { ELISE_ASSERT(aS1->attr().Name()<aS2->attr().Name(),"Order assertion in cAppli_Hom1Im::AddArc"); /* if (mShow) std::cout << " ARC " << aS1->attr().Name() << " " << aS2->attr().Name() << "\n"; */ cXml_Ori2Im aXml = mNM->GetOri2Im(aS1->attr().Name(),aS2->attr().Name()); int aNbMin = HOM_NbMinPTs; if ((!aXml.Geom().IsInit()) || (aXml.NbPts() < aNbMin)) return nullptr; const cXml_O2IComputed & aG = aXml.Geom().Val(); if ((!aG.Elips2().IsInit())) return nullptr; /* const cXml_O2IComputed & aXG = aXml.Geom().Val(); if (mModeGps) { if (! aXG.OriCpleGps().IsInit()) return; const cXml_OriCple & aCpl = aXG.OriCpleGps().Val(); int aNbPts = aXml.NbPts(); double aDist = euclid(aCpl.Ori1().Centre()-aCpl.Ori2().Centre()); aS1->attr().AddSol(cOneSolSim(aS2,Xml2El(aCpl.Ori1()),aNbPts,aDist)); aS2->attr().AddSol(cOneSolSim(aS1,Xml2El(aCpl.Ori2()),aNbPts,aDist)); } */ cOrHom_AttrArcSym * anAttr = new cOrHom_AttrArcSym(aXml); tArcGT & aRes = aS1->attr().Appli().Gr().add_arc(*aS1,*aS2,cOrHom_AttrArc(anAttr,true),cOrHom_AttrArc(anAttr,false)); // add_arc return & aRes; } tSomGT * cAppli_Hom1Im::AddAnIm(int aNum,const std::string & aName) { if (mMapS[aName] == 0) { if (aNum<0) { if (aNum==-1) { std::cout << "For name=" << aName << "\n"; ELISE_ASSERT(false,"cAppli_Hom1Im::AddAnIm cannot get Image"); } return 0; } mMapS[aName] = &(mGr.new_som(cOrHom_AttrSom(aNum,aName,*this))); mVecS.push_back(mMapS[aName]); /* if (mShow) std::cout <<" Add " << aName << "\n"; */ } return mMapS[aName]; } tSomGT * cAppli_Hom1Im::GetAnIm(const std::string & aName,bool SVP) {return AddAnIm(SVP? -2 : -1,aName);} cAppli_Hom1Im::cAppli_Hom1Im(int argc,char ** argv,bool aModePrelim,bool aModeGps) : mModePrelim (aModePrelim), mModeGps (aModeGps), mSomC (0), mNM (0), mNbInc (0), mSys (nullptr), mMulRab (0.2), mNbEtape (50), mCdgGPS (0,0,0) { #if (ELISE_X11) mW = 0; #endif ElInitArgMain ( argc,argv, LArgMain() << EAMC(mPat,"Central image"), LArgMain() << ArgCMA() << EAM(mMulRab,"MulRab",true," Rab multiplier in visusal mode, def= 0.2") << EAM(mNbEtape,"NbIter",true," Number of steps") << EAM(mModeVert,"Vert",true,"Compute vertical orientation") ); if (!EAMIsInit(&mNbEtape) && (mModeVert)) { mNbEtape = 1; } if (aModeGps) { ELISE_ASSERT(EAMIsInit(&mOriGPS),"No GPS ORI in GPS mode"); } mGpsOut = "Out-"+mOriGPS; mEASF.Init(mPat); mNM = cCommonMartiniAppli::NM(mEASF.mDir); const cInterfChantierNameManipulateur::tSet * aVN = mEASF.SetIm(); for(int aK=0 ; aK<int(aVN->size()) ; aK++) { AddAnIm(mVecS.size(),(*aVN)[aK]); } // Cas preliminaire, on rajoute tous les sommets connexe if (mModePrelim) { ELISE_ASSERT(aVN->size()==1,"Expect just one image in preliminary mode"); mNameC = (*aVN)[0]; mSomC = GetAnIm(mNameC,false); std::list<std::string> aLC = mNM->Liste2SensImOrientedWith(mNameC); for (std::list<std::string>::const_iterator itL=aLC.begin() ; itL!=aLC.end() ; itL++) { AddAnIm(mVecS.size(),*itL); } } // Ajout des arcs int aNbATest=0 ; std::vector<Pt2df> aVP; for (int aKS=0 ; aKS<int(mVecS.size()) ; aKS++) { tSomGT * aS1 = mVecS[aKS]; std::list<std::string> aLC = mNM->ListeImOrientedWith(aS1->attr().Name()); for (std::list<std::string>::const_iterator itL=aLC.begin() ; itL!=aLC.end() ; itL++) { std::cout << "Aaaa " << *itL << "\n"; tSomGT * aS2 = GetAnIm(*itL,true); std::cout << "BBbbb\n"; if (aS2) { tArcGT * anA = AddArc(aS1,aS2); if (anA) { const cOrHom_AttrArcSym & anAS = anA->attr().ASym(); aVP.push_back(Pt2df(anAS.ResH(),anAS.PdsNb())); aNbATest++; } } } } mResiduStd = PropPond(aVP,0.66); double aSomPdsRes = 0.0; for (int aKS=0 ; aKS<int(mVecS.size()) ; aKS++) { tSomGT * aS1 = mVecS[aKS]; for (tItAGT ait=aS1->begin(mSubAS); ait.go_on() ; ait++) { cOrHom_AttrArcSym & aAS = (*ait).attr().ASym(); aAS.SetStdPds(mResiduStd); aSomPdsRes += aAS.PdsRes(); aNbATest--; } } double aMul = (mVecS.size()) / aSomPdsRes; aSomPdsRes = 0; // For check for (int aKS=0 ; aKS<int(mVecS.size()) ; aKS++) { tSomGT * aS1 = mVecS[aKS]; for (tItAGT ait=aS1->begin(mSubAS); ait.go_on() ; ait++) { cOrHom_AttrArcSym & aAS = (*ait).attr().ASym(); aAS.SetMulFin(aMul); aSomPdsRes += aAS.PdsFin(); } } if (mModeGps) { mNbInc = mVecS.size() * 8; mSys = new L2SysSurResol(mNbInc); Pt3dr aSomGPS(0,0,0); for (int aKS=0 ; aKS<int(mVecS.size()) ; aKS++) { aSomGPS = aSomGPS + mVecS[aKS]->attr().GPS(); } mCdgGPS = aSomGPS / mVecS.size(); aSomGPS = Pt3dr(0,0,0); double aSomD2 = 0.0; for (int aKS=0 ; aKS<int(mVecS.size()) ; aKS++) { Pt3dr & aGPSK = mVecS[aKS]->attr().GPS(); aGPSK = aGPSK - mCdgGPS; aSomD2 += euclid(aGPSK); aSomGPS = aSomGPS + aGPSK; } double aMoyD = (aSomD2/mVecS.size()) ; mMulGps = (1/aMoyD) * sqrt(mVecS.size()); aSomD2 = 0.0; mGpsMin = Pt2dr( 1e5, 1e5); mGpsMax = Pt2dr(-1e5,-1e5); for (int aKS=0 ; aKS<int(mVecS.size()) ; aKS++) { Pt3dr & aGPSK = mVecS[aKS]->attr().GPS(); aGPSK = aGPSK * mMulGps; aSomD2 += euclid(aGPSK); mGpsMin = Inf(mGpsMin,Pt2dr(aGPSK.x,aGPSK.y)); mGpsMax = Sup(mGpsMax,Pt2dr(aGPSK.x,aGPSK.y)); } double aRab = dist4(mGpsMax-mGpsMin) * mMulRab; Pt2dr aPRab(aRab,aRab); mGpsMin = mGpsMin - aPRab; mGpsMax = mGpsMax + aPRab; std::cout << "GGg " << aSomGPS<< " D2 " << aSomD2 / mVecS.size() << mGpsMin << mGpsMax << "\n"; #if (ELISE_X11) if (1) { Pt2dr aDG = mGpsMax-mGpsMin; Pt2dr aSzWMax(1000,800); mScaleW = ElMin(aSzWMax.x/aDG.x,aSzWMax.y/aDG.y); mW = Video_Win::PtrWStd(round_ni(aDG*mScaleW)); } #endif // Calcul d'une solution initiale Affine for (int aKEtape=0 ; aKEtape<mNbEtape ; aKEtape++) { double aPdsGround = 1e-2; if (aKEtape>=3) aPdsGround = aPdsGround * pow(1e-1,(aKEtape-3)/3.0); double aPdsAffin = 1.0; bool ModeAffine = (aKEtape==0) || mModeVert; bool CoordLoc = (aKEtape!=0); mSys->SetPhaseEquation(nullptr); // Poids sur les gps et contrainte affine for (int aKS=0 ; aKS<int(mVecS.size()) ; aKS++) { tSomGT & aSom = *(mVecS[aKS]); aSom.attr().AddObsGround(aPdsGround,CoordLoc); if (ModeAffine) { ELISE_ASSERT(!CoordLoc,"No affine cst in loc coord"); aSom.attr().AddObsFixAffinite(CoordLoc); } if (mModeVert) { aSom.attr().AddObsFixSimil(CoordLoc); } } for (int aKS=0 ; aKS<int(mVecS.size()) ; aKS++) { if (aKS%10==0) std::cout << "Fill Eq " << (aKS *100.0) / mVecS.size() << " % \n"; tSomGT * aS1 = mVecS[aKS]; for (tItAGT ait=aS1->begin(mSubAS); ait.go_on() ; ait++) { aS1->attr().AddEqH12(*ait,aPdsAffin,ModeAffine,CoordLoc); } } std::cout << "sssSolving \n"; bool aOk; Im1D_REAL8 aSol = mSys->GSSR_Solve(&aOk); ELISE_ASSERT(aOk,"GSSR_Solve"); Pt2dr aResT(0,0); double aDResT=0; for (int aKS=0 ; aKS<int(mVecS.size()) ; aKS++) { tSomGT & aSom = *(mVecS[aKS]); Pt2dr aRes =aSom.attr().SetSol(aSol.data(),CoordLoc); aResT = aResT + aRes; aDResT += euclid(aRes); } std::cout << " PdsG= " << aPdsGround << "\n"; std::cout << " Dist " << aDResT /mVecS.size() << " Bias " << aResT / double(mVecS.size()) << "\n"; Pt3dr aSomD(0,0,0); double aSomP=0; for (int aKS=0 ; aKS<int(mVecS.size()) ; aKS++) { tSomGT * aS1 = mVecS[aKS]; for (tItAGT ait=aS1->begin(mSubAS); ait.go_on() ; ait++) { Pt3dr aD = aS1->attr().TestSol(*ait); double aP = (*ait).attr().ASym().PdsFin(); aSomD = aSomD + aD * aP; aSomP += aP; } } std::cout << "MoyD " << aSomD / aSomP << "\n"; mSys->GSSR_Reset(true); if (aKEtape>0) WClik(); WClear(); if (aKEtape > -1) { for (int aKS=0 ; aKS<int(mVecS.size()) ; aKS++) { tSomGT * aS1 = mVecS[aKS]; aS1->attr().SaveSolHom(aKEtape); } } // getchar(); } /* // std::vector<int> aVNbMax; std::vector<double> aVDistMax; for (int aKS=0 ; aKS<int(mVecS.size()) ; aKS++) { tSomGT * aS1 = mVecS[aKS]; int aNbMax = aS1->attr().NbPtsMax(); if (aNbMax<0) { ELISE_ASSERT(aNbMax>=0,"No sol by gps"); } aVNbMax.push_back(aS1->attr().NbPtsMax()); aVDistMax.push_back(aS1->attr().DistPMax()); } for (int aKS=0 ; aKS<int(mVecS.size()) ; aKS++) { tSomGT * aS1 = mVecS[aKS]; aS1->attr().ExportGps(); } */ } } int TestNewOriHom1Im_main(int argc,char ** argv) { cAppli_Hom1Im anAppli(argc,argv,true,false); return EXIT_SUCCESS; } int TestNewOriGpsSim_main(int argc,char ** argv) { cAppli_Hom1Im anAppli(argc,argv,false,true); return EXIT_SUCCESS; } /*Footer-MicMac-eLiSe-25/06/2007 Ce logiciel est un programme informatique servant a la mise en correspondances d'images pour la reconstruction du relief. Ce logiciel est regi par la licence CeCILL-B soumise au droit français et respectant les principes de diffusion des logiciels libres. Vous pouvez utiliser, modifier et/ou redistribuer ce programme sous les conditions de la licence CeCILL-B telle que diffusee par le CEA, le CNRS et l'INRIA sur le site "http://www.cecill.info". En contrepartie de l'accessibilite au code source et des droits de copie, de modification et de redistribution accordes par cette licence, il n'est offert aux utilisateurs qu'une garantie limitee. Pour les mêmes raisons, seule une responsabilite restreinte pese sur l'auteur du programme, le titulaire des droits patrimoniaux et les concedants successifs. A cet egard l'attention de l'utilisateur est attiree sur les risques associes au chargement, l'utilisation, la modification et/ou au developpement et la reproduction du logiciel par l'utilisateur etant donne sa specificite de logiciel libre, qui peut le rendre complexe manipuler et qui le reserve donc des developpeurs et des professionnels avertis possedant des connaissances informatiques approfondies. Les utilisateurs sont donc invites a charger et tester l'adequation du logiciel a leurs besoins dans des conditions permettant d'assurer la securite de leurs systemes et ou de leurs donnees et, plus generalement, a l'utiliser et l'exploiter dans les mêmes conditions de securite. Le fait que vous puissiez acceder a cet en-tête signifie que vous avez pris connaissance de la licence CeCILL-B, et que vous en avez accepte les termes. Footer-MicMac-eLiSe-25/06/2007*/
122c6477059ff6597b3e28be9a67b00a3c2f34e0
4540b627dfeda33422e49e89b44ce9589f7c3e0a
/generators/FlameEffect.cpp
2793e4d3d0cede765a2347fbe80f333be6086ad2
[]
no_license
romanchom/libLunaEsp32
f88bba2f6c8b8c0f9cc06e51f6f4f1e655489aca
42c4922e5676407af7ba0dc77b50f2c278d02183
refs/heads/master
2022-02-24T09:36:10.711744
2022-01-30T12:42:01
2022-01-30T12:42:01
153,509,549
0
0
null
null
null
null
UTF-8
C++
false
false
651
cpp
FlameEffect.cpp
#include "FlameEffect.hpp" namespace luna { FlameEffect::FlameEffect() : mTemperatureLow(1500.0f), mTemperatureHigh(3000.0f), mFrequency(1.0f) {} std::unique_ptr<Generator> FlameEffect::generator(Time const & t) { return std::make_unique<FlameGenerator>(t.total, mTemperatureLow, mTemperatureHigh, mFrequency); }; std::vector<std::tuple<std::string, AbstractProperty *>> FlameEffect::properties() { return { {"tempLow", &mTemperatureLow}, {"tempHigh", &mTemperatureHigh}, {"frequency", &mFrequency} }; } }
c64d6f9bee0ef1c2aa6726beaa4cd36aff3f20d6
3d46c17d32854e48f7eda1a84bb575c421b0e63a
/src/raytracer/octree/node.cpp
2e380d3de3292311d831ff69e51f838b3555c3bc
[]
no_license
andreasots/raytracer
021216179da7b3ee3205c43bef106b31ea2ba3c6
33bfb06f1027c98ee54b9b903a12e61009c91136
refs/heads/master
2016-09-05T14:55:38.045820
2012-08-01T11:59:08
2012-08-01T11:59:08
1,744,616
0
0
null
null
null
null
UTF-8
C++
false
false
3,766
cpp
node.cpp
#include "raytracer/octree/node.h" #include "raytracer/allocator.h" #include <SIMD/AABox.h> #include <iostream> namespace Raytracer { namespace Octree { Node::Node() { for(int i = 0; i < 8; i++) subnodes[i] = NULL; } Node::~Node() { for(int i = 0; i < 8; i++) deallocate<Node, 16>(subnodes[i], 1); } bool Node::add(const SIMD::AABox &bounds, const std::tuple<SIMD::AABox, std::size_t> &o) { if(!bounds.encloses(std::get<0>(o))) return false; bool ret = false; SIMD::Vec avg = 0.5*(SIMD::Vec(bounds.min().data())+SIMD::Vec(bounds.max().data())); SIMD::AABox bbox; for(int i = 0; !ret && i < 8; i++) { if(!subnodes[i]) subnodes[i] = new (allocate<Node, 16>(1)) Node; bbox.setMin(SIMD::Point((i & 1 ? bounds.min()[0] : avg[0]), (i & 2 ? bounds.min()[1] : avg[1]), (i & 4 ? bounds.min()[2] : avg[2]))); bbox.setMax(SIMD::Point((i & 1 ? avg[0] : bounds.max()[0]), (i & 2 ? avg[1] : bounds.max()[1]), (i & 4 ? avg[2] : bounds.max()[2]))); ret = subnodes[i]->add(bbox, o); } if(!ret) m_objects.push_back(std::get<1>(o)); return true; } RT_FLOAT Node::intersect(const SIMD::Ray &r, const SIMD::AABox &dist, std::size_t &id, RT_FLOAT &u, RT_FLOAT &v, RT_FLOAT max, const std::vector<Raytracer::Object*> &objects, unsigned long long &intersections, unsigned long long &hits) { SIMD::AABox bbox; SIMD::Vec avg = 0.5*(SIMD::Vec(dist.min().data())+SIMD::Vec(dist.min().data())); bbox.setMin(SIMD::Point(_mm_min_ps(dist.min().data(), dist.max().data()))); bbox.setMax(SIMD::Point(_mm_max_ps(dist.min().data(), dist.max().data()))); RT_FLOAT tIn = std::max(bbox.min()[0], std::max(bbox.min()[1], bbox.min()[2])); RT_FLOAT tOut = std::min(bbox.max()[0], std::min(bbox.max()[1], bbox.max()[2])); // if(tIn > max || tOut < 0 || tIn > tOut) // return max; RT_FLOAT ret = max; for(auto i = m_objects.begin(); i != m_objects.end(); i++) { RT_FLOAT U, V; RT_FLOAT T = objects[*i]->intersect(r, U, V); if(T < ret) { ret = T; id = *i; u = U; v = V; hits++; } intersections++; } for(int i = 0; i < 8; i++) { if(!subnodes[i]) continue; bbox.setMin(SIMD::Point((i & 1 ? dist.min()[0] : avg[0]), (i & 2 ? dist.min()[1] : avg[1]), (i & 4 ? dist.min()[2] : avg[2]))); bbox.setMax(SIMD::Point((i & 1 ? avg[0] : dist.max()[0]), (i & 2 ? avg[1] : dist.max()[1]), (i & 4 ? avg[2] : dist.max()[2]))); std::size_t ID; RT_FLOAT U, V, T = subnodes[i]->intersect(r, bbox, ID, U, V, ret, objects, intersections, hits); if(T < ret) { ret = T; id = ID; u = U; v = V; } } return ret; } void Node::optimize() { for(int i = 0; i < 8; i++) { if(!subnodes[i]) continue; if(!subnodes[i]->m_objects.size()) { int j; for(j = 0; j < 8; j++) if(subnodes[i]->subnodes[j]) break; if(j == 8) { deallocate<Node, 16>(subnodes[i], 1); subnodes[i] = NULL; continue; } } subnodes[i]->optimize(); } } } // namespace Octree } // namespace Raytracer
76ed4af2e4f2c338ea6145f35cd18bb554920564
928d35c68db207748e5c05aa65e3cb1a90100aeb
/Leetcode/matrixBitMan/gfgAndPratice/matrixOperations.cpp
f589daee54b6a1b7df29bbba4b0f71a53c68d3d1
[]
no_license
satvik-tha-god/Algorithms
580768970ef5c9dbebfaa82f4e2286843c349aba
9d7386dec1c05aeab95e992068faf0ddfc522fb1
refs/heads/master
2023-08-07T19:08:35.957414
2021-09-16T19:22:08
2021-09-16T19:22:08
373,586,892
0
0
null
null
null
null
UTF-8
C++
false
false
1,335
cpp
matrixOperations.cpp
int main()//addition { int n = 2, m = 2; int a[n][m] = { { 2, 5 }, { 1, 7 } }; int b[n][m] = { { 3, 7 }, { 2, 9 } }; int c[n][m]; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) { c[i][j] = a[i][j] + b[i][j]; } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) cout << c[i][j] << " "; cout << endl; } } int main()//substraction { int n = 2, m = 2; int a[n][m] = { { 2, 5 }, { 1, 7 } }; int b[n][m] = { { 3, 7 }, { 2, 9 } }; int c[n][m]; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) { c[i][j] = a[i][j] - b[i][j]; } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) cout << c[i][j] << " "; cout << endl; } } int main()//multiplication { int n = 2, m = 2; int a[n][m] = { { 2, 5 }, { 1, 7 } }; int b[n][m] = { { 3, 7 }, { 2, 9 } }; int c[n][m]; int i, j, k; for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { c[i][j] = 0; for (k = 0; k < n; k++) c[i][j] += a[i][k] * b[k][j]; } } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) cout << c[i][j] << " "; cout << endl; } }
999f250d52d679401bed55a7513a5b4cc0d4e674
b3fb4e259f5c51e701d560e1f352a4215039bd40
/lab5_q12.cpp
d10d6b1747d2b89d512715e1c92df58b3b54afa4
[]
no_license
ShashankSaumya123/CS-141
a4f64eda253b2d2db3749ed39176de66cae0892b
7888bdeeaf4032c9d1057ab960f0123683633915
refs/heads/master
2021-07-07T17:34:10.890498
2019-03-02T10:26:57
2019-03-02T10:26:57
143,713,879
0
1
null
2019-03-02T10:26:58
2018-08-06T10:36:42
C++
UTF-8
C++
false
false
592
cpp
lab5_q12.cpp
// Ask for month number and print number of days in that month // including library #include<iostream> using namespace std; int main() { // defining variables int month; // Asking for input cout << "Please write the month number" << endl; cin >> month; // if else if ((month == 1)||(month == 3)||(month == 5)||(month == 7)||(month == 8)||(month == 10)||(month == 12)) cout << "The number of days are 31" << endl; else if (month == 2) cout << "The number of days are 28" << endl; // considering year to be non leap year else cout << "The number of days are 30" << endl; return 0; }
f81a1aa9787a37fa292cb7dacb692d94653ab7a7
a4dbd78f17520fd1f640eadee41fe6541f219a58
/tcc/src/utility/ellipsisproximityalgorithm.h
7d7fdd167da290a1299d2e2e67a6ce3555b81789
[]
no_license
guigsson/CCO
761f928e39209c0596f26d0375187eccf629d62b
4f0ef3ab43ce6db2df48f4c58f2278993d5a3367
refs/heads/master
2020-05-21T11:14:47.572010
2018-05-07T19:53:38
2018-05-07T19:53:38
43,181,389
0
0
null
null
null
null
UTF-8
C++
false
false
647
h
ellipsisproximityalgorithm.h
#ifndef ELLIPSISPROXIMITYALGORITHM_H #define ELLIPSISPROXIMITYALGORITHM_H #include "utility/proximityalgorithm.h" #define ELLIPSIS_A_B_RATE 0.3 #define ELLIPSIS_OUTER_DIST_RATE 1.1 class EllipsisProximityAlgorithm : public ProximityAlgorithm { public: EllipsisProximityAlgorithm(); bool InBetween(const QPointF&p, const QPointF& p1, const QPointF& p2) const override; void SetEllipsisRates(qreal ab_rate, qreal outer_rate); void SetEllipsisABRate(qreal ab_rate); void SetEllipsisOuterRate(qreal outer_rate); private: qreal ellipsis_ab_rate_; qreal ellipsis_outer_rate_; }; #endif // ELLIPSISPROXIMITYALGORITHM_H
9ce805419ead802dcd3496cc586a876a0282b634
78ff83abb52324c18cc32b7b951aaa0227f7a3d2
/main.cpp
73e1c8d1781188a2e0801aa57bed976db56e59a0
[]
no_license
jqoo/demo
eb43141f14435408707cf3b5de53fd8a336e302b
91112368ec48efe4b2ee26c8967d47d32c756a6c
refs/heads/master
2021-07-17T16:29:02.017526
2020-04-28T01:56:52
2020-04-28T01:56:52
132,213,025
0
0
null
2020-02-13T01:24:30
2018-05-05T03:59:42
C++
GB18030
C++
false
false
4,538
cpp
main.cpp
#include <iostream> #include <vector> #include <string> #include <iterator> #include <locale> #include "Matcher.h" #include <queue> using namespace std; int test1() { cout<<"Test KMP:"<<endl; KmpMatcher<char> m("mAiN"); char* p = "#include <iostream> using namespace std;int main();int main(){return 0;}"; string s(p); cout<<"string : "<<s<<endl; KmpMatcher<char>::pattern_type::iterator iter; m.sense_case(false); iter = m.find(s.begin(),s.end()); if(iter != s.end()) { cout<<"position: "<<iter-s.begin()<<" :"; copy( iter,s.end(),ostream_iterator<char>(cout) ); cout<<endl; } cout<<"total match: "<<m.count(s.begin(),s.end())<<endl; return 0; } int test2() { cout<<"Test ACKMP:"<<endl; char* pp[] = { "hers", "his", "she" }; char* p = "This is a test.She shers hers this.."; string s(p); cout<<"string : "<<s<<endl; AcKmpMatcher<char> acm(pp,pp+sizeof(pp)/sizeof(pp[0])); pair<string::iterator,AcKmpMatcher<char>::position_type> result; result = acm.find(s.begin(),s.end()); while(result.first != s.end()) { cout<<"position: "<<result.first-s.begin()<<" : "<<*acm.get_pattern(result.second)<<" : "; copy( result.first,s.end(),ostream_iterator<char>(cout) ); ++result.first; result = acm.find(result.first,s.end()); cout<<endl; } cout<<"total match: "<<acm.count(s.begin(),s.end())<<endl; return 0; } int main() { test1(); cout<<endl; test2(); return 0; } /* template<typename Elem,typename Traits = char_traits<Elem> > class Equal { public: Equal() : loc() { ptype = &use_facet<ctype<Elem> >(&loc); } Equal(const locale& l) : loc(l){ ptype = &use_facet<ctype<Elem> >(&loc); } bool eq(const Elem& e1,const Elem& e2) const { return Traits::eq( ptype->toupper(e1),ptype->toupper(e2) ); } private: locale loc; ctype<Elem>* ptype; }; template<typename Elem, typename PatternTraits = char_traits<Elem>, typename PatternEqualFunc = Equal<Elem,PatternTraits> > class KmpMatcher { public: typedef PatternTraits pattern_traits_type; typedef PatternEqualFunc pattern_equal_func; typedef basic_string<Elem,PatternTraits> pattern_type; protected: typedef vector<int> Fn; public: KmpMatcher(const pattern_type& s) : ptn(s),f(s.length()) { construct(); } template<typename RandomIter> RandomIter find( RandomIter beg,RandomIter end ) const { pattern_type::size_type k = 0; // state - k, pos - k while( k < ptn.length() && beg != end ) { if( pfunc->eq(*beg,ptn[k]) ) { ++k; ++beg; } else { if( f[k] < 0 ) { // 状态为负,跳过 k = 0; ++beg; } else k = f[k]; } } if( beg != end ) return beg - ptn.length(); return end; } template<typename RandomIter> size_t count( RandomIter beg,RandomIter end ) const { size_t sum = 0; beg = find(beg,end); while( beg != end ) { ++sum; beg = find(++beg,end); } return sum; } protected: void construct() { f[0] = -1; // s = 0 for(pattern_type::size_type i = 0;i + 1 < ptn.length();++i) { int k = f[i]; // s = i // 查找能够最长的前缀 while( k >= 0 && !pfunc->eq(ptn[i],ptn[k]) ) k = f[k]; // 每次设置下一个状态的实效函数 f[i+1] = k + 1; // s = i + 1 } // 优化 for(Fn::size_type i = 1;i < f.size();++i) { int k = f[i]; while( k >= 0 && pfunc->eq(ptn[i],ptn[k]) ) // ptn[i]下一个接受字符 k = f[k]; f[i] = k; } } private: pattern_type ptn; pattern_equal_func* pfunc; Fn f; }; // class my_traits : protected char_traits<char> { // public: // static bool eq(const char& left, const char& right) { // return tolower(left) == tolower(right); // } // }; */
b98b4ebfd9cbadd5f67e1504a3de7addc4114e3e
78f78bfecc4e3de2bf452178d4e8cbc6758110c4
/samples/cortex/m3-iar/stm32f1xx/4-debug/src/main.cpp
21c1f4cb6282f953a8f9ce7ce3ed978981a7a378
[ "MIT" ]
permissive
scmrtos/scmrtos-sample-projects
249f6259b4b7de99854aad10f7de177289d1d3b3
3b34a485b6ca4b16705c250383ae5d30c81966f1
refs/heads/master
2021-11-17T14:55:35.186727
2021-02-04T15:43:10
2021-02-04T15:43:10
43,736,411
10
9
null
null
null
null
UTF-8
C++
false
false
5,900
cpp
main.cpp
//****************************************************************************** //* //* FULLNAME: Single-Chip Microcontroller Real-Time Operating System //* //* NICKNAME: scmRTOS //* //* PROCESSOR: ARM Cortex-M3 //* //* TOOLKIT: EWARM (IAR Systems) //* //* PURPOSE: Port Test File //* //* Version: v5.2.0 //* //* //* Copyright (c) 2003-2021, scmRTOS Team //* //* Permission is hereby granted, free of charge, to any person //* obtaining a copy of this software and associated documentation //* files (the "Software"), to deal in the Software without restriction, //* including without limitation the rights to use, copy, modify, merge, //* publish, distribute, sublicense, and/or sell copies of the Software, //* and to permit persons to whom the Software is furnished to do so, //* subject to the following conditions: //* //* The above copyright notice and this permission notice shall be included //* in all copies or substantial portions of the Software. //* //* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, //* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF //* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. //* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY //* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, //* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH //* THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. //* //* ================================================================= //* Project sources: https://github.com/scmrtos/scmrtos //* Documentation: https://github.com/scmrtos/scmrtos/wiki/Documentation //* Wiki: https://github.com/scmrtos/scmrtos/wiki //* Sample projects: https://github.com/scmrtos/scmrtos-sample-projects //* ================================================================= //* //****************************************************************************** //* Ported by Andrey Chuikin, Copyright (c) 2008-2021 //* //* //* Demo based on STM32F103RB microcontroller from ST: www.st.com //* #include <scmRTOS.h> #include <stdio.h> #include "stm32F10x.h" typedef TProfiler<0> TProfilerBase; //--------------------------------------------------------------------------- class TProcProfiler : public TProfilerBase { public: TProcProfiler() {/* Timer initialization can be here */} void get_results(timeout_t acquire_period); }; //--------------------------------------------------------------------------- template<> uint32_t TProfilerBase::time_interval() { static uint16_t prev_ticks; uint16_t ticks = TIM3->CNT; uint16_t diff = ticks - prev_ticks; prev_ticks = ticks; return diff; } //--------------------------------------------------------------------------- // // Process types // typedef OS::process<OS::pr0, 512> TProc1; typedef OS::process<OS::pr1, 512> TProc2; typedef OS::process<OS::pr2, 512> TProc3; typedef OS::process<OS::pr3, 1024> TBackgroundProc; //--------------------------------------------------------------------------- // // Process objects // TProc1 Proc1; TProc2 Proc2; TProc3 Proc3; TBackgroundProc BackgroundProc; OS::TEventFlag ef; OS::TEventFlag Timer_B_Ovf; TProcProfiler Profiler; //--------------------------------------------------------------------------- // void main() { // Setup STM32F103 Timer3. RCC->APB1ENR |= RCC_APB1ENR_TIM3EN; // Enable TIM3 clock. TIM3->CR1 = 0; // Count up to ARR, no divisor, auto reload. TIM3->ARR = 0xFFFF; // Period (full scale). TIM3->PSC = 79; // Set prescaler to 80: 1us tick @ 8MHz HSI. 65.536 ms period TIM3->EGR = TIM_EGR_UG; // Generate an update event to reload the prescaler value immediately. TIM3->CR1 = TIM_CR1_CEN; // Run timer. //----------------------------------------------------------------------- OS::run(); } //--------------------------------------------------------------------------- template<> OS_PROCESS void TProc1::exec() { for(;;) { ef.wait(); } } //--------------------------------------------------------------------------- template<> OS_PROCESS void TProc2::exec() { for(;;) { Timer_B_Ovf.wait(); } } //--------------------------------------------------------------------------- template<> OS_PROCESS void TProc3::exec() { for(;;) { OS::sleep(10); ef.signal(); } } //--------------------------------------------------------------------------- template<> void TBackgroundProc::exec() { for(;;) { // Every 1 second get profiler results. Profiler.get_results(500); } } //--------------------------------------------------------------------------- void OS::system_timer_user_hook() { static int cnt=0; if (++cnt == 25) { cnt = 0; Timer_B_Ovf.signal_isr(); } } //--------------------------------------------------------------------------- void OS::idle_process_user_hook() { } //--------------------------------------------------------------------------- void OS::context_switch_user_hook() { Profiler.advance_counters(); } //--------------------------------------------------------------------------- void TProcProfiler::get_results(timeout_t acquire_period) { OS::sleep(acquire_period); TProfiler::process_data(); printf("------------------------------\n"); for(uint_fast8_t i = 0; i < OS::PROCESS_COUNT; ++i) { size_t slack = OS::get_proc(i)->stack_slack() * sizeof(stack_item_t); double cpu = Profiler.get_result(i)/100.0; printf("Proc pr%d | CPU %5.2f | Slack %d\n", scmRTOS_PRIORITY_ORDER ? scmRTOS_PROCESS_COUNT-i : i, cpu, slack); } }
839d628e213df22a68d1c89230c456cdcbd9bd06
49eb433ff628912371ffef8687043f897c162be1
/ex52/dirsizer/allocateentry.cc
13b92ffb2b45523b43fe6ff84549d72a79aa6a1f
[]
no_license
grebnetiew/cpp-2-52
c32c8924abdec612d1eeeef4b0cedc22607390dd
cc3197ef1b330d812fe6287d940165a3048efa05
refs/heads/master
2016-09-08T01:34:37.505413
2015-01-27T13:42:52
2015-01-27T13:42:52
29,914,011
0
0
null
null
null
null
UTF-8
C++
false
false
233
cc
allocateentry.cc
#include "dirsizer.ih" #include <stddef.h> // offsetof struct dirent *DirSizer::allocateEntry() const { return static_cast<struct dirent *>( operator new(offsetof(struct dirent, d_name) + d_maxNameLen + 1)); }
5749a6d7999d60e984991e68f58e24987b80712b
52b9808797d8e4fab0acc1c6f8a7b93d6a4ce0fc
/DSA Project/RBT.h
36536536e8c40a3aab5ec6cf8191f9ef34753c80
[]
no_license
musakhan18/Data-structures-and-Algorithms
a16033b6f7307bef80fdf85a992fc240a3ecc0a9
0f5b3ced96dd246f2c2ff5e46c9eb4de6655f554
refs/heads/main
2023-06-28T13:43:11.671066
2021-08-04T09:11:23
2021-08-04T09:11:23
359,820,421
0
0
null
null
null
null
UTF-8
C++
false
false
923
h
RBT.h
#pragma once #include<iostream> using namespace std; struct Node { int data; Node* leftChild; Node* rightChild; char colour; }; class RBT { private: Node* root; int c = 0; void inorderTraversalCode(Node* temp); int leaf(Node*); int max(Node*); public: void RBTinsertionCode(Node* ,int); void rightsinglerotate(Node* n_node); void leftsinglerotate(Node* n_node); void RBTinsertion(int num) { Node* temp = root; RBTinsertionCode(temp, num); } RBT() { root = nullptr; } int count(); int height(); void LeftdoubleRotation(Node*); void RighttdoubleRotation(Node*); bool is_empty(); void inorderTraversal(); void preorder(); void postorder(); void inorder(); Node* FindParent(int); Node* FindUncle(int); Node* FindGrandParent(int); Node* check(Node*); void pre_order(Node*); void post_order(Node*); void in_order(Node*); };
8d136b7bacf7792e83d379e94b7576044dd0374b
a3d6556180e74af7b555f8d47d3fea55b94bcbda
/chrome/browser/ui/views/editor_menu/editor_menu_promo_card_view.h
7b39c9269bcf82202bfba4502492896462f1d943
[ "BSD-3-Clause" ]
permissive
chromium/chromium
aaa9eda10115b50b0616d2f1aed5ef35d1d779d6
a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c
refs/heads/main
2023-08-24T00:35:12.585945
2023-08-23T22:01:11
2023-08-23T22:01:11
120,360,765
17,408
7,102
BSD-3-Clause
2023-09-10T23:44:27
2018-02-05T20:55:32
null
UTF-8
C++
false
false
1,284
h
editor_menu_promo_card_view.h
// Copyright 2023 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_UI_VIEWS_EDITOR_MENU_EDITOR_MENU_PROMO_CARD_VIEW_H_ #define CHROME_BROWSER_UI_VIEWS_EDITOR_MENU_EDITOR_MENU_PROMO_CARD_VIEW_H_ #include "ui/base/metadata/metadata_header_macros.h" #include "ui/views/widget/unique_widget_ptr.h" namespace chromeos::editor_menu { // A view which shows a promo card to introduce the Editor Menu feature. class EditorMenuPromoCardView : public views::View { public: METADATA_HEADER(EditorMenuPromoCardView); explicit EditorMenuPromoCardView(const gfx::Rect& anchor_view_bounds); EditorMenuPromoCardView(const EditorMenuPromoCardView&) = delete; EditorMenuPromoCardView& operator=(const EditorMenuPromoCardView&) = delete; ~EditorMenuPromoCardView() override; static views::UniqueWidgetPtr CreateWidget( const gfx::Rect& anchor_view_bounds); // views::View: void GetAccessibleNodeData(ui::AXNodeData* node_data) override; void UpdateBounds(const gfx::Rect& anchor_view_bounds); private: void InitLayout(); void InitButtonBar(); }; } // namespace chromeos::editor_menu #endif // CHROME_BROWSER_UI_VIEWS_EDITOR_MENU_EDITOR_MENU_PROMO_CARD_VIEW_H_
619027a779f7760c2122f51a800a024647db261d
2d42a50f7f3b4a864ee19a42ea88a79be4320069
/source/attributes/camera/iprojection.h
11ecc09c66b3b64066f298a991caef29ae5676b9
[]
no_license
Mikalai/punk_project_a
8a4f55e49e2ad478fdeefa68293012af4b64f5d4
8829eb077f84d4fd7b476fd951c93377a3073e48
refs/heads/master
2016-09-06T05:58:53.039941
2015-01-24T11:56:49
2015-01-24T11:56:49
14,536,431
1
0
null
2014-06-26T06:40:50
2013-11-19T20:03:46
C
UTF-8
C++
false
false
409
h
iprojection.h
#ifndef _H_IPROJECTION #define _H_IPROJECTION #include <config.h> #include <system/factory/interface.h> #include <core/iobject.h> PUNK_ENGINE_BEGIN namespace Attributes { DECLARE_PUNK_GUID(IID_IProjection, "69EF1F1D-778E-482A-881D-3770FB2EC35E"); class IProjection : public Core::IObject { public: }; using IProjectionPtr = Core::Pointer < IProjection >; } PUNK_ENGINE_END #endif // _H_IPROJECTION
8896675d517eafeeb1d435d19095d0614aee9bc0
83f727ae888371f414339d9cf2460e830c036b9a
/tasks/Task.cpp
734882717f5e4fe2a40cd3777d99a86a4afb1be7
[]
no_license
nilsbore/simulation-orogen-imaging_sonar_simulation
b47f98e2a16fddb23bf2452779cf6793200d13f3
4565a98796691e0e3a1484c8853896b821411c0c
refs/heads/master
2021-08-26T09:27:24.484624
2017-09-26T23:45:42
2017-11-23T01:05:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,459
cpp
Task.cpp
/* Generated from orogen/lib/orogen/templates/tasks/Task.cpp */ #include "Task.hpp" // Rock includes #include <gpu_sonar_simulation/Utils.hpp> #include <frame_helper/FrameHelper.h> #include <base/Float.hpp> using namespace imaging_sonar_simulation; using namespace base::samples::frame; Task::Task(std::string const& name) : TaskBase(name) { } Task::Task(std::string const& name, RTT::ExecutionEngine* engine) : TaskBase(name, engine) { } Task::~Task() { } bool Task::configureHook() { if (!TaskBase::configureHook()) return false; // check if the properties have valid values if (_range.value() <= 0) { RTT::log(RTT::Error) << "The range must be positive." << RTT::endlog(); return false; } if (_gain.value() < 0 || _gain.value() > 1) { RTT::log(RTT::Error) << "The gain must be between 0.0 and 1.0." << RTT::endlog(); return false; } if (_bin_count.value() <= 0 || _bin_count.value() > 1500) { RTT::log(RTT::Error) << "The number of bins must be positive and less than 1500." << RTT::endlog(); return false; } if (_beam_width.value().getRad() <= 0 || _beam_height.value().getRad() <= 0) { RTT::log(RTT::Error) << "The sonar opening angles must be positives." << RTT::endlog(); return false; } if (_attenuation_properties.value().frequency < 0.1 || _attenuation_properties.value().frequency > 1000) { RTT::log(RTT::Error) << "The sonar frequency must be between 100 Hz and 1 MHz." << RTT::endlog(); return false; } if(_attenuation_properties.value().temperature.getCelsius() < -6 || _attenuation_properties.value().temperature.getCelsius() > 35 || base::isNaN(_attenuation_properties.value().temperature.getCelsius())) { RTT::log(RTT::Error) << "The water temperature value must be between -6 and 35 Celsius degrees." << RTT::endlog(); return false; } if (_attenuation_properties.value().salinity < 0 || _attenuation_properties.value().salinity > 50) { RTT::log(RTT::Error) << "The water salinity must be between 0 (only consider freshwater contribution) and 50 ppt." << RTT::endlog(); return false; } if (_attenuation_properties.value().acidity < 7.7 || _attenuation_properties.value().acidity > 8.3) { RTT::log(RTT::Error) << "The water acidity must have pH between 7.7 and 8.3." << RTT::endlog(); return false; } // set the attributes range = _range.value(); gain = _gain.value(); normal_depth_map.setMaxRange(_range.value()); sonar_sim.bin_count = _bin_count.value(); sonar_sim.beam_width = _beam_width.value(); sonar_sim.beam_height = _beam_height.value(); attenuation_properties = _attenuation_properties.value(); return true; } bool Task::startHook() { if (!TaskBase::startHook()) return false; return true; } void Task::updateHook() { TaskBase::updateHook(); } void Task::errorHook() { TaskBase::errorHook(); } void Task::stopHook() { TaskBase::stopHook(); } void Task::cleanupHook() { TaskBase::cleanupHook(); } void Task::setupShader(uint value, bool isHeight) { double const half_fovx = sonar_sim.beam_width.getRad() / 2; double const half_fovy = sonar_sim.beam_height.getRad() / 2; // initialize shader (NormalDepthMap and ImageViewerCaptureTool) normal_depth_map = normal_depth_map::NormalDepthMap(range, half_fovx, half_fovy); capture = normal_depth_map::ImageViewerCaptureTool(sonar_sim.beam_height.getRad(), sonar_sim.beam_width.getRad(), value, isHeight); capture.setBackgroundColor(osg::Vec4d(0.0, 0.0, 0.0, 1.0)); osg::ref_ptr<osg::Group> root = vizkit3dWorld->getWidget()->getRootNode(); normal_depth_map.addNodeChild(root); } void Task::updateSonarPose(base::samples::RigidBodyState pose) { // convert OSG (Z-forward) to RoCK coordinate system (X-forward) osg::Matrixd rock_coordinate_matrix = osg::Matrixd::rotate( M_PI_2, osg::Vec3(0, 0, 1)) * osg::Matrixd::rotate(-M_PI_2, osg::Vec3(1, 0, 0)); // transformation matrixes multiplication osg::Matrixd matrix; matrix.setTrans(osg::Vec3(pose.position.x(), pose.position.y(), pose.position.z())); matrix.setRotate(osg::Quat(pose.orientation.x(), pose.orientation.y(), pose.orientation.z(), pose.orientation.w())); matrix.invert(matrix); // correct coordinate system and apply geometric transformations osg::Matrixd m = matrix * rock_coordinate_matrix; osg::Vec3 eye, center, up; m.getLookAt(eye, center, up); capture.setCameraPosition(eye, center, up); } void Task::processShader(osg::ref_ptr<osg::Image>& osg_image, std::vector<float>& bins) { // receives shader image in opencv format cv::Mat cv_image, cv_depth; gpu_sonar_simulation::convertOSG2CV(osg_image, cv_image); osg::ref_ptr<osg::Image> osg_depth = capture.getDepthBuffer(); gpu_sonar_simulation::convertOSG2CV(osg_depth, cv_depth); // replace depth matrix std::vector<cv::Mat> channels; cv::split(cv_image, channels); channels[1] = cv_depth; cv::merge(channels, cv_image); // decode shader informations to sonar data sonar_sim.decodeShader(cv_image, bins, _enable_speckle_noise.value()); // apply the additional gain sonar_sim.applyAdditionalGain(bins, gain); // display shader image if (_write_shader_image.value()) { std::unique_ptr<Frame> frame(new Frame()); cv_image.convertTo(cv_image, CV_8UC3, 255); cv::flip(cv_image, cv_image, 0); frame_helper::FrameHelper::copyMatToFrame(cv_image, *frame.get()); frame->time = base::Time::now(); _shader_image.write(RTT::extras::ReadOnlyPointer<Frame>(frame.release())); } } bool Task::setRange(double value) { if (value <= 0) { RTT::log(RTT::Error) << "The range must be positive." << RTT::endlog(); return false; } range = value; normal_depth_map.setMaxRange(value); return (imaging_sonar_simulation::TaskBase::setRange(value)); } bool Task::setGain(double value) { if (value < 0 || value > 1) { RTT::log(RTT::Error) << "The gain must be between 0.0 and 1.0." << RTT::endlog(); return false; } gain = value; return (imaging_sonar_simulation::TaskBase::setGain(value)); } bool Task::setAttenuation_properties(::imaging_sonar_simulation::AcousticAttenuationProperties const & value) { if (value.frequency < 0.1 || value.frequency > 1000) { RTT::log(RTT::Error) << "The sonar frequency must be between 100 Hz and 1 MHz." << RTT::endlog(); return false; } if (value.temperature.getCelsius() < -6 || value.temperature.getCelsius() > 35 || base::isNaN(value.temperature.getCelsius())) { RTT::log(RTT::Error) << "The water temperature value must be between -6 and 35 Celsius degrees." << RTT::endlog(); return false; } if (value.salinity < 0 || value.salinity > 50) { RTT::log(RTT::Error) << "The water salinity must be between 0 (only consider freshwater contribution) and 50 ppt." << RTT::endlog(); return false; } if (value.acidity < 7.7 || value.acidity > 8.3) { RTT::log(RTT::Error) << "The water acidity must have pH between 7.7 and 8.3." << RTT::endlog(); return false; } attenuation_properties = value; return (imaging_sonar_simulation::TaskBase::setAttenuation_properties(value)); }
208cd593b301f9df71749af6863391ff83c1167e
f74b295b4056dedd33d8a04f9fb7222b190ac164
/src/transmitter/transmitter.ino
1ac3653461b5dd6b97832b55ead8dd7e1f871827
[]
no_license
richsergsam/Arduino-RF-liquid-level-sensor
2817414dba58f3f766d49d981d9bebcdd4262fda
3d18eb3068f9c57598ae28e403614220cadc5b62
refs/heads/main
2022-12-26T04:13:27.313871
2020-10-17T19:15:50
2020-10-17T19:15:50
301,960,618
0
0
null
null
null
null
UTF-8
C++
false
false
3,672
ino
transmitter.ino
//----------------------БИБЛИОТЕКИ--------------------- #include "GyverPower.h" // с понижением частоты "уйдут" функции времени // для их коррекции можно сделать так: #define millis() (millis() << (CLKPR & 0xF)) #define micros() (micros() << (CLKPR & 0xF)) #define delay(x) delay((x) >> (CLKPR & 0xf)) #define delayMicroseconds(x) delayMicroseconds((x) >> (CLKPR & 0xf)) // данные дефайны нужно прописать ПЕРЕД подключением остальных библиотек. // Таким образом дефайн сможет "проникнуть" в библиотеку и скорректировать // работу используемых там функций времени #include <RH_ASK.h> //-----------------------НАСТРОЙКИ--------------------- #define battery_min 3000 // минимальный уровень заряда батареи для отображения #define battery_max 4200 // максимальный уровень заряда батареи для отображения float my_vcc_const = 1.067; // константа вольтметра byte sensor_pin = 7; // Подтяжка через резистор 10КОм к VCC для режима INPUT byte prescaler = PRESCALER_4; byte clock_multiplier = pow(2, prescaler); unsigned int serial_and_rf_clock = 1200; void setup() { power.setSystemPrescaler(prescaler); Serial.begin(serial_and_rf_clock * clock_multiplier); // Debugging only Serial.println("Current internal clock: " + String(F_CPU / clock_multiplier / 1000000) + " MGhz;"); power.setSleepMode(POWERDOWN_SLEEP); } void loop() { // Send sensors values checkSensorAndSendData(); // Wait 10 sec power.sleepDelay(5*1000); } void checkSensorAndSendData(){ long vcc = readVcc(); pinMode(sensor_pin, INPUT_PULLUP); byte sensor_status = digitalRead(sensor_pin); pinMode(sensor_pin, INPUT); Serial.println(sendVccAndSensor(vcc, sensor_status)); } String sendVccAndSensor(long vcc, int sensor_status) { String msg = String(vcc) + "; " + String(sensor_status); sendData(msg); return msg; } void sendData(String message) { RH_ASK driver(serial_and_rf_clock * clock_multiplier, 11, 12, 0); if (!driver.init()) Serial.println("RF driver init failed"); else Serial.println("RF driver init ok"); int l = message.length() + 1; char msg_buffer[l]; message.toCharArray(msg_buffer, l); driver.send((uint8_t *)msg_buffer, strlen(msg_buffer)); driver.waitPacketSent(); } long readVcc() { //функция чтения внутреннего опорного напряжения, универсальная (для всех ардуин) #if defined(__AVR_ATmega32U4__) || defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) ADMUX = _BV(REFS0) | _BV(MUX4) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1); #elif defined (__AVR_ATtiny24__) || defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__) ADMUX = _BV(MUX5) | _BV(MUX0); #elif defined (__AVR_ATtiny25__) || defined(__AVR_ATtiny45__) || defined(__AVR_ATtiny85__) ADMUX = _BV(MUX3) | _BV(MUX2); #else ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1); #endif delay(2); // Wait for Vref to settle ADCSRA |= _BV(ADSC); // Start conversion while (bit_is_set(ADCSRA, ADSC)); // measuring uint8_t low = ADCL; // must read ADCL first - it then locks ADCH uint8_t high = ADCH; // unlocks both long result = (high << 8) | low; result = my_vcc_const * 1023 * 1000 / result; // расчёт реального VCC return result; // возвращает VCC }
9abfd7e22d64faeea91d36e09bd8923b3c03dfb7
675e55b07deb42ad99dddbe8746899e051127701
/65_Valid_Number/65.cpp
debc67245e9d1ecfbbbddc1bc2a90a3114743e04
[]
no_license
wyc25013/leetcode
3bbef070b72a16666a1cdf0d4710d3558c30f4be
5358f3c2cc7a5999d134b77bc87c8764dad2ddc2
refs/heads/master
2021-01-18T15:17:05.658334
2015-10-14T02:14:39
2015-10-14T02:14:39
37,750,911
0
0
null
null
null
null
UTF-8
C++
false
false
1,369
cpp
65.cpp
#include <string> #include <iostream> using namespace std; class Solution { public: bool isNumber(string s) { int len = s.length(); // cut all space and sign int start = 0; while(s[start]==' ') start++; if(start==len) return false; int cntsign = 0; while(s[start]=='+' || s[start]=='-'){ start++; cntsign++; } if(cntsign > 1) return false; int end = len-1; while(s[end]==' ') end--; if(end == -1) return false; int cntdot = 0; int cnte = 0; cntsign = 0; for(int i = start; i <= end; i++){ if(s[i]==' ') return false; else if(s[i]=='.'){ if(i==start&&i==end) return false; if(cntdot==0) cntdot++; else return false; if(cnte==1) return false; } else if(s[i]=='e'){ if(i==start) return false; if(s[i-1]=='+'||s[i-1]=='-') return false; if(cnte==0) cnte++; else return false; if(i==end) return false; if(s[i-1]=='.'){ if(i-1==start) return false; else{ if(s[i-2] <'0'||s[i-2]>'9') return false; } } } else if(s[i]=='-'||s[i]=='+'){ if(s[i-1]!='e') return false; if(cntsign==0) cntsign++; else return false; if(i==end) return false; } else if((s[i] < '0' || s[i] > '9') && s[i]!='-'&&s[i]!='+'&&s[i]!='e'&&s[i]!='.') return false; } return true; } };
eccd6ea02dc9407aca525cc07871f0945a725ec8
5a00ce827b1d6d0bff7d5ea0e8e4934696dd7c6d
/src/MixedView.cpp
90781770758abc26b0339ec76f957d97ce0e3bed
[]
no_license
IvanGH2/SoundAnalysis
3a5887c56820cbcc72008f06dfcb9ab1f66956a1
118fd491e0f104064f3269757d4b0b6cf31803f6
refs/heads/master
2022-12-30T15:35:25.595265
2020-10-18T12:54:50
2020-10-18T12:54:50
305,091,987
0
0
null
null
null
null
UTF-8
C++
false
false
4,113
cpp
MixedView.cpp
/* Copyright 2020 Ivan Balen This file is part of the Sound analysis library. The Sound analysis library is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. The Sound analysis 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 General Public License for more details. You should have received a copy of the Lesser GNU General Public License along with the Sound analysis library. If not, see <http://www.gnu.org/licenses/>.*/ //--------------------------------------------------------------------------- #pragma hdrstop #include "MixedView.h" //--------------------------------------------------------------------------- TMixedView::TMixedView(unsigned w, unsigned h, unsigned numChannels) : TContainerView(w, h, numChannels) { //unsigned channelHeight = numChannels == 1 ? h - cWaveformMargin : (h-cWaveformMargin-cWaveformSpacing)/2; pBmp0 = new Graphics::TBitmap; //pBmp0->Height = h; //pBmp0->Width = w; pBmp0->PixelFormat = pf32bit; if(numChannels == 2){ pBmp1 = new Graphics::TBitmap; pBmp1->PixelFormat = pf32bit; } } bool TMixedView::IsRedrawNeeded(unsigned w, unsigned h, float tLevel){ return width!=w || height!=h || transparencyLevel!=tLevel ? true : false; } Graphics::TBitmap *TMixedView::GetContainerViewLeft(){ // if(pBmp0->Empty) DrawMixedView(); return pBmp0; } Graphics::TBitmap *TMixedView::GetContainerViewRight(){ // if(!pBmp1) // DrawMixedView(); return pBmp1; } void TMixedView::DrawMixedView(){ unsigned *pPixel, *pPixel0, *pPixel1, *pPixel_, *pPixel0_, *pPixel1_; unsigned char cRed0, cGreen0, cBlue0,cRed1, cGreen1, cBlue1, bRedColor, bGreenColor, bBlueColor; unsigned char cRed0_, cGreen0_, cBlue0_,cRed1_, cGreen1_, cBlue1_, bRedColor_, bGreenColor_, bBlueColor_; const unsigned w = pMixBmp01->Width<pMixBmp02->Width ? pMixBmp01->Width : pMixBmp02->Width; const unsigned h = pMixBmp01->Height<pMixBmp02->Height ? pMixBmp01->Height : pMixBmp02->Height; /*if(pBmp0) delete pBmp0; pBmp0 = new Graphics::TBitmap; pBmp0->PixelFormat = pf32bit;*/ pBmp0->Width = w; pBmp0->Height = h; if(numChannels==2){ pBmp1->Width = w; pBmp1->Height = h; } for(int i=0;i<h;i++){ pPixel0 = (unsigned*)pMixBmp01->ScanLine[i]; pPixel1 = (unsigned*)pMixBmp02->ScanLine[i]; pPixel = (unsigned*)pBmp0->ScanLine[i]; if(numChannels==2){ pPixel0_ = (unsigned*)pMixBmp11->ScanLine[i]; pPixel1_ = (unsigned*)pMixBmp12->ScanLine[i]; pPixel_ = (unsigned*)pBmp1->ScanLine[i]; } const unsigned cGreenShift = 8; const unsigned cBlueShift = 16; const float w0 = transparencyLevel; const float w1 = 1.0f-transparencyLevel; for(int j=0;j<w;j++){ unsigned pixel0 = pPixel0[j]; unsigned pixel1 = pPixel1[j]; cBlue0 = pixel0 >> cBlueShift; cGreen0 = pixel0 >> cGreenShift & 0xFF; cRed0 = pixel0 & 0xFF; cBlue1 = pixel1 >> cBlueShift; cGreen1 = pixel1 >> cGreenShift & 0xFF; cRed1 = pixel1 & 0xFF; //blend the current bitmap pixel with the overlay colour bRedColor = (cRed0*w0+cRed1*w1); bGreenColor = (cGreen0*w0+cGreen1*w1); bBlueColor = (cBlue0*w0+cBlue1*w1); if(numChannels==2){ unsigned pixel0_ = pPixel0_[j]; unsigned pixel1_ = pPixel1_[j]; cBlue0_ = pixel0_ >> cBlueShift; cGreen0_ = pixel0_ >> cGreenShift & 0xFF; cRed0_ = pixel0_ & 0xFF; cBlue1_ = pixel1_ >> cBlueShift; cGreen1_ = pixel1_ >> cGreenShift & 0xFF; cRed1_ = pixel1_ & 0xFF; bRedColor_ = (cRed0_*w0+cRed1_*w1); bGreenColor_ = (cGreen0_*w0+cGreen1_*w1); bBlueColor_ = (cBlue0_*w0+cBlue1_*w1); pPixel_[j] = ((bBlueColor_ << cBlueShift) | (bGreenColor_ << cGreenShift)) | bRedColor_; } pPixel[j] = ((bBlueColor << cBlueShift) | (bGreenColor << cGreenShift)) | bRedColor; } } } #pragma package(smart_init)
6ea067576e4cb39742d17b93d99201f3d0a6eaf2
356ca0e5d593832f6b766ce70a7edb209d463b23
/oxref/xrefdata/keepfirst.cc
1456007a1e7e678a6fb5ecb1af8608644e0fe033
[]
no_license
fbb-git/oxref
dc5631033953b1b5b7a7fbf4a2120340da5d1e9b
60bddcf36617cc34612becddb6ae1e83b71a29b7
refs/heads/master
2021-05-04T06:34:33.369266
2018-06-25T12:59:56
2018-06-25T12:59:56
41,297,715
0
1
null
null
null
null
UTF-8
C++
false
false
1,169
cc
keepfirst.cc
#include "xrefdata.ih" void XrefData::keepFirst(size_t openParIdx) { //cout << d_cooked << "\n"; size_t begin = openParIdx; while (d_cooked[begin] != ')') { ++begin; // beyond the separator if (d_cooked[begin] == ' ') // keep blank after sep. ++begin; size_t next = d_cooked.find_first_not_of(" \t", begin); // erase extra d_cooked.erase(begin, next - begin); // blanks // find end of 1st word: // < begins template // , ends argument // ) ends parlist // blank ends 1st word begin = d_cooked.find_first_of("*&<,) \t", begin); begin = eraseParam(begin); // erase the param. from // 'begin', return , or ) // position } }
3993cec29b10be74eed104bc381634acf34d42cb
057a475216e9beed41983481aafcaf109bbf58da
/src/Processors/Transforms/MergeJoinTransform.h
6bf4484df247373a7c61cd0f91ac9da811b5840a
[ "Apache-2.0" ]
permissive
ClickHouse/ClickHouse
fece5204263a5b4d693854b6039699265f1bb27f
6649328db809d51a694c358571539bc5820464be
refs/heads/master
2023-08-31T18:48:36.615225
2023-08-31T17:51:24
2023-08-31T17:51:24
60,246,359
23,878
5,449
Apache-2.0
2023-09-14T20:10:52
2016-06-02T08:28:18
C++
UTF-8
C++
false
false
7,408
h
MergeJoinTransform.h
#pragma once #include <cassert> #include <cstddef> #include <memory> #include <mutex> #include <optional> #include <unordered_map> #include <utility> #include <vector> #include <boost/core/noncopyable.hpp> #include <Common/PODArray.h> #include <Core/SortCursor.h> #include <Core/SortDescription.h> #include <IO/ReadBuffer.h> #include <Parsers/ASTTablesInSelectQuery.h> #include <Processors/Chunk.h> #include <Processors/Merges/Algorithms/IMergingAlgorithm.h> #include <Processors/Merges/IMergingTransform.h> namespace Poco { class Logger; } namespace DB { class IJoin; using JoinPtr = std::shared_ptr<IJoin>; class FullMergeJoinCursor; using FullMergeJoinCursorPtr = std::unique_ptr<FullMergeJoinCursor>; /// Used instead of storing previous block struct JoinKeyRow { std::vector<ColumnPtr> row; JoinKeyRow() = default; explicit JoinKeyRow(const SortCursorImpl & impl_, size_t pos) { row.reserve(impl_.sort_columns.size()); for (const auto & col : impl_.sort_columns) { auto new_col = col->cloneEmpty(); new_col->insertFrom(*col, pos); row.push_back(std::move(new_col)); } } void reset() { row.clear(); } bool equals(const SortCursorImpl & impl) const { if (row.empty()) return false; assert(this->row.size() == impl.sort_columns_size); for (size_t i = 0; i < impl.sort_columns_size; ++i) { int cmp = this->row[i]->compareAt(0, impl.getRow(), *impl.sort_columns[i], impl.desc[i].nulls_direction); if (cmp != 0) return false; } return true; } }; /// Remembers previous key if it was joined in previous block class AnyJoinState : boost::noncopyable { public: AnyJoinState() = default; void set(size_t source_num, const SortCursorImpl & cursor) { assert(cursor.rows); keys[source_num] = JoinKeyRow(cursor, cursor.rows - 1); } void setValue(Chunk value_) { value = std::move(value_); } bool empty() const { return keys[0].row.empty() && keys[1].row.empty(); } /// current keys JoinKeyRow keys[2]; /// for LEFT/RIGHT join use previously joined row from other table. Chunk value; }; /// Accumulate blocks with same key and cross-join them class AllJoinState : boost::noncopyable { public: struct Range { Range() = default; explicit Range(Chunk chunk_, size_t begin_, size_t length_) : begin(begin_) , length(length_) , current(begin_) , chunk(std::move(chunk_)) { assert(length > 0 && begin + length <= chunk.getNumRows()); } size_t begin; size_t length; size_t current; Chunk chunk; }; AllJoinState(const SortCursorImpl & lcursor, size_t lpos, const SortCursorImpl & rcursor, size_t rpos) : keys{JoinKeyRow(lcursor, lpos), JoinKeyRow(rcursor, rpos)} { } void addRange(size_t source_num, Chunk chunk, size_t begin, size_t length) { if (source_num == 0) left.emplace_back(std::move(chunk), begin, length); else right.emplace_back(std::move(chunk), begin, length); } bool next() { /// advance right to one row, when right finished, advance left to next block assert(!left.empty() && !right.empty()); if (finished()) return false; bool has_next_right = nextRight(); if (has_next_right) return true; return nextLeft(); } bool finished() const { return lidx >= left.size(); } size_t blocksStored() const { return left.size() + right.size(); } const Range & getLeft() const { return left[lidx]; } const Range & getRight() const { return right[ridx]; } /// Left and right types can be different because of nullable JoinKeyRow keys[2]; private: bool nextLeft() { lidx += 1; return lidx < left.size(); } bool nextRight() { /// cycle through right rows right[ridx].current += 1; if (right[ridx].current >= right[ridx].begin + right[ridx].length) { /// reset current row index to the beginning, because range will be accessed again right[ridx].current = right[ridx].begin; ridx += 1; if (ridx >= right.size()) { ridx = 0; return false; } } return true; } std::vector<Range> left; std::vector<Range> right; size_t lidx = 0; size_t ridx = 0; }; /* * Wrapper for SortCursorImpl */ class FullMergeJoinCursor : boost::noncopyable { public: explicit FullMergeJoinCursor(const Block & sample_block_, const SortDescription & description_) : sample_block(sample_block_.cloneEmpty()) , desc(description_) { } bool fullyCompleted() const; void setChunk(Chunk && chunk); const Chunk & getCurrent() const; Chunk detach(); SortCursorImpl * operator-> () { return &cursor; } const SortCursorImpl * operator-> () const { return &cursor; } SortCursorImpl cursor; const Block & sampleBlock() const { return sample_block; } Columns sampleColumns() const { return sample_block.getColumns(); } private: Block sample_block; SortDescription desc; Chunk current_chunk; bool recieved_all_blocks = false; }; /* * This class is used to join chunks from two sorted streams. * It is used in MergeJoinTransform. */ class MergeJoinAlgorithm final : public IMergingAlgorithm { public: explicit MergeJoinAlgorithm(JoinPtr table_join, const Blocks & input_headers, size_t max_block_size_); virtual void initialize(Inputs inputs) override; virtual void consume(Input & input, size_t source_num) override; virtual Status merge() override; void logElapsed(double seconds); private: std::optional<Status> handleAnyJoinState(); Status anyJoin(JoinKind kind); std::optional<Status> handleAllJoinState(); Status allJoin(JoinKind kind); Chunk createBlockWithDefaults(size_t source_num); Chunk createBlockWithDefaults(size_t source_num, size_t start, size_t num_rows) const; /// For `USING` join key columns should have values from right side instead of defaults std::unordered_map<size_t, size_t> left_to_right_key_remap; std::vector<FullMergeJoinCursorPtr> cursors; /// Keep some state to make connection between data in different blocks AnyJoinState any_join_state; std::unique_ptr<AllJoinState> all_join_state; JoinPtr table_join; size_t max_block_size; struct Statistic { size_t num_blocks[2] = {0, 0}; size_t num_rows[2] = {0, 0}; size_t max_blocks_loaded = 0; }; Statistic stat; Poco::Logger * log; }; class MergeJoinTransform final : public IMergingTransform<MergeJoinAlgorithm> { using Base = IMergingTransform<MergeJoinAlgorithm>; public: MergeJoinTransform( JoinPtr table_join, const Blocks & input_headers, const Block & output_header, size_t max_block_size, UInt64 limit_hint = 0); String getName() const override { return "MergeJoinTransform"; } protected: void onFinish() override; Poco::Logger * log; }; }
07b20dff3c1c6424223043008674ad83cae575b6
54cd2cca6dea49b4f96f50b4a54db2673edff478
/51CTO下载-钱能c++第二版源码/ch12/f1205.cpp
198746ae63648842c2ce9a461632872fcde495f9
[]
no_license
fashioning/Leetcode
2b13dec74af05b184844da177c98249897204206
2a21c369afa3509806c748ac60867d3a0da70c94
refs/heads/master
2020-12-30T10:23:17.562412
2018-10-22T14:19:06
2018-10-22T14:19:06
40,231,848
0
0
null
2018-10-22T14:19:07
2015-08-05T07:40:24
C++
WINDOWS-1252
C++
false
false
590
cpp
f1205.cpp
//===================================== // f1205.cpp // Ð麯Êý //===================================== #include<iostream> using namespace std; //------------------------------------- class Base{ public: virtual void fn(){ cout <<"In Base class\n"; } };//----------------------------------- class Sub : public Base{ public: virtual void fn(){ cout <<"In Sub class\n"; } };//----------------------------------- void test(Base& b){ b.fn(); }//------------------------------------ int main(){ Base bc; Sub sc; test(bc); test(sc); }//====================================
a24bf257fd49cc1b78946a3d022734cf3c2e3716
6fc94468f49fddb1166b34db9c6120682538d824
/C.S.P0008/C.S.P0008/main.cpp
ebc6ea71f12acb2086eb4386d0585d5c1e96aad8
[]
no_license
hungndse130670/SE130670_2
7cadaae1038084967dd993b3d885ebe3fb7c5af3
5e669843946e065d8b61d597da909a6f936bf15e
refs/heads/master
2022-11-21T08:37:12.734311
2020-07-20T05:58:04
2020-07-20T05:58:04
281,025,974
0
0
null
null
null
null
UTF-8
C++
false
false
553
cpp
main.cpp
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: main.cpp * Author: duchu * * Created on June 5, 2020, 1:42 PM */ #include <cstdlib> #include <stdio.h> using namespace std; /* * */ int main(int argc, char** argv) { char c[1000]; printf("Enter a string: "); fgets(c, sizeof (c), stdin); int count = 0; while (c[count] != '\0'){ } return 0; }
b2f5bb339ae92a373e9b792f9f29a860f7ed9beb
26c825925b8b9e90b2db4fd2d4144ad9bf8517c4
/sources/SLAM/Frame/CalcNormalMap.cpp
9fc4cca970ac99d15fb8d15826caaf80be761092
[]
no_license
neophack/Cross-Platform-Dense-SLAM
f4051a09817716c757dfe8a69bc32df283c3b5d8
45ee66abff199f10ea3ee4039577c55a2b3ae952
refs/heads/master
2023-03-17T21:23:16.782906
2018-11-29T11:20:43
2018-11-29T11:20:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
442
cpp
CalcNormalMap.cpp
#include "CalcNormalMap.h" namespace rgbd { CalcNormalMap::CalcNormalMap( const gl::Shader::Ptr prog ) : prog(prog) { } void CalcNormalMap::execute( gl::Texture::Ptr srcVertexMap, gl::Texture::Ptr dstNormalMap ) { prog->use(); srcVertexMap->bindImage(0, GL_READ_ONLY); dstNormalMap->bindImage(1, GL_WRITE_ONLY); glDispatchCompute(dstNormalMap->getWidth() / 20, dstNormalMap->getHeight() / 20, 1); prog->disuse(); } }
a44714c34447b5a221235a1dd3fdc2a7abf45995
94788a3a6d5636b280daaae9879220143001826b
/INO/20180915_internet/20180915_internet.ino
7454b39a3b9568156fffe407dcef353ab15dbc89
[]
no_license
LeoLovina/Arduino
2100922d0e056fbfdacdd8b09017ef4f9912d289
a1476b41967e9e7a21996d3963a05008e86ff394
refs/heads/master
2020-03-28T07:34:25.965332
2018-11-04T01:54:26
2018-11-04T01:54:26
147,910,300
0
0
null
null
null
null
UTF-8
C++
false
false
1,241
ino
20180915_internet.ino
/* d1 min board 1. 利用 D3 讀取 switch (設定為 Input_Pullup) 2. 使用 ESP8266WiFi 程式庫 連線 wifi wifi by 陳建榮 This example code is in the public domain. */ #include <ESP8266WiFi.h> #define READ_PIN 0 // GPIO: 0, d1 min:D3 #define D1 5 // GPIO: 5, d1 min D1 #define D0 16 // GPIO: 16, d1 min D0 unsigned long previousTime = 0; void setup() { // initialize wifi Serial.begin(115200); Serial.println(); WiFi.begin("505-AP", "mis505505"); Serial.print("Connecting"); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(); Serial.print("Connected, IP address: "); Serial.println(WiFi.localIP()); pinMode(READ_PIN, INPUT_PULLUP) ; pinMode(D1, OUTPUT) ; pinMode(D0, OUTPUT) ; } void loop() { bool switchValue = !digitalRead(READ_PIN); // Serial.println(switchValue); unsigned long currentTime = millis(); if (abs(currentTime - previousTime) > 1000) { previousTime = currentTime; controlLED(switchValue); } } void controlLED(bool switchValue) { if (switchValue) { digitalWrite(D0, HIGH); digitalWrite(D1, HIGH); } else { digitalWrite(D0, LOW); digitalWrite(D1, LOW); } }
4ed165327d055ec100ab3087ad0a01fb8b9a68d5
02b65e4c746f4abe0f14ea3b71c7cfb44479675a
/5.21.homework.3..cpp
58a66f794c644d1c32fd79322f94a144876dc70b
[]
no_license
bayraa77/5.21.homework
988f28dc5542bf27efed818562e7ab8e895eafa2
5cbee31d72d18dee9935046143858346ebe81d52
refs/heads/main
2023-05-07T19:35:53.145646
2021-06-01T05:47:55
2021-06-01T05:47:55
369,733,671
0
0
null
null
null
null
UTF-8
C++
false
false
367
cpp
5.21.homework.3..cpp
#include<iostream> using namespace std; int main(){ char a; cout<<" enter any letter : "; cin>>a; switch(a){ case 'a': case 'A': case 'e': case 'E': case 'i': case 'I': case 'o': case 'O': case 'u': case 'U': cout<<" this is a vowel "; break; default : cout<<" this is a consonant"; } }
24b444adfcaa4f1a21e512fa4f282846fcd27943
e5bc91dfb180a7b2fae9cd6d2cc96bbb16d3cfda
/CodeinC.cpp
89cb290f48455c3bc99dffdc9e48c1ebfb2c8401
[]
no_license
NobleLip/AssemblyComparer
631816bfc42a2ddba08fd77772761ee3c7d80aae
e89553887bd8045d83875a7575c2fdc3258a4a58
refs/heads/main
2023-05-12T22:29:35.573835
2021-05-31T22:56:33
2021-05-31T22:56:33
372,199,341
0
0
null
null
null
null
UTF-8
C++
false
false
3,726
cpp
CodeinC.cpp
#include "stdio.h" #include "conio.h" #include <stdlib.h> #include "string.h" #include <time.h> #include <malloc.h> #ifdef _WIN32 #include <intrin.h> #else #include <x86intrin.h> #endif #define Tamanho 1000000 extern "C" { //indicate that we have an external function void binarize(unsigned char, unsigned char*, int); } void Graf(unsigned __int64 Grafico[], int Max) { for (int z = 0; z < 50; z++) { if ((Max - z * 40000) / (1000000) >= 1 || (Max - z * 40000) / (1000000) == 2 && (Max - z * 40000) / (1000000) <= 2) { printf("\n%d |", Max - z * 40000); } else if (((Max - z * 40000) / (100000) >= 1 && (Max - z * 40000) / (100000) <= 9)) { printf("\n%d |", Max - z * 40000); } else { printf("\n%d |", Max - z * 40000); } for (int i = 0; i < 100; i++) { if (Grafico[i] / (Max - (z * 40000)) >= 1) { printf("#"); } else { printf(" "); } } } printf("\n\n\n"); } int main(int argc, char* argv[]) { unsigned char Limite = 56; unsigned char* ArrayChar; ArrayChar = (unsigned char*)malloc(Tamanho); unsigned char* ArrayChar1; ArrayChar1 = (unsigned char*)malloc(Tamanho); unsigned __int64 ArrayTempos[100]; unsigned __int64 Grafico[100]; unsigned __int64 initial_counter, final_counter, initial_counter1, final_counter1; for (int z = 0; z < 100; z++) { for (int i = 0; i < Tamanho; i++) { ArrayChar[i] = i; } initial_counter = __rdtsc(); binarize(Limite, ArrayChar, Tamanho); final_counter = __rdtsc(); ArrayTempos[z] = (final_counter - initial_counter); } int Soma = 0; int Minimo = ArrayTempos[0]; int Maximo = ArrayTempos[0]; for (int i = 0; i < 100; i++) { Grafico[i] = ArrayTempos[i]; } Graf(Grafico, 2000000); for (int i = 0; i < 100; i++) { if (i % 10 == 0 && i !=0 ) { printf("\n"); } printf("%I64d ", ArrayTempos[i]); Soma += ArrayTempos[i]; if (Minimo > ArrayTempos[i]) { Minimo = ArrayTempos[i]; } if (Maximo < ArrayTempos[i]) { Maximo = ArrayTempos[i]; } } unsigned __int64 temp; for (int i = 0; i < 100; i++) { for (int j = i + 1; j < 100; j++) { if (ArrayTempos[i] > ArrayTempos[j]) { temp = ArrayTempos[i]; ArrayTempos[i] = ArrayTempos[j]; ArrayTempos[j] = temp; } } } printf("\n\nMedia Ciclos de Clock = %d\nMaximo de Clocks = %d\nMinimo de Clocks = %d\nMediana d Clocks = %d\n\n\n", Soma/100, Maximo, Minimo, (ArrayTempos[49]+ ArrayTempos[50])/2); unsigned __int64 ArrayTempos1[100]; unsigned __int64 Grafico1[100]; for (int z = 0; z < 100; z++) { for (int i = 0; i < Tamanho; i++) { ArrayChar1[i] = i; } initial_counter1 = __rdtsc(); for (int i = 0; i < Tamanho; i++) { if (ArrayChar1[i] < Limite) { ArrayChar1[i] = 0; } else { ArrayChar1[i] = 255; } } final_counter1 = __rdtsc(); ArrayTempos1[z] = (final_counter1 - initial_counter1); } Soma = 0; Minimo = ArrayTempos1[0]; Maximo = ArrayTempos1[0]; for (int i = 0; i < 100; i++) { Grafico1[i] = ArrayTempos1[i]; } Graf(Grafico1, 5000000); for (int i = 0; i < 100; i++) { if (i % 10 == 0 && i != 0) { printf("\n"); } printf("%I64d ", ArrayTempos1[i]); Soma += ArrayTempos1[i]; if (Minimo > ArrayTempos1[i]) { Minimo = ArrayTempos1[i]; } if (Maximo < ArrayTempos1[i]) { Maximo = ArrayTempos1[i]; } } for (int i = 0; i < 100; i++) { for (int j = i + 1; j < 100; j++) { if (ArrayTempos1[i] > ArrayTempos1[j]) { temp = ArrayTempos1[i]; ArrayTempos1[i] = ArrayTempos1[j]; ArrayTempos1[j] = temp; } } } printf("\n\nMedia Ciclos de Clock = %d\nMaximo de Clocks = %d\nMinimo de Clocks = %d\nMediana d Clocks = %d\n\n\n", Soma / 100, Maximo, Minimo, (ArrayTempos1[49] + ArrayTempos1[50]) / 2); }
c3598dde7556818b07e0097868cd08b64a751418
fa1a685e8c3dd2fb1f2ce422779b5602e1d4b770
/automapping/src/PosicionAdyacente.h
6e2af0a1027488035a28ae197ff2f94da3affdc7
[]
no_license
nFichin/automapper
1f15392b8f5eaaabf8de630f0126b25f54a07cf6
2820ddd3d89d9e41f988cad14ae293cdcd018d38
refs/heads/master
2020-04-22T10:46:25.018895
2013-05-19T18:17:46
2013-05-19T18:17:46
9,200,513
1
0
null
null
null
null
UTF-8
C++
false
false
486
h
PosicionAdyacente.h
#ifndef POSICIONADYACENTE_H_ #define POSICIONADYACENTE_H_ #include "Posicion.h" enum ladoAdyacencia_t{ DERECHA = 0x01, IZQUIERDA = 0x02, ARRIBA = 0x03, ABAJO = 0x04 }; class PosicionAdyacente: public Posicion { public: ladoAdyacencia_t ladoAdyacencia; PosicionAdyacente(int fila,int columna,ladoAdyacencia_t ladoAdyacencia); virtual ~PosicionAdyacente(); static ladoAdyacencia_t DireccionOpuesta(ladoAdyacencia_t lado); }; #endif /* POSICIONADYACENTE_H_ */
480debdd120c869ee10cdb0c5e372e60bf33567a
a1b1a844881146b1e678063f3b98164a74b69521
/demo/Examples/animate-bmp.cpp
895d74cbf216adf885b517d3a292932bbf25dabe
[]
no_license
qPCR4vir/myNana
9378655fbba2f14bc612ae795233fe7a2150e426
5d00798dc770895defeb0cb3a859816f0f0c25e2
refs/heads/master
2021-01-22T01:27:43.503510
2015-11-11T08:45:05
2015-11-11T08:45:05
27,862,064
1
0
null
null
null
null
UTF-8
C++
false
false
525
cpp
animate-bmp.cpp
#include <nana/gui/wvl.hpp> #include <nana/gui/animation.hpp> int main() { using namespace nana::gui; //Build frames frameset fset; fset.push_back(nana::paint::image(STR("a_pic0.bmp"))); fset.push_back(nana::paint::image(STR("a_pic1.bmp"))); fset.push_back(nana::paint::image(STR("a_pic2.bmp"))); //A widget to display animation. form fm; fm.show(); animation ani; ani.push_back(fset); ani.output(fm, nana::point()); ani.looped(true); ani.play(); exec(); }
f3e432ae0f7ebcddefbf1ff9d32a26a597c07993
091afb7001e86146209397ea362da70ffd63a916
/inst/include/nt2/core/include/functions/rng.hpp
506ec2ed204e125252e1b85e7730d077e0c35f59
[]
no_license
RcppCore/RcppNT2
f156b58c08863243f259d1e609c9a7a8cf669990
cd7e548daa2d679b6ccebe19744b9a36f1e9139c
refs/heads/master
2021-01-10T16:15:16.861239
2016-02-02T22:18:25
2016-02-02T22:18:25
50,460,545
15
1
null
2019-11-15T22:08:50
2016-01-26T21:29:34
C++
UTF-8
C++
false
false
151
hpp
rng.hpp
#ifndef NT2_CORE_INCLUDE_FUNCTIONS_RNG_HPP_INCLUDED #define NT2_CORE_INCLUDE_FUNCTIONS_RNG_HPP_INCLUDED #include <nt2/core/functions/rng.hpp> #endif
a1dfab2bd9f2812fdc888d198ee03586b136f893
1b9484f051414df045b4be62d44b2e095ba5a71f
/include/ofp/header.h
e3e4a390937c94d6f1db7234f0254235a3fecb06
[ "MIT" ]
permissive
byllyfish/oftr
be1ad64864e56911e669849b4a40a2ef29e2ba3e
5368b65d17d57286412478adcea84371ef5e4fc4
refs/heads/master
2022-02-17T15:37:56.907140
2022-02-01T04:24:44
2022-02-01T04:24:44
13,504,446
1
1
MIT
2022-02-01T04:24:44
2013-10-11T16:59:19
C++
UTF-8
C++
false
false
1,443
h
header.h
// Copyright (c) 2015-2018 William W. Fisher (at gmail dot com) // This file is distributed under the MIT License. #ifndef OFP_HEADER_H_ #define OFP_HEADER_H_ #include "ofp/byteorder.h" #include "ofp/constants.h" namespace ofp { class Header { public: explicit Header(OFPType type) : type_{type} {} UInt8 version() const { return version_; } void setVersion(UInt8 version) { version_ = version; } OFPType type() const { return type_; } void setType(OFPType type) { type_ = type; } void setRawType(UInt8 type) { type_ = static_cast<OFPType>(type); } UInt16 length() const { return length_; } void setLength(size_t length) { assert(length <= OFP_MAX_SIZE); length_ = UInt16_narrow_cast(length); } UInt32 xid() const { return xid_; } void setXid(UInt32 xid) { xid_ = xid; } static OFPType translateType(UInt8 version, UInt8 type, UInt8 newVersion); bool validateInput(UInt8 negotiatedVersion) const; bool validateVersionAndType() const; private: Big8 version_ = 0; // OFP_VERSION. OFPType type_; // One of the OFPT_ constants. Big16 length_ = 0; // Length including this ofp_header. Big32 xid_ = 0; // Transaction id for this packet. template <class T> friend struct llvm::yaml::MappingTraits; }; static_assert(sizeof(Header) == 8, "Unexpected size."); static_assert(IsStandardLayout<Header>(), "Expected standard layout."); } // namespace ofp #endif // OFP_HEADER_H_
8360002a613ad03d460fabfdeaeb1f9441f10df5
d961ba1a3832a475feba8d8a6171886fe22c5767
/imu/imu.ino
582d895bc84b005bc8e2113f6f6867b253cc93b2
[]
no_license
hfrk/arduino
d42d8bb60eb42dd5fb0cfd97344d0ac811748195
10c64978fae2ed1496198e6a72cbc39686d9e770
refs/heads/main
2023-07-21T16:56:16.077586
2021-09-10T09:29:51
2021-09-10T09:29:51
312,867,081
0
0
null
null
null
null
UTF-8
C++
false
false
945
ino
imu.ino
#include "Sensor.h" MPU6050 mpu; Magnetometer mag; TENDOF dof10; void setup(){ Serial.begin(57600); Wire.begin(); Wire.setClock(400000); delay(100); mpu.initialize(); mag.initialize(); dof10.initialize(); delay(100); } void loop(){ reading_sensor(); } void reading_sensor(){ float fdata[3]; // temporary data holder mpu.getAccScaled(fdata); Serial.println("MPU6050 reading:"); Serial.println("roll angle: " + String(mpu.getRoll(fdata)) + " deg"); Serial.println("pitch angle: " + String(mpu.getPitch(fdata)) + " deg"); mag.readMagScaled(fdata); Serial.println("Magnetometer reading:"); Serial.println("heading: " + String(mag.getHeading(fdata[0], fdata[1])) + " deg"); dof10.getAccScaled(fdata); Serial.println("10-DOF reading:"); Serial.println("roll angle: " + String(dof10.getRoll(fdata)) + " deg"); Serial.println("pitch angle: " + String(dof10.getPitch(fdata)) + " deg"); delay(100); }
0a8d10b6cd80520e5d47fd024d3cde9bd0407e7b
67a52ef3f5785d465795940b73eab47667b477e6
/exlib/include/utils_arm.h
24d3e85c307a6fb38f957bd88fc98dffdc5e7603
[]
no_license
FIBOSIO/fibjs_vender
3ae706e0ea81edfc36358f47e28d07bcd5e28530
c7d03a8193a708e9513a31df576af9b0fefa745c
refs/heads/master
2020-03-18T11:27:15.843237
2018-03-31T17:05:39
2018-03-31T17:05:39
134,672,385
1
1
null
null
null
null
UTF-8
C++
false
false
3,316
h
utils_arm.h
/* * utils_arm.h * Created on: Jul 10, 2014 * * Copyright (c) 2014 by Leo Hoo * lion@9465.net */ namespace exlib { #pragma pack(1) class registers { public: intptr_t r0; intptr_t r1; intptr_t r2; intptr_t r3; intptr_t r4; intptr_t r5; intptr_t r6; intptr_t r7; intptr_t r8; intptr_t r9; intptr_t r10; union { intptr_t r11; intptr_t fp; }; intptr_t r12; union { intptr_t r13; intptr_t sp; }; union { intptr_t r14; intptr_t lr; }; }; #pragma pack() typedef void (*LinuxKernelMemoryBarrierFunc)(void); inline void MemoryBarrier() { (*(LinuxKernelMemoryBarrierFunc)0xffff0fa0)(); } inline void yield() { __asm__ volatile("mov r0,r0 @ nop"); } template <typename T> inline T* CompareAndSwap(T* volatile* ptr, T* old_value, T* new_value) { T *oldval, *res; do { __asm__ volatile( "ldrex %0, [%3]\n" "mov %1, #0\n" "cmp %0, %4\n" #ifdef __thumb2__ "it eq\n" #endif "strexeq %1, %5, [%3]\n" : "=&r"(oldval), "=&r"(res), "+m"(*ptr) : "r"(ptr), "r"(old_value), "r"(new_value) : "cc", "memory"); } while (res != 0); return oldval; } inline intptr_t CompareAndSwap(volatile intptr_t* ptr, intptr_t old_value, intptr_t new_value) { intptr_t oldval, res; do { __asm__ volatile( "ldrex %0, [%3]\n" "mov %1, #0\n" "cmp %0, %4\n" #ifdef __thumb2__ "it eq\n" #endif "strexeq %1, %5, [%3]\n" : "=&r"(oldval), "=&r"(res), "+m"(*ptr) : "r"(ptr), "r"(old_value), "r"(new_value) : "cc", "memory"); } while (res != 0); return oldval; } inline intptr_t atom_add(volatile intptr_t* dest, intptr_t incr) { intptr_t value; intptr_t res; do { __asm__ volatile( "ldrex %0, [%3]\n" "add %0, %0, %4\n" "strex %1, %0, [%3]\n" : "=&r"(value), "=&r"(res), "+m"(*dest) : "r"(dest), "r"(incr) : "cc", "memory"); } while (res); return value; } inline intptr_t atom_inc(volatile intptr_t* dest) { return atom_add(dest, 1); } inline intptr_t atom_dec(volatile intptr_t* dest) { return atom_add(dest, -1); } inline intptr_t atom_xchg(volatile intptr_t* ptr, intptr_t new_value) { intptr_t old_value; intptr_t res; do { __asm__ volatile( "ldrex %0, [%3]\n" "strex %1, %4, [%3]\n" : "=&r"(old_value), "=&r"(res), "+m"(*ptr) : "r"(ptr), "r"(new_value) : "cc", "memory"); } while (res != 0); return old_value; } template <typename T> inline T* atom_xchg(T* volatile* ptr, T* new_value) { T* old_value; T* res; do { __asm__ volatile( "ldrex %0, [%3]\n" "strex %1, %4, [%3]\n" : "=&r"(old_value), "=&r"(res), "+m"(*ptr) : "r"(ptr), "r"(new_value) : "cc", "memory"); } while (res != 0); return old_value; } inline void* CompareAndSwap(void* volatile* ptr, void* old_value, void* new_value) { return CompareAndSwap((char* volatile*)ptr, (char*)old_value, (char*)new_value); } }
d9632bce4b081f26590824a8c24f180edb87a279
f1c5d59a93aa613f2727a8c1696a8238f61f8dd0
/Linked List/insertData.cpp
2653dc7a6d530ac4c2e1655b8858859136c6de10
[ "MIT" ]
permissive
FahimMuntashir/theAlgorithms
fd0563c7a1931194000ddfae3c8ea02dbd67e8f3
58348ea5c45059121a1cf83b8f99b4ac46973f01
refs/heads/main
2023-07-18T17:24:34.490169
2021-09-08T16:31:16
2021-09-08T16:31:16
302,953,947
0
0
null
null
null
null
UTF-8
C++
false
false
1,196
cpp
insertData.cpp
/* * * Author : Fahim Muntashir * Handle: f12r * */ #include <bits/stdc++.h> using namespace std; #define f12r ios_base::sync_with_stdio(false), cin.tie(NULL) const double EPSILON = 1e-9; #define MOD 1000000007 #define pi acos(-1) #define ll long long #define endl "\n" /********** Main() function **********/ struct Node { int data; struct Node *link; }; struct Node* insertData(struct Node *head, int data) { struct Node *temp; temp = new Node; temp->data = data; temp->link = nullptr; head->link = temp; return temp; } void display(struct Node *head) { if (head == nullptr) { cout << "empty list" << endl; } while (head != nullptr) { cout << head->data << " "; head = head->link; } cout << endl; } int main() { f12r; struct Node *head = nullptr; head = new Node; head->data = 10; struct Node *current = nullptr; current =head; current = insertData(current, 20); current = insertData(current, 30); current = insertData(current, 40); current = head; display(head); // insertData(head, 100); // display(head); return 0; }
1500b88ce73bc89c830af8d85eef93ca748b557f
8c8820fb84dea70d31c1e31dd57d295bd08dd644
/MediaUtils/Public/MediaRecorder.h
4619803beed6ecbc0c818bd1c29b2302fe2cfad4
[]
no_license
redisread/UE-Runtime
e1a56df95a4591e12c0fd0e884ac6e54f69d0a57
48b9e72b1ad04458039c6ddeb7578e4fc68a7bac
refs/heads/master
2022-11-15T08:30:24.570998
2020-06-20T06:37:55
2020-06-20T06:37:55
274,085,558
3
0
null
null
null
null
UTF-8
C++
false
false
3,163
h
MediaRecorder.h
// Copyright Epic Games, Inc. All Rights Reserved. #pragma once #include "CoreTypes.h" #include "Async/Future.h" #include "IImageWrapper.h" #include "MediaSampleQueue.h" #include "Misc/Timespan.h" #include "Templates/SharedPointer.h" class FMediaPlayerFacade; class FMediaRecorderClockSink; class IImageWriteQueue; /** * Records samples from a media player. * Loop, seek or reverse and not supported. * Currently only records texture samples and that support sample format 8bit BGRA, half float RBGA */ class MEDIAUTILS_API FMediaRecorder { public: /** Default constructor. */ FMediaRecorder(); public: enum class EMediaRecorderNumerationStyle { AppendFrameNumber, AppendSampleTime }; struct FMediaRecorderData { /** The media player facade to record from. */ TSharedRef<FMediaPlayerFacade, ESPMode::ThreadSafe> PlayerFacade; /** BaseFilename(including with path and filename) for each recorded frames. */ FString BaseFilename; /** How to numerate the filename. */ EMediaRecorderNumerationStyle NumerationStyle; /** The format to save the image to. */ EImageFormat TargetImageFormat; /** If the format support it, set the alpha to 1 (or 255) */ bool bResetAlpha; /** * An image format specific compression setting. * For EXRs, either 0 (Default) or 1 (Uncompressed) * For others, a value between 1 (worst quality, best compression) and 100 (best quality, worst compression) */ int32 CompressionQuality; FMediaRecorderData(const TSharedRef<FMediaPlayerFacade, ESPMode::ThreadSafe>& InPlayerFacade, const FString& InBaseFilename) : PlayerFacade(InPlayerFacade) , BaseFilename(InBaseFilename) , NumerationStyle(EMediaRecorderNumerationStyle::AppendSampleTime) , TargetImageFormat(EImageFormat::EXR) , bResetAlpha(false) , CompressionQuality(0) { } }; public: /** * Start recording samples from a given media player. */ void StartRecording(const FMediaRecorderData& InRecoderData); /** * Stop recording media samples. */ void StopRecording(); /** * Is currently recording media samples. */ bool IsRecording() const { return bRecording; } /** * Blocking call that will wait for all frames to be recorded before returning. */ bool WaitPendingTasks(const FTimespan& InDuration); protected: /** * Tick the recorder. * * @param Timecode The current timecode. */ void TickRecording(); private: friend class FMediaRecorderClockSink; /** The recorder's media clock sink. */ TSharedPtr<FMediaRecorderClockSink, ESPMode::ThreadSafe> ClockSink; /** Texture sample queue. */ TSharedPtr<FMediaTextureSampleQueue, ESPMode::ThreadSafe> SampleQueue; /** Whether recording is in progress. */ bool bRecording; /** Warning for unsupported format have been showed. */ bool bUnsupportedWarningShowed; /** Number of frames recorded. */ int32 FrameCount; /** Media Recorder Data saved options. */ FString BaseFilename; EMediaRecorderNumerationStyle NumerationStyle; EImageFormat TargetImageFormat; bool bSetAlpha; int32 CompressionQuality; /** The image writer. */ IImageWriteQueue* ImageWriteQueue; TFuture<void> CompletedFence; };
952a033e04a77cf4da8a1d813218eb5ff29be5b0
5c9a7a6eb22704a39039ff8375ab8d932b682a4f
/audioplayer/src/main/cpp/audio-lib.cpp
bf05162611dbfa5cb95410917cbe443c3d255f5e
[]
no_license
guchengzhi/JniExample
0badcb15faf0b2721987ecf999b66da3f82332f0
80757cb8056d4eb32e273c6c8e5b530fda0c5549
refs/heads/master
2022-03-11T13:17:32.886399
2019-02-07T09:33:59
2019-02-07T09:33:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,240
cpp
audio-lib.cpp
#include <jni.h> #include <string> // //extern "C" { //#include <libavformat/avformat.h> //} #include "FFmpeg.h" JavaVM *jvm = NULL; FFmpeg *ffmpeg = NULL; CallJava *callJava = NULL; PlayStatus *playStatus = NULL; //native 退出 bool nexit = true; pthread_t pthread_start; extern "C" JNIEXPORT void JNICALL Java_com_example_audioplayer_player_AudioPlayer__1prepare(JNIEnv *env, jobject instance, jstring source_) { const char *source = env->GetStringUTFChars(source_, 0); LOGD("source:%s", source) if (ffmpeg == NULL) { if (callJava == NULL) { callJava = new CallJava(env, jvm, &instance); } playStatus = new PlayStatus(); callJava->onCallOnLoad(MAIN_THREAD, true); ffmpeg = new FFmpeg(playStatus, callJava, source); ffmpeg->prepare(); } } void *callback_start(void *data) { FFmpeg *ffmpeg = (FFmpeg *) data; if (ffmpeg != NULL) { ffmpeg->start(); } pthread_exit(&pthread_start); } extern "C" JNIEXPORT void JNICALL Java_com_example_audioplayer_player_AudioPlayer__1start(JNIEnv *env, jobject instance) { pthread_create(&pthread_start, NULL, callback_start, ffmpeg); } extern "C" JNIEXPORT void JNICALL Java_com_example_audioplayer_player_AudioPlayer__1pause(JNIEnv *env, jobject instance) { if (ffmpeg != NULL) { ffmpeg->pause(); } } extern "C" JNIEXPORT void JNICALL Java_com_example_audioplayer_player_AudioPlayer__1resume(JNIEnv *env, jobject instance) { if (ffmpeg != NULL) { ffmpeg->resume(); } } extern "C" JNIEXPORT void JNICALL Java_com_example_audioplayer_player_AudioPlayer__1stop(JNIEnv *env, jobject instance) { if (!nexit) { return; } nexit = false; jclass jcls = env->GetObjectClass(instance); jmethodID onCallPlayNextMethodId = env->GetMethodID(jcls, "onCallPlayNext", "()V"); if (ffmpeg != NULL) { ffmpeg->release(); delete (ffmpeg); ffmpeg = NULL; //真正的delete if (callJava != NULL) { delete (callJava); callJava = NULL; } if (playStatus != NULL) { delete (playStatus); playStatus = NULL; } } LOGD("audio-lib 释放完毕") nexit = true; env->CallVoidMethod(instance, onCallPlayNextMethodId); } extern "C" JNIEXPORT void JNICALL Java_com_example_audioplayer_player_AudioPlayer__1seek(JNIEnv *env, jobject instance, jint seconds) { if (ffmpeg != NULL) { ffmpeg->seek(seconds); } } extern "C" JNIEXPORT void JNICALL Java_com_example_audioplayer_player_AudioPlayer__1setVolume(JNIEnv *env, jobject instance, jint percent) { if (ffmpeg != NULL) { ffmpeg->setVolume(percent); } } //在加载动态库时回去调用 JNI_Onload 方法,在这里可以得到 JavaVM 实例对象 JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) { JNIEnv *env; jvm = vm; if (vm->GetEnv((void **) &env, JNI_VERSION_1_6) != JNI_OK) { return -1; } return JNI_VERSION_1_6; }
d85f555cbdccb4dd17c183b55e7a7624864afeef
0eba0ae14b55c5894eebb65e0e28a98e4cbe44c7
/alLayer/alLayer.cpp
2fc6ec060615ad79f0b59ca5f1d4d596eaa75a98
[ "MIT" ]
permissive
Jedzia/alShaders
0d88e06b9a5bd25442d56fc359130ed1cc4f62fc
8e5b330ab6259aa56f85515a4b3b629923e9742d
refs/heads/master
2022-04-17T04:48:44.231126
2020-04-16T11:07:54
2020-04-16T11:07:54
255,810,508
8
3
null
null
null
null
UTF-8
C++
false
false
11,901
cpp
alLayer.cpp
#include "alUtil.h" #include <ai.h> #include <vector> #include <string> #include <cassert> #include "cryptomatte/cryptomatte.h" #include "aovs.h" AI_SHADER_NODE_EXPORT_METHODS(alLayer) struct ShaderData { // AOV names std::vector<AtString> aovs; std::vector<AtString> aovs_rgba; bool standardAovs; CryptomatteData* cryptomatte; }; enum alLayerParams { p_layer1, p_layer2, p_mix, p_debug, p_aov_diffuse_color, p_aov_direct_diffuse, p_aov_direct_diffuse_raw, p_aov_indirect_diffuse, p_aov_indirect_diffuse_raw, p_aov_direct_backlight, p_aov_indirect_backlight, p_aov_direct_specular, p_aov_indirect_specular, p_aov_direct_specular_2, p_aov_indirect_specular_2, p_aov_single_scatter, p_aov_sss, p_aov_refraction, p_aov_emission, p_aov_uv, p_aov_depth, p_aov_light_group_1, p_aov_light_group_2, p_aov_light_group_3, p_aov_light_group_4, p_aov_light_group_5, p_aov_light_group_6, p_aov_light_group_7, p_aov_light_group_8, p_aov_light_group_9, p_aov_light_group_10, p_aov_light_group_11, p_aov_light_group_12, p_aov_light_group_13, p_aov_light_group_14, p_aov_light_group_15, p_aov_light_group_16, p_aov_id_1, p_aov_id_2, p_aov_id_3, p_aov_id_4, p_aov_id_5, p_aov_id_6, p_aov_id_7, p_aov_id_8, p_aov_crypto_asset, p_aov_crypto_object, p_aov_crypto_material, p_aov_shadow_group_1, p_aov_shadow_group_2, p_aov_shadow_group_3, p_aov_shadow_group_4, p_aov_shadow_group_5, p_aov_shadow_group_6, p_aov_shadow_group_7, p_aov_shadow_group_8, p_aov_shadow_group_9, p_aov_shadow_group_10, p_aov_shadow_group_11, p_aov_shadow_group_12, p_aov_shadow_group_13, p_aov_shadow_group_14, p_aov_shadow_group_15, p_aov_shadow_group_16, p_standardAovs, p_aiEnableMatte, p_aiMatteColor, p_aiMatteColorA }; enum DebugModes { kOff = 0, kLayer1, kLayer2, kMixer }; static const char* debugModeNames[] = {"off", "layer1", "layer2", "mixer", NULL}; node_parameters { AiParameterRGB("layer1", 0.0f, 0.0f, 0.0f); AiParameterRGB("layer2", 0.0f, 0.0f, 0.0f); AiParameterFlt("mix", 0.0f); AiParameterEnum("debug", kOff, debugModeNames); AiParameterStr("aov_diffuse_color", "diffuse_color"); AiParameterStr("aov_direct_diffuse", "direct_diffuse"); AiParameterStr("aov_direct_diffuse_raw", "direct_diffuse_raw"); AiParameterStr("aov_indirect_diffuse", "indirect_diffuse"); AiParameterStr("aov_indirect_diffuse_raw", "indirect_diffuse_raw"); AiParameterStr("aov_direct_backlight", "direct_backlight"); AiParameterStr("aov_indirect_backlight", "indirect_backlight"); AiParameterStr("aov_direct_specular", "direct_specular"); AiParameterStr("aov_indirect_specular", "indirect_specular"); AiParameterStr("aov_direct_specular_2", "direct_specular_2"); AiParameterStr("aov_indirect_specular_2", "indirect_specular_2"); AiParameterStr("aov_single_scatter", "single_scatter"); AiParameterStr("aov_sss", "sss"); AiParameterStr("aov_refraction", "refraction"); AiParameterStr("aov_emission", "emission"); AiParameterStr("aov_uv", "uv"); AiParameterStr("aov_depth", "depth"); AiParameterStr("aov_light_group_1", "light_group_1"); AiParameterStr("aov_light_group_2", "light_group_2"); AiParameterStr("aov_light_group_3", "light_group_3"); AiParameterStr("aov_light_group_4", "light_group_4"); AiParameterStr("aov_light_group_5", "light_group_5"); AiParameterStr("aov_light_group_6", "light_group_6"); AiParameterStr("aov_light_group_7", "light_group_7"); AiParameterStr("aov_light_group_8", "light_group_8"); AiParameterStr("aov_light_group_9", "light_group_9"); AiParameterStr("aov_light_group_10", "light_group_10"); AiParameterStr("aov_light_group_11", "light_group_11"); AiParameterStr("aov_light_group_12", "light_group_12"); AiParameterStr("aov_light_group_13", "light_group_13"); AiParameterStr("aov_light_group_14", "light_group_14"); AiParameterStr("aov_light_group_15", "light_group_15"); AiParameterStr("aov_light_group_16", "light_group_16"); AiParameterStr("aov_id_1", "id_1"); AiParameterStr("aov_id_2", "id_2"); AiParameterStr("aov_id_3", "id_3"); AiParameterStr("aov_id_4", "id_4"); AiParameterStr("aov_id_5", "id_5"); AiParameterStr("aov_id_6", "id_6"); AiParameterStr("aov_id_7", "id_7"); AiParameterStr("aov_id_8", "id_8"); AiParameterStr("aov_crypto_asset", "crypto_asset"); AiParameterStr("aov_crypto_object", "crypto_object"); AiParameterStr("aov_crypto_material", "crypto_material"); AiParameterStr("aov_shadow_group_1", "shadow_group_1"); AiParameterStr("aov_shadow_group_2", "shadow_group_2"); AiParameterStr("aov_shadow_group_3", "shadow_group_3"); AiParameterStr("aov_shadow_group_4", "shadow_group_4"); AiParameterStr("aov_shadow_group_5", "shadow_group_5"); AiParameterStr("aov_shadow_group_6", "shadow_group_6"); AiParameterStr("aov_shadow_group_7", "shadow_group_7"); AiParameterStr("aov_shadow_group_8", "shadow_group_8"); AiParameterStr("aov_shadow_group_9", "shadow_group_9"); AiParameterStr("aov_shadow_group_10", "shadow_group_10"); AiParameterStr("aov_shadow_group_11", "shadow_group_11"); AiParameterStr("aov_shadow_group_12", "shadow_group_12"); AiParameterStr("aov_shadow_group_13", "shadow_group_13"); AiParameterStr("aov_shadow_group_14", "shadow_group_14"); AiParameterStr("aov_shadow_group_15", "shadow_group_15"); AiParameterStr("aov_shadow_group_16", "shadow_group_16"); AiParameterBool("standardCompatibleAOVs", false); AiParameterBool("aiEnableMatte", false); AiParameterRGB("aiMatteColor", 0.0f, 0.0f, 0.0f); AiParameterFlt("aiMatteColorA", 0.0f); } node_loader { if (i > 0) return 0; node->methods = alLayer; node->output_type = AI_TYPE_RGB; node->name = "alLayer"; node->node_type = AI_NODE_SHADER; strcpy(node->version, AI_VERSION); return true; } node_initialize { ShaderData* data = new ShaderData; data->cryptomatte = new CryptomatteData(); AiNodeSetLocalData(node, data); } node_finish { if (AiNodeGetLocalData(node)) { ShaderData* data = (ShaderData*)AiNodeGetLocalData(node); if (data->cryptomatte) delete data->cryptomatte; AiNodeSetLocalData(node, NULL); delete data; } } node_update { ShaderData* data = (ShaderData*)AiNodeGetLocalData(node); // set up AOVs REGISTER_AOVS data->standardAovs =AiNodeGetBool(node, "standardAovs"); data->cryptomatte->setup_all(AiNodeGetStr(node, "aov_crypto_asset"), AiNodeGetStr(node, "aov_crypto_object"), AiNodeGetStr(node, "aov_crypto_material")); } shader_evaluate { ShaderData* data = (ShaderData*)AiNodeGetLocalData(node); AtRGB result = AI_RGB_BLACK; AtRGB result_opacity = AI_RGB_WHITE; float mix = AiShaderEvalParamFlt(p_mix); int debug = AiShaderEvalParamEnum(p_debug); if (debug == kMixer) { result = AtRGB(mix, mix, mix); } else { if (debug == kLayer1) mix = 0.0f; else if (debug == kLayer2) mix = 1.0f; int als_raytype = ALS_RAY_UNDEFINED; AiStateGetMsgInt(AtString("als_raytype"), &als_raytype); if (als_raytype != ALS_RAY_SSS && mix >= (1.0f - IMPORTANCE_EPS)) { result = AiShaderEvalParamRGB(p_layer2); // ToDoJed: Fix for Porting->v6, opacity needs fix, out.CLOSURE() // result_opacity = sg->out_opacity; } else if (als_raytype != ALS_RAY_SSS && mix <= IMPORTANCE_EPS) { result = AiShaderEvalParamRGB(p_layer1); // ToDoJed: Fix for Porting->v6, opacity needs fix, out.CLOSURE() // result_opacity = sg->out_opacity; } else { if (sg->Rt & AI_RAY_CAMERA) // handle aovs { AiStateSetMsgInt(AtString("als_context"), ALS_CONTEXT_LAYER); // RGB AOVs AtRGB tmp[NUM_AOVs]; memset(tmp, 0, sizeof(AtRGB) * NUM_AOVs); AtRGB layer1 = AiShaderEvalParamRGB(p_layer1); // ToDoJed: Fix for Porting->v6, opacity needs fix, out.CLOSURE() // AtRGB layer1_opacity = sg->out_opacity; for (size_t i = 0; i < data->aovs.size(); ++i) { if (!AiAOVGetRGB(sg, data->aovs[i], tmp[i])) { tmp[i] = AI_RGB_BLACK; } AiAOVSetRGB(sg, data->aovs[i], AI_RGB_BLACK); } // RGBA AOVs AtRGBA tmp_rgba[NUM_AOVs_RGBA]; memset(tmp_rgba, 0, sizeof(AtRGBA) * NUM_AOVs_RGBA); for (size_t i = 0; i < data->aovs_rgba.size(); ++i) { if (!AiAOVGetRGBA(sg, data->aovs_rgba[i], tmp_rgba[i])) { tmp_rgba[i] = AI_RGBA_ZERO; } AiAOVSetRGBA(sg, data->aovs_rgba[i], AI_RGBA_ZERO); } AtRGB layer2 = AiShaderEvalParamRGB(p_layer2); result = lerp(layer1, layer2, mix); // ToDoJed: Fix for Porting->v6, opacity needs fix, out.CLOSURE() // result_opacity = lerp(layer1_opacity, sg->out_opacity, mix); for (size_t i = 0; i < data->aovs.size(); ++i) { AtRGB tmp2; if (!AiAOVGetRGB(sg, data->aovs[i], tmp2)) { tmp2 = AI_RGB_BLACK; } AiAOVSetRGB(sg, data->aovs[i], lerp(tmp[i], tmp2, mix)); } for (size_t i = 0; i < data->aovs_rgba.size(); ++i) { AtRGBA tmp_rgba2; if (!AiAOVGetRGBA(sg, data->aovs_rgba[i], tmp_rgba2)) { tmp_rgba2 = AI_RGBA_ZERO; } AiAOVSetRGBA(sg, data->aovs_rgba[i], lerp(tmp_rgba[i], tmp_rgba2, mix)); } AiStateSetMsgInt(AtString("als_context"), ALS_CONTEXT_NONE); } else // just layer the results { AiStateSetMsgInt(AtString("als_context"), ALS_CONTEXT_LAYER); AtRGB deepGroupTmp1[NUM_LIGHT_GROUPS]; AtRGB deepGroupTmp2[NUM_LIGHT_GROUPS]; memset(deepGroupTmp1, 0, sizeof(AtRGB) * NUM_LIGHT_GROUPS); memset(deepGroupTmp2, 0, sizeof(AtRGB) * NUM_LIGHT_GROUPS); AtRGB* deepGroupPtr = NULL; AtRGB layer1 = AiShaderEvalParamRGB(p_layer1); // ToDoJed: Fix for Porting->v6, opacity needs fix, out.CLOSURE() // AtRGB layer1_opacity = sg->out_opacity; if (AiStateGetMsgPtr(AtString("als_deepGroupPtr"), (void**)&deepGroupPtr)) { memcpy(deepGroupTmp1, deepGroupPtr, sizeof(AtRGB) * NUM_LIGHT_GROUPS); } AtRGB layer2 = AiShaderEvalParamRGB(p_layer2); result = lerp(layer1, layer2, mix); // ToDoJed: Fix for Porting->v6, opacity needs fix, out.CLOSURE() // result_opacity = lerp(layer1_opacity, sg->out_opacity, mix); if (AiStateGetMsgPtr(AtString("als_deepGroupPtr"), (void**)&deepGroupPtr)) { memcpy(deepGroupTmp2, deepGroupPtr, sizeof(AtRGB) * NUM_LIGHT_GROUPS); for (int i = 0; i < NUM_LIGHT_GROUPS; ++i) { deepGroupPtr[i] = lerp(deepGroupTmp1[i], deepGroupTmp2[i], mix); } } AiStateSetMsgInt(AtString("als_context"), ALS_CONTEXT_NONE); } } } sg->out.RGB() = result; // ToDoJed: Fix for Porting->v6, opacity needs fix, out.CLOSURE() // sg->out_opacity = result_opacity; data->cryptomatte->do_cryptomattes(sg, node, -1, -1, -1); }
1268c95dd894f60c398d01743d961ee8d1710d5c
da72a74bd754719826a27b12d690cb519a3e43ad
/kvs/include/metadata.hpp
0b698acd628922ab481b4596af9a5108a425aa79
[ "Apache-2.0" ]
permissive
arvindsankar/fluent
1b9c668a938cc8214d0e0109f0585fc0363c5094
fad6d46c64e6805e3feaaa5c14f4c7f1670515d4
refs/heads/master
2020-04-08T03:18:28.661383
2018-11-26T01:22:51
2018-11-26T01:22:51
158,970,417
1
0
Apache-2.0
2018-11-24T20:17:49
2018-11-24T20:17:49
null
UTF-8
C++
false
false
4,486
hpp
metadata.hpp
// Copyright 2018 U.C. Berkeley RISE Lab // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef SRC_INCLUDE_METADATA_HPP_ #define SRC_INCLUDE_METADATA_HPP_ #include "threads.hpp" const std::string kMetadataDelimiter = "|"; const char kMetadataDelimiterChar = '|'; // represents the replication state for each key struct KeyInfo { std::unordered_map<unsigned, unsigned> global_replication_map_; std::unordered_map<unsigned, unsigned> local_replication_map_; }; // per-tier metadata struct TierData { TierData() : thread_number_(1), default_replication_(1), node_capacity_(0) {} TierData(unsigned t_num, unsigned rep, unsigned long long node_capacity) : thread_number_(t_num), default_replication_(rep), node_capacity_(node_capacity) {} unsigned thread_number_; unsigned default_replication_; unsigned long long node_capacity_; }; inline bool is_metadata(Key key) { std::vector<std::string> v; split(key, '|', v); if (v[0] == kMetadataIdentifier) { return true; } else { return false; } } // NOTE: This needs to be here because it needs the definition of TierData extern std::unordered_map<unsigned, TierData> kTierDataMap; enum MetadataType { replication, server_stats, key_access, key_size }; inline Key get_metadata_key(const ServerThread& st, unsigned tier_id, unsigned thread_num, MetadataType type) { std::string suffix; switch (type) { case MetadataType::server_stats: suffix = "stats"; break; case MetadataType::key_access: suffix = "access"; break; case MetadataType::key_size: suffix = "size"; break; default: return ""; // this should never happen; see note below about // MetadataType::replication } return kMetadataIdentifier + kMetadataDelimiter + st.get_public_ip() + kMetadataDelimiter + st.get_private_ip() + kMetadataDelimiter + std::to_string(thread_num) + kMetadataDelimiter + std::to_string(tier_id) + kMetadataDelimiter + suffix; } // This version of the function should only be called with // MetadataType::replication, so if it's called with something else, we return // an empty string. // NOTE: There should probably be a less silent error check. inline Key get_metadata_key(std::string data_key, MetadataType type) { if (type == MetadataType::replication) { return kMetadataIdentifier + kMetadataDelimiter + data_key + kMetadataDelimiter + "replication"; } return ""; } inline Key get_key_from_metadata(Key metadata_key) { std::vector<std::string> tokens; split(metadata_key, '|', tokens); if (tokens[tokens.size() - 1] == "replication") { return tokens[1]; } return ""; } inline std::vector<std::string> split_metadata_key(Key key) { std::vector<std::string> tokens; split(key, kMetadataDelimiterChar, tokens); return tokens; } inline void warmup_placement_to_defaults( std::unordered_map<Key, KeyInfo>& placement, unsigned& kDefaultGlobalMemoryReplication, unsigned& kDefaultGlobalEbsReplication, unsigned& kDefaultLocalReplication) { for (unsigned i = 1; i <= 1000000; i++) { // key is 8 bytes Key key = std::string(8 - std::to_string(i).length(), '0') + std::to_string(i); placement[key].global_replication_map_[1] = kDefaultGlobalMemoryReplication; placement[key].global_replication_map_[2] = kDefaultGlobalEbsReplication; placement[key].local_replication_map_[1] = kDefaultLocalReplication; placement[key].local_replication_map_[2] = kDefaultLocalReplication; } } inline void init_replication(std::unordered_map<Key, KeyInfo>& placement, const Key& key) { for (const unsigned& tier_id : kAllTierIds) { placement[key].global_replication_map_[tier_id] = kTierDataMap[tier_id].default_replication_; placement[key].local_replication_map_[tier_id] = kDefaultLocalReplication; } } #endif // SRC_INCLUDE_METADATA_HPP_
181b9d403721b1b29dac2fbc4dae1992da9477a1
c31e83456a83457265abb75e70d9f3f4839dea24
/Problems/Strstr.cpp
6ae51bd756736241d1cff2a3fafb2da04f14ef3f
[]
no_license
valentin-stamate/Inline-Assembly-Problems
67b583a0c810f91ad5bdcbaf1dc1b364b190ff4d
53cadd0bd9fff6030eb61ffeee361086da248458
refs/heads/master
2023-08-12T20:37:49.300921
2020-02-02T20:49:19
2020-02-02T20:49:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
529
cpp
Strstr.cpp
int strstr(char*, char*) { _asm { mov ebx, [ebp + 8] mov ecx, [ebp + 12] mov esi, 0 while_1: cmp [ebx + 1 * esi], 0 je return_f push esi mov edi, 0 while_2: cmp [ecx + 1 * edi], 0 je continue_ mov al, [ebx + 1 * esi] cmp al, [ecx + 1 * edi] jne continue_ inc esi inc edi jmp while_2 continue_: pop esi cmp [ecx + 1 * edi], 0 je return_t; inc esi jmp while_1 return_f: mov eax, -1 jmp return_ return_t: mov eax, esi return_: } }
9460c719e6901165b69c88b4d7efabfd8428e65b
c33843ec1deea9f2917d28f7c8d71629e3733f66
/src/cpp/ee/core/WhenAny.hpp
40fa7a74faebfc5628967a8df09d34b85e9051fe
[ "MIT" ]
permissive
Senspark/ee-x
c7129f3cd7de8a0879f2079164727a05501e19b6
60a66ad3dc6e14802a7c5d8d585a8499be13f5b8
refs/heads/master
2023-08-20T07:19:27.472704
2021-08-19T03:04:35
2022-03-14T09:39:51
62,603,267
18
11
MIT
2023-05-08T03:33:24
2016-07-05T03:28:21
C++
UTF-8
C++
false
false
1,200
hpp
WhenAny.hpp
// // WhenAny.hpp // ee-x-d542b565 // // Created by eps on 1/8/21. // #ifndef EE_X_WHEN_ANY_HPP #define EE_X_WHEN_ANY_HPP #ifdef __cplusplus #include "ee/core/LambdaAwaiter.hpp" #include "ee/core/NoAwait.hpp" #include "ee/core/Task.hpp" namespace ee { namespace core { namespace detail { template <class T> void whenAnyHelper(const std::shared_ptr<bool>& flag, const std::function<void()>& resolve, T&& callable) { noAwait([flag, resolve, callable]() -> Task<> { co_await callable(); if (*flag) { *flag = false; resolve(); } }); } } // namespace detail template <class... Args> Task<> whenAny(Args&&... args) { auto callableTuple = std::forward_as_tuple(std::forward<Args>(args)...); auto flag = std::make_shared<bool>(true); co_await LambdaAwaiter<>([&callableTuple, flag](auto&& resolve) { std::apply( [flag, resolve](auto&&... callables) { ((detail::whenAnyHelper(flag, resolve, callables)), ...); }, callableTuple); }); } } // namespace core using core::whenAny; } // namespace ee #endif // __cplusplus #endif /* EE_X_WHEN_ANY_HPP */
382b5f17e52822e1915b91354b9b6c35e8472da8
805e7cb4f5d97f303f7175699c4b6007872baab1
/source/src/network/mitecom/mitecom-handler.cpp
154dd284446be2201ef2abe5c07a7b4fa740dbc9
[ "MIT" ]
permissive
electric-sheep-uc/black-sheep
0d1315af0a67759ad175fde4eff97fb57fd560d9
e908203d9516e01f90f4ed4c796cf4143d0df0c0
refs/heads/master
2020-06-24T01:15:50.109820
2019-07-25T09:56:53
2019-07-25T09:56:53
198,805,036
7
1
null
null
null
null
UTF-8
C++
false
false
3,321
cpp
mitecom-handler.cpp
#include "mitecom-handler.h" #include "mitecom-data.h" #include <assert.h> #include <stdio.h> #include <arpa/inet.h> /*------------------------------------------------------------------------------------------------*/ /** * Take an incoming message and check if the message was received correctly and store the data in * data struct defined in @mitecom-data.h * @param messageData * @param messageLength * @param teamID * @return */ MixedTeamMate MixedTeamParser::parseIncoming(const void* messageData, uint32_t messageLength, int teamID) { // test endianness, the default code only supports little endian, so a conversion between host byte order // and network byte order should cause a mismatch to the original value assert(htonl(0x12345678) != 0x12345678); MixedTeamMate mate; mate.robotID = 0; // mark as invalid const MixedTeamCommMessage *message = (const MixedTeamCommMessage*)messageData; // check magic bytes in header if ('MXTC' != message->messageMagic) { fprintf(stderr, "Magic value mismatch in received message.\n"); return mate; } // we currently support version 1 only if (1 != message->messageVersion) { fprintf(stderr, "Unsupported protocol received.\n"); return mate; } // check that we got the full message if (messageLength != sizeof(MixedTeamCommMessage) + sizeof(MixedTeamCommValueStruct) * message->messageLength) { fprintf(stderr, "Mismatched message length.\n"); return mate; } // only handle messages from members of our own team if (message->teamID != teamID) { return mate; } /* * create a mate and store its corresponding values */ mate.robotID = message->robotID; for (uint16_t index = 0; index < message->messageLength; index++) { MITECOM_KEYTYPE key = message->values[index].key; MITECOM_DATATYPE value = message->values[index].value; mate.data[key] = value; } return mate; } /*------------------------------------------------------------------------------------------------*/ /** ** Create the serialization of a team mate's information. The result of this ** function can be directly broadcasted. ** ** @param messageSizePtr pointer to an integer to store the size of the serialized message ** @param mate the team member data to serialize (see @mitecom-data.h) ** @param teamID the ID of the team this team mate belongs to ** @param robotID the ID of the robot ** ** @return pointer to allocated structure (must be released with free()) */ MixedTeamCommMessage *MixedTeamParser::create(uint32_t *messageSizePtr, const MixedTeamMate &mate, uint16_t teamID, uint16_t robotID) { uint32_t messageSize = sizeof(MixedTeamCommMessage) + mate.data.size() * sizeof(MixedTeamCommValue); *messageSizePtr = messageSize; MixedTeamCommMessage *msgPtr = (MixedTeamCommMessage*)malloc(messageSize); // FIXME msgPtr->messageMagic = 'MXTC'; msgPtr->messageVersion = 1; msgPtr->messageLength = mate.data.size(); msgPtr->messageFlags = 0; msgPtr->teamID = teamID; msgPtr->robotID = robotID; uint32_t index = 0; for (MixedTeamMateData::const_iterator it = mate.data.begin(); it != mate.data.end(); it++) { msgPtr->values[index].key = it->first; msgPtr->values[index].value = it->second; index++; } return msgPtr; }
95bc46924e531722d8fe5fe4d3b971b714284b44
7a44204672c44e103aad47f3afd18952fbd9afd0
/src/SupportClasses/SpikeStreamMapper.cpp
92af9710d56b6dd1312afe58c8074bd7b1c1fe2f
[ "MIT" ]
permissive
AuditoryBiophysicsLab/EarLab
202acdb79489ea903c20e45239a9a3ba820caeba
bc5ccc39076ee0419078e9ff5147e98f28fac3c9
refs/heads/master
2020-04-15T20:45:36.062819
2019-07-10T11:54:27
2019-07-10T11:54:27
27,502,131
3
1
null
2017-06-28T01:53:57
2014-12-03T18:47:42
C++
UTF-8
C++
false
false
2,763
cpp
SpikeStreamMapper.cpp
#include "SpikeStreamMapper.h" #include "EarlabException.h" #include <memory.h> SpikeStreamMapper::SpikeStreamMapper(int InputCellCount, int OutputCellCount, char *MapFileName) { FILE *fp; int curChar; int BitNumber = 0; int OutputCellID = 0; inputCellCount = InputCellCount; outputCellCount = OutputCellCount; mapFileName = MapFileName; MapArray = new char *[outputCellCount]; for (int outputCell = 0; outputCell < outputCellCount; outputCell++) { MapArray[outputCell] = new char [inputCellCount]; memset(MapArray[outputCell], 0, inputCellCount); } fp = fopen(mapFileName, "r"); if (fp == NULL) throw new EarlabException("SpikeStreamMapper: Error opening map file \"%s\"\n", mapFileName); while (!feof(fp)) { curChar = fgetc(fp); if (curChar == EOF) break; switch ((char)curChar) { case '1': MapArray[OutputCellID][BitNumber] = 1; BitNumber++; break; case '0': MapArray[OutputCellID][BitNumber] = 0; BitNumber++; break; case '\n': OutputCellID++; BitNumber = 0; break; default: break; } // switch ((char)curChar) //if (BitNumber >= inputCellCount) if (BitNumber > inputCellCount) // BitNumber should reach inputCellCount, then 10 ('\n') should be the next curChar throw new EarlabException("SpikeStreamMapper: Error initializing output channel %d. Input bitmap length is greater than %d", OutputCellID, inputCellCount); //if (OutputCellID >= outputCellCount) if (OutputCellID > outputCellCount) // OutputCellID should equal outputCellCount just before eof throw new EarlabException("SpikeStreamMapper: Error initializing output channel %d. Specified maximum output channel is %d", OutputCellID, outputCellCount); } // while (!feof(fp)) } // SpikeStreamMapper::SpikeStreamMapper(int InputCellCount, int OutputCellCount, char *MapFileName) SpikeStreamMapper::~SpikeStreamMapper() { for (int outputCell = 0; outputCell < outputCellCount; outputCell++) delete [] MapArray[outputCell]; delete [] MapArray; } int SpikeStreamMapper::CountMappedSpikes(SpikeStream *SpikeStream, int CellID) { int SpikeCount = 0; // Loop through all the cells in the input stream for (int InputCellID = 0; InputCellID < inputCellCount; InputCellID++) // If the current input cell is selected to be mapped to the specified output cell (CellID) // AND the current input cell has a spike in the current time step THEN bump the count of // spikes that are feeding the current input cell in this time step if ((MapArray[CellID][InputCellID] != 0) && (SpikeStream->CountSpikes(InputCellID) != 0)) SpikeCount++; // Return the count of selected spikes in the current time step return SpikeCount; }
77c639bd554af69c2611cf3fbcc6fb2a2eadc228
7bb673af6c51bb31e04d8dee7f840538e91c9f69
/include/Random.hpp
0a75e43779ee2d981528d665186836c22e64942e
[ "MIT" ]
permissive
grncbg/ANSL-NetworkSimulator
4166ad61d7abd1fe2ba2e3cadd1e20c328b87404
6a49390218518559e1ffaed6c91468e8873d90c0
refs/heads/master
2020-04-06T19:30:29.961183
2018-12-22T14:06:43
2018-12-22T14:06:43
157,739,666
0
0
MIT
2018-12-18T09:51:34
2018-11-15T16:19:17
C++
UTF-8
C++
false
false
1,708
hpp
Random.hpp
#ifndef INCLUDED_RANDOM_HPP #define INCLUDED_RANDOM_HPP // dorward declaration namespace boost::random { // mersenne_twister typedef __SIZE_TYPE__ size_t; typedef long unsigned int uint_fast64_t; template <class UIntType, size_t w, size_t n, size_t m, size_t r, UIntType a, size_t u, UIntType d, size_t s, UIntType b, size_t t, UIntType c, size_t l, UIntType f> class mersenne_twister_engine; using mt19937_64 = mersenne_twister_engine< uint_fast64_t, 64, 312, 156, 31, 0xb5026f5aa96619e9, 29, 0x5555555555555555,17, 0x71d67fffeda60000, 37, 0xfff7eee000000000, 43, 6364136223846793005 >; // poisson_distribution template <class IntType, class RealType> class poisson_distribution; // exponential_distribution template <class RealType> class exponential_distribution; } // // class Random // template <class T> class Random { // protected members protected: boost::random::mt19937_64* engine; // public functions public: Random(); virtual ~Random(); virtual T get() const = 0; virtual T operator()() const final; }; // // class Poison // class Poisson : public Random<int> { // private members private: boost::random::poisson_distribution<int, double>* poisson; // public functions public: Poisson(double); ~Poisson(); int get() const override; }; // // class Exponential // class Exponential : public Random<double> { // private members private: boost::random::exponential_distribution<double>* exponential; // public functions public: Exponential(double); ~Exponential(); double get() const override; }; #endif
4133943fc6c968c5211aa10c69f58cd20ac8a467
3443729995fcaf70d2cbcb2af604731ec1bc589a
/LeetCode/23. Merge k Sorted Lists.cpp
48b919df100055b3186f26be66e6471cea193fa4
[]
no_license
Altudy/solutionheejoon
dc8faca784307ac0bba214317dd26d6519fb440b
de49671d15487ba15f41487d24ea0b5a6c8ffcce
refs/heads/master
2021-07-01T17:30:22.107345
2021-02-01T13:43:10
2021-02-01T13:43:10
212,311,666
1
2
null
null
null
null
UTF-8
C++
false
false
1,998
cpp
23. Merge k Sorted Lists.cpp
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode* mergeKLists(vector<ListNode*>& lists) { priority_queue<ListNode*, vector<ListNode*>, cmp> pq; ListNode* ans = nullptr; if (lists.size() == 0) return ans; // make pq for (auto list : lists) { while (list != nullptr) { pq.push(list); list = list->next; } } ListNode* pre = nullptr; if (!pq.empty()) { ans = pq.top(); pre = pq.top(); pq.pop(); } while (!pq.empty()) { pre->next = pq.top(); pq.pop(); pre = pre->next; } if (pre != nullptr) pre->next = nullptr; return ans; } struct cmp { bool operator()(ListNode* a, ListNode* b) { return a->val > b->val; } }; }; /////////////////////////////////////////////////////// /* best solution class Solution { public: ListNode *mergeTwoLists(ListNode* l1, ListNode* l2) { if (NULL == l1) return l2; else if (NULL == l2) return l1; if (l1->val <= l2->val) { l1->next = mergeTwoLists(l1->next, l2); return l1; } else { l2->next = mergeTwoLists(l1, l2->next); return l2; } } ListNode *mergeKLists(vector<ListNode *> &lists) { if (lists.empty()) return NULL; int len = lists.size(); while (len > 1) { for (int i = 0; i < len / 2; ++i) { lists[i] = mergeTwoLists(lists[i], lists[len - 1 - i]); } len = (len + 1) / 2; } return lists.front(); } }; */
4a1c0a4999d9d0c3523d1edada5988bdb01afd63
4aa3ff56e35d2d4cdeba40f45795f62f276859b3
/Engine/Network/ActionBuffer.h
e869175db9e4ee030e06ba36f90b2e1c7bd5ef3f
[ "Apache-2.0" ]
permissive
SixShoot/lastchaos-source-client
fde6a750afc4d7c5df3e9e0c542b056573c1b42d
3d88594dba7347b1bb45378136605e31f73a8555
refs/heads/master
2023-06-28T17:20:35.951648
2021-07-31T21:51:49
2021-07-31T21:51:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
845
h
ActionBuffer.h
#ifndef SE_INCL_ACTIONBUFFER_H #define SE_INCL_ACTIONBUFFER_H #ifdef PRAGMA_ONCE #pragma once #endif // #include <Engine/Base/Lists.h> // buffer of player actions, sorted by time of arrival class CActionBuffer { public: CListHead ab_lhActions; public: CActionBuffer(void); ~CActionBuffer(void); void Clear(void); // add a new action to the buffer void AddAction(const CPlayerAction &pa); // remove oldest buffered action void RemoveOldest(void); // flush all actions up to given time tag void FlushUntilTime(__int64 llNewest); // get number of actions buffered INDEX GetCount(void); // get an action by its index (0=oldest) void GetActionByIndex(INDEX i, CPlayerAction &pa); // get last action older than given timetag CPlayerAction *GetLastOlderThan(__int64 llTime); }; #endif /* include-once check. */
37ef976db136ea9aa8a54a499f041503a5c1c3e5
7b8aac984fbaf154c5fce208ed423f6edc42d7cc
/templates/src/main.cpp
140a7649a19804b62d2b55c5511f9b9726f0efe3
[]
no_license
dankegel/obi-noodoo2
8bf8f2268988adaf55409715323bb2a63a612315
e07b39bbfb021698b8dbd3a130bd31763df342f5
refs/heads/master
2021-04-27T01:40:55.688916
2018-02-23T22:43:38
2018-02-23T22:43:38
122,680,437
0
0
null
null
null
null
UTF-8
C++
false
false
1,631
cpp
main.cpp
/* (c) oblong industries */ #include <libLoam/c++/ArgParse.h> #include <libNoodoo2/VisiFeld.h> #include <libNoodoo2/VisiDrome.h> #include <libNoodoo2/Scene.h> #include <libNoodoo2/MeshyThing.h> using namespace oblong::loam; using namespace oblong::basement; using namespace oblong::noodoo2; // Note: This hook assumes only one VisiFeld will be created and that this will therefore only be called once. ObRetort VisiFeldSetupHook (VisiDrome *drome, VisiFeld *vf, Atmosphere *atm) { ObRetort error; // Create Scene ObRef<Scene *> scene = new Scene (SceneMode::Flat, error); if (error.IsError ()) return error; // Create Mesh ObRef<MeshyThing *> meshy = new MeshyThing (error); if (error.IsError ()) return error; // Add data to mesh meshy->Geometry ().AppendPosition ({-1.0, -1.0, 0.0}); meshy->Geometry ().AppendPosition ({1.0, -1.0, 0.0}); meshy->Geometry ().AppendPosition ({0.0, 1.0, 0.0}); // Specify draw mode for data meshy->Geometry ().SetDrawMode (VertexDrawMode::Triangles); // Set color of mesh meshy->SetColor (ObColor (1.0, 0.0, 0.0)); // Set scale of mesh meshy->SetScale (Vect (50.0, 50.0, 50.0)); // Append Scene to VisiFeld vf->AppendScene (~scene); // Attach mesh to Scene scene->RootShowyThing ()->AppendChild (~meshy); // Set Root Node pose scene->RootShowyThing ()->TranslateLikeFeld (vf); scene->RootShowyThing ()->RotateLikeFeld (vf); return OB_OK; } int main (int ac, char **av) { VisiDrome *drome = new VisiDrome (); drome->AppendFeldSetupHook (VisiFeldSetupHook, "mesh"); drome->Respire (); drome->Delete (); return 0; }
306cb2c962d3d11548bcabafd42c37205e935023
1b90be9561c10508eea59cb36c1f1665d0ef947f
/stan/math/prim/fun/identity_free.hpp
0652ac11e24ca108099906890f0ad78e8f0f6e15
[ "BSD-3-Clause", "GPL-2.0-only", "Apache-2.0" ]
permissive
stan-dev/math
473e7c1eaf11f84eaf2032c2455e12ba65feef39
bdf281f4e7f8034f47974d14dea7f09e600ac02a
refs/heads/develop
2023-08-31T09:02:59.224115
2023-08-29T15:17:01
2023-08-29T15:17:01
38,388,440
732
240
BSD-3-Clause
2023-09-14T19:44:20
2015-07-01T18:40:54
C++
UTF-8
C++
false
false
743
hpp
identity_free.hpp
#ifndef STAN_MATH_PRIM_FUN_IDENTITY_FREE_HPP #define STAN_MATH_PRIM_FUN_IDENTITY_FREE_HPP #include <stan/math/prim/meta.hpp> namespace stan { namespace math { /** * Returns the result of applying the inverse of the identity * constraint transform to the input. This promotes the input to the least upper * bound of the input types. * * * @tparam T type of value to promote * @tparam Types Other types. * @param[in] x value to promote * @return value */ template <typename T, typename... Types, require_all_not_var_matrix_t<T, Types...>* = nullptr> inline auto identity_free(T&& x, Types&&... /* args */) { return promote_scalar_t<return_type_t<T, Types...>, T>(x); } } // namespace math } // namespace stan #endif
be6f08bf712e05cd60bf0c910512156ed3947958
e91e67cbd5190c3f285932559e33d3fbd2c90f4b
/Codeforces/A. Lucky Division.cpp
0aa658c05e637f3a92bbbbeb8ccfd53c3ef98e17
[]
no_license
Fahimefto/Solved-problem
0dd83f367a935fc142f0a86304aee207ba5825dd
1f2df5d33e6345b55a6f99f4eee53cf25655c6c0
refs/heads/master
2020-12-19T00:45:14.378188
2020-06-01T07:29:58
2020-06-01T07:29:58
235,568,430
0
0
null
null
null
null
UTF-8
C++
false
false
204
cpp
A. Lucky Division.cpp
#include<bits/stdc++.h> using namespace std; int main() { int x; cin>>x; if(x%4==0 || x%7==0 || x%47==0 || x%744==0 || x%477==0 ) cout<<"YES"<<endl; else cout<<"NO"; }
43eb64a993ed5a78f3377cb7baa223e545c4d481
7e97b46635bc9f28b7102845192a2938313a21f3
/ABC/AGC004_A.cpp
7df9f4d2483ec5115520fd2fe1c76c59f3877c93
[]
no_license
ittsu-code/Atcoder_ittsucode
3a8f609c649cfd8357c829c3f4aa787c41543211
3294babf5d6e25f80a74a77fd49ae535d252d4da
refs/heads/master
2022-11-06T03:41:55.136071
2020-06-16T14:53:34
2020-06-16T14:53:34
249,254,658
0
0
null
null
null
null
UTF-8
C++
false
false
373
cpp
AGC004_A.cpp
#include <bits/stdc++.h> using namespace std; int main() { long long A, B, C; cin >> A >> B >> C; vector X = {A, B, C}; sort(X.begin(), X.end()); if (X.at(0) % 2 == 0 || X.at(1) % 2 == 0 || X.at(2) % 2 == 0) cout << 0 << endl; else cout << ((X.at(2) + 1) * X.at(0) * X.at(1) * 4) - (X.at(0) * X.at(1) * X.at(2) * 4) << endl; }
7fb522694af1781123ac0df9bac521a7442569ef
303e592c312459bf9eb3ce231b1357c4de91124b
/pku/1009/1009.cpp
681688f07f1444d5b43a18c9fbd34c520f25b8b5
[]
no_license
kohyatoh/contests
866c60a1687f8a59d440da3356c6117f9596e8ce
b3dffeaf15564d57aec5c306f5f84bd448bc791f
refs/heads/master
2021-01-17T15:06:23.216232
2016-07-18T14:06:05
2016-07-18T14:06:05
2,369,261
0
1
null
null
null
null
UTF-8
C++
false
false
2,790
cpp
1009.cpp
#include <stdio.h> #include <stdlib.h> #include <algorithm> using namespace std; #define rep(i, n) for(int i=0; i<(int)(n); i++) int w, n, p[2000], s[2000], sum, x[2000]; int zn, z[6000]; int main() { for(;;) { scanf("%d", &w); printf("%d\n", w); if(w==0) return 0; n=-1, sum=0; do { n++; scanf("%d%d", p+n, s+n); x[n]=sum; sum+=s[n]; } while(p[n]>0 || s[n]>0); x[n]=sum; int rp=-1, rs=0; rep(i, n) { zn = 0; z[zn++] = x[i]; if(s[i]>1) z[zn++] = x[i]+1; z[zn++] = x[i+1]; if(s[i]>1) z[zn++] = x[i+1]-1; rep(j, i) { if(x[i]<x[j]+w && x[j]+w<x[i+1]) z[zn++]=x[j]+w; if(x[i]<x[j]+w-1 && x[j]+w-1<x[i+1]) z[zn++]=x[j]+w-1; if(x[i]<x[j]+w+1 && x[j]+w+1<x[i+1]) z[zn++]=x[j]+w+1; if(x[i]<x[j+1]+w && x[j+1]+w<x[i+1]) z[zn++]=x[j+1]+w; if(x[i]<x[j+1]+w-1 && x[j+1]+w-1<x[i+1]) z[zn++]=x[j+1]+w-1; if(x[i]<x[j+1]+w+1 && x[j+1]+w+1<x[i+1]) z[zn++]=x[j+1]+w+1; } for(int j=i+1; j<n; j++) { if(x[i]<x[j]-w && x[j]-w<x[i+1]) z[zn++]=x[j]-w; if(x[i]<x[j]-w-1 && x[j]-w-1<x[i+1]) z[zn++]=x[j]-w-1; if(x[i]<x[j]-w+1 && x[j]-w+1<x[i+1]) z[zn++]=x[j]-w+1; if(x[i]<x[j+1]-w && x[j+1]-w<x[i+1]) z[zn++]=x[j+1]-w; if(x[i]<x[j+1]-w-1 && x[j+1]-w-1<x[i+1]) z[zn++]=x[j+1]-w-1; if(x[i]<x[j+1]-w+1 && x[j+1]-w+1<x[i+1]) z[zn++]=x[j+1]-w+1; } std::sort(z, z+zn); zn = std::unique(z, z+zn)-z; int a=0, b=i; rep(j, zn-1) { while(a<i && x[a+1]+w<=z[j]) a++; while(b<n && x[b+1]-w<=z[j]) b++; int md=0; if(j==0 && x[i]%w) md=max(md, abs(p[i]-p[i-1])); if(j==zn-2 && (x[i+1])%w) md=max(md, abs(p[i]-p[i+1])); if(a<i && x[a]+w<=z[j]) md=max(md, abs(p[i]-p[a])); if(0<a && x[a]+w==z[j] && z[j]%w) md=max(md, abs(p[i]-p[a-1])); if(a<i && x[a+1]+w==z[j+1] && (z[j+1])%w) md=max(md, abs(p[i]-p[a+1])); if(b<n && x[b]-w<=z[j]) md=max(md, abs(p[i]-p[b])); if(i<b && x[b]-w==z[j] && z[j]%w) md=max(md, abs(p[i]-p[b-1])); if(b<n && x[b+1]-w==z[j+1] && (z[j+1])%w) md=max(md, abs(p[i]-p[b+1])); if(rp==md) rs+=z[j+1]-z[j]; else { if(rp>=0) printf("%d %d\n", rp, rs); rp=md, rs=z[j+1]-z[j]; } } } printf("%d %d\n", rp, rs); printf("%d %d\n", 0, 0); } }
ea4eab584164d2d090944d963cb4bda66039db1a
682f56561c3a9c2d64b45eb005d3a063eaae6095
/account.cpp
429cac13883a5c54b294b5424b47abc02199d4d2
[]
no_license
bevanDon/3060U_phase2
d096cda56810847817dd10ad64163d1c0deecf5b
c771c9ea205eb54ffbd1d3d4ef18ec813f4cf8e7
refs/heads/main
2023-03-15T18:34:36.617776
2021-03-08T20:34:38
2021-03-08T20:34:38
340,991,921
0
0
null
null
null
null
UTF-8
C++
false
false
1,690
cpp
account.cpp
/* User class */ #include <iostream> class Account{ std::string accountName; //accountName for user login std::string accountID; //account ID for user login int accountType; //Type of account (standard = 0, admin = 1) float money; //value in the users account int isActive; //0 = active, 1 = inactive int planType; //0 = student, 1 = regular public: //default constructor Account(){ this->accountName = ""; this->accountID = ""; this->accountType = 0; this->money = 0.00; this->isActive = 0; this->planType = 0; } //constructor Account(std::string accountName, std::string accountID, int accountType, float money){ this->accountName = accountName; this->accountID = accountID; this->accountType = accountType; this->money = money; } std::string getUsername(){ return this->accountName; } void setUsername(std::string accountName){ this->accountName = accountName; } std::string getUserID(){ return this->accountID; } void setUserID(std::string accountID){ this->accountID = accountID; } int getAccountType(){ return this->accountType; } void setAccountType(int accountType){ this->accountType = accountType; } float getMoney(){ return this->money; } void addMoney(float money){ this->money = this->money + money; } void subMoney(float money){ this->money = this->money - money; } int getStatus(){ return this->isActive; } void updateStatus(int newStatus){ this->isActive = newStatus; } int getPlanType(){ return this->planType; } void updatePlanType(int newPlanType){ this->planType = newPlanType; } };
962bc3e00e9848343253d6af9d6d155df5b4eda7
5f0ccc599968f8d6db9cef32446dbadeb2414868
/src/datetimehelper.h
23fb474a3be5ce2893bb9b17d9620f88ad0b7340
[]
no_license
dprelec/forum-qml-new
5b39223832010a322f8d822931b343a2364c4827
8ec4426856db57952ca1a3f74a4ff33699dac976
refs/heads/master
2021-01-18T01:28:41.092275
2013-06-25T03:01:44
2013-06-25T03:01:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
302
h
datetimehelper.h
#ifndef DATETIMEHELPER_H #define DATETIMEHELPER_H #include <QString> class DateTimeHelper { public: DateTimeHelper(); static QString parseDateTime(const QString dateTime); static QString parseDate(QString date); static QString parseTime(QString time); }; #endif // DATETIMEHELPER_H
533b4569c8e4535137919f0de7dbfb69f2b48faa
1a5331af71a79baf014bc463f8c23eb6d92ca406
/3rdPartyLibs/protobuf-3.20.1/src/google/protobuf/unittest_mset.pb.cc
ceac316472915ec82a8d3bd641f4ca8d57084184
[ "LicenseRef-scancode-protobuf" ]
permissive
DLR-TS/SUMOLibraries
be8a1d7b32a428fc9a31d6e324170c4ad8ce358b
48faf165ba098b832cd8963992902427c212acac
refs/heads/main
2023-08-09T09:14:35.238792
2023-08-08T12:25:10
2023-08-08T12:25:10
116,371,656
26
21
null
2023-03-24T10:20:04
2018-01-05T10:11:39
C++
UTF-8
C++
false
true
85,689
cc
unittest_mset.pb.cc
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/unittest_mset.proto #include "google/protobuf/unittest_mset.pb.h" #include <algorithm> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/extension_set.h> #include <google/protobuf/wire_format_lite.h> #include <google/protobuf/descriptor.h> #include <google/protobuf/generated_message_reflection.h> #include <google/protobuf/reflection_ops.h> #include <google/protobuf/wire_format.h> // @@protoc_insertion_point(includes) #include <google/protobuf/port_def.inc> PROTOBUF_PRAGMA_INIT_SEG namespace _pb = ::PROTOBUF_NAMESPACE_ID; namespace _pbi = _pb::internal; namespace protobuf_unittest { PROTOBUF_CONSTEXPR TestMessageSetContainer::TestMessageSetContainer( ::_pbi::ConstantInitialized) : message_set_(nullptr){} struct TestMessageSetContainerDefaultTypeInternal { PROTOBUF_CONSTEXPR TestMessageSetContainerDefaultTypeInternal() : _instance(::_pbi::ConstantInitialized{}) {} ~TestMessageSetContainerDefaultTypeInternal() {} union { TestMessageSetContainer _instance; }; }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 TestMessageSetContainerDefaultTypeInternal _TestMessageSetContainer_default_instance_; PROTOBUF_CONSTEXPR NestedTestMessageSetContainer::NestedTestMessageSetContainer( ::_pbi::ConstantInitialized) : container_(nullptr) , child_(nullptr){} struct NestedTestMessageSetContainerDefaultTypeInternal { PROTOBUF_CONSTEXPR NestedTestMessageSetContainerDefaultTypeInternal() : _instance(::_pbi::ConstantInitialized{}) {} ~NestedTestMessageSetContainerDefaultTypeInternal() {} union { NestedTestMessageSetContainer _instance; }; }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 NestedTestMessageSetContainerDefaultTypeInternal _NestedTestMessageSetContainer_default_instance_; PROTOBUF_CONSTEXPR TestMessageSetExtension1::TestMessageSetExtension1( ::_pbi::ConstantInitialized) : test_aliasing_(&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}) , recursive_(nullptr) , i_(0){} struct TestMessageSetExtension1DefaultTypeInternal { PROTOBUF_CONSTEXPR TestMessageSetExtension1DefaultTypeInternal() : _instance(::_pbi::ConstantInitialized{}) {} ~TestMessageSetExtension1DefaultTypeInternal() {} union { TestMessageSetExtension1 _instance; }; }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 TestMessageSetExtension1DefaultTypeInternal _TestMessageSetExtension1_default_instance_; PROTOBUF_CONSTEXPR TestMessageSetExtension2::TestMessageSetExtension2( ::_pbi::ConstantInitialized) : str_(&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}){} struct TestMessageSetExtension2DefaultTypeInternal { PROTOBUF_CONSTEXPR TestMessageSetExtension2DefaultTypeInternal() : _instance(::_pbi::ConstantInitialized{}) {} ~TestMessageSetExtension2DefaultTypeInternal() {} union { TestMessageSetExtension2 _instance; }; }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 TestMessageSetExtension2DefaultTypeInternal _TestMessageSetExtension2_default_instance_; PROTOBUF_CONSTEXPR NestedTestInt::NestedTestInt( ::_pbi::ConstantInitialized) : child_(nullptr) , a_(0u){} struct NestedTestIntDefaultTypeInternal { PROTOBUF_CONSTEXPR NestedTestIntDefaultTypeInternal() : _instance(::_pbi::ConstantInitialized{}) {} ~NestedTestIntDefaultTypeInternal() {} union { NestedTestInt _instance; }; }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 NestedTestIntDefaultTypeInternal _NestedTestInt_default_instance_; PROTOBUF_CONSTEXPR TestMessageSetExtension3::TestMessageSetExtension3( ::_pbi::ConstantInitialized) : msg_(nullptr){} struct TestMessageSetExtension3DefaultTypeInternal { PROTOBUF_CONSTEXPR TestMessageSetExtension3DefaultTypeInternal() : _instance(::_pbi::ConstantInitialized{}) {} ~TestMessageSetExtension3DefaultTypeInternal() {} union { TestMessageSetExtension3 _instance; }; }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 TestMessageSetExtension3DefaultTypeInternal _TestMessageSetExtension3_default_instance_; PROTOBUF_CONSTEXPR RawMessageSet_Item::RawMessageSet_Item( ::_pbi::ConstantInitialized) : message_(&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}) , type_id_(0){} struct RawMessageSet_ItemDefaultTypeInternal { PROTOBUF_CONSTEXPR RawMessageSet_ItemDefaultTypeInternal() : _instance(::_pbi::ConstantInitialized{}) {} ~RawMessageSet_ItemDefaultTypeInternal() {} union { RawMessageSet_Item _instance; }; }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 RawMessageSet_ItemDefaultTypeInternal _RawMessageSet_Item_default_instance_; PROTOBUF_CONSTEXPR RawMessageSet::RawMessageSet( ::_pbi::ConstantInitialized) : item_(){} struct RawMessageSetDefaultTypeInternal { PROTOBUF_CONSTEXPR RawMessageSetDefaultTypeInternal() : _instance(::_pbi::ConstantInitialized{}) {} ~RawMessageSetDefaultTypeInternal() {} union { RawMessageSet _instance; }; }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 RawMessageSetDefaultTypeInternal _RawMessageSet_default_instance_; } // namespace protobuf_unittest static ::_pb::Metadata file_level_metadata_google_2fprotobuf_2funittest_5fmset_2eproto[8]; static constexpr ::_pb::EnumDescriptor const** file_level_enum_descriptors_google_2fprotobuf_2funittest_5fmset_2eproto = nullptr; static constexpr ::_pb::ServiceDescriptor const** file_level_service_descriptors_google_2fprotobuf_2funittest_5fmset_2eproto = nullptr; const uint32_t TableStruct_google_2fprotobuf_2funittest_5fmset_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { PROTOBUF_FIELD_OFFSET(::protobuf_unittest::TestMessageSetContainer, _has_bits_), PROTOBUF_FIELD_OFFSET(::protobuf_unittest::TestMessageSetContainer, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ ~0u, // no _inlined_string_donated_ PROTOBUF_FIELD_OFFSET(::protobuf_unittest::TestMessageSetContainer, message_set_), 0, PROTOBUF_FIELD_OFFSET(::protobuf_unittest::NestedTestMessageSetContainer, _has_bits_), PROTOBUF_FIELD_OFFSET(::protobuf_unittest::NestedTestMessageSetContainer, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ ~0u, // no _inlined_string_donated_ PROTOBUF_FIELD_OFFSET(::protobuf_unittest::NestedTestMessageSetContainer, container_), PROTOBUF_FIELD_OFFSET(::protobuf_unittest::NestedTestMessageSetContainer, child_), 0, 1, PROTOBUF_FIELD_OFFSET(::protobuf_unittest::TestMessageSetExtension1, _has_bits_), PROTOBUF_FIELD_OFFSET(::protobuf_unittest::TestMessageSetExtension1, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ ~0u, // no _inlined_string_donated_ PROTOBUF_FIELD_OFFSET(::protobuf_unittest::TestMessageSetExtension1, i_), PROTOBUF_FIELD_OFFSET(::protobuf_unittest::TestMessageSetExtension1, recursive_), PROTOBUF_FIELD_OFFSET(::protobuf_unittest::TestMessageSetExtension1, test_aliasing_), 2, 1, 0, PROTOBUF_FIELD_OFFSET(::protobuf_unittest::TestMessageSetExtension2, _has_bits_), PROTOBUF_FIELD_OFFSET(::protobuf_unittest::TestMessageSetExtension2, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ ~0u, // no _inlined_string_donated_ PROTOBUF_FIELD_OFFSET(::protobuf_unittest::TestMessageSetExtension2, str_), 0, PROTOBUF_FIELD_OFFSET(::protobuf_unittest::NestedTestInt, _has_bits_), PROTOBUF_FIELD_OFFSET(::protobuf_unittest::NestedTestInt, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ ~0u, // no _inlined_string_donated_ PROTOBUF_FIELD_OFFSET(::protobuf_unittest::NestedTestInt, a_), PROTOBUF_FIELD_OFFSET(::protobuf_unittest::NestedTestInt, child_), 1, 0, PROTOBUF_FIELD_OFFSET(::protobuf_unittest::TestMessageSetExtension3, _has_bits_), PROTOBUF_FIELD_OFFSET(::protobuf_unittest::TestMessageSetExtension3, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ ~0u, // no _inlined_string_donated_ PROTOBUF_FIELD_OFFSET(::protobuf_unittest::TestMessageSetExtension3, msg_), 0, PROTOBUF_FIELD_OFFSET(::protobuf_unittest::RawMessageSet_Item, _has_bits_), PROTOBUF_FIELD_OFFSET(::protobuf_unittest::RawMessageSet_Item, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ ~0u, // no _inlined_string_donated_ PROTOBUF_FIELD_OFFSET(::protobuf_unittest::RawMessageSet_Item, type_id_), PROTOBUF_FIELD_OFFSET(::protobuf_unittest::RawMessageSet_Item, message_), 1, 0, ~0u, // no _has_bits_ PROTOBUF_FIELD_OFFSET(::protobuf_unittest::RawMessageSet, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ ~0u, // no _inlined_string_donated_ PROTOBUF_FIELD_OFFSET(::protobuf_unittest::RawMessageSet, item_), }; static const ::_pbi::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { { 0, 7, -1, sizeof(::protobuf_unittest::TestMessageSetContainer)}, { 8, 16, -1, sizeof(::protobuf_unittest::NestedTestMessageSetContainer)}, { 18, 27, -1, sizeof(::protobuf_unittest::TestMessageSetExtension1)}, { 30, 37, -1, sizeof(::protobuf_unittest::TestMessageSetExtension2)}, { 38, 46, -1, sizeof(::protobuf_unittest::NestedTestInt)}, { 48, 55, -1, sizeof(::protobuf_unittest::TestMessageSetExtension3)}, { 56, 64, -1, sizeof(::protobuf_unittest::RawMessageSet_Item)}, { 66, -1, -1, sizeof(::protobuf_unittest::RawMessageSet)}, }; static const ::_pb::Message* const file_default_instances[] = { &::protobuf_unittest::_TestMessageSetContainer_default_instance_._instance, &::protobuf_unittest::_NestedTestMessageSetContainer_default_instance_._instance, &::protobuf_unittest::_TestMessageSetExtension1_default_instance_._instance, &::protobuf_unittest::_TestMessageSetExtension2_default_instance_._instance, &::protobuf_unittest::_NestedTestInt_default_instance_._instance, &::protobuf_unittest::_TestMessageSetExtension3_default_instance_._instance, &::protobuf_unittest::_RawMessageSet_Item_default_instance_._instance, &::protobuf_unittest::_RawMessageSet_default_instance_._instance, }; const char descriptor_table_protodef_google_2fprotobuf_2funittest_5fmset_2eproto[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = "\n#google/protobuf/unittest_mset.proto\022\021p" "rotobuf_unittest\032/google/protobuf/unitte" "st_mset_wire_format.proto\"Z\n\027TestMessage" "SetContainer\022\?\n\013message_set\030\001 \001(\0132*.prot" "o2_wireformat_unittest.TestMessageSet\"\237\001" "\n\035NestedTestMessageSetContainer\022=\n\tconta" "iner\030\001 \001(\0132*.protobuf_unittest.TestMessa" "geSetContainer\022\?\n\005child\030\002 \001(\01320.protobuf" "_unittest.NestedTestMessageSetContainer\"" "\371\001\n\030TestMessageSetExtension1\022\t\n\001i\030\017 \001(\005\022" "=\n\trecursive\030\020 \001(\0132*.proto2_wireformat_u" "nittest.TestMessageSet\022\031\n\rtest_aliasing\030" "\021 \001(\tB\002\010\0022x\n\025message_set_extension\022*.pro" "to2_wireformat_unittest.TestMessageSet\030\260" "\246^ \001(\0132+.protobuf_unittest.TestMessageSe" "tExtension1\"\241\001\n\030TestMessageSetExtension2" "\022\013\n\003str\030\031 \001(\t2x\n\025message_set_extension\022*" ".proto2_wireformat_unittest.TestMessageS" "et\030\371\273^ \001(\0132+.protobuf_unittest.TestMessa" "geSetExtension2\"K\n\rNestedTestInt\022\t\n\001a\030\001 " "\001(\007\022/\n\005child\030\002 \001(\0132 .protobuf_unittest.N" "estedTestInt\"\304\001\n\030TestMessageSetExtension" "3\022-\n\003msg\030# \001(\0132 .protobuf_unittest.Neste" "dTestInt2y\n\025message_set_extension\022*.prot" "o2_wireformat_unittest.TestMessageSet\030\251\303" "\216] \001(\0132+.protobuf_unittest.TestMessageSe" "tExtension3\"n\n\rRawMessageSet\0223\n\004item\030\001 \003" "(\n2%.protobuf_unittest.RawMessageSet.Ite" "m\032(\n\004Item\022\017\n\007type_id\030\002 \002(\005\022\017\n\007message\030\003 " "\002(\014B\005H\001\370\001\001" ; static const ::_pbi::DescriptorTable* const descriptor_table_google_2fprotobuf_2funittest_5fmset_2eproto_deps[1] = { &::descriptor_table_google_2fprotobuf_2funittest_5fmset_5fwire_5fformat_2eproto, }; static ::_pbi::once_flag descriptor_table_google_2fprotobuf_2funittest_5fmset_2eproto_once; const ::_pbi::DescriptorTable descriptor_table_google_2fprotobuf_2funittest_5fmset_2eproto = { false, false, 1170, descriptor_table_protodef_google_2fprotobuf_2funittest_5fmset_2eproto, "google/protobuf/unittest_mset.proto", &descriptor_table_google_2fprotobuf_2funittest_5fmset_2eproto_once, descriptor_table_google_2fprotobuf_2funittest_5fmset_2eproto_deps, 1, 8, schemas, file_default_instances, TableStruct_google_2fprotobuf_2funittest_5fmset_2eproto::offsets, file_level_metadata_google_2fprotobuf_2funittest_5fmset_2eproto, file_level_enum_descriptors_google_2fprotobuf_2funittest_5fmset_2eproto, file_level_service_descriptors_google_2fprotobuf_2funittest_5fmset_2eproto, }; PROTOBUF_ATTRIBUTE_WEAK const ::_pbi::DescriptorTable* descriptor_table_google_2fprotobuf_2funittest_5fmset_2eproto_getter() { return &descriptor_table_google_2fprotobuf_2funittest_5fmset_2eproto; } // Force running AddDescriptors() at dynamic initialization time. PROTOBUF_ATTRIBUTE_INIT_PRIORITY2 static ::_pbi::AddDescriptorsRunner dynamic_init_dummy_google_2fprotobuf_2funittest_5fmset_2eproto(&descriptor_table_google_2fprotobuf_2funittest_5fmset_2eproto); namespace protobuf_unittest { // =================================================================== class TestMessageSetContainer::_Internal { public: using HasBits = decltype(std::declval<TestMessageSetContainer>()._has_bits_); static const ::proto2_wireformat_unittest::TestMessageSet& message_set(const TestMessageSetContainer* msg); static void set_has_message_set(HasBits* has_bits) { (*has_bits)[0] |= 1u; } }; const ::proto2_wireformat_unittest::TestMessageSet& TestMessageSetContainer::_Internal::message_set(const TestMessageSetContainer* msg) { return *msg->message_set_; } void TestMessageSetContainer::clear_message_set() { if (message_set_ != nullptr) message_set_->Clear(); _has_bits_[0] &= ~0x00000001u; } TestMessageSetContainer::TestMessageSetContainer(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned) : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned) { SharedCtor(); // @@protoc_insertion_point(arena_constructor:protobuf_unittest.TestMessageSetContainer) } TestMessageSetContainer::TestMessageSetContainer(const TestMessageSetContainer& from) : ::PROTOBUF_NAMESPACE_ID::Message(), _has_bits_(from._has_bits_) { _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); if (from._internal_has_message_set()) { message_set_ = new ::proto2_wireformat_unittest::TestMessageSet(*from.message_set_); } else { message_set_ = nullptr; } // @@protoc_insertion_point(copy_constructor:protobuf_unittest.TestMessageSetContainer) } inline void TestMessageSetContainer::SharedCtor() { message_set_ = nullptr; } TestMessageSetContainer::~TestMessageSetContainer() { // @@protoc_insertion_point(destructor:protobuf_unittest.TestMessageSetContainer) if (auto *arena = _internal_metadata_.DeleteReturnArena<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>()) { (void)arena; return; } SharedDtor(); } inline void TestMessageSetContainer::SharedDtor() { GOOGLE_DCHECK(GetArenaForAllocation() == nullptr); if (this != internal_default_instance()) delete message_set_; } void TestMessageSetContainer::SetCachedSize(int size) const { _cached_size_.Set(size); } void TestMessageSetContainer::Clear() { // @@protoc_insertion_point(message_clear_start:protobuf_unittest.TestMessageSetContainer) uint32_t cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x00000001u) { GOOGLE_DCHECK(message_set_ != nullptr); message_set_->Clear(); } _has_bits_.Clear(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } const char* TestMessageSetContainer::_InternalParse(const char* ptr, ::_pbi::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure _Internal::HasBits has_bits{}; while (!ctx->Done(&ptr)) { uint32_t tag; ptr = ::_pbi::ReadTag(ptr, &tag); switch (tag >> 3) { // optional .proto2_wireformat_unittest.TestMessageSet message_set = 1; case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 10)) { ptr = ctx->ParseMessage(_internal_mutable_message_set(), ptr); CHK_(ptr); } else goto handle_unusual; continue; default: goto handle_unusual; } // switch handle_unusual: if ((tag == 0) || ((tag & 7) == 4)) { CHK_(ptr); ctx->SetLastTag(tag); goto message_done; } ptr = UnknownFieldParse( tag, _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(), ptr, ctx); CHK_(ptr != nullptr); } // while message_done: _has_bits_.Or(has_bits); return ptr; failure: ptr = nullptr; goto message_done; #undef CHK_ } uint8_t* TestMessageSetContainer::_InternalSerialize( uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const { // @@protoc_insertion_point(serialize_to_array_start:protobuf_unittest.TestMessageSetContainer) uint32_t cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // optional .proto2_wireformat_unittest.TestMessageSet message_set = 1; if (cached_has_bits & 0x00000001u) { target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessage(1, _Internal::message_set(this), _Internal::message_set(this).GetCachedSize(), target, stream); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { target = ::_pbi::WireFormat::InternalSerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream); } // @@protoc_insertion_point(serialize_to_array_end:protobuf_unittest.TestMessageSetContainer) return target; } size_t TestMessageSetContainer::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:protobuf_unittest.TestMessageSetContainer) size_t total_size = 0; uint32_t cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // optional .proto2_wireformat_unittest.TestMessageSet message_set = 1; cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x00000001u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( *message_set_); } return MaybeComputeUnknownFieldsSize(total_size, &_cached_size_); } const ::PROTOBUF_NAMESPACE_ID::Message::ClassData TestMessageSetContainer::_class_data_ = { ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSizeCheck, TestMessageSetContainer::MergeImpl }; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*TestMessageSetContainer::GetClassData() const { return &_class_data_; } void TestMessageSetContainer::MergeImpl(::PROTOBUF_NAMESPACE_ID::Message* to, const ::PROTOBUF_NAMESPACE_ID::Message& from) { static_cast<TestMessageSetContainer *>(to)->MergeFrom( static_cast<const TestMessageSetContainer &>(from)); } void TestMessageSetContainer::MergeFrom(const TestMessageSetContainer& from) { // @@protoc_insertion_point(class_specific_merge_from_start:protobuf_unittest.TestMessageSetContainer) GOOGLE_DCHECK_NE(&from, this); uint32_t cached_has_bits = 0; (void) cached_has_bits; if (from._internal_has_message_set()) { _internal_mutable_message_set()->::proto2_wireformat_unittest::TestMessageSet::MergeFrom(from._internal_message_set()); } _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); } void TestMessageSetContainer::CopyFrom(const TestMessageSetContainer& from) { // @@protoc_insertion_point(class_specific_copy_from_start:protobuf_unittest.TestMessageSetContainer) if (&from == this) return; Clear(); MergeFrom(from); } bool TestMessageSetContainer::IsInitialized() const { if (_internal_has_message_set()) { if (!message_set_->IsInitialized()) return false; } return true; } void TestMessageSetContainer::InternalSwap(TestMessageSetContainer* other) { using std::swap; _internal_metadata_.InternalSwap(&other->_internal_metadata_); swap(_has_bits_[0], other->_has_bits_[0]); swap(message_set_, other->message_set_); } ::PROTOBUF_NAMESPACE_ID::Metadata TestMessageSetContainer::GetMetadata() const { return ::_pbi::AssignDescriptors( &descriptor_table_google_2fprotobuf_2funittest_5fmset_2eproto_getter, &descriptor_table_google_2fprotobuf_2funittest_5fmset_2eproto_once, file_level_metadata_google_2fprotobuf_2funittest_5fmset_2eproto[0]); } // =================================================================== class NestedTestMessageSetContainer::_Internal { public: using HasBits = decltype(std::declval<NestedTestMessageSetContainer>()._has_bits_); static const ::protobuf_unittest::TestMessageSetContainer& container(const NestedTestMessageSetContainer* msg); static void set_has_container(HasBits* has_bits) { (*has_bits)[0] |= 1u; } static const ::protobuf_unittest::NestedTestMessageSetContainer& child(const NestedTestMessageSetContainer* msg); static void set_has_child(HasBits* has_bits) { (*has_bits)[0] |= 2u; } }; const ::protobuf_unittest::TestMessageSetContainer& NestedTestMessageSetContainer::_Internal::container(const NestedTestMessageSetContainer* msg) { return *msg->container_; } const ::protobuf_unittest::NestedTestMessageSetContainer& NestedTestMessageSetContainer::_Internal::child(const NestedTestMessageSetContainer* msg) { return *msg->child_; } NestedTestMessageSetContainer::NestedTestMessageSetContainer(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned) : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned) { SharedCtor(); // @@protoc_insertion_point(arena_constructor:protobuf_unittest.NestedTestMessageSetContainer) } NestedTestMessageSetContainer::NestedTestMessageSetContainer(const NestedTestMessageSetContainer& from) : ::PROTOBUF_NAMESPACE_ID::Message(), _has_bits_(from._has_bits_) { _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); if (from._internal_has_container()) { container_ = new ::protobuf_unittest::TestMessageSetContainer(*from.container_); } else { container_ = nullptr; } if (from._internal_has_child()) { child_ = new ::protobuf_unittest::NestedTestMessageSetContainer(*from.child_); } else { child_ = nullptr; } // @@protoc_insertion_point(copy_constructor:protobuf_unittest.NestedTestMessageSetContainer) } inline void NestedTestMessageSetContainer::SharedCtor() { ::memset(reinterpret_cast<char*>(this) + static_cast<size_t>( reinterpret_cast<char*>(&container_) - reinterpret_cast<char*>(this)), 0, static_cast<size_t>(reinterpret_cast<char*>(&child_) - reinterpret_cast<char*>(&container_)) + sizeof(child_)); } NestedTestMessageSetContainer::~NestedTestMessageSetContainer() { // @@protoc_insertion_point(destructor:protobuf_unittest.NestedTestMessageSetContainer) if (auto *arena = _internal_metadata_.DeleteReturnArena<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>()) { (void)arena; return; } SharedDtor(); } inline void NestedTestMessageSetContainer::SharedDtor() { GOOGLE_DCHECK(GetArenaForAllocation() == nullptr); if (this != internal_default_instance()) delete container_; if (this != internal_default_instance()) delete child_; } void NestedTestMessageSetContainer::SetCachedSize(int size) const { _cached_size_.Set(size); } void NestedTestMessageSetContainer::Clear() { // @@protoc_insertion_point(message_clear_start:protobuf_unittest.NestedTestMessageSetContainer) uint32_t cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x00000003u) { if (cached_has_bits & 0x00000001u) { GOOGLE_DCHECK(container_ != nullptr); container_->Clear(); } if (cached_has_bits & 0x00000002u) { GOOGLE_DCHECK(child_ != nullptr); child_->Clear(); } } _has_bits_.Clear(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } const char* NestedTestMessageSetContainer::_InternalParse(const char* ptr, ::_pbi::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure _Internal::HasBits has_bits{}; while (!ctx->Done(&ptr)) { uint32_t tag; ptr = ::_pbi::ReadTag(ptr, &tag); switch (tag >> 3) { // optional .protobuf_unittest.TestMessageSetContainer container = 1; case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 10)) { ptr = ctx->ParseMessage(_internal_mutable_container(), ptr); CHK_(ptr); } else goto handle_unusual; continue; // optional .protobuf_unittest.NestedTestMessageSetContainer child = 2; case 2: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 18)) { ptr = ctx->ParseMessage(_internal_mutable_child(), ptr); CHK_(ptr); } else goto handle_unusual; continue; default: goto handle_unusual; } // switch handle_unusual: if ((tag == 0) || ((tag & 7) == 4)) { CHK_(ptr); ctx->SetLastTag(tag); goto message_done; } ptr = UnknownFieldParse( tag, _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(), ptr, ctx); CHK_(ptr != nullptr); } // while message_done: _has_bits_.Or(has_bits); return ptr; failure: ptr = nullptr; goto message_done; #undef CHK_ } uint8_t* NestedTestMessageSetContainer::_InternalSerialize( uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const { // @@protoc_insertion_point(serialize_to_array_start:protobuf_unittest.NestedTestMessageSetContainer) uint32_t cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // optional .protobuf_unittest.TestMessageSetContainer container = 1; if (cached_has_bits & 0x00000001u) { target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessage(1, _Internal::container(this), _Internal::container(this).GetCachedSize(), target, stream); } // optional .protobuf_unittest.NestedTestMessageSetContainer child = 2; if (cached_has_bits & 0x00000002u) { target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessage(2, _Internal::child(this), _Internal::child(this).GetCachedSize(), target, stream); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { target = ::_pbi::WireFormat::InternalSerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream); } // @@protoc_insertion_point(serialize_to_array_end:protobuf_unittest.NestedTestMessageSetContainer) return target; } size_t NestedTestMessageSetContainer::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:protobuf_unittest.NestedTestMessageSetContainer) size_t total_size = 0; uint32_t cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x00000003u) { // optional .protobuf_unittest.TestMessageSetContainer container = 1; if (cached_has_bits & 0x00000001u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( *container_); } // optional .protobuf_unittest.NestedTestMessageSetContainer child = 2; if (cached_has_bits & 0x00000002u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( *child_); } } return MaybeComputeUnknownFieldsSize(total_size, &_cached_size_); } const ::PROTOBUF_NAMESPACE_ID::Message::ClassData NestedTestMessageSetContainer::_class_data_ = { ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSizeCheck, NestedTestMessageSetContainer::MergeImpl }; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*NestedTestMessageSetContainer::GetClassData() const { return &_class_data_; } void NestedTestMessageSetContainer::MergeImpl(::PROTOBUF_NAMESPACE_ID::Message* to, const ::PROTOBUF_NAMESPACE_ID::Message& from) { static_cast<NestedTestMessageSetContainer *>(to)->MergeFrom( static_cast<const NestedTestMessageSetContainer &>(from)); } void NestedTestMessageSetContainer::MergeFrom(const NestedTestMessageSetContainer& from) { // @@protoc_insertion_point(class_specific_merge_from_start:protobuf_unittest.NestedTestMessageSetContainer) GOOGLE_DCHECK_NE(&from, this); uint32_t cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = from._has_bits_[0]; if (cached_has_bits & 0x00000003u) { if (cached_has_bits & 0x00000001u) { _internal_mutable_container()->::protobuf_unittest::TestMessageSetContainer::MergeFrom(from._internal_container()); } if (cached_has_bits & 0x00000002u) { _internal_mutable_child()->::protobuf_unittest::NestedTestMessageSetContainer::MergeFrom(from._internal_child()); } } _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); } void NestedTestMessageSetContainer::CopyFrom(const NestedTestMessageSetContainer& from) { // @@protoc_insertion_point(class_specific_copy_from_start:protobuf_unittest.NestedTestMessageSetContainer) if (&from == this) return; Clear(); MergeFrom(from); } bool NestedTestMessageSetContainer::IsInitialized() const { if (_internal_has_container()) { if (!container_->IsInitialized()) return false; } if (_internal_has_child()) { if (!child_->IsInitialized()) return false; } return true; } void NestedTestMessageSetContainer::InternalSwap(NestedTestMessageSetContainer* other) { using std::swap; _internal_metadata_.InternalSwap(&other->_internal_metadata_); swap(_has_bits_[0], other->_has_bits_[0]); ::PROTOBUF_NAMESPACE_ID::internal::memswap< PROTOBUF_FIELD_OFFSET(NestedTestMessageSetContainer, child_) + sizeof(NestedTestMessageSetContainer::child_) - PROTOBUF_FIELD_OFFSET(NestedTestMessageSetContainer, container_)>( reinterpret_cast<char*>(&container_), reinterpret_cast<char*>(&other->container_)); } ::PROTOBUF_NAMESPACE_ID::Metadata NestedTestMessageSetContainer::GetMetadata() const { return ::_pbi::AssignDescriptors( &descriptor_table_google_2fprotobuf_2funittest_5fmset_2eproto_getter, &descriptor_table_google_2fprotobuf_2funittest_5fmset_2eproto_once, file_level_metadata_google_2fprotobuf_2funittest_5fmset_2eproto[1]); } // =================================================================== class TestMessageSetExtension1::_Internal { public: using HasBits = decltype(std::declval<TestMessageSetExtension1>()._has_bits_); static void set_has_i(HasBits* has_bits) { (*has_bits)[0] |= 4u; } static const ::proto2_wireformat_unittest::TestMessageSet& recursive(const TestMessageSetExtension1* msg); static void set_has_recursive(HasBits* has_bits) { (*has_bits)[0] |= 2u; } static void set_has_test_aliasing(HasBits* has_bits) { (*has_bits)[0] |= 1u; } }; const ::proto2_wireformat_unittest::TestMessageSet& TestMessageSetExtension1::_Internal::recursive(const TestMessageSetExtension1* msg) { return *msg->recursive_; } void TestMessageSetExtension1::clear_recursive() { if (recursive_ != nullptr) recursive_->Clear(); _has_bits_[0] &= ~0x00000002u; } TestMessageSetExtension1::TestMessageSetExtension1(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned) : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned) { SharedCtor(); // @@protoc_insertion_point(arena_constructor:protobuf_unittest.TestMessageSetExtension1) } TestMessageSetExtension1::TestMessageSetExtension1(const TestMessageSetExtension1& from) : ::PROTOBUF_NAMESPACE_ID::Message(), _has_bits_(from._has_bits_) { _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); test_aliasing_.InitDefault(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING test_aliasing_.Set("", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING if (from._internal_has_test_aliasing()) { test_aliasing_.Set(from._internal_test_aliasing(), GetArenaForAllocation()); } if (from._internal_has_recursive()) { recursive_ = new ::proto2_wireformat_unittest::TestMessageSet(*from.recursive_); } else { recursive_ = nullptr; } i_ = from.i_; // @@protoc_insertion_point(copy_constructor:protobuf_unittest.TestMessageSetExtension1) } inline void TestMessageSetExtension1::SharedCtor() { test_aliasing_.InitDefault(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING test_aliasing_.Set("", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING ::memset(reinterpret_cast<char*>(this) + static_cast<size_t>( reinterpret_cast<char*>(&recursive_) - reinterpret_cast<char*>(this)), 0, static_cast<size_t>(reinterpret_cast<char*>(&i_) - reinterpret_cast<char*>(&recursive_)) + sizeof(i_)); } TestMessageSetExtension1::~TestMessageSetExtension1() { // @@protoc_insertion_point(destructor:protobuf_unittest.TestMessageSetExtension1) if (auto *arena = _internal_metadata_.DeleteReturnArena<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>()) { (void)arena; return; } SharedDtor(); } inline void TestMessageSetExtension1::SharedDtor() { GOOGLE_DCHECK(GetArenaForAllocation() == nullptr); test_aliasing_.Destroy(); if (this != internal_default_instance()) delete recursive_; } void TestMessageSetExtension1::SetCachedSize(int size) const { _cached_size_.Set(size); } void TestMessageSetExtension1::Clear() { // @@protoc_insertion_point(message_clear_start:protobuf_unittest.TestMessageSetExtension1) uint32_t cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x00000003u) { if (cached_has_bits & 0x00000001u) { test_aliasing_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000002u) { GOOGLE_DCHECK(recursive_ != nullptr); recursive_->Clear(); } } i_ = 0; _has_bits_.Clear(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } const char* TestMessageSetExtension1::_InternalParse(const char* ptr, ::_pbi::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure _Internal::HasBits has_bits{}; while (!ctx->Done(&ptr)) { uint32_t tag; ptr = ::_pbi::ReadTag(ptr, &tag); switch (tag >> 3) { // optional int32 i = 15; case 15: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 120)) { _Internal::set_has_i(&has_bits); i_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // optional .proto2_wireformat_unittest.TestMessageSet recursive = 16; case 16: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 130)) { ptr = ctx->ParseMessage(_internal_mutable_recursive(), ptr); CHK_(ptr); } else goto handle_unusual; continue; // optional string test_aliasing = 17 [ctype = STRING_PIECE]; case 17: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 138)) { auto str = _internal_mutable_test_aliasing(); ptr = ::_pbi::InlineGreedyStringParser(str, ptr, ctx); CHK_(ptr); #ifndef NDEBUG ::_pbi::VerifyUTF8(str, "protobuf_unittest.TestMessageSetExtension1.test_aliasing"); #endif // !NDEBUG } else goto handle_unusual; continue; default: goto handle_unusual; } // switch handle_unusual: if ((tag == 0) || ((tag & 7) == 4)) { CHK_(ptr); ctx->SetLastTag(tag); goto message_done; } ptr = UnknownFieldParse( tag, _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(), ptr, ctx); CHK_(ptr != nullptr); } // while message_done: _has_bits_.Or(has_bits); return ptr; failure: ptr = nullptr; goto message_done; #undef CHK_ } uint8_t* TestMessageSetExtension1::_InternalSerialize( uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const { // @@protoc_insertion_point(serialize_to_array_start:protobuf_unittest.TestMessageSetExtension1) uint32_t cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // optional int32 i = 15; if (cached_has_bits & 0x00000004u) { target = stream->EnsureSpace(target); target = ::_pbi::WireFormatLite::WriteInt32ToArray(15, this->_internal_i(), target); } // optional .proto2_wireformat_unittest.TestMessageSet recursive = 16; if (cached_has_bits & 0x00000002u) { target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessage(16, _Internal::recursive(this), _Internal::recursive(this).GetCachedSize(), target, stream); } // optional string test_aliasing = 17 [ctype = STRING_PIECE]; if (cached_has_bits & 0x00000001u) { ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->_internal_test_aliasing().data(), static_cast<int>(this->_internal_test_aliasing().length()), ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE, "protobuf_unittest.TestMessageSetExtension1.test_aliasing"); target = stream->WriteStringMaybeAliased( 17, this->_internal_test_aliasing(), target); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { target = ::_pbi::WireFormat::InternalSerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream); } // @@protoc_insertion_point(serialize_to_array_end:protobuf_unittest.TestMessageSetExtension1) return target; } size_t TestMessageSetExtension1::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:protobuf_unittest.TestMessageSetExtension1) size_t total_size = 0; uint32_t cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x00000007u) { // optional string test_aliasing = 17 [ctype = STRING_PIECE]; if (cached_has_bits & 0x00000001u) { total_size += 2 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->_internal_test_aliasing()); } // optional .proto2_wireformat_unittest.TestMessageSet recursive = 16; if (cached_has_bits & 0x00000002u) { total_size += 2 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( *recursive_); } // optional int32 i = 15; if (cached_has_bits & 0x00000004u) { total_size += ::_pbi::WireFormatLite::Int32SizePlusOne(this->_internal_i()); } } return MaybeComputeUnknownFieldsSize(total_size, &_cached_size_); } const ::PROTOBUF_NAMESPACE_ID::Message::ClassData TestMessageSetExtension1::_class_data_ = { ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSizeCheck, TestMessageSetExtension1::MergeImpl }; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*TestMessageSetExtension1::GetClassData() const { return &_class_data_; } void TestMessageSetExtension1::MergeImpl(::PROTOBUF_NAMESPACE_ID::Message* to, const ::PROTOBUF_NAMESPACE_ID::Message& from) { static_cast<TestMessageSetExtension1 *>(to)->MergeFrom( static_cast<const TestMessageSetExtension1 &>(from)); } void TestMessageSetExtension1::MergeFrom(const TestMessageSetExtension1& from) { // @@protoc_insertion_point(class_specific_merge_from_start:protobuf_unittest.TestMessageSetExtension1) GOOGLE_DCHECK_NE(&from, this); uint32_t cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = from._has_bits_[0]; if (cached_has_bits & 0x00000007u) { if (cached_has_bits & 0x00000001u) { _internal_set_test_aliasing(from._internal_test_aliasing()); } if (cached_has_bits & 0x00000002u) { _internal_mutable_recursive()->::proto2_wireformat_unittest::TestMessageSet::MergeFrom(from._internal_recursive()); } if (cached_has_bits & 0x00000004u) { i_ = from.i_; } _has_bits_[0] |= cached_has_bits; } _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); } void TestMessageSetExtension1::CopyFrom(const TestMessageSetExtension1& from) { // @@protoc_insertion_point(class_specific_copy_from_start:protobuf_unittest.TestMessageSetExtension1) if (&from == this) return; Clear(); MergeFrom(from); } bool TestMessageSetExtension1::IsInitialized() const { if (_internal_has_recursive()) { if (!recursive_->IsInitialized()) return false; } return true; } void TestMessageSetExtension1::InternalSwap(TestMessageSetExtension1* other) { using std::swap; auto* lhs_arena = GetArenaForAllocation(); auto* rhs_arena = other->GetArenaForAllocation(); _internal_metadata_.InternalSwap(&other->_internal_metadata_); swap(_has_bits_[0], other->_has_bits_[0]); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( &test_aliasing_, lhs_arena, &other->test_aliasing_, rhs_arena ); ::PROTOBUF_NAMESPACE_ID::internal::memswap< PROTOBUF_FIELD_OFFSET(TestMessageSetExtension1, i_) + sizeof(TestMessageSetExtension1::i_) - PROTOBUF_FIELD_OFFSET(TestMessageSetExtension1, recursive_)>( reinterpret_cast<char*>(&recursive_), reinterpret_cast<char*>(&other->recursive_)); } ::PROTOBUF_NAMESPACE_ID::Metadata TestMessageSetExtension1::GetMetadata() const { return ::_pbi::AssignDescriptors( &descriptor_table_google_2fprotobuf_2funittest_5fmset_2eproto_getter, &descriptor_table_google_2fprotobuf_2funittest_5fmset_2eproto_once, file_level_metadata_google_2fprotobuf_2funittest_5fmset_2eproto[2]); } // =================================================================== class TestMessageSetExtension2::_Internal { public: using HasBits = decltype(std::declval<TestMessageSetExtension2>()._has_bits_); static void set_has_str(HasBits* has_bits) { (*has_bits)[0] |= 1u; } }; TestMessageSetExtension2::TestMessageSetExtension2(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned) : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned) { SharedCtor(); // @@protoc_insertion_point(arena_constructor:protobuf_unittest.TestMessageSetExtension2) } TestMessageSetExtension2::TestMessageSetExtension2(const TestMessageSetExtension2& from) : ::PROTOBUF_NAMESPACE_ID::Message(), _has_bits_(from._has_bits_) { _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); str_.InitDefault(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING str_.Set("", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING if (from._internal_has_str()) { str_.Set(from._internal_str(), GetArenaForAllocation()); } // @@protoc_insertion_point(copy_constructor:protobuf_unittest.TestMessageSetExtension2) } inline void TestMessageSetExtension2::SharedCtor() { str_.InitDefault(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING str_.Set("", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING } TestMessageSetExtension2::~TestMessageSetExtension2() { // @@protoc_insertion_point(destructor:protobuf_unittest.TestMessageSetExtension2) if (auto *arena = _internal_metadata_.DeleteReturnArena<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>()) { (void)arena; return; } SharedDtor(); } inline void TestMessageSetExtension2::SharedDtor() { GOOGLE_DCHECK(GetArenaForAllocation() == nullptr); str_.Destroy(); } void TestMessageSetExtension2::SetCachedSize(int size) const { _cached_size_.Set(size); } void TestMessageSetExtension2::Clear() { // @@protoc_insertion_point(message_clear_start:protobuf_unittest.TestMessageSetExtension2) uint32_t cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x00000001u) { str_.ClearNonDefaultToEmpty(); } _has_bits_.Clear(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } const char* TestMessageSetExtension2::_InternalParse(const char* ptr, ::_pbi::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure _Internal::HasBits has_bits{}; while (!ctx->Done(&ptr)) { uint32_t tag; ptr = ::_pbi::ReadTag(ptr, &tag); switch (tag >> 3) { // optional string str = 25; case 25: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 202)) { auto str = _internal_mutable_str(); ptr = ::_pbi::InlineGreedyStringParser(str, ptr, ctx); CHK_(ptr); #ifndef NDEBUG ::_pbi::VerifyUTF8(str, "protobuf_unittest.TestMessageSetExtension2.str"); #endif // !NDEBUG } else goto handle_unusual; continue; default: goto handle_unusual; } // switch handle_unusual: if ((tag == 0) || ((tag & 7) == 4)) { CHK_(ptr); ctx->SetLastTag(tag); goto message_done; } ptr = UnknownFieldParse( tag, _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(), ptr, ctx); CHK_(ptr != nullptr); } // while message_done: _has_bits_.Or(has_bits); return ptr; failure: ptr = nullptr; goto message_done; #undef CHK_ } uint8_t* TestMessageSetExtension2::_InternalSerialize( uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const { // @@protoc_insertion_point(serialize_to_array_start:protobuf_unittest.TestMessageSetExtension2) uint32_t cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // optional string str = 25; if (cached_has_bits & 0x00000001u) { ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->_internal_str().data(), static_cast<int>(this->_internal_str().length()), ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE, "protobuf_unittest.TestMessageSetExtension2.str"); target = stream->WriteStringMaybeAliased( 25, this->_internal_str(), target); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { target = ::_pbi::WireFormat::InternalSerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream); } // @@protoc_insertion_point(serialize_to_array_end:protobuf_unittest.TestMessageSetExtension2) return target; } size_t TestMessageSetExtension2::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:protobuf_unittest.TestMessageSetExtension2) size_t total_size = 0; uint32_t cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // optional string str = 25; cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x00000001u) { total_size += 2 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->_internal_str()); } return MaybeComputeUnknownFieldsSize(total_size, &_cached_size_); } const ::PROTOBUF_NAMESPACE_ID::Message::ClassData TestMessageSetExtension2::_class_data_ = { ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSizeCheck, TestMessageSetExtension2::MergeImpl }; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*TestMessageSetExtension2::GetClassData() const { return &_class_data_; } void TestMessageSetExtension2::MergeImpl(::PROTOBUF_NAMESPACE_ID::Message* to, const ::PROTOBUF_NAMESPACE_ID::Message& from) { static_cast<TestMessageSetExtension2 *>(to)->MergeFrom( static_cast<const TestMessageSetExtension2 &>(from)); } void TestMessageSetExtension2::MergeFrom(const TestMessageSetExtension2& from) { // @@protoc_insertion_point(class_specific_merge_from_start:protobuf_unittest.TestMessageSetExtension2) GOOGLE_DCHECK_NE(&from, this); uint32_t cached_has_bits = 0; (void) cached_has_bits; if (from._internal_has_str()) { _internal_set_str(from._internal_str()); } _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); } void TestMessageSetExtension2::CopyFrom(const TestMessageSetExtension2& from) { // @@protoc_insertion_point(class_specific_copy_from_start:protobuf_unittest.TestMessageSetExtension2) if (&from == this) return; Clear(); MergeFrom(from); } bool TestMessageSetExtension2::IsInitialized() const { return true; } void TestMessageSetExtension2::InternalSwap(TestMessageSetExtension2* other) { using std::swap; auto* lhs_arena = GetArenaForAllocation(); auto* rhs_arena = other->GetArenaForAllocation(); _internal_metadata_.InternalSwap(&other->_internal_metadata_); swap(_has_bits_[0], other->_has_bits_[0]); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( &str_, lhs_arena, &other->str_, rhs_arena ); } ::PROTOBUF_NAMESPACE_ID::Metadata TestMessageSetExtension2::GetMetadata() const { return ::_pbi::AssignDescriptors( &descriptor_table_google_2fprotobuf_2funittest_5fmset_2eproto_getter, &descriptor_table_google_2fprotobuf_2funittest_5fmset_2eproto_once, file_level_metadata_google_2fprotobuf_2funittest_5fmset_2eproto[3]); } // =================================================================== class NestedTestInt::_Internal { public: using HasBits = decltype(std::declval<NestedTestInt>()._has_bits_); static void set_has_a(HasBits* has_bits) { (*has_bits)[0] |= 2u; } static const ::protobuf_unittest::NestedTestInt& child(const NestedTestInt* msg); static void set_has_child(HasBits* has_bits) { (*has_bits)[0] |= 1u; } }; const ::protobuf_unittest::NestedTestInt& NestedTestInt::_Internal::child(const NestedTestInt* msg) { return *msg->child_; } NestedTestInt::NestedTestInt(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned) : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned) { SharedCtor(); // @@protoc_insertion_point(arena_constructor:protobuf_unittest.NestedTestInt) } NestedTestInt::NestedTestInt(const NestedTestInt& from) : ::PROTOBUF_NAMESPACE_ID::Message(), _has_bits_(from._has_bits_) { _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); if (from._internal_has_child()) { child_ = new ::protobuf_unittest::NestedTestInt(*from.child_); } else { child_ = nullptr; } a_ = from.a_; // @@protoc_insertion_point(copy_constructor:protobuf_unittest.NestedTestInt) } inline void NestedTestInt::SharedCtor() { ::memset(reinterpret_cast<char*>(this) + static_cast<size_t>( reinterpret_cast<char*>(&child_) - reinterpret_cast<char*>(this)), 0, static_cast<size_t>(reinterpret_cast<char*>(&a_) - reinterpret_cast<char*>(&child_)) + sizeof(a_)); } NestedTestInt::~NestedTestInt() { // @@protoc_insertion_point(destructor:protobuf_unittest.NestedTestInt) if (auto *arena = _internal_metadata_.DeleteReturnArena<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>()) { (void)arena; return; } SharedDtor(); } inline void NestedTestInt::SharedDtor() { GOOGLE_DCHECK(GetArenaForAllocation() == nullptr); if (this != internal_default_instance()) delete child_; } void NestedTestInt::SetCachedSize(int size) const { _cached_size_.Set(size); } void NestedTestInt::Clear() { // @@protoc_insertion_point(message_clear_start:protobuf_unittest.NestedTestInt) uint32_t cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x00000001u) { GOOGLE_DCHECK(child_ != nullptr); child_->Clear(); } a_ = 0u; _has_bits_.Clear(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } const char* NestedTestInt::_InternalParse(const char* ptr, ::_pbi::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure _Internal::HasBits has_bits{}; while (!ctx->Done(&ptr)) { uint32_t tag; ptr = ::_pbi::ReadTag(ptr, &tag); switch (tag >> 3) { // optional fixed32 a = 1; case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 13)) { _Internal::set_has_a(&has_bits); a_ = ::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<uint32_t>(ptr); ptr += sizeof(uint32_t); } else goto handle_unusual; continue; // optional .protobuf_unittest.NestedTestInt child = 2; case 2: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 18)) { ptr = ctx->ParseMessage(_internal_mutable_child(), ptr); CHK_(ptr); } else goto handle_unusual; continue; default: goto handle_unusual; } // switch handle_unusual: if ((tag == 0) || ((tag & 7) == 4)) { CHK_(ptr); ctx->SetLastTag(tag); goto message_done; } ptr = UnknownFieldParse( tag, _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(), ptr, ctx); CHK_(ptr != nullptr); } // while message_done: _has_bits_.Or(has_bits); return ptr; failure: ptr = nullptr; goto message_done; #undef CHK_ } uint8_t* NestedTestInt::_InternalSerialize( uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const { // @@protoc_insertion_point(serialize_to_array_start:protobuf_unittest.NestedTestInt) uint32_t cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // optional fixed32 a = 1; if (cached_has_bits & 0x00000002u) { target = stream->EnsureSpace(target); target = ::_pbi::WireFormatLite::WriteFixed32ToArray(1, this->_internal_a(), target); } // optional .protobuf_unittest.NestedTestInt child = 2; if (cached_has_bits & 0x00000001u) { target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessage(2, _Internal::child(this), _Internal::child(this).GetCachedSize(), target, stream); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { target = ::_pbi::WireFormat::InternalSerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream); } // @@protoc_insertion_point(serialize_to_array_end:protobuf_unittest.NestedTestInt) return target; } size_t NestedTestInt::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:protobuf_unittest.NestedTestInt) size_t total_size = 0; uint32_t cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x00000003u) { // optional .protobuf_unittest.NestedTestInt child = 2; if (cached_has_bits & 0x00000001u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( *child_); } // optional fixed32 a = 1; if (cached_has_bits & 0x00000002u) { total_size += 1 + 4; } } return MaybeComputeUnknownFieldsSize(total_size, &_cached_size_); } const ::PROTOBUF_NAMESPACE_ID::Message::ClassData NestedTestInt::_class_data_ = { ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSizeCheck, NestedTestInt::MergeImpl }; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*NestedTestInt::GetClassData() const { return &_class_data_; } void NestedTestInt::MergeImpl(::PROTOBUF_NAMESPACE_ID::Message* to, const ::PROTOBUF_NAMESPACE_ID::Message& from) { static_cast<NestedTestInt *>(to)->MergeFrom( static_cast<const NestedTestInt &>(from)); } void NestedTestInt::MergeFrom(const NestedTestInt& from) { // @@protoc_insertion_point(class_specific_merge_from_start:protobuf_unittest.NestedTestInt) GOOGLE_DCHECK_NE(&from, this); uint32_t cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = from._has_bits_[0]; if (cached_has_bits & 0x00000003u) { if (cached_has_bits & 0x00000001u) { _internal_mutable_child()->::protobuf_unittest::NestedTestInt::MergeFrom(from._internal_child()); } if (cached_has_bits & 0x00000002u) { a_ = from.a_; } _has_bits_[0] |= cached_has_bits; } _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); } void NestedTestInt::CopyFrom(const NestedTestInt& from) { // @@protoc_insertion_point(class_specific_copy_from_start:protobuf_unittest.NestedTestInt) if (&from == this) return; Clear(); MergeFrom(from); } bool NestedTestInt::IsInitialized() const { return true; } void NestedTestInt::InternalSwap(NestedTestInt* other) { using std::swap; _internal_metadata_.InternalSwap(&other->_internal_metadata_); swap(_has_bits_[0], other->_has_bits_[0]); ::PROTOBUF_NAMESPACE_ID::internal::memswap< PROTOBUF_FIELD_OFFSET(NestedTestInt, a_) + sizeof(NestedTestInt::a_) - PROTOBUF_FIELD_OFFSET(NestedTestInt, child_)>( reinterpret_cast<char*>(&child_), reinterpret_cast<char*>(&other->child_)); } ::PROTOBUF_NAMESPACE_ID::Metadata NestedTestInt::GetMetadata() const { return ::_pbi::AssignDescriptors( &descriptor_table_google_2fprotobuf_2funittest_5fmset_2eproto_getter, &descriptor_table_google_2fprotobuf_2funittest_5fmset_2eproto_once, file_level_metadata_google_2fprotobuf_2funittest_5fmset_2eproto[4]); } // =================================================================== class TestMessageSetExtension3::_Internal { public: using HasBits = decltype(std::declval<TestMessageSetExtension3>()._has_bits_); static const ::protobuf_unittest::NestedTestInt& msg(const TestMessageSetExtension3* msg); static void set_has_msg(HasBits* has_bits) { (*has_bits)[0] |= 1u; } }; const ::protobuf_unittest::NestedTestInt& TestMessageSetExtension3::_Internal::msg(const TestMessageSetExtension3* msg) { return *msg->msg_; } TestMessageSetExtension3::TestMessageSetExtension3(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned) : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned) { SharedCtor(); // @@protoc_insertion_point(arena_constructor:protobuf_unittest.TestMessageSetExtension3) } TestMessageSetExtension3::TestMessageSetExtension3(const TestMessageSetExtension3& from) : ::PROTOBUF_NAMESPACE_ID::Message(), _has_bits_(from._has_bits_) { _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); if (from._internal_has_msg()) { msg_ = new ::protobuf_unittest::NestedTestInt(*from.msg_); } else { msg_ = nullptr; } // @@protoc_insertion_point(copy_constructor:protobuf_unittest.TestMessageSetExtension3) } inline void TestMessageSetExtension3::SharedCtor() { msg_ = nullptr; } TestMessageSetExtension3::~TestMessageSetExtension3() { // @@protoc_insertion_point(destructor:protobuf_unittest.TestMessageSetExtension3) if (auto *arena = _internal_metadata_.DeleteReturnArena<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>()) { (void)arena; return; } SharedDtor(); } inline void TestMessageSetExtension3::SharedDtor() { GOOGLE_DCHECK(GetArenaForAllocation() == nullptr); if (this != internal_default_instance()) delete msg_; } void TestMessageSetExtension3::SetCachedSize(int size) const { _cached_size_.Set(size); } void TestMessageSetExtension3::Clear() { // @@protoc_insertion_point(message_clear_start:protobuf_unittest.TestMessageSetExtension3) uint32_t cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x00000001u) { GOOGLE_DCHECK(msg_ != nullptr); msg_->Clear(); } _has_bits_.Clear(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } const char* TestMessageSetExtension3::_InternalParse(const char* ptr, ::_pbi::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure _Internal::HasBits has_bits{}; while (!ctx->Done(&ptr)) { uint32_t tag; ptr = ::_pbi::ReadTag(ptr, &tag); switch (tag >> 3) { // optional .protobuf_unittest.NestedTestInt msg = 35; case 35: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 26)) { ptr = ctx->ParseMessage(_internal_mutable_msg(), ptr); CHK_(ptr); } else goto handle_unusual; continue; default: goto handle_unusual; } // switch handle_unusual: if ((tag == 0) || ((tag & 7) == 4)) { CHK_(ptr); ctx->SetLastTag(tag); goto message_done; } ptr = UnknownFieldParse( tag, _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(), ptr, ctx); CHK_(ptr != nullptr); } // while message_done: _has_bits_.Or(has_bits); return ptr; failure: ptr = nullptr; goto message_done; #undef CHK_ } uint8_t* TestMessageSetExtension3::_InternalSerialize( uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const { // @@protoc_insertion_point(serialize_to_array_start:protobuf_unittest.TestMessageSetExtension3) uint32_t cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // optional .protobuf_unittest.NestedTestInt msg = 35; if (cached_has_bits & 0x00000001u) { target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessage(35, _Internal::msg(this), _Internal::msg(this).GetCachedSize(), target, stream); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { target = ::_pbi::WireFormat::InternalSerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream); } // @@protoc_insertion_point(serialize_to_array_end:protobuf_unittest.TestMessageSetExtension3) return target; } size_t TestMessageSetExtension3::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:protobuf_unittest.TestMessageSetExtension3) size_t total_size = 0; uint32_t cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // optional .protobuf_unittest.NestedTestInt msg = 35; cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x00000001u) { total_size += 2 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( *msg_); } return MaybeComputeUnknownFieldsSize(total_size, &_cached_size_); } const ::PROTOBUF_NAMESPACE_ID::Message::ClassData TestMessageSetExtension3::_class_data_ = { ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSizeCheck, TestMessageSetExtension3::MergeImpl }; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*TestMessageSetExtension3::GetClassData() const { return &_class_data_; } void TestMessageSetExtension3::MergeImpl(::PROTOBUF_NAMESPACE_ID::Message* to, const ::PROTOBUF_NAMESPACE_ID::Message& from) { static_cast<TestMessageSetExtension3 *>(to)->MergeFrom( static_cast<const TestMessageSetExtension3 &>(from)); } void TestMessageSetExtension3::MergeFrom(const TestMessageSetExtension3& from) { // @@protoc_insertion_point(class_specific_merge_from_start:protobuf_unittest.TestMessageSetExtension3) GOOGLE_DCHECK_NE(&from, this); uint32_t cached_has_bits = 0; (void) cached_has_bits; if (from._internal_has_msg()) { _internal_mutable_msg()->::protobuf_unittest::NestedTestInt::MergeFrom(from._internal_msg()); } _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); } void TestMessageSetExtension3::CopyFrom(const TestMessageSetExtension3& from) { // @@protoc_insertion_point(class_specific_copy_from_start:protobuf_unittest.TestMessageSetExtension3) if (&from == this) return; Clear(); MergeFrom(from); } bool TestMessageSetExtension3::IsInitialized() const { return true; } void TestMessageSetExtension3::InternalSwap(TestMessageSetExtension3* other) { using std::swap; _internal_metadata_.InternalSwap(&other->_internal_metadata_); swap(_has_bits_[0], other->_has_bits_[0]); swap(msg_, other->msg_); } ::PROTOBUF_NAMESPACE_ID::Metadata TestMessageSetExtension3::GetMetadata() const { return ::_pbi::AssignDescriptors( &descriptor_table_google_2fprotobuf_2funittest_5fmset_2eproto_getter, &descriptor_table_google_2fprotobuf_2funittest_5fmset_2eproto_once, file_level_metadata_google_2fprotobuf_2funittest_5fmset_2eproto[5]); } // =================================================================== class RawMessageSet_Item::_Internal { public: using HasBits = decltype(std::declval<RawMessageSet_Item>()._has_bits_); static void set_has_type_id(HasBits* has_bits) { (*has_bits)[0] |= 2u; } static void set_has_message(HasBits* has_bits) { (*has_bits)[0] |= 1u; } static bool MissingRequiredFields(const HasBits& has_bits) { return ((has_bits[0] & 0x00000003) ^ 0x00000003) != 0; } }; RawMessageSet_Item::RawMessageSet_Item(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned) : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned) { SharedCtor(); // @@protoc_insertion_point(arena_constructor:protobuf_unittest.RawMessageSet.Item) } RawMessageSet_Item::RawMessageSet_Item(const RawMessageSet_Item& from) : ::PROTOBUF_NAMESPACE_ID::Message(), _has_bits_(from._has_bits_) { _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); message_.InitDefault(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING message_.Set("", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING if (from._internal_has_message()) { message_.Set(from._internal_message(), GetArenaForAllocation()); } type_id_ = from.type_id_; // @@protoc_insertion_point(copy_constructor:protobuf_unittest.RawMessageSet.Item) } inline void RawMessageSet_Item::SharedCtor() { message_.InitDefault(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING message_.Set("", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING type_id_ = 0; } RawMessageSet_Item::~RawMessageSet_Item() { // @@protoc_insertion_point(destructor:protobuf_unittest.RawMessageSet.Item) if (auto *arena = _internal_metadata_.DeleteReturnArena<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>()) { (void)arena; return; } SharedDtor(); } inline void RawMessageSet_Item::SharedDtor() { GOOGLE_DCHECK(GetArenaForAllocation() == nullptr); message_.Destroy(); } void RawMessageSet_Item::SetCachedSize(int size) const { _cached_size_.Set(size); } void RawMessageSet_Item::Clear() { // @@protoc_insertion_point(message_clear_start:protobuf_unittest.RawMessageSet.Item) uint32_t cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x00000001u) { message_.ClearNonDefaultToEmpty(); } type_id_ = 0; _has_bits_.Clear(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } const char* RawMessageSet_Item::_InternalParse(const char* ptr, ::_pbi::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure _Internal::HasBits has_bits{}; while (!ctx->Done(&ptr)) { uint32_t tag; ptr = ::_pbi::ReadTag(ptr, &tag); switch (tag >> 3) { // required int32 type_id = 2; case 2: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 16)) { _Internal::set_has_type_id(&has_bits); type_id_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // required bytes message = 3; case 3: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 26)) { auto str = _internal_mutable_message(); ptr = ::_pbi::InlineGreedyStringParser(str, ptr, ctx); CHK_(ptr); } else goto handle_unusual; continue; default: goto handle_unusual; } // switch handle_unusual: if ((tag == 0) || ((tag & 7) == 4)) { CHK_(ptr); ctx->SetLastTag(tag); goto message_done; } ptr = UnknownFieldParse( tag, _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(), ptr, ctx); CHK_(ptr != nullptr); } // while message_done: _has_bits_.Or(has_bits); return ptr; failure: ptr = nullptr; goto message_done; #undef CHK_ } uint8_t* RawMessageSet_Item::_InternalSerialize( uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const { // @@protoc_insertion_point(serialize_to_array_start:protobuf_unittest.RawMessageSet.Item) uint32_t cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // required int32 type_id = 2; if (cached_has_bits & 0x00000002u) { target = stream->EnsureSpace(target); target = ::_pbi::WireFormatLite::WriteInt32ToArray(2, this->_internal_type_id(), target); } // required bytes message = 3; if (cached_has_bits & 0x00000001u) { target = stream->WriteBytesMaybeAliased( 3, this->_internal_message(), target); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { target = ::_pbi::WireFormat::InternalSerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream); } // @@protoc_insertion_point(serialize_to_array_end:protobuf_unittest.RawMessageSet.Item) return target; } size_t RawMessageSet_Item::RequiredFieldsByteSizeFallback() const { // @@protoc_insertion_point(required_fields_byte_size_fallback_start:protobuf_unittest.RawMessageSet.Item) size_t total_size = 0; if (_internal_has_message()) { // required bytes message = 3; total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::BytesSize( this->_internal_message()); } if (_internal_has_type_id()) { // required int32 type_id = 2; total_size += ::_pbi::WireFormatLite::Int32SizePlusOne(this->_internal_type_id()); } return total_size; } size_t RawMessageSet_Item::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:protobuf_unittest.RawMessageSet.Item) size_t total_size = 0; if (((_has_bits_[0] & 0x00000003) ^ 0x00000003) == 0) { // All required fields are present. // required bytes message = 3; total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::BytesSize( this->_internal_message()); // required int32 type_id = 2; total_size += ::_pbi::WireFormatLite::Int32SizePlusOne(this->_internal_type_id()); } else { total_size += RequiredFieldsByteSizeFallback(); } uint32_t cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; return MaybeComputeUnknownFieldsSize(total_size, &_cached_size_); } const ::PROTOBUF_NAMESPACE_ID::Message::ClassData RawMessageSet_Item::_class_data_ = { ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSizeCheck, RawMessageSet_Item::MergeImpl }; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*RawMessageSet_Item::GetClassData() const { return &_class_data_; } void RawMessageSet_Item::MergeImpl(::PROTOBUF_NAMESPACE_ID::Message* to, const ::PROTOBUF_NAMESPACE_ID::Message& from) { static_cast<RawMessageSet_Item *>(to)->MergeFrom( static_cast<const RawMessageSet_Item &>(from)); } void RawMessageSet_Item::MergeFrom(const RawMessageSet_Item& from) { // @@protoc_insertion_point(class_specific_merge_from_start:protobuf_unittest.RawMessageSet.Item) GOOGLE_DCHECK_NE(&from, this); uint32_t cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = from._has_bits_[0]; if (cached_has_bits & 0x00000003u) { if (cached_has_bits & 0x00000001u) { _internal_set_message(from._internal_message()); } if (cached_has_bits & 0x00000002u) { type_id_ = from.type_id_; } _has_bits_[0] |= cached_has_bits; } _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); } void RawMessageSet_Item::CopyFrom(const RawMessageSet_Item& from) { // @@protoc_insertion_point(class_specific_copy_from_start:protobuf_unittest.RawMessageSet.Item) if (&from == this) return; Clear(); MergeFrom(from); } bool RawMessageSet_Item::IsInitialized() const { if (_Internal::MissingRequiredFields(_has_bits_)) return false; return true; } void RawMessageSet_Item::InternalSwap(RawMessageSet_Item* other) { using std::swap; auto* lhs_arena = GetArenaForAllocation(); auto* rhs_arena = other->GetArenaForAllocation(); _internal_metadata_.InternalSwap(&other->_internal_metadata_); swap(_has_bits_[0], other->_has_bits_[0]); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( &message_, lhs_arena, &other->message_, rhs_arena ); swap(type_id_, other->type_id_); } ::PROTOBUF_NAMESPACE_ID::Metadata RawMessageSet_Item::GetMetadata() const { return ::_pbi::AssignDescriptors( &descriptor_table_google_2fprotobuf_2funittest_5fmset_2eproto_getter, &descriptor_table_google_2fprotobuf_2funittest_5fmset_2eproto_once, file_level_metadata_google_2fprotobuf_2funittest_5fmset_2eproto[6]); } // =================================================================== class RawMessageSet::_Internal { public: }; RawMessageSet::RawMessageSet(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned) : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned), item_(arena) { SharedCtor(); // @@protoc_insertion_point(arena_constructor:protobuf_unittest.RawMessageSet) } RawMessageSet::RawMessageSet(const RawMessageSet& from) : ::PROTOBUF_NAMESPACE_ID::Message(), item_(from.item_) { _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); // @@protoc_insertion_point(copy_constructor:protobuf_unittest.RawMessageSet) } inline void RawMessageSet::SharedCtor() { } RawMessageSet::~RawMessageSet() { // @@protoc_insertion_point(destructor:protobuf_unittest.RawMessageSet) if (auto *arena = _internal_metadata_.DeleteReturnArena<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>()) { (void)arena; return; } SharedDtor(); } inline void RawMessageSet::SharedDtor() { GOOGLE_DCHECK(GetArenaForAllocation() == nullptr); } void RawMessageSet::SetCachedSize(int size) const { _cached_size_.Set(size); } void RawMessageSet::Clear() { // @@protoc_insertion_point(message_clear_start:protobuf_unittest.RawMessageSet) uint32_t cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; item_.Clear(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } const char* RawMessageSet::_InternalParse(const char* ptr, ::_pbi::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure while (!ctx->Done(&ptr)) { uint32_t tag; ptr = ::_pbi::ReadTag(ptr, &tag); switch (tag >> 3) { // repeated group Item = 1 { ... }; case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 11)) { ptr -= 1; do { ptr += 1; ptr = ctx->ParseGroup(_internal_add_item(), ptr, 11); CHK_(ptr); if (!ctx->DataAvailable(ptr)) break; } while (::PROTOBUF_NAMESPACE_ID::internal::ExpectTag<11>(ptr)); } else goto handle_unusual; continue; default: goto handle_unusual; } // switch handle_unusual: if ((tag == 0) || ((tag & 7) == 4)) { CHK_(ptr); ctx->SetLastTag(tag); goto message_done; } ptr = UnknownFieldParse( tag, _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(), ptr, ctx); CHK_(ptr != nullptr); } // while message_done: return ptr; failure: ptr = nullptr; goto message_done; #undef CHK_ } uint8_t* RawMessageSet::_InternalSerialize( uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const { // @@protoc_insertion_point(serialize_to_array_start:protobuf_unittest.RawMessageSet) uint32_t cached_has_bits = 0; (void) cached_has_bits; // repeated group Item = 1 { ... }; for (unsigned i = 0, n = static_cast<unsigned>(this->_internal_item_size()); i < n; i++) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteGroup(1, this->_internal_item(i), target, stream); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { target = ::_pbi::WireFormat::InternalSerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream); } // @@protoc_insertion_point(serialize_to_array_end:protobuf_unittest.RawMessageSet) return target; } size_t RawMessageSet::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:protobuf_unittest.RawMessageSet) size_t total_size = 0; uint32_t cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // repeated group Item = 1 { ... }; total_size += 2UL * this->_internal_item_size(); for (const auto& msg : this->item_) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::GroupSize(msg); } return MaybeComputeUnknownFieldsSize(total_size, &_cached_size_); } const ::PROTOBUF_NAMESPACE_ID::Message::ClassData RawMessageSet::_class_data_ = { ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSizeCheck, RawMessageSet::MergeImpl }; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*RawMessageSet::GetClassData() const { return &_class_data_; } void RawMessageSet::MergeImpl(::PROTOBUF_NAMESPACE_ID::Message* to, const ::PROTOBUF_NAMESPACE_ID::Message& from) { static_cast<RawMessageSet *>(to)->MergeFrom( static_cast<const RawMessageSet &>(from)); } void RawMessageSet::MergeFrom(const RawMessageSet& from) { // @@protoc_insertion_point(class_specific_merge_from_start:protobuf_unittest.RawMessageSet) GOOGLE_DCHECK_NE(&from, this); uint32_t cached_has_bits = 0; (void) cached_has_bits; item_.MergeFrom(from.item_); _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); } void RawMessageSet::CopyFrom(const RawMessageSet& from) { // @@protoc_insertion_point(class_specific_copy_from_start:protobuf_unittest.RawMessageSet) if (&from == this) return; Clear(); MergeFrom(from); } bool RawMessageSet::IsInitialized() const { if (!::PROTOBUF_NAMESPACE_ID::internal::AllAreInitialized(item_)) return false; return true; } void RawMessageSet::InternalSwap(RawMessageSet* other) { using std::swap; _internal_metadata_.InternalSwap(&other->_internal_metadata_); item_.InternalSwap(&other->item_); } ::PROTOBUF_NAMESPACE_ID::Metadata RawMessageSet::GetMetadata() const { return ::_pbi::AssignDescriptors( &descriptor_table_google_2fprotobuf_2funittest_5fmset_2eproto_getter, &descriptor_table_google_2fprotobuf_2funittest_5fmset_2eproto_once, file_level_metadata_google_2fprotobuf_2funittest_5fmset_2eproto[7]); } #if !defined(_MSC_VER) || (_MSC_VER >= 1900 && _MSC_VER < 1912) const int TestMessageSetExtension1::kMessageSetExtensionFieldNumber; #endif PROTOBUF_ATTRIBUTE_INIT_PRIORITY2 ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< ::proto2_wireformat_unittest::TestMessageSet, ::PROTOBUF_NAMESPACE_ID::internal::MessageTypeTraits< ::protobuf_unittest::TestMessageSetExtension1 >, 11, false> TestMessageSetExtension1::message_set_extension(kMessageSetExtensionFieldNumber, ::protobuf_unittest::TestMessageSetExtension1::default_instance(), nullptr); #if !defined(_MSC_VER) || (_MSC_VER >= 1900 && _MSC_VER < 1912) const int TestMessageSetExtension2::kMessageSetExtensionFieldNumber; #endif PROTOBUF_ATTRIBUTE_INIT_PRIORITY2 ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< ::proto2_wireformat_unittest::TestMessageSet, ::PROTOBUF_NAMESPACE_ID::internal::MessageTypeTraits< ::protobuf_unittest::TestMessageSetExtension2 >, 11, false> TestMessageSetExtension2::message_set_extension(kMessageSetExtensionFieldNumber, ::protobuf_unittest::TestMessageSetExtension2::default_instance(), nullptr); #if !defined(_MSC_VER) || (_MSC_VER >= 1900 && _MSC_VER < 1912) const int TestMessageSetExtension3::kMessageSetExtensionFieldNumber; #endif PROTOBUF_ATTRIBUTE_INIT_PRIORITY2 ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< ::proto2_wireformat_unittest::TestMessageSet, ::PROTOBUF_NAMESPACE_ID::internal::MessageTypeTraits< ::protobuf_unittest::TestMessageSetExtension3 >, 11, false> TestMessageSetExtension3::message_set_extension(kMessageSetExtensionFieldNumber, ::protobuf_unittest::TestMessageSetExtension3::default_instance(), nullptr); // @@protoc_insertion_point(namespace_scope) } // namespace protobuf_unittest PROTOBUF_NAMESPACE_OPEN template<> PROTOBUF_NOINLINE ::protobuf_unittest::TestMessageSetContainer* Arena::CreateMaybeMessage< ::protobuf_unittest::TestMessageSetContainer >(Arena* arena) { return Arena::CreateMessageInternal< ::protobuf_unittest::TestMessageSetContainer >(arena); } template<> PROTOBUF_NOINLINE ::protobuf_unittest::NestedTestMessageSetContainer* Arena::CreateMaybeMessage< ::protobuf_unittest::NestedTestMessageSetContainer >(Arena* arena) { return Arena::CreateMessageInternal< ::protobuf_unittest::NestedTestMessageSetContainer >(arena); } template<> PROTOBUF_NOINLINE ::protobuf_unittest::TestMessageSetExtension1* Arena::CreateMaybeMessage< ::protobuf_unittest::TestMessageSetExtension1 >(Arena* arena) { return Arena::CreateMessageInternal< ::protobuf_unittest::TestMessageSetExtension1 >(arena); } template<> PROTOBUF_NOINLINE ::protobuf_unittest::TestMessageSetExtension2* Arena::CreateMaybeMessage< ::protobuf_unittest::TestMessageSetExtension2 >(Arena* arena) { return Arena::CreateMessageInternal< ::protobuf_unittest::TestMessageSetExtension2 >(arena); } template<> PROTOBUF_NOINLINE ::protobuf_unittest::NestedTestInt* Arena::CreateMaybeMessage< ::protobuf_unittest::NestedTestInt >(Arena* arena) { return Arena::CreateMessageInternal< ::protobuf_unittest::NestedTestInt >(arena); } template<> PROTOBUF_NOINLINE ::protobuf_unittest::TestMessageSetExtension3* Arena::CreateMaybeMessage< ::protobuf_unittest::TestMessageSetExtension3 >(Arena* arena) { return Arena::CreateMessageInternal< ::protobuf_unittest::TestMessageSetExtension3 >(arena); } template<> PROTOBUF_NOINLINE ::protobuf_unittest::RawMessageSet_Item* Arena::CreateMaybeMessage< ::protobuf_unittest::RawMessageSet_Item >(Arena* arena) { return Arena::CreateMessageInternal< ::protobuf_unittest::RawMessageSet_Item >(arena); } template<> PROTOBUF_NOINLINE ::protobuf_unittest::RawMessageSet* Arena::CreateMaybeMessage< ::protobuf_unittest::RawMessageSet >(Arena* arena) { return Arena::CreateMessageInternal< ::protobuf_unittest::RawMessageSet >(arena); } PROTOBUF_NAMESPACE_CLOSE // @@protoc_insertion_point(global_scope) #include <google/protobuf/port_undef.inc>
ae9c8d9bd502269e6523147f61fe9ce3ad195282
b5a2d8e68402f5094c6a0b2ee4361f5a535f135b
/力扣_C++/图论/787.cpp
933117a81484f159446d8decf0c260dcdd3e28bb
[]
no_license
iStitches/leetCode
cb918dcee3db9f820911053331df4e605bf39db5
5ba17fc21eaea212d36e30bbbf8f228461ed66fb
refs/heads/master
2023-04-09T03:36:27.509287
2021-04-19T15:57:43
2021-04-19T15:57:43
294,427,484
0
0
null
null
null
null
UTF-8
C++
false
false
799
cpp
787.cpp
#include<iostream> #include<algorithm> #include<vector> #include<cstring> #define MAX_VALUE 0x7fffffff #define MAX_SIZE 1000 using namespace std; int n,a,b,c,src,dst,k; int graph[MAX_SIZE][MAX_SIZE]; int res = MAX_VALUE; bool visited[MAX_SIZE]; void dfs(int src,int dst,int k,int price){ if(src == dst){ res = price; return; } if(k == 0) return; for(int i=0;i<n;i++){ if(graph[src][i]>0 && !visited[i]){ if(price+graph[src][i]<=res){ visited[i]=true; dfs(i,dst,k-1,price+graph[src][i]); visited[i]=false; } } } } int main(){ cin>>n; memset(graph,0,sizeof(graph)); memset(visited,false,sizeof(visited)); for(int i=0;i<n;i++) { cin>>a>>b>>c; graph[a][b]=c; } cin>>src>>dst>>k; dfs(src,dst,k+1,0); if(res == MAX_VALUE) cout<<-1; else cout<<res; }
0976890637113ba968d3aab86537e0ad6a0777e1
827afdbb047bcf8359529d49496b7d7d2eec1f0e
/CPP/ModdedObjects/re2/Examples/Solution/src/ex_re2.cpp
035aaaea406e08ca802182c135fe8ec5e3055ecf
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
Radicalware/Libraries
7c51d403c221fbf8d2746ad9f8aaf95821058668
d280ec79d855513412ab64435fd121b9298c3774
refs/heads/master
2023-04-09T10:54:57.618924
2023-03-23T03:13:01
2023-03-23T03:13:01
122,286,234
8
1
Apache-2.0
2021-07-29T06:29:19
2018-02-21T03:05:30
C++
UTF-8
C++
false
false
1,752
cpp
ex_re2.cpp
 #include <iostream> #include <string_view> #include "re2/re2.h" using std::cout; using std::endl; void test1() { cout << "===================================\n"; std::string str; std::string data = "XXoneZZ XXtwoZZ"; re2::StringPiece pc = data; RE2::FindAndConsume(&pc, RE2(R"((?:XX)(\w+)(?:ZZ))"), &str); cout << str << endl; RE2::FindAndConsume(&pc, RE2(R"((?:XX)(\w+)(?:ZZ))"), &str); cout << str << endl; cout << "orig: " << data << endl; cout << "peice: " << pc << endl; cout << "data: " << data << endl; } void test2() { cout << "===================================\n"; std::string str; std::string data = "XXoneZZ XXtwoZZ"; re2::RE2::Options ops; re2::RE2 rex(R"((XX|ZZ))", ops); re2::RE2 rex2(R"((XX|ZZ|YY))", ops); re2::StringPiece pc = data; int value = 0; auto test = [&](int i) { size_t loc = RE2::FindAndConsume(&pc, rex, &str); cout << "data: " << data << endl; cout << "pc: " << pc << endl; cout << "str: " << str << endl; cout << "-------------------\n"; }; for (int i = 0; i < 5; i++) test(i); cout << "orig: " << data << endl; cout << "peice: " << pc << endl; cout << "data: " << data << endl; } void test3() { std::string data = "XXoneZZ XXtwoZZ"; //xstring xdata = data; //xdata.Findall(RE2(R"((?:XX)(\w+)(?:ZZ))")).Join('-').Print(2); } int main() { //test1(); test2(); //test3(); // notes: // re2 = slower to create regex object // std = faster to create regex object // re2 = faster to run scans // std = slower to run scans // summary, if you scan a lot, use re2, for one-offs, use std return 0; }
014a42949ee78bc5469a682d8030d13914ffb7b0
815edcbf058f48be3a57eba6ab68798861e0be5c
/friend functions.cpp
e56cf4ab5bd0e5787476cc396847bcb668e95afb
[]
no_license
7starmohit/c-friend-function
cd1c5867f60a1c618badeb5cac0b2dba9f684d68
4062d78324c526cac11972a3c94bf136fbe9937b
refs/heads/main
2023-04-28T22:30:13.815155
2021-05-08T16:25:46
2021-05-08T16:25:46
365,560,310
0
0
null
null
null
null
UTF-8
C++
false
false
571
cpp
friend functions.cpp
#include<iostream> using namespace std; class complex{ int a; int b; public: void set_data(int w1,int w2) { a=w1; b=w2; } friend complex sumof_complex(complex q1,complex q2); void printdata(void) { cout<<"the complex number is :"<<a<<" + "<<b<<"i"<<endl; } }; complex sumof_complex(complex q1,complex q2) { complex q3; q3.set_data((q1.a+q2.a),(q1.b+q2.b)); return q3; } int main() { complex n1,n2,sum; n1.set_data(2,3); n1.printdata(); n2.set_data(4,7); n2.printdata(); sum=sumof_complex(n1,n2); sum.printdata(); return 0; }
b796f74e02079e17819aa3cb689dbbc6f583c107
e9c0ffba62f5bd0c7bc1b3ca6173b40f3ab488f6
/LeetCode/Longest-Turbulent-Subarray.cpp
10451c05a1a808ef4f519ca0bbba3f64242d67dc
[]
no_license
iiison/technical-interview-prep
501f15877feef3b6b6e1bf3c1ba8b06b894a923b
55b91267cdeeb45756fe47e1817cb5f80ed6d368
refs/heads/master
2022-11-24T11:21:22.526093
2020-08-04T13:49:32
2020-08-04T13:49:32
285,201,793
1
0
null
2020-08-05T06:33:34
2020-08-05T06:33:33
null
UTF-8
C++
false
false
984
cpp
Longest-Turbulent-Subarray.cpp
/* A subarray A[i], A[i+1], ..., A[j] of A is said to be turbulent if and only if: >> For i <= k < j, A[k] > A[k+1] when k is odd, and A[k] < A[k+1] when k is even; >> OR, for i <= k < j, A[k] > A[k+1] when k is even, and A[k] < A[k+1] when k is odd. That is, the subarray is turbulent if the comparison sign flips between each adjacent pair of elements in the subarray. Return the length of a maximum size turbulent subarray of A. Example 1: Input: [9,4,2,10,7,8,8,1,9] Output: 5 Explanation: (A[1] > A[2] < A[3] > A[4] < A[5]) Example 2: Input: [4,8,12,16] Output: 2 Example 3: Input: [100] Output: 1 */ int maxTurbulenceSize(vector<int>& A) { vector<vector<int>> dp(A.size(), vector<int>(2, 1)); int res = 1; for (int i = 1; i < A.size(); i++) { if (A[i] > A[i - 1]) dp[i][0] = dp[i - 1][1] + 1; else if (A[i] < A[i - 1]) dp[i][1] = dp[i - 1][0] + 1; res = max(res, max(dp[i][0], dp[i][1])); } return res; }
1a115f11791c58f14791bcff0c8b5520ad7affe6
9739cc18419ac711ac7ccc1a8c7febd4127bfe75
/skrypty/tql/Parser_temp.cpp
c72ca06fdd518b3b8b46202c35e94fbcfa9461c1
[]
no_license
sumlib/main
ac27e14252c65cf2ef9a111d24797c856b0429fa
5e085b319916435e37ac216cfd2f0a32ee6b36b4
refs/heads/master
2021-01-10T20:30:16.863531
2011-05-12T19:20:34
2011-05-12T19:20:34
369,944
0
0
null
null
null
null
UTF-8
C++
false
false
43,608
cpp
Parser_temp.cpp
#define YY_parse_h_included /*#define YY_USE_CLASS */ /* A Bison++ parser, made from TQL.y */ /* with Bison++ version bison++ Version 1.21.9-1, adapted from GNU bison by coetmeur@icdc.fr Maintained by Magnus Ekdahl <magnus@debian.org> */ #define yyparse TQLparse #define yylex TQLlex #define yyerror TQLerror #define yylval TQLlval #define yychar TQLchar #define yydebug TQLdebug #line 1 "/usr/share/bison++/bison.cc" /* -*-C-*- Note some compilers choke on comments on `#line' lines. */ /* Skeleton output parser for bison, Copyright (C) 1984, 1989, 1990 Bob Corbett and Richard Stallman This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 1, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. As a special exception, when this file is copied by Bison++ into a Bison++ output file, you may use that output file without restriction. This special exception was added by the Free Software Foundation in version 1.24 of Bison, and has been in Bison++ since 1.21.9. */ /* HEADER SECTION */ #if defined( _MSDOS ) || defined(MSDOS) || defined(__MSDOS__) #define __MSDOS_AND_ALIKE #endif #if defined(_WINDOWS) && defined(_MSC_VER) #define __HAVE_NO_ALLOCA #define __MSDOS_AND_ALIKE #endif #ifndef alloca #if defined( __GNUC__) #define alloca __builtin_alloca #elif (!defined (__STDC__) && defined (sparc)) || defined (__sparc__) || defined (__sparc) || defined (__sgi) #include <alloca.h> #elif defined (__MSDOS_AND_ALIKE) #include <malloc.h> #ifndef __TURBOC__ /* MS C runtime lib */ #define alloca _alloca #endif #elif defined(_AIX) /* pragma must be put before any C/C++ instruction !! */ #pragma alloca #include <malloc.h> #elif defined(__hpux) #ifdef __cplusplus extern "C" { void *alloca (unsigned int); }; #else /* not __cplusplus */ void *alloca (); #endif /* not __cplusplus */ #endif /* not _AIX not MSDOS, or __TURBOC__ or _AIX, not sparc. */ #endif /* alloca not defined. */ #ifdef c_plusplus #ifndef __cplusplus #define __cplusplus #endif #endif #ifdef __cplusplus #ifndef YY_USE_CLASS /*#warning "For C++ its recomended to use bison++, otherwise classes won't be generated"*/ #endif #else #ifndef __STDC__ #define const #endif #ifdef YY_USE_CLASS #error "This is a C++ header generated by bison++, please use a C++ compiler!" #endif #endif #include <stdio.h> #define YYBISON 1 #line 88 "/usr/share/bison++/bison.cc" #line 2 "TQL.y" #include <stdlib.h> #include <stdio.h> #include <string.h> #include "Absyn.h" #define initialize_lexer TQL_initialize_lexer extern int yyparse(void); extern int yylex(void); extern int initialize_lexer(FILE * inp); int yyline = 1; void yyerror(const char *str) { fprintf(stderr,"error in line %d: %s\n",yyline, str); } ZapZloz YY_RESULT_ZapZloz_ = 0; ZapZloz pZapZloz(FILE *inp) { symbols_init(); initialize_lexer(inp); if (yyparse()) { /* Failure */ return 0; } else { /* Success */ return YY_RESULT_ZapZloz_; } } Query YY_RESULT_Query_ = 0; Query pQuery(FILE *inp) { initialize_lexer(inp); if (yyparse()) { /* Failure */ return 0; } else { /* Success */ return YY_RESULT_Query_; } } QueryLine YY_RESULT_QueryLine_ = 0; QueryLine pQueryLine(FILE *inp) { initialize_lexer(inp); if (yyparse()) { /* Failure */ return 0; } else { /* Success */ return YY_RESULT_QueryLine_; } } Expr YY_RESULT_Expr_ = 0; Expr pExpr(FILE *inp) { initialize_lexer(inp); if (yyparse()) { /* Failure */ return 0; } else { /* Success */ return YY_RESULT_Expr_; } } QueryList YY_RESULT_QueryList_ = 0; QueryList pQueryList(FILE *inp) { initialize_lexer(inp); if (yyparse()) { /* Failure */ return 0; } else { /* Success */ return YY_RESULT_QueryList_; } } QueryLineList YY_RESULT_QueryLineList_ = 0; QueryLineList pQueryLineList(FILE *inp) { initialize_lexer(inp); if (yyparse()) { /* Failure */ return 0; } else { /* Success */ return YY_RESULT_QueryLineList_; } } int YY_RESULT_Przerwa_ = 0; int pPrzerwa(FILE *inp) { initialize_lexer(inp); if (yyparse()) { /* Failure */ return 0; } else { /* Success */ return YY_RESULT_Przerwa_; } } ListPrzerwa YY_RESULT_ListPrzerwa_ = 0; ListPrzerwa pListPrzerwa(FILE *inp) { initialize_lexer(inp); if (yyparse()) { /* Failure */ return 0; } else { /* Success */ return YY_RESULT_ListPrzerwa_; } } Text YY_RESULT_Text_ = 0; Text pText(FILE *inp) { initialize_lexer(inp); if (yyparse()) { /* Failure */ return 0; } else { /* Success */ return YY_RESULT_Text_; } } Nazwa YY_RESULT_Nazwa_ = 0; Nazwa pNazwa(FILE *inp) { initialize_lexer(inp); if (yyparse()) { /* Failure */ return 0; } else { /* Success */ return YY_RESULT_Nazwa_; } } QueryList reverseQueryList(QueryList l) { QueryList prev = 0; QueryList tmp = 0; while (l) { tmp = l->querylist_; l->querylist_ = prev; prev = l; l = tmp; } return prev; } QueryLineList reverseQueryLineList(QueryLineList l) { QueryLineList prev = 0; QueryLineList tmp = 0; while (l) { tmp = l->querylinelist_; l->querylinelist_ = prev; prev = l; l = tmp; } return prev; } ListPrzerwa reverseListPrzerwa(ListPrzerwa l) { ListPrzerwa prev = 0; ListPrzerwa tmp = 0; while (l) { tmp = l->listprzerwa_; l->listprzerwa_ = prev; prev = l; l = tmp; } return prev; } #line 199 "TQL.y" typedef union { int int_; char char_; double double_; int string_; ZapZloz zapzloz_; Query zapytanie_; QueryLine liniazapytania_; Expr wyraz_; QueryList querylist_; QueryLineList querylinelist_; Przerwa przerwa_; ListPrzerwa listprzerwa_; Text tekst_; Nazwa nazwa_; } yy_parse_stype; #define YY_parse_STYPE yy_parse_stype #ifndef YY_USE_CLASS #define YYSTYPE yy_parse_stype #endif #line 88 "/usr/share/bison++/bison.cc" /* %{ and %header{ and %union, during decl */ #define YY_parse_BISON 1 #ifndef YY_parse_COMPATIBILITY #ifndef YY_USE_CLASS #define YY_parse_COMPATIBILITY 1 #else #define YY_parse_COMPATIBILITY 0 #endif #endif #if YY_parse_COMPATIBILITY != 0 /* backward compatibility */ #ifdef YYLTYPE #ifndef YY_parse_LTYPE #define YY_parse_LTYPE YYLTYPE #endif #endif /* Testing alternative bison solution /#ifdef YYSTYPE*/ #ifndef YY_parse_STYPE #define YY_parse_STYPE YYSTYPE #endif /*#endif*/ #ifdef YYDEBUG #ifndef YY_parse_DEBUG #define YY_parse_DEBUG YYDEBUG #endif #endif /* use goto to be compatible */ #ifndef YY_parse_USE_GOTO #define YY_parse_USE_GOTO 1 #endif #endif /* use no goto to be clean in C++ */ #ifndef YY_parse_USE_GOTO #define YY_parse_USE_GOTO 0 #endif #ifndef YY_parse_PURE #line 130 "/usr/share/bison++/bison.cc" #line 130 "/usr/share/bison++/bison.cc" /* YY_parse_PURE */ #endif /* section apres lecture def, avant lecture grammaire S2 */ #line 134 "/usr/share/bison++/bison.cc" #define YY_parse_PARSE TQLparse #define YY_parse_LEX TQLlex #define YY_parse_ERROR TQLerror #define YY_parse_LVAL TQLlval #define YY_parse_CHAR TQLchar #define YY_parse_DEBUG TQLdebug #line 134 "/usr/share/bison++/bison.cc" /* prefix */ #ifndef YY_parse_DEBUG #line 136 "/usr/share/bison++/bison.cc" #define YY_parse_DEBUG 1 #line 136 "/usr/share/bison++/bison.cc" /* YY_parse_DEBUG */ #endif #ifndef YY_parse_LSP_NEEDED #line 141 "/usr/share/bison++/bison.cc" #line 141 "/usr/share/bison++/bison.cc" /* YY_parse_LSP_NEEDED*/ #endif /* DEFAULT LTYPE*/ #ifdef YY_parse_LSP_NEEDED #ifndef YY_parse_LTYPE #ifndef BISON_YYLTYPE_ISDECLARED #define BISON_YYLTYPE_ISDECLARED typedef struct yyltype { int timestamp; int first_line; int first_column; int last_line; int last_column; char *text; } yyltype; #endif #define YY_parse_LTYPE yyltype #endif #endif /* DEFAULT STYPE*/ /* We used to use `unsigned long' as YY_parse_STYPE on MSDOS, but it seems better to be consistent. Most programs should declare their own type anyway. */ #ifndef YY_parse_STYPE #define YY_parse_STYPE int #endif /* DEFAULT MISCELANEOUS */ #ifndef YY_parse_PARSE #define YY_parse_PARSE yyparse #endif #ifndef YY_parse_LEX #define YY_parse_LEX yylex #endif #ifndef YY_parse_LVAL #define YY_parse_LVAL yylval #endif #ifndef YY_parse_LLOC #define YY_parse_LLOC yylloc #endif #ifndef YY_parse_CHAR #define YY_parse_CHAR yychar #endif #ifndef YY_parse_NERRS #define YY_parse_NERRS yynerrs #endif #ifndef YY_parse_DEBUG_FLAG #define YY_parse_DEBUG_FLAG yydebug #endif #ifndef YY_parse_ERROR #define YY_parse_ERROR yyerror #endif #ifndef YY_parse_PARSE_PARAM #ifndef YY_USE_CLASS #ifdef YYPARSE_PARAM #define YY_parse_PARSE_PARAM void* YYPARSE_PARAM #else #ifndef __STDC__ #ifndef __cplusplus #define YY_parse_PARSE_PARAM #endif #endif #endif #endif #ifndef YY_parse_PARSE_PARAM #define YY_parse_PARSE_PARAM void #endif #endif #if YY_parse_COMPATIBILITY != 0 /* backward compatibility */ #ifdef YY_parse_LTYPE #ifndef YYLTYPE #define YYLTYPE YY_parse_LTYPE #else /* WARNING obsolete !!! user defined YYLTYPE not reported into generated header */ #endif #endif /* Removed due to bison compabilityproblems /#ifndef YYSTYPE /#define YYSTYPE YY_parse_STYPE /#else*/ /* WARNING obsolete !!! user defined YYSTYPE not reported into generated header */ /*#endif*/ #ifdef YY_parse_PURE # ifndef YYPURE # define YYPURE YY_parse_PURE # endif #endif #ifdef YY_parse_DEBUG # ifndef YYDEBUG # define YYDEBUG YY_parse_DEBUG # endif #endif #define YY_parse_ERROR_VERBOSE 1 #ifndef YY_parse_ERROR_VERBOSE #ifdef YYERROR_VERBOSE #define YY_parse_ERROR_VERBOSE YYERROR_VERBOSE #endif #endif #ifndef YY_parse_LSP_NEEDED # ifdef YYLSP_NEEDED # define YY_parse_LSP_NEEDED YYLSP_NEEDED # endif #endif #endif #ifndef YY_USE_CLASS /* TOKEN C */ #line 263 "/usr/share/bison++/bison.cc" #define _ERROR_ 258 #define _SYMB_NEWLINE 259 #define _SYMB_DWUKROPEK 260 #define _SYMB_AND 261 #define _SYMB_OR 262 #define _SYMB_NOT 263 #define _SYMB_ALL 264 #define _SYMB_LEWIAS 265 #define _SYMB_PRAWIAS 266 #define _SYMB_AS 267 #define _SYMB_DEFINE 268 #define _SYMB_DWUKROPEK0 269 #define _SYMB_DWUKROPEK1 270 #define _SYMB_DIGIT_IDENT 271 #define _STRING_ 272 #define _IDENT_ 273 #line 263 "/usr/share/bison++/bison.cc" /* #defines tokens */ #else /* CLASS */ #ifndef YY_parse_CLASS #define YY_parse_CLASS parse #endif #ifndef YY_parse_INHERIT #define YY_parse_INHERIT #endif #ifndef YY_parse_MEMBERS #define YY_parse_MEMBERS #endif #ifndef YY_parse_LEX_BODY #define YY_parse_LEX_BODY #endif #ifndef YY_parse_ERROR_BODY #define YY_parse_ERROR_BODY #endif #ifndef YY_parse_CONSTRUCTOR_PARAM #define YY_parse_CONSTRUCTOR_PARAM #endif #ifndef YY_parse_CONSTRUCTOR_CODE #define YY_parse_CONSTRUCTOR_CODE #endif #ifndef YY_parse_CONSTRUCTOR_INIT #define YY_parse_CONSTRUCTOR_INIT #endif /* choose between enum and const */ #ifndef YY_parse_USE_CONST_TOKEN #define YY_parse_USE_CONST_TOKEN 0 /* yes enum is more compatible with flex, */ /* so by default we use it */ #endif #if YY_parse_USE_CONST_TOKEN != 0 #ifndef YY_parse_ENUM_TOKEN #define YY_parse_ENUM_TOKEN yy_parse_enum_token #endif #endif class YY_parse_CLASS YY_parse_INHERIT { public: #if YY_parse_USE_CONST_TOKEN != 0 /* static const int token ... */ #line 307 "/usr/share/bison++/bison.cc" static const int _ERROR_; static const int _SYMB_NEWLINE; static const int _SYMB_DWUKROPEK; static const int _SYMB_AND; static const int _SYMB_OR; static const int _SYMB_NOT; static const int _SYMB_ALL; static const int _SYMB_LEWIAS; static const int _SYMB_PRAWIAS; static const int _SYMB_AS; static const int _SYMB_DEFINE; static const int _SYMB_DWUKROPEK0; static const int _SYMB_DWUKROPEK1; static const int _SYMB_DIGIT_IDENT; static const int _STRING_; static const int _IDENT_; #line 307 "/usr/share/bison++/bison.cc" /* decl const */ #else enum YY_parse_ENUM_TOKEN { YY_parse_NULL_TOKEN=0 #line 310 "/usr/share/bison++/bison.cc" ,_ERROR_=258 ,_SYMB_NEWLINE=259 ,_SYMB_DWUKROPEK=260 ,_SYMB_AND=261 ,_SYMB_OR=262 ,_SYMB_NOT=263 ,_SYMB_ALL=264 ,_SYMB_LEWIAS=265 ,_SYMB_PRAWIAS=266 ,_SYMB_AS=267 ,_SYMB_DEFINE=268 ,_SYMB_DWUKROPEK0=269 ,_SYMB_DWUKROPEK1=270 ,_SYMB_DIGIT_IDENT=271 ,_STRING_=272 ,_IDENT_=273 #line 310 "/usr/share/bison++/bison.cc" /* enum token */ }; /* end of enum declaration */ #endif public: int YY_parse_PARSE (YY_parse_PARSE_PARAM); virtual void YY_parse_ERROR(char *msg) YY_parse_ERROR_BODY; #ifdef YY_parse_PURE #ifdef YY_parse_LSP_NEEDED virtual int YY_parse_LEX (YY_parse_STYPE *YY_parse_LVAL,YY_parse_LTYPE *YY_parse_LLOC) YY_parse_LEX_BODY; #else virtual int YY_parse_LEX (YY_parse_STYPE *YY_parse_LVAL) YY_parse_LEX_BODY; #endif #else virtual int YY_parse_LEX() YY_parse_LEX_BODY; YY_parse_STYPE YY_parse_LVAL; #ifdef YY_parse_LSP_NEEDED YY_parse_LTYPE YY_parse_LLOC; #endif int YY_parse_NERRS; int YY_parse_CHAR; #endif #if YY_parse_DEBUG != 0 int YY_parse_DEBUG_FLAG; /* nonzero means print parse trace */ #endif public: YY_parse_CLASS(YY_parse_CONSTRUCTOR_PARAM); public: YY_parse_MEMBERS }; /* other declare folow */ #if YY_parse_USE_CONST_TOKEN != 0 #line 341 "/usr/share/bison++/bison.cc" const int YY_parse_CLASS::_ERROR_=258; const int YY_parse_CLASS::_SYMB_NEWLINE=259; const int YY_parse_CLASS::_SYMB_DWUKROPEK=260; const int YY_parse_CLASS::_SYMB_AND=261; const int YY_parse_CLASS::_SYMB_OR=262; const int YY_parse_CLASS::_SYMB_NOT=263; const int YY_parse_CLASS::_SYMB_ALL=264; const int YY_parse_CLASS::_SYMB_LEWIAS=265; const int YY_parse_CLASS::_SYMB_PRAWIAS=266; const int YY_parse_CLASS::_SYMB_AS=267; const int YY_parse_CLASS::_SYMB_DEFINE=268; const int YY_parse_CLASS::_SYMB_DWUKROPEK0=269; const int YY_parse_CLASS::_SYMB_DWUKROPEK1=270; const int YY_parse_CLASS::_SYMB_DIGIT_IDENT=271; const int YY_parse_CLASS::_STRING_=272; const int YY_parse_CLASS::_IDENT_=273; #line 341 "/usr/share/bison++/bison.cc" /* const YY_parse_CLASS::token */ #endif /*apres const */ YY_parse_CLASS::YY_parse_CLASS(YY_parse_CONSTRUCTOR_PARAM) YY_parse_CONSTRUCTOR_INIT { #if YY_parse_DEBUG != 0 YY_parse_DEBUG_FLAG=0; #endif YY_parse_CONSTRUCTOR_CODE; }; #endif #line 352 "/usr/share/bison++/bison.cc" #define YYFINAL 49 #define YYFLAG -32768 #define YYNTBASE 19 #define YYTRANSLATE(x) ((unsigned)(x) <= 273 ? yytranslate[x] : 31) static const char yytranslate[] = { 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18 }; #if YY_parse_DEBUG != 0 static const short yyprhs[] = { 0, 0, 2, 5, 12, 19, 21, 25, 29, 33, 35, 38, 40, 44, 47, 50, 52, 56, 58, 61, 64, 68, 70, 71, 74, 76, 78, 80 }; static const short yyrhs[] = { 25, 0, 26, 28, 0, 13, 4, 20, 12, 30, 28, 0, 15, 4, 20, 14, 30, 28, 0, 28, 0, 18, 5, 22, 0, 22, 6, 23, 0, 22, 7, 23, 0, 23, 0, 8, 23, 0, 24, 0, 29, 9, 29, 0, 29, 9, 0, 9, 29, 0, 29, 0, 10, 22, 11, 0, 20, 0, 20, 25, 0, 21, 4, 0, 21, 4, 26, 0, 4, 0, 0, 28, 27, 0, 17, 0, 18, 0, 16, 0, 17, 0 }; #endif #if (YY_parse_DEBUG != 0) || defined(YY_parse_ERROR_VERBOSE) static const short yyrline[] = { 0, 250, 252, 253, 254, 255, 257, 259, 260, 261, 263, 264, 266, 267, 268, 269, 270, 272, 273, 275, 276, 278, 280, 281, 283, 284, 285, 287 }; static const char * const yytname[] = { "$","error","$illegal.","_ERROR_", "_SYMB_NEWLINE","_SYMB_DWUKROPEK","_SYMB_AND","_SYMB_OR","_SYMB_NOT","_SYMB_ALL","_SYMB_LEWIAS","_SYMB_PRAWIAS", "_SYMB_AS","_SYMB_DEFINE","_SYMB_DWUKROPEK0","_SYMB_SEARCH","_SYMB_12","_STRING_","_IDENT_","ZapZloz", "Query","QueryLine","Expr","Expr1","Expr2","QueryList","QueryLineList", "Przerwa","ListPrzerwa","Text","Nazwa","" }; #endif static const short yyr1[] = { 0, 19, 20, 20, 20, 20, 21, 22, 22, 22, 23, 23, 24, 24, 24, 24, 24, 25, 25, 26, 26, 27, 28, 28, 29, 29, 29, 30 }; static const short yyr2[] = { 0, 1, 2, 6, 6, 1, 3, 3, 3, 1, 2, 1, 3, 2, 2, 1, 3, 1, 2, 2, 3, 1, 0, 2, 1, 1, 1, 1 }; static const short yydefact[] = { 22, 0, 0, 0, 17, 0, 1, 22, 5, 22, 22, 0, 18, 19, 2, 21, 23, 0, 0, 0, 0, 0, 26, 24, 25, 6, 9, 11, 15, 20, 0, 0, 10, 14, 0, 0, 0, 13, 27, 22, 22, 16, 7, 8, 12, 3, 4, 0, 0, 0 }; static const short yydefgoto[] = { 47, 4, 5, 25, 26, 27, 6, 7, 16, 8, 28, 39 }; static const short yypact[] = { -9, 6, 15, 0, -2, 30,-32768,-32768, 31, -9, -9, 13,-32768, 18, 31,-32768,-32768, 25, 24, 13, 8, 13,-32768,-32768,-32768, 21,-32768,-32768, 32,-32768, 22, 22,-32768,-32768, 1, 13, 13, 8,-32768,-32768,-32768, -32768,-32768,-32768,-32768, 31, 31, 40, 42,-32768 }; static const short yypgoto[] = {-32768, 5,-32768, 23, -18,-32768, 39, 33,-32768, -7, -17, 14 }; #define YYLAST 46 static const short yytable[] = { 14, 32, -22, 33, 1, 11, 2, 35, 36, 3, 9, 1, 41, 2, 17, 18, 3, 42, 43, 10, 44, 19, 20, 21, 22, 23, 24, 35, 36, 22, 23, 24, 45, 46, 13, 15, 3, 30, 31, 38, 48, 37, 49, 12, 34, 40, 29 }; static const short yycheck[] = { 7, 19, 4, 20, 13, 5, 15, 6, 7, 18, 4, 13, 11, 15, 9, 10, 18, 35, 36, 4, 37, 8, 9, 10, 16, 17, 18, 6, 7, 16, 17, 18, 39, 40, 4, 4, 18, 12, 14, 17, 0, 9, 0, 4, 21, 31, 13 }; #line 352 "/usr/share/bison++/bison.cc" /* fattrs + tables */ /* parser code folow */ /* This is the parser code that is written into each bison parser when the %semantic_parser declaration is not specified in the grammar. It was written by Richard Stallman by simplifying the hairy parser used when %semantic_parser is specified. */ /* Note: dollar marks section change the next is replaced by the list of actions, each action as one case of the switch. */ #if YY_parse_USE_GOTO != 0 /* SUPRESSION OF GOTO : on some C++ compiler (sun c++) the goto is strictly forbidden if any constructor/destructor is used in the whole function (very stupid isn't it ?) so goto are to be replaced with a 'while/switch/case construct' here are the macro to keep some apparent compatibility */ #define YYGOTO(lb) {yy_gotostate=lb;continue;} #define YYBEGINGOTO enum yy_labels yy_gotostate=yygotostart; \ for(;;) switch(yy_gotostate) { case yygotostart: { #define YYLABEL(lb) } case lb: { #define YYENDGOTO } } #define YYBEGINDECLARELABEL enum yy_labels {yygotostart #define YYDECLARELABEL(lb) ,lb #define YYENDDECLARELABEL }; #else /* macro to keep goto */ #define YYGOTO(lb) goto lb #define YYBEGINGOTO #define YYLABEL(lb) lb: #define YYENDGOTO #define YYBEGINDECLARELABEL #define YYDECLARELABEL(lb) #define YYENDDECLARELABEL #endif /* LABEL DECLARATION */ YYBEGINDECLARELABEL YYDECLARELABEL(yynewstate) YYDECLARELABEL(yybackup) /* YYDECLARELABEL(yyresume) */ YYDECLARELABEL(yydefault) YYDECLARELABEL(yyreduce) YYDECLARELABEL(yyerrlab) /* here on detecting error */ YYDECLARELABEL(yyerrlab1) /* here on error raised explicitly by an action */ YYDECLARELABEL(yyerrdefault) /* current state does not do anything special for the error token. */ YYDECLARELABEL(yyerrpop) /* pop the current state because it cannot handle the error token */ YYDECLARELABEL(yyerrhandle) YYENDDECLARELABEL /* ALLOCA SIMULATION */ /* __HAVE_NO_ALLOCA */ #ifdef __HAVE_NO_ALLOCA int __alloca_free_ptr(char *ptr,char *ref) {if(ptr!=ref) free(ptr); return 0;} #define __ALLOCA_alloca(size) malloc(size) #define __ALLOCA_free(ptr,ref) __alloca_free_ptr((char *)ptr,(char *)ref) #ifdef YY_parse_LSP_NEEDED #define __ALLOCA_return(num) \ do { return( __ALLOCA_free(yyss,yyssa)+\ __ALLOCA_free(yyvs,yyvsa)+\ __ALLOCA_free(yyls,yylsa)+\ (num)); } while(0) #else #define __ALLOCA_return(num) \ do { return( __ALLOCA_free(yyss,yyssa)+\ __ALLOCA_free(yyvs,yyvsa)+\ (num)); } while(0) #endif #else #define __ALLOCA_return(num) do { return(num); } while(0) #define __ALLOCA_alloca(size) alloca(size) #define __ALLOCA_free(ptr,ref) #endif /* ENDALLOCA SIMULATION */ #define yyerrok (yyerrstatus = 0) #define yyclearin (YY_parse_CHAR = YYEMPTY) #define YYEMPTY -2 #define YYEOF 0 #define YYACCEPT __ALLOCA_return(0) #define YYABORT __ALLOCA_return(1) #define YYERROR YYGOTO(yyerrlab1) /* Like YYERROR except do call yyerror. This remains here temporarily to ease the transition to the new meaning of YYERROR, for GCC. Once GCC version 2 has supplanted version 1, this can go. */ #define YYFAIL YYGOTO(yyerrlab) #define YYRECOVERING() (!!yyerrstatus) #define YYBACKUP(token, value) \ do \ if (YY_parse_CHAR == YYEMPTY && yylen == 1) \ { YY_parse_CHAR = (token), YY_parse_LVAL = (value); \ yychar1 = YYTRANSLATE (YY_parse_CHAR); \ YYPOPSTACK; \ YYGOTO(yybackup); \ } \ else \ { YY_parse_ERROR ("syntax error: cannot back up"); YYERROR; } \ while (0) #define YYTERROR 1 #define YYERRCODE 256 #ifndef YY_parse_PURE /* UNPURE */ #define YYLEX YY_parse_LEX() #ifndef YY_USE_CLASS /* If nonreentrant, and not class , generate the variables here */ int YY_parse_CHAR; /* the lookahead symbol */ YY_parse_STYPE YY_parse_LVAL; /* the semantic value of the */ /* lookahead symbol */ int YY_parse_NERRS; /* number of parse errors so far */ #ifdef YY_parse_LSP_NEEDED YY_parse_LTYPE YY_parse_LLOC; /* location data for the lookahead */ /* symbol */ #endif #endif #else /* PURE */ #ifdef YY_parse_LSP_NEEDED #define YYLEX YY_parse_LEX(&YY_parse_LVAL, &YY_parse_LLOC) #else #define YYLEX YY_parse_LEX(&YY_parse_LVAL) #endif #endif #ifndef YY_USE_CLASS #if YY_parse_DEBUG != 0 int YY_parse_DEBUG_FLAG; /* nonzero means print parse trace */ /* Since this is uninitialized, it does not stop multiple parsers from coexisting. */ #endif #endif /* YYINITDEPTH indicates the initial size of the parser's stacks */ #ifndef YYINITDEPTH #define YYINITDEPTH 200 #endif /* YYMAXDEPTH is the maximum size the stacks can grow to (effective only if the built-in stack extension method is used). */ #if YYMAXDEPTH == 0 #undef YYMAXDEPTH #endif #ifndef YYMAXDEPTH #define YYMAXDEPTH 10000 #endif #if __GNUC__ > 1 /* GNU C and GNU C++ define this. */ #define __yy_bcopy(FROM,TO,COUNT) __builtin_memcpy(TO,FROM,COUNT) #else /* not GNU C or C++ */ /* This is the most reliable way to avoid incompatibilities in available built-in functions on various systems. */ #ifdef __cplusplus static void __yy_bcopy (char *from, char *to, int count) #else #ifdef __STDC__ static void __yy_bcopy (char *from, char *to, int count) #else static void __yy_bcopy (from, to, count) char *from; char *to; int count; #endif #endif { register char *f = from; register char *t = to; register int i = count; while (i-- > 0) *t++ = *f++; } #endif int #ifdef YY_USE_CLASS YY_parse_CLASS:: #endif YY_parse_PARSE(YY_parse_PARSE_PARAM) #ifndef __STDC__ #ifndef __cplusplus #ifndef YY_USE_CLASS /* parameter definition without protypes */ YY_parse_PARSE_PARAM_DEF #endif #endif #endif { register int yystate; register int yyn; register short *yyssp; register YY_parse_STYPE *yyvsp; int yyerrstatus; /* number of tokens to shift before error messages enabled */ int yychar1=0; /* lookahead token as an internal (translated) token number */ short yyssa[YYINITDEPTH]; /* the state stack */ YY_parse_STYPE yyvsa[YYINITDEPTH]; /* the semantic value stack */ short *yyss = yyssa; /* refer to the stacks thru separate pointers */ YY_parse_STYPE *yyvs = yyvsa; /* to allow yyoverflow to reallocate them elsewhere */ #ifdef YY_parse_LSP_NEEDED YY_parse_LTYPE yylsa[YYINITDEPTH]; /* the location stack */ YY_parse_LTYPE *yyls = yylsa; YY_parse_LTYPE *yylsp; #define YYPOPSTACK (yyvsp--, yyssp--, yylsp--) #else #define YYPOPSTACK (yyvsp--, yyssp--) #endif int yystacksize = YYINITDEPTH; #ifdef YY_parse_PURE int YY_parse_CHAR; YY_parse_STYPE YY_parse_LVAL; int YY_parse_NERRS; #ifdef YY_parse_LSP_NEEDED YY_parse_LTYPE YY_parse_LLOC; #endif #endif YY_parse_STYPE yyval; /* the variable used to return */ /* semantic values from the action */ /* routines */ int yylen; /* start loop, in which YYGOTO may be used. */ YYBEGINGOTO #if YY_parse_DEBUG != 0 if (YY_parse_DEBUG_FLAG) fprintf(stderr, "Starting parse\n"); #endif yystate = 0; yyerrstatus = 0; YY_parse_NERRS = 0; YY_parse_CHAR = YYEMPTY; /* Cause a token to be read. */ /* Initialize stack pointers. Waste one element of value and location stack so that they stay on the same level as the state stack. The wasted elements are never initialized. */ yyssp = yyss - 1; yyvsp = yyvs; #ifdef YY_parse_LSP_NEEDED yylsp = yyls; #endif /* Push a new state, which is found in yystate . */ /* In all cases, when you get here, the value and location stacks have just been pushed. so pushing a state here evens the stacks. */ YYLABEL(yynewstate) *++yyssp = yystate; if (yyssp >= yyss + yystacksize - 1) { /* Give user a chance to reallocate the stack */ /* Use copies of these so that the &'s don't force the real ones into memory. */ YY_parse_STYPE *yyvs1 = yyvs; short *yyss1 = yyss; #ifdef YY_parse_LSP_NEEDED YY_parse_LTYPE *yyls1 = yyls; #endif /* Get the current used size of the three stacks, in elements. */ int size = yyssp - yyss + 1; #ifdef yyoverflow /* Each stack pointer address is followed by the size of the data in use in that stack, in bytes. */ #ifdef YY_parse_LSP_NEEDED /* This used to be a conditional around just the two extra args, but that might be undefined if yyoverflow is a macro. */ yyoverflow("parser stack overflow", &yyss1, size * sizeof (*yyssp), &yyvs1, size * sizeof (*yyvsp), &yyls1, size * sizeof (*yylsp), &yystacksize); #else yyoverflow("parser stack overflow", &yyss1, size * sizeof (*yyssp), &yyvs1, size * sizeof (*yyvsp), &yystacksize); #endif yyss = yyss1; yyvs = yyvs1; #ifdef YY_parse_LSP_NEEDED yyls = yyls1; #endif #else /* no yyoverflow */ /* Extend the stack our own way. */ if (yystacksize >= YYMAXDEPTH) { YY_parse_ERROR("parser stack overflow"); __ALLOCA_return(2); } yystacksize *= 2; if (yystacksize > YYMAXDEPTH) yystacksize = YYMAXDEPTH; yyss = (short *) __ALLOCA_alloca (yystacksize * sizeof (*yyssp)); __yy_bcopy ((char *)yyss1, (char *)yyss, size * sizeof (*yyssp)); __ALLOCA_free(yyss1,yyssa); yyvs = (YY_parse_STYPE *) __ALLOCA_alloca (yystacksize * sizeof (*yyvsp)); __yy_bcopy ((char *)yyvs1, (char *)yyvs, size * sizeof (*yyvsp)); __ALLOCA_free(yyvs1,yyvsa); #ifdef YY_parse_LSP_NEEDED yyls = (YY_parse_LTYPE *) __ALLOCA_alloca (yystacksize * sizeof (*yylsp)); __yy_bcopy ((char *)yyls1, (char *)yyls, size * sizeof (*yylsp)); __ALLOCA_free(yyls1,yylsa); #endif #endif /* no yyoverflow */ yyssp = yyss + size - 1; yyvsp = yyvs + size - 1; #ifdef YY_parse_LSP_NEEDED yylsp = yyls + size - 1; #endif #if YY_parse_DEBUG != 0 if (YY_parse_DEBUG_FLAG) fprintf(stderr, "Stack size increased to %d\n", yystacksize); #endif if (yyssp >= yyss + yystacksize - 1) YYABORT; } #if YY_parse_DEBUG != 0 if (YY_parse_DEBUG_FLAG) fprintf(stderr, "Entering state %d\n", yystate); #endif YYGOTO(yybackup); YYLABEL(yybackup) /* Do appropriate processing given the current state. */ /* Read a lookahead token if we need one and don't already have one. */ /* YYLABEL(yyresume) */ /* First try to decide what to do without reference to lookahead token. */ yyn = yypact[yystate]; if (yyn == YYFLAG) YYGOTO(yydefault); /* Not known => get a lookahead token if don't already have one. */ /* yychar is either YYEMPTY or YYEOF or a valid token in external form. */ if (YY_parse_CHAR == YYEMPTY) { #if YY_parse_DEBUG != 0 if (YY_parse_DEBUG_FLAG) fprintf(stderr, "Reading a token: "); #endif YY_parse_CHAR = YYLEX; } /* Convert token to internal form (in yychar1) for indexing tables with */ if (YY_parse_CHAR <= 0) /* This means end of input. */ { yychar1 = 0; YY_parse_CHAR = YYEOF; /* Don't call YYLEX any more */ #if YY_parse_DEBUG != 0 if (YY_parse_DEBUG_FLAG) fprintf(stderr, "Now at end of input.\n"); #endif } else { yychar1 = YYTRANSLATE(YY_parse_CHAR); #if YY_parse_DEBUG != 0 if (YY_parse_DEBUG_FLAG) { fprintf (stderr, "Next token is %d (%s", YY_parse_CHAR, yytname[yychar1]); /* Give the individual parser a way to print the precise meaning of a token, for further debugging info. */ #ifdef YYPRINT YYPRINT (stderr, YY_parse_CHAR, YY_parse_LVAL); #endif fprintf (stderr, ")\n"); } #endif } yyn += yychar1; if (yyn < 0 || yyn > YYLAST || yycheck[yyn] != yychar1) YYGOTO(yydefault); yyn = yytable[yyn]; /* yyn is what to do for this token type in this state. Negative => reduce, -yyn is rule number. Positive => shift, yyn is new state. New state is final state => don't bother to shift, just return success. 0, or most negative number => error. */ if (yyn < 0) { if (yyn == YYFLAG) YYGOTO(yyerrlab); yyn = -yyn; YYGOTO(yyreduce); } else if (yyn == 0) YYGOTO(yyerrlab); if (yyn == YYFINAL) YYACCEPT; /* Shift the lookahead token. */ #if YY_parse_DEBUG != 0 if (YY_parse_DEBUG_FLAG) fprintf(stderr, "Shifting token %d (%s), ", YY_parse_CHAR, yytname[yychar1]); #endif /* Discard the token being shifted unless it is eof. */ if (YY_parse_CHAR != YYEOF) YY_parse_CHAR = YYEMPTY; *++yyvsp = YY_parse_LVAL; #ifdef YY_parse_LSP_NEEDED *++yylsp = YY_parse_LLOC; #endif /* count tokens shifted since error; after three, turn off error status. */ if (yyerrstatus) yyerrstatus--; yystate = yyn; YYGOTO(yynewstate); /* Do the default action for the current state. */ YYLABEL(yydefault) yyn = yydefact[yystate]; if (yyn == 0) YYGOTO(yyerrlab); /* Do a reduction. yyn is the number of a rule to reduce with. */ YYLABEL(yyreduce) yylen = yyr2[yyn]; if (yylen > 0) yyval = yyvsp[1-yylen]; /* implement default value of the action */ #if YY_parse_DEBUG != 0 if (YY_parse_DEBUG_FLAG) { int i; fprintf (stderr, "Reducing via rule %d (line %d), ", yyn, yyrline[yyn]); /* Print the symbols being reduced, and their result. */ for (i = yyprhs[yyn]; yyrhs[i] > 0; i++) fprintf (stderr, "%s ", yytname[yyrhs[i]]); fprintf (stderr, " -> %s\n", yytname[yyr1[yyn]]); } #endif #line 839 "/usr/share/bison++/bison.cc" switch (yyn) { case 1: #line 250 "TQL.y" { yyval.zapzloz_ = make_ZapZloz(yyvsp[0].querylist_); YY_RESULT_ZapZloz_= yyval.zapzloz_; ; break;} case 2: #line 252 "TQL.y" { yyval.zapytanie_ = make_SingleQuery(yyvsp[-1].querylinelist_, reverseListPrzerwa(yyvsp[0].listprzerwa_)); YY_RESULT_Query_= yyval.zapytanie_; ; break;} case 3: #line 253 "TQL.y" { yyval.zapytanie_ = make_DefQuery(yyvsp[-3].zapytanie_, yyvsp[-1].nazwa_, reverseListPrzerwa(yyvsp[0].listprzerwa_)); YY_RESULT_Query_= yyval.zapytanie_; ; break;} case 4: #line 254 "TQL.y" { yyval.zapytanie_ = make_CallQuery(yyvsp[-3].zapytanie_, yyvsp[-1].nazwa_, reverseListPrzerwa(yyvsp[0].listprzerwa_)); YY_RESULT_Query_= yyval.zapytanie_; ; break;} case 5: #line 255 "TQL.y" { yyval.zapytanie_ = make_EmptyQuery(reverseListPrzerwa(yyvsp[0].listprzerwa_)); YY_RESULT_Query_= yyval.zapytanie_; ; break;} case 6: #line 257 "TQL.y" { yyval.liniazapytania_ = make_LiniaZap(yyvsp[-2].string_, yyvsp[0].wyraz_); YY_RESULT_QueryLine_= yyval.liniazapytania_; ; break;} case 7: #line 259 "TQL.y" { yyval.wyraz_ = make_AndExpr(yyvsp[-2].wyraz_, yyvsp[0].wyraz_); YY_RESULT_Expr_= yyval.wyraz_; ; break;} case 8: #line 260 "TQL.y" { yyval.wyraz_ = make_OrExpr(yyvsp[-2].wyraz_, yyvsp[0].wyraz_); YY_RESULT_Expr_= yyval.wyraz_; ; break;} case 9: #line 261 "TQL.y" { yyval.wyraz_ = yyvsp[0].wyraz_; YY_RESULT_Expr_= yyval.wyraz_; ; break;} case 10: #line 263 "TQL.y" { yyval.wyraz_ = make_NotExpr(yyvsp[0].wyraz_); YY_RESULT_Expr_= yyval.wyraz_; ; break;} case 11: #line 264 "TQL.y" { yyval.wyraz_ = yyvsp[0].wyraz_; YY_RESULT_Expr_= yyval.wyraz_; ; break;} case 12: #line 266 "TQL.y" { yyval.wyraz_ = make_PartExpr(yyvsp[-2].tekst_, yyvsp[0].tekst_); YY_RESULT_Expr_= yyval.wyraz_; ; break;} case 13: #line 267 "TQL.y" { yyval.wyraz_ = make_LPartExpr(yyvsp[-1].tekst_); YY_RESULT_Expr_= yyval.wyraz_; ; break;} case 14: #line 268 "TQL.y" { yyval.wyraz_ = make_RPartExpr(yyvsp[0].tekst_); YY_RESULT_Expr_= yyval.wyraz_; ; break;} case 15: #line 269 "TQL.y" { yyval.wyraz_ = make_TextExpr(yyvsp[0].tekst_); YY_RESULT_Expr_= yyval.wyraz_; ; break;} case 16: #line 270 "TQL.y" { yyval.wyraz_ = yyvsp[-1].wyraz_; YY_RESULT_Expr_= yyval.wyraz_; ; break;} case 17: #line 272 "TQL.y" { yyval.querylist_ = make_QueryList(yyvsp[0].zapytanie_, 0); YY_RESULT_QueryList_= yyval.querylist_; ; break;} case 18: #line 273 "TQL.y" { yyval.querylist_ = make_QueryList(yyvsp[-1].zapytanie_, yyvsp[0].querylist_); YY_RESULT_QueryList_= yyval.querylist_; ; break;} case 19: #line 275 "TQL.y" { yyval.querylinelist_ = make_QueryLineList(yyvsp[-1].liniazapytania_, 0); YY_RESULT_QueryLineList_= yyval.querylinelist_; ; break;} case 20: #line 276 "TQL.y" { yyval.querylinelist_ = make_QueryLineList(yyvsp[-2].liniazapytania_, yyvsp[0].querylinelist_); YY_RESULT_QueryLineList_= yyval.querylinelist_; ; break;} case 21: #line 278 "TQL.y" { yyval.przerwa_ = 1; YY_RESULT_Przerwa_= yyval.przerwa_; ; break;} case 22: #line 280 "TQL.y" { yyval.listprzerwa_ = 0; YY_RESULT_ListPrzerwa_= yyval.listprzerwa_; ; break;} case 23: #line 281 "TQL.y" { yyval.listprzerwa_ = make_ListPrzerwa(yyvsp[0].przerwa_, yyvsp[-1].listprzerwa_); YY_RESULT_ListPrzerwa_= yyval.listprzerwa_; ; break;} case 24: #line 283 "TQL.y" { yyval.tekst_ = make_Text(yyvsp[0].string_); YY_RESULT_Text_= yyval.tekst_; ; break;} case 25: #line 284 "TQL.y" { yyval.tekst_ = make_Text(yyvsp[0].string_); YY_RESULT_Text_= yyval.tekst_; ; break;} case 26: #line 285 "TQL.y" { yyval.tekst_ = make_Text(yyvsp[0].string_); YY_RESULT_Text_= yyval.tekst_; ; break;} case 27: #line 287 "TQL.y" { yyval.nazwa_ = make_Nazwa(yyvsp[0].string_); YY_RESULT_Nazwa_= yyval.nazwa_; ; break;} } #line 839 "/usr/share/bison++/bison.cc" /* the action file gets copied in in place of this dollarsign */ yyvsp -= yylen; yyssp -= yylen; #ifdef YY_parse_LSP_NEEDED yylsp -= yylen; #endif #if YY_parse_DEBUG != 0 if (YY_parse_DEBUG_FLAG) { short *ssp1 = yyss - 1; fprintf (stderr, "state stack now"); while (ssp1 != yyssp) fprintf (stderr, " %d", *++ssp1); fprintf (stderr, "\n"); } #endif *++yyvsp = yyval; #ifdef YY_parse_LSP_NEEDED yylsp++; if (yylen == 0) { yylsp->first_line = YY_parse_LLOC.first_line; yylsp->first_column = YY_parse_LLOC.first_column; yylsp->last_line = (yylsp-1)->last_line; yylsp->last_column = (yylsp-1)->last_column; yylsp->text = 0; } else { yylsp->last_line = (yylsp+yylen-1)->last_line; yylsp->last_column = (yylsp+yylen-1)->last_column; } #endif /* Now "shift" the result of the reduction. Determine what state that goes to, based on the state we popped back to and the rule number reduced by. */ yyn = yyr1[yyn]; yystate = yypgoto[yyn - YYNTBASE] + *yyssp; if (yystate >= 0 && yystate <= YYLAST && yycheck[yystate] == *yyssp) yystate = yytable[yystate]; else yystate = yydefgoto[yyn - YYNTBASE]; YYGOTO(yynewstate); YYLABEL(yyerrlab) /* here on detecting error */ if (! yyerrstatus) /* If not already recovering from an error, report this error. */ { ++YY_parse_NERRS; #ifdef YY_parse_ERROR_VERBOSE yyn = yypact[yystate]; if (yyn > YYFLAG && yyn < YYLAST) { int size = 0; char *msg; int x, count; count = 0; /* Start X at -yyn if nec to avoid negative indexes in yycheck. */ for (x = (yyn < 0 ? -yyn : 0); x < (sizeof(yytname) / sizeof(char *)); x++) if (yycheck[x + yyn] == x) size += strlen(yytname[x]) + 15, count++; msg = (char *) malloc(size + 15); if (msg != 0) { strcpy(msg, "parse error"); if (count < 5) { count = 0; for (x = (yyn < 0 ? -yyn : 0); x < (sizeof(yytname) / sizeof(char *)); x++) if (yycheck[x + yyn] == x) { strcat(msg, count == 0 ? ", expecting `" : " or `"); strcat(msg, yytname[x]); strcat(msg, "'"); count++; } } YY_parse_ERROR(msg); free(msg); } else YY_parse_ERROR ("parse error; also virtual memory exceeded"); } else #endif /* YY_parse_ERROR_VERBOSE */ YY_parse_ERROR("parse error"); } YYGOTO(yyerrlab1); YYLABEL(yyerrlab1) /* here on error raised explicitly by an action */ if (yyerrstatus == 3) { /* if just tried and failed to reuse lookahead token after an error, discard it. */ /* return failure if at end of input */ if (YY_parse_CHAR == YYEOF) YYABORT; #if YY_parse_DEBUG != 0 if (YY_parse_DEBUG_FLAG) fprintf(stderr, "Discarding token %d (%s).\n", YY_parse_CHAR, yytname[yychar1]); #endif YY_parse_CHAR = YYEMPTY; } /* Else will try to reuse lookahead token after shifting the error token. */ yyerrstatus = 3; /* Each real token shifted decrements this */ YYGOTO(yyerrhandle); YYLABEL(yyerrdefault) /* current state does not do anything special for the error token. */ #if 0 /* This is wrong; only states that explicitly want error tokens should shift them. */ yyn = yydefact[yystate]; /* If its default is to accept any token, ok. Otherwise pop it.*/ if (yyn) YYGOTO(yydefault); #endif YYLABEL(yyerrpop) /* pop the current state because it cannot handle the error token */ if (yyssp == yyss) YYABORT; yyvsp--; yystate = *--yyssp; #ifdef YY_parse_LSP_NEEDED yylsp--; #endif #if YY_parse_DEBUG != 0 if (YY_parse_DEBUG_FLAG) { short *ssp1 = yyss - 1; fprintf (stderr, "Error: state stack now"); while (ssp1 != yyssp) fprintf (stderr, " %d", *++ssp1); fprintf (stderr, "\n"); } #endif YYLABEL(yyerrhandle) yyn = yypact[yystate]; if (yyn == YYFLAG) YYGOTO(yyerrdefault); yyn += YYTERROR; if (yyn < 0 || yyn > YYLAST || yycheck[yyn] != YYTERROR) YYGOTO(yyerrdefault); yyn = yytable[yyn]; if (yyn < 0) { if (yyn == YYFLAG) YYGOTO(yyerrpop); yyn = -yyn; YYGOTO(yyreduce); } else if (yyn == 0) YYGOTO(yyerrpop); if (yyn == YYFINAL) YYACCEPT; #if YY_parse_DEBUG != 0 if (YY_parse_DEBUG_FLAG) fprintf(stderr, "Shifting error token, "); #endif *++yyvsp = YY_parse_LVAL; #ifdef YY_parse_LSP_NEEDED *++yylsp = YY_parse_LLOC; #endif yystate = yyn; YYGOTO(yynewstate); /* end loop, in which YYGOTO may be used. */ YYENDGOTO } /* END */ #line 1038 "/usr/share/bison++/bison.cc" #line 290 "TQL.y"
1747f45302e1b0feeb0babe54b134e62ee15963f
a33aac97878b2cb15677be26e308cbc46e2862d2
/program_data/PKU_raw/67/1696.c
c76cee53bbc7654d7ccbe273c6b080e11332f1fe
[]
no_license
GabeOchieng/ggnn.tensorflow
f5d7d0bca52258336fc12c9de6ae38223f28f786
7c62c0e8427bea6c8bec2cebf157b6f1ea70a213
refs/heads/master
2022-05-30T11:17:42.278048
2020-05-02T11:33:31
2020-05-02T11:33:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
365
c
1696.c
int main() { int n,a,b,m,p; int i; double x,y; scanf("%d",&n); scanf("%d %d",&a,&b); x=(1.0*b)/(1.0*a); for(i=1;i<n;i++) { scanf("%d %d",&m,&p); y=(1.0*p)/(1.0*m); if(y-x>0.05) { printf("better\n"); } else if (x-y>0.05) { printf("worse\n"); } else { printf("same\n"); } } return 0; }
bd8f53473af0cbc45e6f7a9a5381b315c82bde2a
33ad34f016d7b92bee09a1f206f013418a1f651c
/415. Add Strings.cpp
331e34d602ab4fbb115ecfc0e102e8af21cafa35
[]
no_license
piyushkhemka/Leetcode
a6e4e8c71948f92d47a23ba31e3a7373338ec558
0e7b8064c7e5c1c9bf1cf646a1221848220f30e8
refs/heads/master
2020-04-03T20:57:06.606598
2017-11-23T10:33:16
2017-11-23T10:33:16
58,159,096
3
0
null
null
null
null
UTF-8
C++
false
false
1,115
cpp
415. Add Strings.cpp
class Solution { public: string addStrings(string num1, string num2) { if(num1.empty() && num2.empty()) return ""; if(num1.empty()) return num2; if(num2.empty()) return num1; int n = num1.length()-1; int m = num2.length()-1; string result = ""; int carry = 0; int sum = 0; while(n>=0 && m>=0) { int curdigit = int(num1[n]-'0') + int(num2[m]-'0') + carry; carry = curdigit / 10; result = char(curdigit % 10 + '0') + result; --n; --m; } while(n>=0) { int curdigit = int(num1[n]-'0') + carry; carry = curdigit / 10; result = char(curdigit % 10 + '0') + result; --n; } while(m>=0) { int curdigit = int(num2[m]-'0') + carry; carry = curdigit / 10; result = char(curdigit % 10 + '0') + result; --m; } if(carry) result = char(carry + '0') + result; return result; } };
7d3867d646534c9c450c472c4ad2b4158db2383c
317f2542cd92aa527c2e17af5ef609887a298766
/tools/target_10_2_0_1155/qnx6/usr/include/bb/cascades/resources/multiselecthandler.h
aafc782b3318e0a6e19418700d10f812ee04d138
[]
no_license
sborpo/bb10qnx
ec77f2a96546631dc38b8cc4680c78a1ee09b2a8
33a4b75a3f56806f804c7462d5803b8ab11080f4
refs/heads/master
2020-07-05T06:53:13.352611
2014-12-12T07:39:35
2014-12-12T07:39:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
22,226
h
multiselecthandler.h
/* Copyright (C) 2011-2013 Research In Motion Limited. Proprietary and confidential. */ #ifndef cascades_multiselecthandler_h #define cascades_multiselecthandler_h #include <bb/cascades/bbcascades_global.h> #include <bb/cascades/core/uiobject.h> #include <bb/cascades/resources/actionitem.h> namespace bb { namespace cascades { class MultiSelectActionItem; class MultiSelectHandlerPrivate; class VisualNode; /*! * @brief A handler used during multiple selection to populate the Context Menu. * * The multi-select handler represents a multiple selection session involving the Context Menu. * Only one multi-select handler can be active at at time. The @c active property tells whether * the handler is active or not. Setting the @c active property to @c true will start multiple * selection with this handler and cancel any other handler that was active. During multiple * selection the Context Menu is shown populated with the actions from the current handler. * * The @c %MultiSelectHandler can be specified as an attached object in any control or specified in * the ListView as a multiSelectHandler property. * * There are some special cases where you will get a lot for free from the @c %MultiSelectHandler: * * If you add the @c %MultiSelectHandler to a ListView and that @c %MultiSelectHandler has the * multiSelectAction property set, the ListItems will automatically have a MultiSelectActionItem in * their context menu. If One of the ListItems have the multiSelectAction property set that * MultiSelectActionItem will override the one set in the @c %MultiSelectHandler, but just for that * specific ListItem type. * * If you have a MultiSelectActionItem connected to your @c %MultiSelectHandler that item will activate * the handler automatically. However, if you add a MultiSelectActionItem to a control, then you must connect * the signals and activate the desired @c %MultiSelectHandler manually. * * @code * Container { * background: Color.Black * * attachedObjects: [ * MultiSelectHandler { * id: theFirstSelectHandler * actions: [ * ActionItem { title: "Create Album" }, * ActionItem { title: "Mark as read" }, * ActionItem { title: "Mark as unread" }, * DeleteActionItem { title: "Delete" } * ] * deleteAction: DeleteActionItem { title: "Delete" } * * status: "This is the status text" * * onActiveChanged: { * console.log("First handler active!"); * } * * onCanceled: { * console.log("Multi selection canceled!"); * } * } * ] * } * @endcode * * @code * ListView { * id: theListView * * // This multi-select action will be placed inside the ActionSets of each * // list item that doesn't have a MultiSelectActionItem of its own. * multiSelectAction: MultiSelectActionItem {} * * multiSelectHandler { * // These actions will be shown during multiple selection, while this * // multiSelectHandler is active * actions: [ * ActionItem {title: "Multi-select action"}, * DeleteActionItem {} * ] * * status: "None selected" * * onActiveChanged: { * if (active == true) { * console.log("Multiple selection is activated"); * } * else { * console.log("Multiple selection is deactivated"); * } * } * * onCanceled: { * console.log("Multi selection canceled!"); * } * } * * listItemComponents: [ * ListItemComponent { * id: friend * // This MultiSelectActionItem set on the ListView will automatically show up here. * ActionSet { * } * }, * * ListItemComponent { * id: colleague * // This MultiSelectActionItem set on the ListView will not show up here, since * // it already has a MultiSelectActionItem in the ActionSet. * ActionSet { * MultiSelectActionItem { title: "Special Select"} * } * } * ] * } * @endcode * * Here is an example of multiple handlers. Since only one handler can be active at time, * activating one will deactivate the other and switch the content in the Context Menu. * * @code * Page { * actions: [ * MultiSelectActionItem { * multiSelectHandler: theFirstSelectHandler * onTriggered: { * multiSelectHandler.active = true; * } * } * ] * * Container { * background: Color.Black * * attachedObjects: [ * MultiSelectHandler { * id: theFirstSelectHandler * actions: [ * ActionItem { * title: "Create Album" * }, * ActionItem { * title: "Mark as read" * }, * ActionItem { * title: "Mark as unread" * }, * DeleteActionItem { title: "Delete" } * ] * * status: "This is the status text" * * onActiveChanged: { * console.log("First handler active!"); * } * * onCanceled: { * console.log("Multi selection canceled!"); * } * }, * * MultiSelectHandler { * id: theSecondSelectHandler * actions: [ * ActionItem { * title: "Copy" * }, * ActionItem { * title: "Paste" * }, * DeleteActionItem { title: "Delete" } * ] * * status: "This is the status text" * * onActiveChanged: { * console.log("Second handler active!"); * } * * onCanceled: { * console.log("Multi selection canceled!"); * } * } * ] * } * } * @endcode * * @xmlonly * <qml> * <class register="yes"/> * </qml> * @endxmlonly * @xmlonly * <apigrouping group="User interface/Application structure"/> * @endxmlonly * * @since BlackBerry 10.0.0 */ class BBCASCADES_EXPORT MultiSelectHandler : public UIObject { Q_OBJECT /*! * @brief Indicates whether the handler is activated for multiple selection. * * When a multi-select handler is active, the Context Menu is shown for multiple selection and it * is populated using the content of the active handler. Only one multi-select handler can be active * at at time, so activating one handler will deactivate any previously active handler. * * The default value is @c false, indicating that the handler is not active. * * @since BlackBerry 10.0.0 */ Q_PROPERTY(bool active READ isActive WRITE setActive RESET resetActive NOTIFY activeChanged FINAL) /*! * @brief Actions to display during multiple selection when the handler is active. * * These actions are displayed in the Context Menu during multiple selection when the * multi-select handler is active. * * Only one DeleteActionItem can be shown in the Context Menu. If more than one is added, * only the first one is used and the rest are ignored. It is placed at a fixed position * in the Context Menu along with the other actions. * * * @xmlonly * <qml> * <property name="actions" listType="bb::cascades::AbstractActionItem"/> * </qml> * @endxmlonly * * @since BlackBerry 10.0.0 */ Q_PROPERTY(QDeclarativeListProperty<bb::cascades::AbstractActionItem> actions READ actions FINAL) /*! * @brief The status text to show during multiple selection. * * The selection status text is shown on the Action Bar at a fixed position * during multiple selection when this handler is active. * According to general guidelines this should be a short sentence telling * how many items are selected, e.g. "3 emails selected". * * The default value is @c QString::null, indicating no status text is shown. * * @since BlackBerry 10.0.0 */ Q_PROPERTY(QString status READ status WRITE setStatus RESET resetStatus NOTIFY statusChanged FINAL) /*! \cond PRIVATE */ /*! * @brief Decides if input events should reach the focused control while the multi-select handler is active, * even if the context menu is shown. * * When a multi-select handler is active, the context menu is shown. Normally input events (e.g. key events) * will always go to the context menu when it is showing. Setting @c inputAllowed to @c true will make the input events * go to the focused control even if the context menu is showing. * * The default value is @c false. * * Example use case: * The application has a list with a search field that should be usable (requires key input) while in multi select mode. * * @since BlackBerry 10.2.0 */ Q_PROPERTY(bool inputAllowed READ isInputAllowed WRITE setInputAllowed RESET resetInputAllowed NOTIFY inputAllowedChanged FINAL) /*! \endcond */ public: /*! * @brief Constructs a @c %MultiSelectHandler. * * @since BlackBerry 10.0.0 */ explicit MultiSelectHandler(VisualNode* parent = 0); /*! * @brief Destroys the @c %MultiSelectHandler. * * @since BlackBerry 10.0.0 */ virtual ~MultiSelectHandler(); /*! * @brief Returns whether the multi-select handler is currently active. * * @return @c true if the handler is active, @c false otherwise. * * @since BlackBerry 10.0.0 */ bool isActive() const; /*! * @brief Activates or deactivates the multi-select handler. * * @param active If @c true the handler will be activated for multiple selection, and if @c false the handler will deactivated. * * @since BlackBerry 10.0.0 */ Q_SLOT void setActive(bool active); /*! * @brief Deactivates the multi-select handler. * * @since BlackBerry 10.0.0 */ Q_SLOT void resetActive(); /*! * @brief Returns the number of added actions. * * @see actionAt() * * @return The number of actions. * * @since BlackBerry 10.0.0 */ Q_INVOKABLE int actionCount() const; /*! * @brief Returns a action at the specified index. * * The ownership of the action remains with the handler. * @see actionCount() * * @param index The index of the action. * @return The requested action if the index was valid, @c 0 otherwise. * * @since BlackBerry 10.0.0 */ Q_INVOKABLE bb::cascades::AbstractActionItem* actionAt(int index) const; /*! * @brief Adds an action to show during multiple selection. * * The actions are shown in the Context Menu during multiple selection when this * handler is active. * * The multi-select handler takes ownership of the action, so actions cannot be * shared. If the action already has a parent or if it is @c 0, nothing will happen. * Once completed, the actionAdded() signal is emitted. * * @see removeAction(), removeAllAction() * * @param action The action to add. * * @since BlackBerry 10.0.0 */ Q_INVOKABLE void addAction(bb::cascades::AbstractActionItem* action); /*! * @brief Removes a previously added action. * * Once the action is removed, the handler no longer references it, but it is still * owned by the handler. It is up to the application to either delete the removed * action, transfer its ownership (by setting its parent) to another object or leave * it as a child of the handler (in which case it will be deleted with the handler). * * Once completed, the actionRemoved() signal is emitted. * * @see addAction(), removeAllActions() * * @param action The actionItem to remove. * @return @c true if the action was owned by the @c %MultiSelectHandler, @c false otherwise. * * @since BlackBerry 10.0.0 */ Q_INVOKABLE bool removeAction(bb::cascades::AbstractActionItem* action); /*! * @brief Removes and deletes all the added actions. * * Once completed, the actionRemoved() signal is emitted with @c 0 as its parameter. * * @see addAction(), removeAction() * * @since BlackBerry 10.0.0 */ Q_INVOKABLE void removeAllActions(); /*! * @brief Returns the status text set for this handler. * * @return The status text set for this handler, or @c QString::null of no text was set. * * @since BlackBerry 10.0.0 */ QString status() const; /*! * @brief Sets the status text to show during multiple selection. * * The selection status text is shown on the Action Bar at a fixed position * during multiple selection when this handler is active. * According to general guidelines this should be a short sentence telling * how many items are selected, e.g. "3 emails selected". * * Once completed, the statusChanged() is emitted with the new text. * * \param status The new status text for this list item. * * @since BlackBerry 10.0.0 */ Q_SLOT void setStatus(const QString& status); /*! * @brief Removes the status text by setting it to String::null. * * Once completed, the statusChanged() is emitted with @c String::null. * * @since BlackBerry 10.0.0 */ Q_SLOT void resetStatus(); /*! \cond PRIVATE */ /*! * @brief Returns whether input is allowed when the multi-select handler is active and the context menu is showing. * * @return @c true if input is allowed when the context menu is showing, @c false otherwise. * * @since BlackBerry 10.2.0 */ bool isInputAllowed() const; /*! * @brief Sets wether input is allowed when the multi-select handler is active and the context menu is showing. * * @param inputAllowed @c true if input should be allowed when the multi-select handler is active and the context menu is showing, @c false otherwise. * * @since BlackBerry 10.2.0 */ Q_SLOT void setInputAllowed(bool inputAllowed); /*! * @brief Resets inputAllowed to the default value of @c false. * * @since BlackBerry 10.2.0 */ Q_SLOT void resetInputAllowed(); /*! \endcond */ Q_SIGNALS: /*! * @brief Emitted when the multi-select handler is activated or deactivated. * * @param active If @c true the handler was activated for multiple selection, and if @c false the handler was deactivated. * * @since BlackBerry 10.0.0 */ void activeChanged(bool active); /*! * @brief Emitted when an action has been added to the @c %MultiSelectHandler. * * @param action The action that has been added. * * @since BlackBerry 10.0.0 */ void actionAdded(bb::cascades::AbstractActionItem *action); /*! * @brief Emitted when an action has been removed from the @c %MultiSelectHandler. * * @param action The action that has been removed. @c 0 if emitted by removeAll(). * * @since BlackBerry 10.0.0 */ void actionRemoved(bb::cascades::AbstractActionItem *action); /*! * @brief Emitted when the status text is changed or removed. * * @param status The new status text or @c QString::null if it was removed. * * @since BlackBerry 10.0.0 */ void statusChanged(const QString& status); /*! * @brief Emitted when the multi select is canceled. * * @since BlackBerry 10.0.0 */ void canceled(); /*! \cond PRIVATE */ /*! * @brief Emitted when the inputAllowed property is changed. * * @param inputAllowed The new value of the property. * * @since BlackBerry 10.2.0 */ void inputAllowedChanged(bool inputAllowed); /*! \endcond */ private: /*! \cond PRIVATE */ QDeclarativeListProperty<bb::cascades::AbstractActionItem> actions(); Q_DECLARE_PRIVATE(MultiSelectHandler) Q_DISABLE_COPY(MultiSelectHandler) /*! \endcond */ public: /*! \cond PRIVATE */ typedef MultiSelectHandler ThisClass; typedef UIObject BaseClass; /*! \endcond */ /*! * @brief A builder template for constructing a @c %MultiSelectHandler. * * See MultiSelectHandler::create() for getting a concrete builder for constructing a @c %MultiSelectHandler. * * @since BlackBerry 10.0.0 */ template <typename BuilderType, typename BuiltType> class TBuilder : public BaseClass::TBuilder<BuilderType, BuiltType> { protected: TBuilder(BuiltType* node) : BaseClass::TBuilder<BuilderType, BuiltType>(node) {} public: /*! * @brief Adds an action to show during multiple selection. * * The actions are shown in the Context Menu during multiple selection when this * handler is active. * * The multi-select handler takes ownership of the action, so actions cannot be * shared. If the action already has a parent or if it is @c 0, nothing will happen. * * Using this convenience function in the builder pattern is the equivalent of the * following: * @code * myHandler->addAction(action); * @endcode * * @param action The action to add. * * @since BlackBerry 10.0.0 */ BuilderType& addAction(AbstractActionItem *action) { this->instance().addAction(action); return this->builder(); } /*! * @brief Sets the status text to show during multiple selection. * * Using this convenience function in the builder pattern is the equivalent of the * following: * @code * myHandler->setStatus("3 emails selected"); * @endcode * * @param status The status text to set. * * @since BlackBerry 10.0.0 */ BuilderType& status(const QString& status) { this->instance().setStatus(status); return this->builder(); } /*! \cond PRIVATE */ /*! * @copydoc bb::cascades::MultiSelectHandler::setInputAllowed(bool) */ BuilderType& inputAllowed(bool inputAllowed) { this->instance().setInputAllowed(inputAllowed); return this->builder(); } /*! \endcond */ }; /*! * @brief A concrete builder class for constructing a @c %MultiSelectHandler. * * @since BlackBerry 10.0.0 * */ class Builder : public TBuilder<Builder, MultiSelectHandler> { public: explicit Builder(VisualNode* target) : TBuilder<Builder, MultiSelectHandler>(new MultiSelectHandler(target)) {} }; /*! * @brief Creates and returns a builder for constructing an @c %MultiSelectHandler. * * Using the builder to create a multi-select handler: * @code * Container* targetContainer = Container::create() * MultiSelectHandler* handler = MultiSelectHandler::create(targetContainer) * .addAction(ActionItem::create().title("Reply") * .addAction(ActionItem::create().title("Forward"); * @endcode * * The user needs to specify what VisualNode this @c %MultiSelectHandler will target, * this is done automatically if you use QML but must be provided if it is created * in C++. The target parameter is allowed to be 0 but then the @c %MultiSelectHandler * will do nothing. * * @return A Builder for constructing an @c %MultiSelectHandler. * * @since BlackBerry 10.0.0 */ static Builder create(VisualNode* target) { return Builder(target); } }; } } QML_DECLARE_TYPE(bb::cascades::MultiSelectHandler) #endif // cascades_multiselecthandler_h
a763456bfd51b9fef89af1f793cb63ae9c6b8ed0
e7becda0364ffa548d04aa1fe02fccad11f106bd
/Native/build/Tools/ModelPipeline/pch.h
4390d7cc9b8f3f8f4ac504702a16017e25655bef
[]
no_license
btrowbridge/DirectX.MultiMesh.DataDriven
5593b5746fd4abb7fafdb64538bc7fc916c0acbd
e5e7e9db86e3c5272e092ff194e5b86d4ffcc18b
refs/heads/master
2020-06-29T11:00:20.745244
2016-11-22T22:03:01
2016-11-22T22:03:01
74,432,732
0
0
null
null
null
null
UTF-8
C++
false
false
591
h
pch.h
#pragma once #include "targetver.h" #include <stdio.h> #if defined(DEBUG) || defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #endif #include <wrl.h> #include <DirectXMath.h> #include <memory> #include <vector> #include <iostream> #include <fstream> #include <cstdint> #include <string> #include "Utility.h" #include "Model.h" #include "Mesh.h" #include "ModelMaterial.h" #include "ModelProcessor.h" #include "MeshProcessor.h" #include "ModelMaterialProcessor.h" #include <assimp/Importer.hpp> #include <assimp/scene.h> #include <assimp/postprocess.h>
729b24f262a8bfbc1bb8abc9af4b57495873866e
e96a0bc65d1e015881030f3f94e2145bb2b163ea
/ABC/c154/c.cpp
3ba317fc924a46a24b622452c6db8d9aa4f011ee
[]
no_license
TimTam725/Atcoder
85a8d2f1961da9ed873312e90bd357f46eb2892b
067dcb03e6ad2f311f0b4de911fae273cee5113c
refs/heads/main
2023-06-06T02:06:34.833164
2021-06-20T06:22:01
2021-06-20T06:22:01
378,565,753
0
0
null
null
null
null
UTF-8
C++
false
false
766
cpp
c.cpp
#include<bits/stdc++.h> #include<iomanip> using namespace std; typedef long long ll; typedef long l; typedef pair<int,int> P; #define rep(i,n) for(int i=0;i<n;i++) #define fs first #define sc second #define pb push_back #define mp make_pair #define eb emplace_back #define ALL(A) A.begin(),A.end() const double PI=3.141592653589; const int INF=1000000007; const ll LMAX=1000000000000001; const ll mod=1000000007; ll gcd(ll a,ll b){if(a<b)swap(a,b);while((a%b)!=0){a=b;b=a%b;}return b;} int dx[]={-1,0,1,0}; int dy[]={0,1,0,-1}; int main(){ set<int> s; int n; cin>>n; bool f=0; rep(i,n){ int a; cin>>a; if(s.count(a)) f=1; else s.insert(a); } if(f) puts("NO"); else puts("YES"); return 0; }
92be074646e7c8e605a2465dd846481998991720
617d14f5b3d77333541b906bf96b8ef36ed73dfc
/0452.cpp
02f7f0b92856a457cba28f68a5e3959f945f66c7
[]
no_license
dcyril233/LeetCode
a9b755941447e294c9ad8db14ee5da6c22b2d119
ba8116a35ba5c7cd67eebb06b32bd56903dcc081
refs/heads/master
2023-04-15T14:14:26.529701
2021-04-23T09:54:06
2021-04-23T09:54:06
300,212,577
0
0
null
null
null
null
UTF-8
C++
false
false
1,449
cpp
0452.cpp
#ifdef LEETCODE #include <LeetCodeL.hpp> #endif class Solution { public: int findMinArrowShots(vector<vector<int>>& points) { sort(points.begin(), points.end(), [](vector<int> &a, vector<int> &b){ return a[1] < b[1]; }); int n = points.size(); if(n == 0) return 0; if(n == 1) return 1; int prev = points[0][1]; int count = 1; for(int i = 1; i < n; ++i) { if(points[i][0] > prev) { count++; prev = points[i][1]; } } return count; } }; #ifdef LEETCODE int main() { cout << " 1:" << endl; { vector<vector<int>> points {{10,16},{2,8},{1,6},{7,12}}; cout << Solution().findMinArrowShots(points) << endl; } cout << " 2:" << endl; { vector<vector<int>> points {{1,2},{3,4},{5,6},{7,8}}; cout << Solution().findMinArrowShots(points) << endl; } cout << " 3:" << endl; { vector<vector<int>> points {{1,2},{2,3},{3,4},{4,5}}; cout << Solution().findMinArrowShots(points) << endl; } cout << " 4:" << endl; { vector<vector<int>> points {{1,2}}; cout << Solution().findMinArrowShots(points) << endl; } cout << " 5:" << endl; { vector<vector<int>> points {{2,3}}; cout << Solution().findMinArrowShots(points) << endl; } return 0; } #endif
369bf021b5f12f2ae3f857c3089033ea3a02aad6
4bef310305aa76aebb4cba66f117566ab14c8eeb
/MiCrOmAcRo/micromacro/src/main.cpp
53f7d2f943fba5fb2d2cd01d4b4c0b960cb963d5
[ "LicenseRef-scancode-public-domain", "BSD-3-Clause" ]
permissive
tectronics/rom-bot1
803baf71128040451f17f41f779162fdda537ffc
404c667c2b3cd98bb2c6a2e88a6c7769adcb3fab
refs/heads/master
2018-01-11T14:48:11.133463
2013-08-09T14:36:20
2013-08-09T14:36:20
47,052,526
0
0
null
null
null
null
UTF-8
C++
false
false
4,171
cpp
main.cpp
#include "main.h" #include <string> #include <vector> #include <stdio.h> #include <stdlib.h> #include <iostream> #include "macro.h" #include "luaglue.h" #include "luaengine.h" #include "misc.h" #include "color.h" #include "filesystem.h" #include "logger.h" #include "error.h" int mainRunning; int restoreDefaults(); void splitArgs(std::string cmd, std::vector<std::string> &args); std::string promptForScript(std::vector<std::string> &args); static BOOL WINAPI consoleControlCallback(DWORD dwCtrlType); int main(int argc, char *argv[]) //int WINAPI WinMain(HINSTANCE hThisInstance, HINSTANCE hPrevInstance, // LPSTR lpszArgument, int nCmdShow) { //int argc = __argc; //char **argv = __argv; mainRunning = true; SetConsoleCtrlHandler(consoleControlCallback, true); CLI_OPTIONS clio; handleCommandLineArguments(argc, argv, &clio); SetCurrentDirectory( getAppPath().c_str() ); LuaEngine engine; if( !engine.init(&clio) ) { fprintf(stderr, "Error initializing Lua Engine\n"); exit(1); } bool autoload = (clio.scriptSet); while(mainRunning) { restoreDefaults(); if( !autoload) // Grab filename &args from user { clio.args.clear(); std::string filename = promptForScript(clio.args); clio.scriptName = filename; } if( !engine.checkCommands(clio.scriptName, clio.args) ) { // Not a command, but a script to run. So run it. if( !autoload ) { // Fix script path std::string replacescript = SCRIPT_DIR; replacescript += clio.scriptName; clio.scriptName = replacescript; // Set execution path std::string exePath = getAppPath() + "/"; exePath += getFilePath(clio.scriptName); Macro::instance()->setExecutionPath(exePath); } else { // Set execution path Macro::instance()->setExecutionPath( getFilePath(clio.scriptName)); } engine.run(clio.scriptName, clio.args); } // Disable autoloading now that it has been used (if needed) autoload = false; if( mainRunning ) { #ifdef DISPLAY_DEBUG_MESSAGES Logger::instance()->add("DEBUG: Reinitializing engine."); #endif if( !engine.reinit(&clio) ) { const char *err = "Failed to re-initialize Lua Engine.\n"; fprintf(stderr, err); Logger::instance()->add(err); } #ifdef DISPLAY_DEBUG_MESSAGES Logger::instance()->add("DEBUG: Reinit OK."); #endif } } #ifdef DISPLAY_DEBUG_MESSAGES Logger::instance()->add("DEBUG: Engine cleanup."); #endif engine.cleanup(); return 0; } int restoreDefaults() { setColor(COLOR_LIGHTGRAY); return 0; } void splitArgs(std::string cmd, std::vector<std::string> &args) { unsigned int startpos; startpos = cmd.find(' '); args.push_back( cmd.substr(0, startpos) ); unsigned int lastpos = startpos; while(startpos != std::string::npos) { startpos = cmd.substr(lastpos+1).find(' '); std::string tmp = cmd.substr(lastpos+1, startpos); if( tmp != "" ) args.push_back( tmp ); lastpos += startpos +1; } } std::string promptForScript(std::vector<std::string> &args) { std::string filename; while( kbhit() ) getch(); // Clear keyboard buffer printf("Please enter the script name to run.\n"); printf("Type in \'exit\' (without quotes) to exit.\n"); printf("Script> "); std::string fullcmd; std::cin.clear(); getline(std::cin, fullcmd); std::cin.clear(); splitArgs(fullcmd, args); filename = args[0]; args.erase(args.begin()); // Don't return filename in args array return filename; } static BOOL WINAPI consoleControlCallback(DWORD dwCtrlType) { switch(dwCtrlType) { case CTRL_C_EVENT: case CTRL_CLOSE_EVENT: mainRunning = false; return true; break; } return false; }
6f79df527b0e164da328405411e4b2e20ef07813
8485fc3c53cf2fa541be4a5fee606d4958478c5d
/TTCtrl/Waves.h
5f4a115f6ea2dce00719f0f14cbcc4ecbb8c0d35
[]
no_license
jaredmales/MagAO
8c5a6136dedab9ce0de8d612a8f6cf31cfef6bbf
3d5b87d9e440831c7ede81fd70e74c335d630bbf
refs/heads/master
2021-01-21T22:21:48.942524
2017-09-01T19:10:45
2017-09-01T19:10:45
102,152,105
0
1
null
null
null
null
UTF-8
C++
false
false
2,875
h
Waves.h
#ifndef TT_WAVES_H #define TT_WAVES_H #include "TTCtrl.h" #include "TTCtrlExceptions.h" #include "BcuLib/BcuCommon.h" using namespace Arcetri::Bcu; //@Class: Waves // // Defines K sine waves for the tip-tilt generator, that is // the low-level parameters for te TTCtrl. // (Note: this version supports only K = 3 !!!) // // K, the number of actuators, match the number of waves. // A Waves object can be Requested (REQ), if it maps a requested state // of the mirror, or Current (CUR), if it maps the current status of the // mirror. In both cases a Waves object mantains its status using some // RTDB variables, and allow a synchroniztion with them (matchAndRetrieve method). //@ class Waves { public: // Create the Waves writing the related vars to RTDB Waves(TTCtrl *ctrl, // The TipTilt Controller instantiating this object int direction) // direction is CUR_VAR or REQ_VAR throw(WavesException); ~Waves(); // Setup RTDB variables storing object status void setupVars() throw (AOVarException); void initVars() throw (Config_File_Exception); void notifyVars(); // Copy status (except direction) from another Waves object void copy(Waves *another) throw (AOVarException); // Get Waves local status, copying values into received parameter. void Freqs(double freqs[]) throw (AOVarException); void Amps(double amps[]) throw (AOVarException); void Offsets(double offsets[]) throw (AOVarException); void Phases(double phases[]) throw (AOVarException); // Set Waves local status, getting values from received parameters. // (doesn't send changes to RTDB. Use save() for this purpose) void setFreqs(const double freqs[]) throw (AOVarException); void setAmps(const double amps[]) throw (AOVarException); void setOffsets(const double offsets[]) throw (AOVarException); void setPhases(const double phases[]) throw (AOVarException); // Update the Waves status, downloading parameters form RTDB bool update(Variable *var) throw (AOVarException); // Apply Waves (sends values to BCU) void apply() throw (AOVarException, WavesException); // Save Waves status to RTDB void save() throw (AOVarException); private: // A reference to my controller TTCtrl *_myCtrl; // CUR_VAR or REQ_VAR int _direction; // Number of actuators, that is the number of waves. // This version supports only 3 actuators (_n_act = 3) !!! int _n_act; // Each of this vars contains an array[WAVES] // with values corresponding to WAVES (=3) waves RTDBvar _freqs, _amps, _offsets, _phases; // Stores waves in binary format ready for the BCU struct wave_params { float freq; float phase; float offset; float amp; }; // Object used to send commands to MirrorCtrl and // timeout CommandSender* _comSender; int _timeout_ms; }; #endif //TT_WAVES_H
3b3134b516e733d3649171ac43724de43bf2a2a4
0b413dffe67f8b3513301a37e2144c5f8b86e9da
/Physics.h
acfc2a3de60c01536cfd25cec51f74e04e1a17e4
[]
no_license
andrew0milne/AR_Pool
4e22b75a323a7cf4eecd32f691408816a120dd45
ac9427dd5e2979c155111be8391228a058788557
refs/heads/master
2020-04-25T22:09:03.574111
2019-02-28T12:23:19
2019-02-28T12:23:19
173,102,196
0
0
null
null
null
null
UTF-8
C++
false
false
648
h
Physics.h
#include <system/platform.h> #include "system\debug_log.h" #include "../build/vs2017/GameObject.h" // FRAMEWORK FORWARD DECLARATIONS namespace gef { class Platform; class SpriteRenderer; class Font; class Renderer3D; class Mesh; class Scene; class InputManager; //class Sphere; } #pragma once class Physics { public: Physics(); ~Physics(); float GetDistance(gef::Vector4 pos_1_, gef::Vector4 pos_2_); bool SphereToRayCollision(GameObject* sphere_, GameObject* wall_, int i); bool SphereToSphereCollision(GameObject* object_1_, GameObject* object_2_, bool pocket); float DotProduct(gef::Vector4 vec_1_, gef::Vector4 vec_2_); };
00e89a11e86ca4fcf35aa968261e8604f0c55508
f72f4707c153fbd3871753bc18c374fb71c8e57b
/practice/Untitled1n.cpp
0b6d5c04732bd410c5f76b02425fdcf0425b4a02
[]
no_license
Real-dev-byte/practice
1f95c3c6494b5e9d33c45f6b57ae2a5b259263b0
1f2043387666d4732bf3423ec0b7a9746d312574
refs/heads/master
2022-02-15T11:10:27.500955
2019-09-09T10:43:24
2019-09-09T10:43:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
528
cpp
Untitled1n.cpp
#include<bits/stdc++.h> using namespace std; int d=0; void recur(int r,int c,int f,int k); int main() { int t; cin>>t; while(t--) { int a,b,k,f=0; cin>>a>>b>>k; recur(a,b,f,k); } } void recur(int r,int c,int f,int k) { if((r<1 || r>8)||(c<1 || c>8)) { return; } else { if(f==k) { d++; return; } cout<<r<<" "<<c<<endl; recur(r+1,c,f++,k); recur(r+1,c+1,f++,k); recur(r+1,c-1,f++,k); recur(r-1,c,f++,k); recur(r-1,c+1,f++,k); recur(r-1,c-1,f++,k); recur(r,c+1,f++,k); recur(r,c-1,f++,k); } }
59235e9656492bfde5b7146196588ca8393c7947
a1637b180744459c7eee5e0428fe10549a19e727
/PixelEffect/PixelEffect.Android/TouchInputDeviceAndroid.h
ccc085767cc04c234f271e06b484da1cf8b03562
[]
no_license
bgsa/JumpFlooding
48528c2780307ef946fc88bf097709e10914823d
d817b93bec9ff516fc71af33a6892781a49cc0b9
refs/heads/master
2020-04-02T02:18:40.332248
2018-12-02T15:26:34
2018-12-02T15:26:34
153,902,696
0
0
null
null
null
null
UTF-8
C++
false
false
656
h
TouchInputDeviceAndroid.h
#pragma once #include <InputDevice.h> #include <TouchInputDevice.h> #include <vector> #include <map> #include <algorithm> using namespace std; class TouchInputDeviceAndroid : public TouchInputDevice { private: vector<TouchInputDeviceHandler*> handlers; map<int, TouchItem*> touchItems; public: void update(long long elapsedTime); map<int, TouchItem*> getTouchItems(); void touchPointerIn(TouchEvent e); void touchPointerOut(TouchEvent e); void touchDown(TouchEvent e); void touchUp(TouchEvent e); void touchMove(TouchEvent e); void addHandler(TouchInputDeviceHandler* handler); void removeHandler(TouchInputDeviceHandler* handler); };
ab1246523266788ed6365c1458d3ce3648c5f38a
a93205f24d69075f67288aea26c96b8b826ea7d0
/ProjetY/Button.cpp
44b93c8fa86026e472db846d7f56f6feba390e92
[ "Apache-2.0" ]
permissive
asgards1990/UnderSky
3f442d73e483b1c167127df6e93304e31be49e09
44f217a859757bf7eca285d953f0dcd73276e982
refs/heads/master
2020-03-29T22:53:23.510624
2014-04-20T16:44:18
2014-04-20T16:44:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
522
cpp
Button.cpp
#include "Button.h" Button::Button(): hitbox(Point2d(),Point2d()) { //empty } Button::Button(Point2d bottomLeft, Point2d topRight): hitbox(bottomLeft,topRight) { //empty } Button::~Button() { //empty } bool Button::isLeftClickedOn(sf::RenderWindow *window){ if(sf::Mouse::isButtonPressed(sf::Mouse::Left)){ sf::Vector2f mousePosition = window->mapPixelToCoords(sf::Mouse::getPosition(*window)); Point2d cursor (mousePosition.x,mousePosition.y); return hitbox.isInside(cursor); }else{ return false; } }
4350e1755e0ff5149c4a398e126d148bc5b5a430
006b80537ff822195c4da35580f46f9f2aec94e0
/mini_synth/Device.h
3d084a8c44dccca74c613a833256422da0521d25
[ "MIT" ]
permissive
0x0c/mini_synth
f408fa640445d98c0aa4c3724c275e9a577d42aa
e86b75fd5c808a70df89961d8a32b3fad472daec
refs/heads/master
2020-04-30T12:59:24.339321
2019-04-02T09:34:25
2019-04-02T09:34:25
176,841,798
1
0
null
null
null
null
UTF-8
C++
false
false
3,431
h
Device.h
#pragma once #include <Arduino.h> #include <Arduino_STM32_PSG.h> #include <U8g2lib.h> #include <string> #include <vector> #include "Key.h" #include "RoterlyEncoder.h" namespace bongorian { namespace mini_synth { class Device { private: const uint8_t _rowIO[3] = { PB3, PB4, PB5 }; const uint8_t _columnIO[4] = { PB8, PB9, PB0, PB1 }; const uint8_t _modeSwitchPin = PC13; const uint8_t _encoderSwitchPin = PA4; SAA1099 _saa = SAA1099(PA3, PA5, PA7, PA0, PA1, PA2); uint8_t *_u8log_buffer; public: typedef enum : int { left = 0, right = 1, both = 2 } AudioChannel; const uint8_t numberOfRows = sizeof(this->_rowIO) / sizeof(this->_rowIO[0]); const uint8_t numberOfColumns = sizeof(this->_columnIO) / sizeof(this->_columnIO[0]); RoterlyEncoder encoder = RoterlyEncoder(PA6, PA8, this->_encoderSwitchPin); U8G2_SSD1306_128X64_NONAME_F_HW_I2C display = U8G2_SSD1306_128X64_NONAME_F_HW_I2C(U8G2_R0, U8X8_PIN_NONE); U8G2LOG logger; std::vector<mini_synth::Key *> keys; Device() { for (int i = 0; i < this->numberOfRows; i++) { for (int j = 0; j < this->numberOfColumns; j++) { auto key = new Key(this->_rowIO[i], this->_columnIO[j]); this->keys.push_back(key); } } } void begin() { disableDebugPorts(); pinMode(this->_modeSwitchPin, INPUT); for (int i = 0; i < this->numberOfRows; i++) { for (int j = 0; j < this->numberOfColumns; j++) { auto key = this->keys[i * this->numberOfColumns + j]; key->setup(); } } this->encoder.setup(); int width = 32; int height = 6; this->_u8log_buffer = new uint8_t[width * height]; this->display.begin(this->_encoderSwitchPin, U8X8_PIN_NONE, U8X8_PIN_NONE, U8X8_PIN_NONE, U8X8_PIN_NONE, U8X8_PIN_NONE); this->display.setFont(u8g2_font_ncenB08_tr); this->logger.begin(this->display, width, height, this->_u8log_buffer); this->logger.setLineHeightOffset(0); this->logger.setRedrawMode(0); this->reset(); } void update() { this->encoder.update(); for (int i = 0; i < this->keys.size(); i++) { auto key = this->keys[i]; key->update(); } } bool isFunctionKeyPressed() { return digitalRead(this->_modeSwitchPin) == LOW; } int numberOfKeys() { return this->keys.size(); } bool isKeyPressed(int keyIndex) { if (keyIndex > this->keys.size()) { return Key::State::invalid; } auto key = this->keys[keyIndex]; return key->isPressed(); } bool isKeyLongPressed(int keyIndex) { if (keyIndex > this->keys.size()) { return Key::State::invalid; } auto key = this->keys[keyIndex]; return key->isLongPress(); } Key::State keyState(int keyIndex) { if (keyIndex > this->keys.size()) { return Key::State::invalid; } auto key = this->keys[keyIndex]; return key->currentState(); } void play(uint8_t note, uint8_t channel = 0) { this->_saa.setNote(channel, note); } void volume(uint8_t volume = 0, AudioChannel side = AudioChannel::both, uint8_t channel = 0) { this->_saa.setVolume(channel, volume, side); } void mute(uint8_t channel = 0) { this->_saa.setVolume(channel, 0, 0); this->_saa.setVolume(channel, 0, 1); } void reset(uint8_t channel = 0) { this->_saa.reset(); this->_saa.setNoiseEnable(0); this->_saa.soundEnable(); this->_saa.setVolume(channel, 4, 0); this->_saa.setVolume(channel, 4, 1); } }; } }
fea8871bed1054e4da80079eb4c695af444d5006
9f561d4ce1646b0818b69087b06813a26bb290a5
/Codeforces/C++/A/632A.cpp
8c54696886677b5e57790e0a15447ee1fe6c1a89
[]
no_license
ahmedfci93/Problem-Solving
b5c34601b59075d5b62aead10b8073b6c00f797c
148e9e29bd4fd3cf6fe9f93a7d90983abb83cd38
refs/heads/master
2018-12-22T15:43:55.405718
2018-10-06T16:28:23
2018-10-06T16:28:23
112,637,571
0
0
null
null
null
null
UTF-8
C++
false
false
326
cpp
632A.cpp
#include <iostream> #include <vector> using namespace std; int main() { long long int n ,p,i,pre=1; long long int ans=0; cin>>n>>p; vector<string> pays(n); for(i=0;i<n;i++) cin>>pays[i]; ans=p/2; for(i=n-2;i>=0;i--) { pre*=2; if(pays[i]=="halfplus") { pre++; } ans+=(p/2)*pre; } cout<<ans; return 0; }
58e86778879288471183891ed47c9a0a31b250ee
33a8178528d13e8d21239117eb7af26108dae6cd
/metiscoinMiner.cpp
2f0d6b5b1209417d34db83d51be4ac8930062572
[]
no_license
Nahimana/xptminer-linux
ba409f4060a5807548af41febc882dc1a9dab00f
27a1ff2ee3ff4d2f0503ea23989d35f44ee76e1f
refs/heads/master
2021-01-17T15:57:58.458232
2014-01-26T16:55:01
2014-01-26T16:55:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,026
cpp
metiscoinMiner.cpp
#include"global.h" void metiscoin_process(minerMetiscoinBlock_t* block) { sph_keccak512_context ctx_keccak; sph_shavite512_context ctx_shavite; sph_metis512_context ctx_metis; static unsigned char pblank[1]; block->nonce = 0; uint32 target = *(uint32*)(block->targetShare+28); uint64 hash0[8]; uint64 hash1[8]; uint64 hash2[8]; for(uint32 n=0; n<0x1000; n++) { if( block->height != monitorCurrentBlockHeight ) break; for(uint32 f=0; f<0x8000; f++) { sph_keccak512_init(&ctx_keccak); sph_shavite512_init(&ctx_shavite); sph_metis512_init(&ctx_metis); sph_keccak512(&ctx_keccak, &block->version, 80); sph_keccak512_close(&ctx_keccak, hash0); sph_shavite512(&ctx_shavite, hash0, 64); sph_shavite512_close(&ctx_shavite, hash1); sph_metis512(&ctx_metis, hash1, 64); sph_metis512_close(&ctx_metis, hash2); if( *(uint32*)((uint8*)hash2+28) <= target ) { totalShareCount++; xptMiner_submitShare(block); } block->nonce++; } totalCollisionCount += 0x8000; } }
94a9f51ef1db33b0283e45ee3221d1ba4013983c
042922a450aa3ad7944cdffead3562c6ce7bfbcf
/tests/test_solver.cpp
33f9884c63862be886dd19dca7c2874e324e4b56
[ "MIT" ]
permissive
lacrymose/polysolve
1317daceb02f60851ae24a3eb01b8eab31666064
a94e9b8ed8302d4b479533c67419f31addb1e987
refs/heads/master
2023-06-04T05:13:24.145186
2021-06-22T23:26:04
2021-06-22T23:26:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,813
cpp
test_solver.cpp
//////////////////////////////////////////////////////////////////////////////// #include <polysolve/FEMSolver.hpp> #include <catch.hpp> #include <iostream> #include <unsupported/Eigen/SparseExtra> //////////////////////////////////////////////////////////////////////////////// using namespace polysolve; TEST_CASE("all", "[solver]") { const std::string path = POLYSOLVE_DATA_DIR; Eigen::SparseMatrix<double> A; const bool ok = loadMarket(A, path + "/A_2.mat"); REQUIRE(ok); auto solvers = LinearSolver::availableSolvers(); for (const auto &s : solvers) { if (s == "Eigen::DGMRES") continue; #ifdef WIN32 if (s == "Eigen::ConjugateGradient" || s == "Eigen::BiCGSTAB" || s == "Eigen::GMRES" || s == "Eigen::MINRES") continue; #endif auto solver = LinearSolver::create(s, ""); // solver->setParameters(params); Eigen::VectorXd b(A.rows()); b.setRandom(); Eigen::VectorXd x(b.size()); x.setZero(); solver->analyzePattern(A, A.rows()); solver->factorize(A); solver->solve(b, x); // solver->getInfo(solver_info); // std::cout<<"Solver error: "<<x<<std::endl; const double err = (A * x - b).norm(); INFO("solver: " + s); REQUIRE(err < 1e-8); } } TEST_CASE("pre_factor", "[solver]") { const std::string path = POLYSOLVE_DATA_DIR; Eigen::SparseMatrix<double> A; const bool ok = loadMarket(A, path + "/A_2.mat"); REQUIRE(ok); auto solvers = LinearSolver::availableSolvers(); for (const auto &s : solvers) { if (s == "Eigen::DGMRES") continue; #ifdef WIN32 if (s == "Eigen::ConjugateGradient" || s == "Eigen::BiCGSTAB" || s == "Eigen::GMRES" || s == "Eigen::MINRES") continue; #endif auto solver = LinearSolver::create(s, ""); solver->analyzePattern(A, A.rows()); std::default_random_engine eng{42}; std::uniform_real_distribution<double> urd(0.1, 5); for (int i = 0; i < 10; ++i) { std::vector<Eigen::Triplet<double>> tripletList; for (int k = 0; k < A.outerSize(); ++k) { for (Eigen::SparseMatrix<double>::InnerIterator it(A, k); it; ++it) { if (it.row() == it.col()) { tripletList.emplace_back(it.row(), it.col(), urd(eng) * 100); } else if (it.row() < it.col()) { const double val = -urd(eng); tripletList.emplace_back(it.row(), it.col(), val); tripletList.emplace_back(it.col(), it.row(), val); } } } Eigen::SparseMatrix<double> Atmp(A.rows(), A.cols()); Atmp.setFromTriplets(tripletList.begin(), tripletList.end()); Eigen::VectorXd b(Atmp.rows()); b.setRandom(); Eigen::VectorXd x(b.size()); x.setZero(); solver->factorize(Atmp); solver->solve(b, x); // solver->getInfo(solver_info); // std::cout<<"Solver error: "<<x<<std::endl; const double err = (Atmp * x - b).norm(); INFO("solver: " + s); REQUIRE(err < 1e-8); } } } #ifdef POLYSOLVE_WITH_HYPRE TEST_CASE("hypre", "[solver]") { const std::string path = POLYSOLVE_DATA_DIR; Eigen::SparseMatrix<double> A; const bool ok = loadMarket(A, path + "/A_2.mat"); REQUIRE(ok); auto solver = LinearSolver::create("Hypre", ""); // solver->setParameters(params); Eigen::VectorXd b(A.rows()); b.setRandom(); Eigen::VectorXd x(b.size()); x.setZero(); solver->analyzePattern(A, A.rows()); solver->factorize(A); solver->solve(b, x); // solver->getInfo(solver_info); // std::cout<<"Solver error: "<<x<<std::endl; const double err = (A * x - b).norm(); REQUIRE(err < 1e-8); } TEST_CASE("hypre_initial_guess", "[solver]") { const std::string path = POLYSOLVE_DATA_DIR; Eigen::SparseMatrix<double> A; const bool ok = loadMarket(A, path + "/A_2.mat"); REQUIRE(ok); // solver->setParameters(params); Eigen::VectorXd b(A.rows()); b.setRandom(); Eigen::VectorXd x(A.rows()); x.setZero(); { json solver_info; auto solver = LinearSolver::create("Hypre", ""); solver->analyzePattern(A, A.rows()); solver->factorize(A); solver->solve(b, x); solver->getInfo(solver_info); REQUIRE(solver_info["num_iterations"] > 1); } { json solver_info; auto solver = LinearSolver::create("Hypre", ""); solver->analyzePattern(A, A.rows()); solver->factorize(A); solver->solve(b, x); solver->getInfo(solver_info); REQUIRE(solver_info["num_iterations"] == 1); } // std::cout<<"Solver error: "<<x<<std::endl; const double err = (A * x - b).norm(); REQUIRE(err < 1e-8); } #endif #ifdef POLYSOLVE_WITH_AMGCL TEST_CASE("amgcl_initial_guess", "[solver]") { const std::string path = POLYSOLVE_DATA_DIR; Eigen::SparseMatrix<double> A; const bool ok = loadMarket(A, path + "/A_2.mat"); REQUIRE(ok); // solver->setParameters(params); Eigen::VectorXd b(A.rows()); b.setRandom(); Eigen::VectorXd x(A.rows()); x.setZero(); { json solver_info; auto solver = LinearSolver::create("AMGCL", ""); solver->analyzePattern(A, A.rows()); solver->factorize(A); solver->solve(b, x); solver->getInfo(solver_info); REQUIRE(solver_info["num_iterations"] > 0); } { json solver_info; auto solver = LinearSolver::create("AMGCL", ""); solver->analyzePattern(A, A.rows()); solver->factorize(A); solver->solve(b, x); solver->getInfo(solver_info); REQUIRE(solver_info["num_iterations"] == 0); } // std::cout<<"Solver error: "<<x<<std::endl; const double err = (A * x - b).norm(); REQUIRE(err < 1e-8); } #endif TEST_CASE("saddle_point_test", "[solver]") { #ifdef WIN32 #ifndef NDEBUG return; #endif #endif const std::string path = POLYSOLVE_DATA_DIR; Eigen::SparseMatrix<double> A; bool ok = loadMarket(A, path + "/A0.mat"); REQUIRE(ok); Eigen::VectorXd b; ok = loadMarketVector(b, path + "/b0.mat"); REQUIRE(ok); auto solver = LinearSolver::create("SaddlePointSolver", ""); solver->analyzePattern(A, 9934); solver->factorize(A); Eigen::VectorXd x(A.rows()); solver->solve(b, x); const double err = (A * x - b).norm(); REQUIRE(err < 1e-8); }
8ba787341d06d2cc6cceffaa686fa948c65f77e6
3b07f6b9d8e4321d160c91c4eebd0b522869dc64
/src/Core/Math/Matrix.hpp
f4e0b6415853bf44acbc260e580e0c4844403e53
[]
no_license
KiriCord/BYTEngine
91ae33fe1313b39201722f228f264286496120db
877182c831d7bed3ff99cd7b1c103438e5253c51
refs/heads/master
2023-08-21T15:22:40.624332
2021-10-24T06:38:30
2021-10-24T06:38:30
283,521,617
1
1
null
null
null
null
UTF-8
C++
false
false
433
hpp
Matrix.hpp
#include "Vector2.hpp" #include "Vector3.hpp" class Matrix { //float matrix[2]; Vector2 matrix[2]; //static Matrix public: void Invert(); void Transpose(); void Orthonormalization(); float Determinant(); Vector2 GetRow(int value) const; Vector2 GetColumn(int value) const; Vector2 GetMainDiagonal() const; Vector2 SetRow(int value) const; Vector2 SetColumn(int value) const; };
e4bf114387cb5af9d5d4d53b58e4650d46f544d5
76bb5ef47f010b2c492a1332b61c218604cbdb89
/data_structure/boj_10816.cpp
7c4848cead1080cda037eecfa426d175f68b79e1
[]
no_license
yellowsummer9812/winter_algorithm_camp
ab02f92cfc0ac7294eb8b25ab5aa3d337e4ea703
6d116c1887b98fcfe68e66f804d35f958c963b97
refs/heads/master
2023-03-23T22:45:36.773912
2021-03-24T00:48:47
2021-03-24T00:48:47
327,474,366
0
0
null
null
null
null
UTF-8
C++
false
false
400
cpp
boj_10816.cpp
#include <iostream> #define MAX 10000000 typedef long long ll; using namespace std; ll n, m; ll a[2 * MAX + 1]; int main(){ ios_base::sync_with_stdio(0); cin.tie(0), cout.tie(0); cin>> n; ll tmp; for(ll i = 0; i < n; i++){ cin>> tmp; a[tmp + MAX]++; } cin>> m; for(ll i = 0; i < m; i++){ cin>> tmp; cout<< a[tmp + MAX]<< " "; } }
a06a2ab36393283b48d3707a705f487793db2a5d
555ade8ec24af779ce30f78f140d011139c2097d
/2504_괄호의값.cpp
9e1b003f973bf85eb80f09c9943918d39ed3d614
[]
no_license
hyeon0121/baekjoon_problem
6222e6c837342d419f15ff45ba948cbc95831286
51dcc8d3b0299d2f2714aa66672ea08588e0a55b
refs/heads/master
2021-08-18T15:43:00.302687
2021-06-16T13:46:16
2021-06-16T13:46:16
201,385,374
0
0
null
null
null
null
UTF-8
C++
false
false
958
cpp
2504_괄호의값.cpp
#include <iostream> #include <vector> #include <stack> using namespace std; int main () { string str; cin >> str; int answer = 0; stack<char> s; int tmp = 1; for (int i = 0; i < str.size(); ++i) { if (str[i]=='(') { tmp *= 2; s.push(str[i]); } else if (str[i]=='[') { tmp *= 3; s.push(str[i]); } else if (str[i] == ')') { if (s.empty() || s.top() != '(') { answer = 0; break; } if (str[i-1] == '(') answer += tmp; s.pop(); tmp /= 2; } else if (str[i] == ']') { if (s.empty() || s.top() != '[') { answer = 0; break; } if (str[i-1] == '[') answer += tmp; s.pop(); tmp /= 3; } } if (!s.empty()) answer = 0; cout << answer; return 0; }
d318404daaea94350205efd97c072e39c5ae108b
308f5596f1c7d382520cfce13ceaa5dff6f4f783
/hphp/runtime/ext/snappy/ext_snappy.cpp
64f23d74009a8a05437e1f2b2487153ed4a565e4
[ "PHP-3.01", "Zend-2.0", "MIT" ]
permissive
facebook/hhvm
7e200a309a1cad5304621b0516f781c689d07a13
d8203129dc7e7bf8639a2b99db596baad3d56b46
refs/heads/master
2023-09-04T04:44:12.892628
2023-09-04T00:43:05
2023-09-04T00:43:05
455,600
10,335
2,326
NOASSERTION
2023-09-14T21:24:04
2010-01-02T01:17:06
C++
UTF-8
C++
false
false
2,106
cpp
ext_snappy.cpp
/* +----------------------------------------------------------------------+ | HipHop for PHP | +----------------------------------------------------------------------+ | Copyright (c) 2010-present Facebook, Inc. (http://www.facebook.com) | | Copyright (c) 1997-2010 The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ */ #include "hphp/runtime/ext/extension.h" #include <snappy.h> namespace HPHP { Variant HHVM_FUNCTION(snappy_compress, const String& data) { String s = String(snappy::MaxCompressedLength(data.size()), ReserveString); size_t size; snappy::RawCompress(data.data(), data.size(), s.mutableData(), &size); return s.shrink(size); } Variant HHVM_FUNCTION(snappy_uncompress, const String& data) { size_t dsize; if (!snappy::GetUncompressedLength(data.data(), data.size(), &dsize)) { return false; } String s = String(dsize, ReserveString); if (!snappy::RawUncompress(data.data(), data.size(), s.mutableData())) { return false; } return s.setSize(dsize); } static struct SnappyExtension final : Extension { SnappyExtension() : Extension("snappy", NO_EXTENSION_VERSION_YET, NO_ONCALL_YET) {} void moduleInit() override { HHVM_FE(snappy_compress); HHVM_FE(snappy_uncompress); HHVM_FALIAS(sncompress, snappy_compress); HHVM_FALIAS(snuncompress, snappy_uncompress); } } s_snappy_extension; }
ae218eec0ad8ee2ddd759c95be7b16aa70211ff4
d8f8cd94f057453fdeea69605f0b7990548eff4a
/vlasov/boundaries/outflow.h
7c5f7f189c240fe5c81fa1b761fc27ebdd56a0d4
[ "MIT" ]
permissive
natj/runko
2333e708171f607e1dc62d68fb85a766b5c55169
7cd6375c426723f53c91e31789b7ced72a38c5cb
refs/heads/master
2023-09-04T09:06:35.817058
2023-02-02T13:29:48
2023-02-02T13:29:48
153,752,597
32
19
MIT
2023-09-06T21:10:15
2018-10-19T08:40:56
Python
UTF-8
C++
false
false
977
h
outflow.h
#pragma once #include "../../corgi/corgi.h" #include "../../em-fields/boundaries/damping_tile.h" #include "../../vlasov/tile.h" #include "../spatial-solvers/amr_spatial_solver.h" namespace vlv { namespace outflow { template<size_t D, int S> class Tile : virtual public fields::damping::Tile<D, S>, virtual public vlv::Tile<D> { public: /// constructor Tile(size_t nx, size_t ny, size_t nz) : fields::Tile<D>(nx,ny,nz), fields::damping::Tile<D,S>(nx,ny,nz), vlv::Tile<D>(nx,ny,nz) { } /// switch flag to determine if we move plasma or not bool advance = false; void step_location(corgi::Grid<D>& grid) override { //std::cout<<"BC spatial step\n"; if(advance) { vlv::AmrSpatialLagrangianSolver<Realf> ssol; ssol.solve(*this, grid); } } /// wall location using fields::damping::Tile<D, S>::fld1; using fields::damping::Tile<D, S>::fld2; }; } // end of namespace outflow } // end of namespace vlasov
7a17491e960b56c2faf7021f76693d98ddfbbb04
3cc1de03a54d9da8ea666de170d97c87e29d7e29
/test_parellelmodel_gainsRC.ino
f28bb0b0a0bd64d2b89f69d32bc660c53b43ad30
[]
no_license
ganna1abhi/AD5933-labview-integration
d742e6e5f160187530a0b2c18b19ae37823aa86a
17764db90896579416baced96495a61828fb490f
refs/heads/master
2020-03-24T06:41:20.073468
2018-08-15T16:24:41
2018-08-15T16:24:41
142,537,671
1
0
null
null
null
null
UTF-8
C++
false
false
7,888
ino
test_parellelmodel_gainsRC.ino
// By Dr. Arda Gozen and Abhishek Gannarapu (abhishek.gannarapu@wsu.edu) // Gain factors calculated at different frequencies starting from 2000 Hz to 100 kHz // in steps of 2000 Hz // A 1.5 Mohm Resistor and 10 pF Capacitor (RC) was used as a reference impedance source #include <WireIA.h> #include <inttypes.h> #include <Wire.h> #include <EEPROM.h> #include "Wire.h" #include "Complex.h" // Defining all the register events #define button 2 #define SLAVE_ADDR 0x0D #define ADDR_PTR 0xB0 #define START_FREQ_R1 0x82 #define START_FREQ_R2 0x83 #define START_FREQ_R3 0x84 #define FREG_INCRE_R1 0x85 #define FREG_INCRE_R2 0x86 #define FREG_INCRE_R3 0x87 #define NUM_INCRE_R1 0x88 #define NUM_INCRE_R2 0x89 #define NUM_SCYCLES_R1 0x8A #define NUM_SCYCLES_R2 0x8B #define RE_DATA_R1 0x94 #define RE_DATA_R2 0x95 #define IMG_DATA_R1 0x96 #define IMG_DATA_R2 0x97 #define TEMP_R1 0x92 #define TEMP_R2 0x93 #define CTRL_REG 0x80 #define STATUS_REG 0x8F #define pi 3.14159265358 int data; int statuscheck; const float MCLK = 16.776 * pow(10, 6); // AD5933 Internal Clock Speed 16.776 MHz const float start_freq = 2 * pow(10, 3); // Set start freq, < 100Khz const float incre_freq = 2 * pow(10, 3); // Set freq increment const int incre_num = 50; // Set number of increments; < 511 float re; float img; float mag; float ph; //float gn_mag; //float gn_ph; float cal_mag; float cal_ph; float dev_freq; const float re_act = 98.875*pow(10,3); // actual real value of the resistor const float img_act = -417.48; // actual img value of the resistor const float mag_act = sqrt(pow(double(re_act),2)+pow(double(img_act),2)); // actual magitude const float ph_act = (180.0/3.1415926)*atan(double(img_act)/double(re_act)); // actual phase angle //ph_act = (180.0/3.1415926)*ph_act; // angle in degrees const float gn_mag[] = { 2.01676933647889e-10, 2.01075896245039e-10, 2.02156749829603e-10, 2.02865126394114e-10, 2.03880200885129e-10, 2.04569424353690e-10, 2.05442615763733e-10, 2.06210063740696e-10, 2.06735177014616e-10, 2.06728935086957e-10, 2.07422575115978e-10, 2.07872485518808e-10, 2.08291032237997e-10, 2.09156621954237e-10, 2.09512309596226e-10, 2.10435572286198e-10, 2.10985801047195e-10, 2.11625778859015e-10, 2.11922193697383e-10, 2.11862711483692e-10, 2.12767926798854e-10, 2.13680470743593e-10, 2.14425516345066e-10, 2.14932132756597e-10, 2.15692163638429e-10, 2.16889636729696e-10, 2.17838930172185e-10, 2.19850520559645e-10, 2.23181823975115e-10, 2.26510167932770e-10, 2.31135767962348e-10, 2.35766382974399e-10, 2.40777746794554e-10, 2.45906454664768e-10, 2.51148149301368e-10, 2.56529139594743e-10, 2.61856135586265e-10, 2.67507186793794e-10, 2.72900258632719e-10, 2.78355005904209e-10, 2.84335612005172e-10, 2.90287089194992e-10, 2.96142256708266e-10, 3.02062991022894e-10, 3.07890332582480e-10, 3.13632546133231e-10, 3.19401388529402e-10, 3.25065730924158e-10, 3.30586692957278e-10, 3.36109573695980e-10 }; const float gn_ph[] = { -1.51778679847932, -1.50070096785381, -1.45146628794921, -1.40782279138970, -1.36454353180326, -1.32494953251332, -1.28197906980682, -1.24161064427691, -1.20165116076679, -1.16370221104284, -1.12249524394826, -1.08293005578720, -1.04267862769066, -1.00282442808124, -0.962877762938166, -0.922429028437587, -0.882403104207715, -0.842678065256900, -0.803381427181115, -0.764265685978069, -0.724877414735710, -0.685094432473163, -0.645422905219333, -0.605818769314204, -0.566622498529320, -0.525738167518921, -0.484800653020244, -0.441475913506845, -0.402438287180483, -0.363639408863913, -0.324354385030797, -0.284660914312864, -0.244119542316058, -0.204067286929258, -0.163181157071979, -0.123067163492273, -0.0830839545697892, -0.0439266971456112, -0.00432889396542535, 0.0349102808102506, 0.0742409322479309, 0.113586654213806, 0.152573280032845, 0.192048198088574, 0.231095099786608, 0.270856077191696, 0.309908909139402, 0.349068438320551, 0.388200906243044, 0.428420633017557 }; float mag_un; float ph_un; float re_un; float img_un; int cnt = 0; Complex temp(0,0); Complex c_dev(0,0); Complex c_sht(0,0); IA testIA; void setup() { Wire.begin(9); Serial.begin(9600); // Serial.println("came here"); writeData(CTRL_REG, 0x06); delay(1000); } void loop() { delay(10); writeData(START_FREQ_R1, getFrequency(start_freq, 1)); writeData(START_FREQ_R2, getFrequency(start_freq, 2)); writeData(START_FREQ_R3, getFrequency(start_freq, 3)); delay(10); // Increment by 2 kHz writeData(FREG_INCRE_R1, getFrequency(incre_freq, 1)); writeData(FREG_INCRE_R2, getFrequency(incre_freq, 2)); writeData(FREG_INCRE_R3, getFrequency(incre_freq, 3)); delay(10); // Points in frequency sweep (100), max 511 writeData(NUM_INCRE_R1, (incre_num & 0x001F00) >> 0x08 ); writeData(NUM_INCRE_R2, (incre_num & 0x0000FF)); delay(10); //Serial.println(readData(NUM_SCYCLES_R2)); delay(100); // Setting device to Standby writeData(CTRL_REG, 0xB0); delay(10); writeData(CTRL_REG, 0x10); delay(10); writeData(NUM_SCYCLES_R1, 511); delay(10); writeData(NUM_SCYCLES_R2, 0xFF); delay(10); // //status checking using polling - D2 needs to be high when done // //Start the frequency sweep writeData(CTRL_REG, 0x20); int swp=1; while (swp==1 && cnt < 50) { byte scheck = readData(0x8F); while (scheck != 0b00000010) { //Status check to see if device is ready //Serial.println(scheck, BIN); scheck = byte(readData(0x8F)) & 0b00000010; } //delay(2000); byte R1 = readData(RE_DATA_R1); byte R2 = readData(RE_DATA_R2); re = (R1 << 8) | R2; //Serial.print(re); if (re > pow(2,15)) { re = re - pow(2,16); } // Serial.print(PI); R1 = readData(IMG_DATA_R1); R2 = readData(IMG_DATA_R2); img = (R1 << 8) | R2; //Serial.println(img); if (img > pow(2,15)) { img = img - pow(2,16); } mag = sqrt(pow(double(re),2)+pow(double(img),2)); // four quadrant phase angle check if ( re > 0 && img > 0){ ph = atan(double(img)/double(re)); } else if (re < 0 && img > 0){ ph = pi + atan(double(img)/double(re)); } else if (re < 0 && img < 0){ ph = pi + atan(double(img)/double(re)); } else{ ph = 2*pi + atan(double(img)/double(re)); } mag_un = 1/(gn_mag[cnt]*mag); ph_un = ph - gn_ph[cnt]; re_un = mag_un*cos(ph_un); img_un = -mag_un*sin(ph_un); //Serial.println(ph); // Serial.print(re); Serial.print("\t"); Serial.println(img); Serial.print(re_un); Serial.print("\t"); Serial.println(img_un); if (byte(readData(0x8F)) & 0b00000100) { swp=0; } else{ writeData(CTRL_REG, 0x30); // Serial.print("actual mag: ");Serial.println(dev_freq); delay(1000); } cnt = cnt + 1; } Serial.println("----------------"); cnt = 0; delay(100); delay(10); // //Power down writeData(CTRL_REG,0xA0); } void writeData(int addr, int data) { Wire.beginTransmission(SLAVE_ADDR); Wire.write(addr); Wire.write(data); Wire.endTransmission(); delay(1); } int readData(int addr) { int data; Wire.beginTransmission(SLAVE_ADDR); Wire.write(ADDR_PTR); Wire.write(addr); Wire.endTransmission(); delay(1); Wire.requestFrom(SLAVE_ADDR, 1); if (Wire.available() >= 1) { data = Wire.read(); } else { data = -1; } delay(1); return data; } byte getFrequency(float freq, int n) { long val = long((freq / (MCLK / 4)) * pow(2, 27)); byte code; switch (n) { case 1: code = (val & 0xFF0000) >> 0x10; break; case 2: code = (val & 0x00FF00) >> 0x08; break; case 3: code = (val & 0x0000FF); break; default: code = 0; } return code; }
6c1fdf623dccd8d688e3ed677f910c4a48a70fbe
e16ead64b9c6c8094ce54bcfda9da62289d0eef4
/imgproc/segmentation/ForegroundSegmenterNaiveCRF.cpp
fbd50a0cac6fdaeebecea12f88484e391e6b7a7b
[ "BSD-3-Clause" ]
permissive
Algomorph/surfelwarp
fc8e85164f9d14bad7b00c8af9e528c634c9ddf2
3448229981ff67419ac47126d8f2ac8e9eb3127d
refs/heads/master
2020-07-24T12:30:54.755311
2019-10-22T14:33:25
2019-10-22T14:33:25
207,928,372
3
0
BSD-3-Clause
2019-09-12T00:06:37
2019-09-12T00:06:36
null
UTF-8
C++
false
false
4,852
cpp
ForegroundSegmenterNaiveCRF.cpp
// // Created by wei on 2/24/18. // #include "common/Constants.h" #include "imgproc/segmentation/ForegroundSegmenterNaiveCRF.h" #include "imgproc/segmentation/foreground_crf_window.h" #include "imgproc/segmentation/crf_common.h" #include "common/common_texture_utils.h" #include "visualization/Visualizer.h" void surfelwarp::ForegroundSegmenterNaiveCRF::AllocateBuffer( unsigned clip_rows, unsigned clip_cols ) { //Do subsampling here const auto subsampled_rows = clip_rows / crf_subsample_rate; const auto subsampled_cols = clip_cols / crf_subsample_rate; //Allocate the buffer for unary energy m_unary_energy_map_subsampled.create(subsampled_rows, subsampled_cols); //Allocate the buffer for meanfield q createFloat1TextureSurface(subsampled_rows, subsampled_cols, m_meanfield_foreground_collect_subsampled[0]); createFloat1TextureSurface(subsampled_rows, subsampled_cols, m_meanfield_foreground_collect_subsampled[1]); //Allocate the buffer for segmentation mask createUChar1TextureSurface(subsampled_rows, subsampled_cols, m_segmented_mask_collect_subsampled); //Allocate the upsampled buffer createUChar1TextureSurface(clip_rows, clip_cols, m_foreground_mask_collect_upsampled); createFloat1TextureSurface(clip_rows, clip_cols, m_filter_foreground_mask_collect_upsampled); } void surfelwarp::ForegroundSegmenterNaiveCRF::ReleaseBuffer() { m_unary_energy_map_subsampled.release(); releaseTextureCollect(m_meanfield_foreground_collect_subsampled[0]); releaseTextureCollect(m_meanfield_foreground_collect_subsampled[1]); releaseTextureCollect(m_segmented_mask_collect_subsampled); } void surfelwarp::ForegroundSegmenterNaiveCRF::SetInputImages( cudaTextureObject_t clip_normalized_rgb_img, cudaTextureObject_t raw_depth_img, cudaTextureObject_t clip_depth_img, int frame_idx, cudaTextureObject_t clip_background_rgb ) { m_input_texture.clip_normalize_rgb_img = clip_normalized_rgb_img; m_input_texture.raw_depth_img = raw_depth_img; m_input_texture.clip_depth_img = clip_depth_img; } void surfelwarp::ForegroundSegmenterNaiveCRF::Segment(cudaStream_t stream) { //First init the unary energy and meanfield initMeanfieldUnaryEnergy(stream); //The main loop const auto max_iters = Constants::kMeanfieldSegmentIteration; for(auto i = 0; i < max_iters; i++) { //saveMeanfieldApproximationMap(i); inferenceIteration(stream); } //Write the output to segmentation mask writeSegmentationMask(stream); upsampleFilterForegroundMask(stream); } void surfelwarp::ForegroundSegmenterNaiveCRF::initMeanfieldUnaryEnergy(cudaStream_t stream) { initMeanfieldUnaryForegroundSegmentation( m_input_texture.raw_depth_img, m_input_texture.clip_depth_img, m_unary_energy_map_subsampled, m_meanfield_foreground_collect_subsampled[0].surface, stream ); m_updated_meanfield_idx = 0; } void surfelwarp::ForegroundSegmenterNaiveCRF::inferenceIteration(cudaStream_t stream) { //The index value const auto input_idx = m_updated_meanfield_idx % 2; const int output_idx = (input_idx + 1) % 2; m_updated_meanfield_idx = (m_updated_meanfield_idx + 1) % 2; //the constant value for apperance kernel const float apperance_weight = 0.5f; const float sigma_alpha = 10; const float sigma_beta = 15; //The constant value for smooth kernel const float sigma_gamma = 3; const float smooth_weight = 0.5f; foregroundMeanfieldIterWindow( m_meanfield_foreground_collect_subsampled[input_idx].texture, m_input_texture.clip_normalize_rgb_img, m_unary_energy_map_subsampled, sigma_alpha, sigma_beta, sigma_gamma, apperance_weight, smooth_weight, m_meanfield_foreground_collect_subsampled[output_idx].surface, stream ); } void surfelwarp::ForegroundSegmenterNaiveCRF::writeSegmentationMask(cudaStream_t stream) { const auto write_idx = m_updated_meanfield_idx % 2; writeForegroundSegmentationMask( m_meanfield_foreground_collect_subsampled[write_idx].texture, m_unary_energy_map_subsampled.rows(), m_unary_energy_map_subsampled.cols(), m_segmented_mask_collect_subsampled.surface, stream ); } void surfelwarp::ForegroundSegmenterNaiveCRF::upsampleFilterForegroundMask(cudaStream_t stream) { ForegroundSegmenter::UpsampleFilterForegroundMask( m_segmented_mask_collect_subsampled.texture, m_unary_energy_map_subsampled.rows(), m_unary_energy_map_subsampled.cols(), crf_subsample_rate, Constants::kForegroundSigma, m_foreground_mask_collect_upsampled.surface, m_filter_foreground_mask_collect_upsampled.surface, stream ); } void surfelwarp::ForegroundSegmenterNaiveCRF::saveMeanfieldApproximationMap(const unsigned iter) { std::stringstream ss; ss << iter; std::string file_name = "meanfield-"; file_name += ss.str(); file_name += ".png"; Visualizer::SaveBinaryMeanfield(m_meanfield_foreground_collect_subsampled[m_updated_meanfield_idx].texture, file_name); }
eeb4a4287546b0c7362305809b5b0d6c39dae7e3
93b74c8637e843ac74afb696e36230223b0e18ab
/Sphere/model.h
6a0ef4cd4b48450a6e19295ea838930b5524eaee
[]
no_license
denis-bunakalya/Qt
9a4d9858617ebf5d7e770008da828f9f70fbbce3
03648ddb25d7ee7cebb49f13c6a7149dfa248ed8
refs/heads/master
2021-06-27T12:32:55.769759
2017-09-13T06:53:50
2017-09-13T06:53:50
103,364,533
0
0
null
null
null
null
UTF-8
C++
false
false
1,201
h
model.h
#ifndef MODEL_H #define MODEL_H #include <QObject> #include <QImage> class Model : public QObject { Q_OBJECT public: Model(); int getX() const; int getY() const; int getScale() const; int getFilter() const; QImage* getImage(); static const int minX = -1000; static const int maxX = 1000; static const int defaultX = 0; static const int minY = -1000; static const int maxY = 1000; static const int defaultY = 0; static const int minScale = -1000; static const int maxScale = 1000; static const int defaultScale = 0; static const bool defaultFilter = 0; QSize loadFromFile(QString fileName); void saveToFile(QString fileName, QSize size); void loadImage(QString fileName); signals: void sendX(int); void sendY(int); void sendScale(int); void sendFilter(int); void sendImage(QImage*); void sendSize(int, int); public slots: void receiveX(int value); void receiveY(int value); void receiveScale(int value); void receiveFilter(int value); private: int x; int y; int scale; int filter; QImage image; QString source; }; #endif // MODEL_H
41cf15a77a70987c32aa38340cec80ae3111fb77
b70ed7fb7e896813688e1538e6727baa15301bec
/Stack/5) decode_given_sequence.cpp
d5ed419341e562e19367155bc275db44ab20de28
[]
no_license
sagar-barapatre/Data-Structures-and-Algorithms
6b9c83ad1ea081fd2cc3f61f8d19c35a4a6b21f8
8383475e279bea103e623d462b235aa45d6dc315
refs/heads/master
2023-01-29T06:34:59.229690
2020-12-13T02:35:11
2020-12-13T02:35:11
272,883,213
6
1
null
null
null
null
UTF-8
C++
false
false
422
cpp
5) decode_given_sequence.cpp
#include<iostream> #include<stack> using namespace std; string decodeMinimum(string str) { string result = ""; stack<int> s; for (int i = 0 ; i <= str.length() ; i++) { s.push(i + 1); if (i == str.length() || str[i] == 'I') { while (!s.empty()) { result += to_string(s.top()); s.pop(); } } } return result; } int main() { string str = "IDIDII"; cout << decodeMinimum(str); return 0; }
44cb38f03f8b1c2441347e01a163c568a73a8bbd
7d40f405bf9b73a81a014af4a438da2ee0d73cbe
/parseRegEx/regexToAutomata.cc
b687752c6f956d692a33853a4d06c5826882b001
[ "Apache-2.0" ]
permissive
idea-iitd/ARRIVAL
6447c104c8b27646354fe276342a2e7c8c9d7160
e476da2b376f236c0d3db42ae8af5ad3ddb6db98
refs/heads/master
2021-07-25T13:26:37.775609
2020-05-19T06:05:45
2020-05-19T06:05:45
172,227,158
6
4
null
2019-06-07T10:01:46
2019-02-23T15:01:45
C++
UTF-8
C++
false
false
5,761
cc
regexToAutomata.cc
#ifndef automata_H #include "nodeAutomata.cc" #define automata_H #endif #include <stack> #include <iostream> automata *conversionNode(string regex) { stack<automata *> automatons; stack<char> operators; if (regex[0] == 'U') { automata *curr = new automata(-1); curr->plus(); curr->universal = true; automatons.push(curr); } else { int i = 0; while (i < regex.length()) { // Generate Automata int num = 0; while (regex[i] == '(') { operators.push('('); ++i; } while (isdigit(regex[i])) { num = num * 10 + (regex[i] - '0'); ++i; } automata *curr = new automata(num); // Do operation on Automata if (operators.empty()) { automatons.push(curr); } else if (operators.top() == '.') { automata *operated = automatons.top(); operated->concat(curr); automatons.pop(); operators.pop(); automatons.push(operated); } else if (operators.top() == 'U') { automata *operated = automatons.top(); operated->unionor(curr); automatons.pop(); operators.pop(); automatons.push(operated); } else { automatons.push(curr); } while (regex[i] == ')') { operators.pop(); if (operators.empty()) { } else if (operators.top() == '.') { automata *operated = automatons.top(); automatons.pop(); automata *operated2 = automatons.top(); automatons.pop(); operated2->concat(operated); operators.pop(); automatons.push(operated2); } else if (operators.top() == 'U') { automata *operated = automatons.top(); automatons.pop(); automata *operated2 = automatons.top(); automatons.pop(); operated2->unionor(operated); operators.pop(); automatons.push(operated2); } ++i; } // Next operator push or operate(if * or +) if (regex[i] == '.') { operators.push('.'); ++i; } else if (regex[i] == 'U') { operators.push('U'); ++i; } else if (regex[i] == '*') { automata *operated = automatons.top(); operated->closure(); automatons.pop(); automatons.push(operated); ++i; } else if (regex[i] == '+') { automata *operated = automatons.top(); operated->plus(); automatons.pop(); automatons.push(operated); ++i; } while (regex[i] == ')') { operators.pop(); if (operators.empty()) { } else if (operators.top() == '.') { automata *operated = automatons.top(); automatons.pop(); automata *operated2 = automatons.top(); automatons.pop(); operated2->concat(operated); operators.pop(); automatons.push(operated2); } else if (operators.top() == 'U') { automata *operated = automatons.top(); automatons.pop(); automata *operated2 = automatons.top(); automatons.pop(); operated2->unionor(operated); operators.pop(); automatons.push(operated2); } ++i; if (regex[i] == '.') { operators.push('.'); ++i; } else if (regex[i] == 'U') { operators.push('U'); ++i; } else if (regex[i] == '*') { automata *operated = automatons.top(); operated->closure(); automatons.pop(); automatons.push(operated); ++i; } else if (regex[i] == '+') { automata *operated = automatons.top(); operated->plus(); automatons.pop(); automatons.push(operated); ++i; } } } } automata *a = automatons.top(); state *finalState = new state(-2); for (int i = 0; i < a->finalStates.size(); ++i) { finalState->setTransition(a->finalStates[i], false); } a->finalState = finalState; return a; }
7bcc178ff0eebc7a0f064e9110042d114bc19bfd
6c57b1f26dabd8bb24a41471ced5e0d1ac30735b
/TBS/include/TBS/NamedActivity.h
2d545a03a54312bd57afbd9a0871eff220fa3798
[]
no_license
hadzim/bb
555bb50465fbd604c56c755cdee2cce796118322
a6f43a9780753242e5e9f2af804c5233af4a920e
refs/heads/master
2021-01-21T04:54:53.835407
2016-06-06T06:31:55
2016-06-06T06:31:55
17,916,029
0
0
null
null
null
null
UTF-8
C++
false
false
3,873
h
NamedActivity.h
/* * NamedActivity.h * * Created on: 9.12.2011 * Author: Honza */ #ifndef NAMEDACTIVITY_H_ #define NAMEDACTIVITY_H_ #include "Poco/Foundation.h" #include "Poco/RunnableAdapter.h" #include "Poco/ThreadPool.h" #include "Poco/Event.h" #include "Poco/Mutex.h" #include "TBS/Log.h" namespace TBS { template <class C> class NamedActivity: public Poco::Runnable { public: typedef Poco::RunnableAdapter<C> RunnableAdapterType; typedef typename RunnableAdapterType::Callback Callback; NamedActivity(std::string name, C* pOwner, Callback method) : name(name), _pOwner(pOwner), _runnable(*pOwner, method), _stopped(true), _running(false), _done(false), bgThread(name), joinNeeded(false) /// Creates the activity. Call start() to /// start it. { poco_check_ptr (pOwner) ; } virtual ~NamedActivity() /// Stops and destroys the activity. { stop(); } void start() /// Starts the activity by acquiring a /// thread for it from the default thread pool. { LDEBUG("NamedActivity") << "Start activity " << this->name << LE Poco::FastMutex::ScopedLock lock(_mutex); if (!_running) { _done.reset(); _stopped = false; _running = true; try { bgThread.start(*this); joinNeeded = true; } catch (...) { _running = false; throw; } } LDEBUG("NamedActivity") << "Started activity " << this->name << LE } void stop() { bool joinReallyNeeded = false; { Poco::FastMutex::ScopedLock lock(_mutex); if (_stopped) { return; } _stopped = true; joinReallyNeeded = joinNeeded; joinNeeded = false; } try { wait(5000); LDEBUG("NamedActivity") << "Deleted activity " << this->name << ", join really needed: " << joinReallyNeeded << LE; if (joinReallyNeeded){ LDEBUG("NamedActivity") << "Joining thread of " << this->name << LE; bgThread.join(); LDEBUG("NamedActivity") << "Thread of " << this->name << " joined." << LE; } } catch (Poco::Exception & e){ LERROR("NamedActivity") << "ERROR NamedActivity "<< this->name << ":" << e.displayText() << LE; throw; } } void wait() { if (_running) { _done.wait(); } } void wait(long milliseconds) { if (_running) { try { _done.wait(milliseconds); } catch (Poco::Exception & e) { LOG_STREAM_INFO << "NamedActivity exception: " << e.what() << LE throw; } } } bool isStopped() const { return _stopped; } bool isRunning() const { return _running; } protected: virtual void run() { threadDebug(); LOG_STREAM_DEBUG << "Activity bg started " << this->name << "[" << Poco::Thread::currentTid() << "] [" << Poco::Thread::current()->id() << "]" /*<< syscall(SYS_gettid)*/ << LE try { _runnable.run(); } catch (...) { _running = false; _done.set(); throw; } _running = false; _done.set(); LOG_STREAM_DEBUG << "Activity bg finished " << this->name << "[" << Poco::Thread::currentTid() << "] [" << Poco::Thread::current()->id() << "]" << LE //LOG_STREAM_INFO << this->name << " -> LWP " << syscall(SYS_gettid) << " end" << LE } private: NamedActivity(); NamedActivity(const NamedActivity&); NamedActivity& operator =(const NamedActivity&); std::string name; C* _pOwner; RunnableAdapterType _runnable; volatile bool _stopped; volatile bool _running; Poco::Event _done; Poco::FastMutex _mutex; Poco::Thread bgThread; bool joinNeeded; }; } #endif // Foundation_Activity_INCLUDED
dfa10e2124b0532775eb070080195355c9d8c843
7c96a7c46cf53bdb5d5e08a45b36b6fceacab5f0
/ThirdParty/ioss/vtkioss/text_mesh/Iotm_TextMeshUtils.h
41272fded3c02a73a1778d03fd524bac78b7628e
[ "BSD-3-Clause" ]
permissive
QuanPengWang/VTK
b4dca79a67b5d124e128b7978b5f0470899c0818
6a2b5e8d4e6f5b2184ca7750b624af076b61dd1a
refs/heads/master
2022-04-30T14:18:48.214123
2022-03-16T06:24:24
2022-03-16T06:24:24
200,147,417
0
0
NOASSERTION
2022-03-16T06:24:25
2019-08-02T02:04:28
C++
UTF-8
C++
false
false
73,006
h
Iotm_TextMeshUtils.h
#pragma once // ####################### Start Clang Header Tool Managed Headers ######################## // clang-format off #include <ctype.h> // for toupper #include <stddef.h> // for size_t #include <algorithm> // for remove, etc #include <iterator> // for insert_iterator #include <map> #include <set> // for set #include <sstream> // for operator<<, etc #include <string> // for basic_string, etc #include <utility> // for pair #include <vector> // for vector #include <unordered_map> #include <sstream> // for ostringstream #include <iostream> #include <functional> #include <stdexcept> #include <numeric> #include "vtk_ioss_fmt.h" // xxx(kitware) #include VTK_FMT(fmt/ostream.h) // xxx(kitware) #if defined(_WIN32) && !defined(__CYGWIN__) #define strcasecmp stricmp #endif // clang-format on // ####################### End Clang Header Tool Managed Headers ######################## namespace Iotm { namespace text_mesh { using ErrorHandler = std::function<void(const std::ostringstream &)>; template <class EXCEPTION> void handle_error(const std::ostringstream &message) { throw EXCEPTION((message).str()); } inline void default_error_handler(const std::ostringstream &message) { handle_error<std::logic_error>(message); } template <class ForwardIt, class T> ForwardIt bound_search(ForwardIt first, ForwardIt last, const T &value) { first = std::lower_bound(first, last, value); if (!(first == last) && !(value < *first)) return first; return last; } template <class ForwardIt, class T, class Compare> ForwardIt bound_search(ForwardIt first, ForwardIt last, const T &value, Compare comp) { first = std::lower_bound(first, last, value, comp); if (!(first == last) && !(comp(value, *first))) return first; return last; } inline std::string strip(const std::string &inpt) { auto start_it = inpt.begin(); auto end_it = inpt.rbegin(); while (std::isspace(*start_it)) ++start_it; while (std::isspace(*end_it)) ++end_it; return std::string(start_it, end_it.base()); } inline std::vector<std::string> get_tokens(const std::string &str, const std::string &separators) { std::vector<std::string> tokens; auto first = std::begin(str); while (first != std::end(str)) { const auto second = std::find_first_of(first, std::end(str), std::begin(separators), std::end(separators)); if (first != second) { std::string token = strip(std::string(first, second)); tokens.emplace_back(token); } if (second == std::end(str)) { break; } first = std::next(second); } return tokens; } inline void convert_to_upper_case(std::string &str) { std::transform(str.begin(), str.end(), str.begin(), ::toupper); } inline void convert_to_lower_case(std::string &str) { std::transform(str.begin(), str.end(), str.begin(), ::tolower); } inline bool is_number(const std::string &str) { for (char const &c : str) { if (std::isdigit(c) == 0) return false; } return true; } template <typename T> std::set<T> transform_to_set(const std::vector<T> &dataAsVector) { std::set<T> dataAsSet; for (const T &data : dataAsVector) { dataAsSet.insert(data); } return dataAsSet; } inline std::pair<unsigned, bool> get_id_from_part_name(const std::string &name, const std::string &prefix) { const unsigned prefixLength = prefix.length(); if (name.length() < prefixLength + 1) return std::make_pair(0, false); const std::string namePrefix = name.substr(0, prefixLength); const std::string nameSuffix = name.substr(prefixLength); if (strcasecmp(namePrefix.c_str(), prefix.c_str()) != 0) return std::make_pair(0, false); unsigned id; std::istringstream nameSuffixStream(nameSuffix); nameSuffixStream >> id; if (nameSuffixStream.fail()) { return std::make_pair(0, false); } return std::make_pair(id, true); } template <typename T> class TopologyMapping { public: using Topology = T; virtual ~TopologyMapping() {} Topology topology(const std::string &textMeshName) const { auto it = m_nameToTopology.find(textMeshName); return (it != m_nameToTopology.end() ? it->second : invalid_topology()); } virtual Topology invalid_topology() const = 0; virtual void initialize_topology_map() = 0; protected: std::unordered_map<std::string, Topology> m_nameToTopology; }; class PartIdMapping { public: PartIdMapping() : m_idsAssigned(false) { set_error_handler([](const std::ostringstream &errmsg) { default_error_handler(errmsg); }); } void register_part_name(const std::string &name) { m_partNames.push_back(name); handle_block_part(name); } void register_part_name_with_id(const std::string &name, unsigned id) { register_part_name(name); assign(name, id); } unsigned get(const std::string &name) const { if (!m_idsAssigned) assign_ids(); return get_part_id(name); } std::string get(unsigned id) const { if (!m_idsAssigned) assign_ids(); return get_part_name(id); } unsigned size() const { if (!m_idsAssigned) assign_ids(); return m_ids.size(); } std::vector<std::string> get_part_names_sorted_by_id() const { if (!m_idsAssigned) assign_ids(); std::vector<std::string> names; names.reserve(m_parts.size()); for (auto iter : m_parts) { names.push_back(iter.second); } return names; } bool is_registered(const std::string &name) const { return m_ids.count(name) > 0; } const std::vector<std::string> &get_part_names() const { return m_partNames; } void set_error_handler(ErrorHandler errorHandler) { m_errorHandler = errorHandler; } const std::string get_group_type() const { return "element block"; } void finalize_parse() { if (!m_idsAssigned) assign_ids(); } private: void handle_block_part(const std::string &name) { auto result = get_id_from_part_name(name, "BLOCK_"); if (!result.second) return; assign(name, result.first); } void assign_ids() const { unsigned nextPartId = 1; for (const std::string &name : m_partNames) { if (m_ids.find(name) == m_ids.end()) { while (is_assigned(nextPartId)) nextPartId++; assign(name, nextPartId); } } m_idsAssigned = true; } void assign(const std::string &name, unsigned id) const { validate_name_and_id(name, id); m_ids[name] = id; m_parts[id] = name; } void validate_name_and_id(const std::string &name, unsigned id) const { if (is_registered(name)) { if (m_ids[name] != id) { std::ostringstream errmsg; errmsg << "Cannot assign part '" << name << "' two different ids: " << m_ids[name] << " and " << id; m_errorHandler(errmsg); } } else { if (is_assigned(id)) { std::ostringstream errmsg; errmsg << "Part id " << id << " has already been assigned, cannot assign it to part '" << name << "'"; m_errorHandler(errmsg); } } } bool is_assigned(unsigned id) const { return m_parts.count(id) > 0; } unsigned get_part_id(const std::string &name) const { auto it = m_ids.find(name); if (it == m_ids.end()) { std::ostringstream errmsg; errmsg << "PartIdMapping has no ID for invalid part name " << name; m_errorHandler(errmsg); } return it->second; } std::string get_part_name(unsigned id) const { auto it = m_parts.find(id); if (it == m_parts.end()) { std::ostringstream errmsg; errmsg << "PartIdMapping has no part name for invalid id " << id; m_errorHandler(errmsg); } return it->second; } std::vector<std::string> m_partNames; mutable std::unordered_map<std::string, unsigned> m_ids; mutable std::map<unsigned, std::string> m_parts; mutable bool m_idsAssigned; ErrorHandler m_errorHandler; }; template <typename EntityId> class Coordinates { public: Coordinates() { set_error_handler([](const std::ostringstream &errmsg) { default_error_handler(errmsg); }); } const std::vector<double> &operator[](const EntityId nodeId) const { auto it = m_nodalCoords.find(nodeId); if (it == m_nodalCoords.end()) { std::ostringstream errmsg; errmsg << "Could not find node id " << nodeId; m_errorHandler(errmsg); } return it->second; } void set_coordinate_data(const unsigned spatialDim, const std::set<EntityId> &nodeIds, const std::vector<double> &coordinates) { if (!coordinates.empty()) { validate_num_coordinates(spatialDim, nodeIds, coordinates); fill_coordinate_map(spatialDim, nodeIds, coordinates); m_hasCoordinateData = true; } } void set_error_handler(ErrorHandler errorHandler) { m_errorHandler = errorHandler; } bool has_coordinate_data() const { return m_hasCoordinateData; } private: void validate_num_coordinates(const unsigned spatialDim, const std::set<EntityId> &nodeIds, const std::vector<double> &coordinates) { if (coordinates.size() != nodeIds.size() * spatialDim) { std::ostringstream errmsg; errmsg << "Number of coordinates: " << coordinates.size() << ", Number of nodes: " << nodeIds.size() << ", Spatial dimension: " << spatialDim; m_errorHandler(errmsg); } } void fill_coordinate_map(const unsigned spatialDim, const std::set<EntityId> &nodeIds, const std::vector<double> &coordinates) { std::vector<double>::const_iterator coordIter = coordinates.begin(); for (const EntityId &nodeId : nodeIds) { m_nodalCoords[nodeId] = std::vector<double>(coordIter, coordIter + spatialDim); coordIter += spatialDim; } } bool m_hasCoordinateData{false}; std::unordered_map<EntityId, std::vector<double>> m_nodalCoords; ErrorHandler m_errorHandler; }; template <typename EntityId, typename Topology> struct ElementData { int proc; EntityId identifier; Topology topology; std::vector<EntityId> nodeIds; std::string partName = ""; operator EntityId() const { return identifier; } }; template <typename EntityId, typename Topology> struct ElementDataLess { bool operator()(const ElementData<EntityId, Topology> &lhs, const ElementData<EntityId, Topology> &rhs) { return lhs.identifier < rhs.identifier; }; bool operator()(const ElementData<EntityId, Topology> &lhs, const EntityId rhs) { return lhs.identifier < rhs; }; bool operator()(const EntityId lhs, const ElementData<EntityId, Topology> &rhs) { return lhs < rhs.identifier; }; bool operator()(const EntityId lhs, const EntityId rhs) { return lhs < rhs; }; }; struct SideBlockInfo { std::string name; std::string parentName; std::string sideTopology; std::string elementTopology; std::string touchingBlock; std::vector<size_t> sideIndex; unsigned numNodesPerSide; }; enum SplitType { TOPOLOGY, ELEMENT_BLOCK, NO_SPLIT, INVALID_SPLIT }; inline std::ostream &operator<<(std::ostream &out, const SplitType &t) { switch (t) { case SplitType::TOPOLOGY: return out << "TOPOLOGY"; break; case SplitType::ELEMENT_BLOCK: return out << "ELEMENT_BLOCK"; break; case SplitType::NO_SPLIT: return out << "NO_SPLIT"; break; default: return out << "INVALID"; break; } return out << "INVALID[" << (unsigned)t << "]"; } enum AssemblyType { ASSEMBLY, BLOCK, SIDESET, NODESET, INVALID_ASSEMBLY }; inline std::ostream &operator<<(std::ostream &out, const AssemblyType &t) { switch (t) { case AssemblyType::ASSEMBLY: return out << "ASSEMBLY"; break; case AssemblyType::BLOCK: return out << "ELEMENT_BLOCK"; break; case AssemblyType::SIDESET: return out << "SIDESET"; break; case AssemblyType::NODESET: return out << "NODESET"; break; default: return out << "INVALID"; break; } return out << "INVALID[" << (unsigned)t << "]"; } template <typename EntityId, typename T> struct EntityGroupData { using DataType = T; static constexpr unsigned INVALID_ID = std::numeric_limits<unsigned>::max(); bool hasInputName = false; unsigned id = INVALID_ID; std::string name = ""; std::string type = ""; std::vector<DataType> data; bool has_valid_id() const { return id != 0 && id != INVALID_ID; } bool has_name() const { return !name.empty(); } }; template <typename EntityId, typename GroupData> class EntityGroup { private: using DataType = typename GroupData::DataType; public: EntityGroup(const std::string &type, const std::string &standardNamePrefix, const std::vector<std::string> &invalidNamePrefixes) : m_idsAssigned(false), m_type(type), m_standardPrefix(standardNamePrefix), m_invalidPrefixes(invalidNamePrefixes) { set_error_handler([](const std::ostringstream &errmsg) { default_error_handler(errmsg); }); } virtual ~EntityGroup() {} virtual void set_error_handler(ErrorHandler errorHandler) { m_errorHandler = errorHandler; } GroupData *add_group_data(const std::string &name, const std::vector<DataType> &data) { GroupData groupData; groupData.data = data; groupData.type = m_type; if (!name.empty()) { verify_name(name); groupData.name = name; groupData.hasInputName = true; } m_groupDataVec.push_back(groupData); return &m_groupDataVec.back(); } void finalize_parse() { assign_id_from_standard_name(); assign_id_and_name_for_empty_name(); assign_id_for_non_standard_name(); if (m_groupDataVec.size() != m_groupDataMap.size()) { std::ostringstream errmsg; errmsg << "Error populating " << m_type << " map"; m_errorHandler(errmsg); } m_idsAssigned = true; } size_t size() const { return m_groupDataVec.size(); } const std::vector<GroupData> &get_group_data() const { return m_groupDataVec; } const std::vector<std::string> &get_part_names() const { return m_partNames; } const std::string &get_group_type() const { return m_type; } const GroupData *get_group_data(unsigned id) const { if (is_assigned(id)) { auto iter = m_parts.find(id); return &m_groupDataVec[m_groupDataMap[iter->second]]; } return nullptr; } const GroupData *get_group_data(std::string name) const { convert_to_upper_case(name); if (is_registered(name)) { return &m_groupDataVec[m_groupDataMap[name]]; } return nullptr; } bool is_registered(const std::string &name) const { return m_ids.count(name) > 0; } protected: EntityGroup(); unsigned get_unassigned_id() const { unsigned nextPartId = 1; while (is_assigned(nextPartId)) nextPartId++; return nextPartId; } void validate_group_meta_data(const GroupData &groupData) { if (!groupData.has_name()) { std::ostringstream errmsg; errmsg << m_type << " has no name"; m_errorHandler(errmsg); } if (!groupData.has_valid_id()) { std::ostringstream errmsg; errmsg << m_type << " named " << groupData.name << " has invalid id"; m_errorHandler(errmsg); } if (is_registered(groupData.name)) { std::ostringstream errmsg; errmsg << "Multiple declarations of " << m_type << ": " << groupData.name; m_errorHandler(errmsg); } } void assign(size_t index) { GroupData &groupData = m_groupDataVec[index]; convert_to_upper_case(groupData.name); validate_group_meta_data(groupData); m_partNames.push_back(groupData.name); m_ids[groupData.name] = groupData.id; m_parts[groupData.id] = groupData.name; m_groupDataMap[groupData.name] = index; } void assign_id_from_standard_name() { for (size_t i = 0; i < m_groupDataVec.size(); i++) { GroupData &groupData = m_groupDataVec[i]; if (groupData.has_name()) { std::pair<unsigned, bool> result = get_id_from_part_name(groupData.name, m_standardPrefix); if (result.second) { groupData.id = result.first; assign(i); } } } } void assign_id_and_name_for_empty_name() { for (size_t i = 0; i < m_groupDataVec.size(); i++) { GroupData &groupData = m_groupDataVec[i]; if (!groupData.has_name()) { unsigned id = get_unassigned_id(); std::ostringstream oss; oss << m_standardPrefix; oss << id; std::string name = oss.str(); groupData.id = id; groupData.name = name; assign(i); } } } void assign_id_for_non_standard_name() { for (size_t i = 0; i < m_groupDataVec.size(); i++) { GroupData &groupData = m_groupDataVec[i]; if (groupData.has_name()) { std::pair<unsigned, bool> result = get_id_from_part_name(groupData.name, m_standardPrefix); if (!result.second) { groupData.id = get_unassigned_id(); assign(i); } } } } bool is_assigned(unsigned id) const { return m_parts.count(id) > 0; } void verify_name(const std::string &name) { for (const std::string &invalidPrefix : m_invalidPrefixes) { const unsigned prefixLength = invalidPrefix.length(); const std::string namePrefix = name.substr(0, prefixLength); if (strcasecmp(namePrefix.c_str(), invalidPrefix.c_str()) == 0) { std::ostringstream errmsg; errmsg << "Invalid name '" << name << "' for a " << m_type << " part"; m_errorHandler(errmsg); } } } std::vector<std::string> m_partNames; mutable std::unordered_map<std::string, unsigned> m_ids; mutable std::unordered_map<unsigned, std::string> m_parts; mutable bool m_idsAssigned; mutable std::unordered_map<std::string, size_t> m_groupDataMap; std::string m_type; std::string m_standardPrefix; std::vector<std::string> m_invalidPrefixes; std::vector<GroupData> m_groupDataVec; ErrorHandler m_errorHandler; }; using AssemblyDataType = std::string; template <typename EntityId> struct AssemblyData : public EntityGroupData<EntityId, AssemblyDataType> { using DataType = AssemblyDataType; void set_assembly_type(AssemblyType type_) { assemblyType = type_; } AssemblyType get_assembly_type() const { return assemblyType; } private: AssemblyType assemblyType = INVALID_ASSEMBLY; }; template <typename EntityId> class Assemblies : public EntityGroup<EntityId, AssemblyData<EntityId>> { public: using BaseClass = EntityGroup<EntityId, AssemblyData<EntityId>>; Assemblies() : EntityGroup<EntityId, AssemblyData<EntityId>>("ASSEMBLY", "ASSEMBLY_", {"BLOCK_", "SURFACE_", "NODELIST_"}) { } bool is_cyclic(const std::string &assembly) const { initialize_graph(); return check_for_cycle(assembly); } bool is_cyclic() const { for (const std::string &assembly : BaseClass::get_part_names()) if (is_cyclic(assembly)) { return true; } return false; } std::vector<std::string> &&get_forward_traversal_list(const std::string &assembly) const { initialize_graph(); fill_traversal(assembly); return std::move(m_traversalList); } std::vector<std::string> &&get_reverse_traversal_list(const std::string &assembly) const { initialize_graph(); fill_traversal(assembly); std::reverse(m_traversalList.begin(), m_traversalList.end()); return std::move(m_traversalList); } private: void fill_traversal(const std::string &assembly) const { const AssemblyData<EntityId> *assemblyData = BaseClass::get_group_data(assembly); if (nullptr != assemblyData) { if (m_visitedNodes[assembly] == false) { m_visitedNodes[assembly] = true; m_traversalList.push_back(assembly); if (assemblyData->get_assembly_type() == AssemblyType::ASSEMBLY) { for (const std::string &member : assemblyData->data) { fill_traversal(member); } } } } } bool check_for_cycle(const std::string &assembly) const { bool isCyclic = false; const AssemblyData<EntityId> *assemblyData = BaseClass::get_group_data(assembly); if (nullptr != assemblyData) { if (m_visitedNodes[assembly] == true) { isCyclic = true; } else { m_visitedNodes[assembly] = true; if (assemblyData->get_assembly_type() == AssemblyType::ASSEMBLY) { for (const std::string &member : assemblyData->data) { isCyclic |= check_for_cycle(member); } } } } return isCyclic; } void initialize_graph() const { m_traversalList.clear(); m_traversalList.reserve(BaseClass::size()); for (const std::string &name : BaseClass::get_part_names()) { m_visitedNodes[name] = false; } } mutable std::unordered_map<std::string, bool> m_visitedNodes; mutable std::vector<std::string> m_traversalList; }; template <typename EntityId> using NodesetDataType = EntityId; template <typename EntityId> struct NodesetData : public EntityGroupData<EntityId, NodesetDataType<EntityId>> { using DataType = NodesetDataType<EntityId>; }; template <typename EntityId> class Nodesets : public EntityGroup<EntityId, NodesetData<EntityId>> { public: Nodesets() : EntityGroup<EntityId, NodesetData<EntityId>>("NODESET", "NODELIST_", {"BLOCK_", "SURFACE_", "ASSEMBLY_"}) { } }; template <typename EntityId> using SidesetDataType = std::pair<EntityId, int>; template <typename EntityId, typename Topology> struct SidesetData; template <typename EntityId, typename Topology> class SidesetSplitter { public: SidesetSplitter(SplitType splitType) : m_splitType(splitType) { ErrorHandler errorHandler = [](const std::ostringstream &errmsg) { default_error_handler(errmsg); }; set_error_handler(errorHandler); } SidesetSplitter() : m_splitType(INVALID_SPLIT) { ErrorHandler errorHandler = [](const std::ostringstream &errmsg) { default_error_handler(errmsg); }; set_error_handler(errorHandler); } void set_error_handler(ErrorHandler errorHandler) { m_errorHandler = errorHandler; } void split(const SidesetData<EntityId, Topology> &sideset, const std::vector<ElementData<EntityId, Topology>> &elementData) { m_splitMap.clear(); m_sidesetName = sideset.name; if (get_split_type() == SplitType::TOPOLOGY) { split_by_topology(sideset, elementData); } else if (get_split_type() == SplitType::ELEMENT_BLOCK) { split_by_element_block(sideset, elementData); } else if (get_split_type() == SplitType::NO_SPLIT) { split_by_no_split(sideset, elementData); } else { std::ostringstream errmsg; errmsg << "Invalid split type: " << get_split_type(); m_errorHandler(errmsg); } build_index_proc_map(sideset, elementData); } std::vector<SideBlockInfo> get_side_block_info() const { std::vector<SideBlockInfo> infoVec; infoVec.reserve(m_splitMap.size()); for (auto iter = m_splitMap.begin(); iter != m_splitMap.end(); iter++) { const std::string &sideBlockName = iter->first; SideBlockInfo info = get_side_block_info(sideBlockName); infoVec.push_back(info); } return infoVec; } std::vector<size_t> get_indices_local_to_proc(const std::vector<size_t> &index, int proc) const { std::vector<size_t> indexForProc; indexForProc.reserve(index.size()); for (size_t elemPairIndex : index) { if (is_index_local_to_proc(elemPairIndex, proc)) { indexForProc.push_back(elemPairIndex); } } indexForProc.resize(indexForProc.size()); return indexForProc; } SideBlockInfo get_side_block_info(const std::string &name) const { SideBlockInfo info; auto iter = m_splitMap.find(name); if (iter != m_splitMap.end()) { const SplitData &splitData = iter->second; info.name = name; info.parentName = splitData.sidesetName; info.sideTopology = splitData.sideTopology; info.elementTopology = splitData.elemTopology; info.numNodesPerSide = splitData.sideNodeCount; info.touchingBlock = splitData.touchingBlock; info.sideIndex = splitData.index; } return info; } SplitType get_split_type() const { return m_splitType; } void set_split_type(SplitType inputSplitType) { m_splitType = inputSplitType; } private: void build_index_proc_map(const SidesetData<EntityId, Topology> &sideset, const std::vector<ElementData<EntityId, Topology>> &elementData) { for (size_t i = 0; i < sideset.data.size(); ++i) { const SidesetDataType<EntityId> &elemSidePair = sideset.data[i]; EntityId elemId = elemSidePair.first; auto iter = bound_search(elementData.begin(), elementData.end(), elemId, ElementDataLess<EntityId, Topology>()); if (iter == elementData.end()) { std::ostringstream errmsg; errmsg << "Error! Sideset with id: " << sideset.id << " and name: " << sideset.name << " has reference to invalid element '" << elemId << "'."; m_errorHandler(errmsg); } m_indexProcMap[i] = iter->proc; } } bool is_index_local_to_proc(size_t elemPairIndex, int proc) const { auto iter = m_indexProcMap.find(elemPairIndex); if (iter == m_indexProcMap.end()) { std::ostringstream errmsg; errmsg << "Sideset with name: " << m_sidesetName << " is referencing an invalid index " << elemPairIndex; m_errorHandler(errmsg); } return iter->second == proc; } struct SplitData { bool metaDataSet; std::string sidesetName; std::string touchingBlock; std::string elemTopology; std::string sideTopology; int sideNodeCount; std::vector<size_t> index; SplitData() : metaDataSet(false), sideNodeCount(-1) {} }; void fill_split_data(std::string key, size_t index, const ElementData<EntityId, Topology> &elemData, int side) { convert_to_upper_case(key); SplitData &splitData = m_splitMap[key]; splitData.index.push_back(index); if (!splitData.metaDataSet) { splitData.sidesetName = m_sidesetName; splitData.elemTopology = elemData.topology.name(); splitData.sideTopology = elemData.topology.side_topology_name(side); splitData.sideNodeCount = elemData.topology.side_topology_num_nodes(side); if (get_split_type() == ELEMENT_BLOCK) { splitData.touchingBlock = elemData.partName; } splitData.metaDataSet = true; } } using Criterion = std::function<std::string(const SidesetData<EntityId, Topology> &sideset, const ElementData<EntityId, Topology> &elemData, int side)>; void split_by_criterion(const SidesetData<EntityId, Topology> &sideset, const std::vector<ElementData<EntityId, Topology>> &elementData, Criterion criterion) { for (size_t index = 0; index < sideset.data.size(); ++index) { const SidesetDataType<EntityId> &elemSidePair = sideset.data[index]; EntityId elemId = elemSidePair.first; int side = elemSidePair.second; auto iter = bound_search(elementData.begin(), elementData.end(), elemId, ElementDataLess<EntityId, Topology>()); if (iter == elementData.end()) { std::ostringstream errmsg; errmsg << "Error! Sideset with id: " << sideset.id << " and name: " << sideset.name << " has reference to invalid element '" << elemId << "'."; m_errorHandler(errmsg); } std::string key = criterion(sideset, *iter, side); fill_split_data(key, index, *iter, side); } } void split_by_topology(const SidesetData<EntityId, Topology> &sideset, const std::vector<ElementData<EntityId, Topology>> &elementData) { Criterion criterion = [](const SidesetData<EntityId, Topology> &sideSet, const ElementData<EntityId, Topology> &elemData, int side) { if (sideSet.has_standard_name()) { return "SURFACE_" + elemData.topology.name() + "_" + elemData.topology.side_topology_name(side) + "_" + std::to_string(sideSet.id); } return sideSet.name + "_" + elemData.topology.name() + "_" + elemData.topology.side_topology_name(side); }; split_by_criterion(sideset, elementData, criterion); } void split_by_element_block(const SidesetData<EntityId, Topology> &sideset, const std::vector<ElementData<EntityId, Topology>> &elementData) { Criterion criterion = [](const SidesetData<EntityId, Topology> &sideSet, const ElementData<EntityId, Topology> &elemData, int side) { if (sideSet.has_standard_name()) { return "SURFACE_" + elemData.partName + "_" + elemData.topology.side_topology_name(side) + "_" + std::to_string(sideSet.id); } return sideSet.name + "_" + elemData.partName + "_" + elemData.topology.side_topology_name(side); }; split_by_criterion(sideset, elementData, criterion); } void split_by_no_split(const SidesetData<EntityId, Topology> &sideset, const std::vector<ElementData<EntityId, Topology>> &elementData) { std::vector<size_t> splitIndex(sideset.data.size()); std::iota(std::begin(splitIndex), std::end(splitIndex), 0); SplitData &splitData = m_splitMap[sideset.name]; splitData.index = splitIndex; splitData.sidesetName = m_sidesetName; splitData.elemTopology = "unknown"; splitData.sideTopology = "unknown"; splitData.sideNodeCount = -1; splitData.metaDataSet = true; } SplitType m_splitType; std::string m_sidesetName; std::unordered_map<size_t, int> m_indexProcMap; std::unordered_map<std::string, SplitData> m_splitMap; ErrorHandler m_errorHandler; }; template <typename EntityId, typename Topology> struct SidesetData : public EntityGroupData<EntityId, SidesetDataType<EntityId>> { using DataType = SidesetDataType<EntityId>; using BaseClass = EntityGroupData<EntityId, SidesetDataType<EntityId>>; void set_split_type(SplitType splitType) { sidesetSplitter.set_split_type(splitType); } SplitType get_split_type() const { return sidesetSplitter.get_split_type(); } void set_error_handler(ErrorHandler errorHandler) { sidesetSplitter.set_error_handler(errorHandler); } void split(const std::vector<ElementData<EntityId, Topology>> &elementData) { sidesetSplitter.split(*this, elementData); } std::vector<size_t> get_sideblock_indices_local_to_proc(const SideBlockInfo &info, int proc) const { return sidesetSplitter.get_indices_local_to_proc(info.sideIndex, proc); } SideBlockInfo get_side_block_info(const std::string &sideBlockName) const { return sidesetSplitter.get_side_block_info(sideBlockName); } std::vector<SideBlockInfo> get_side_block_info() const { return sidesetSplitter.get_side_block_info(); } bool has_standard_name() const { if (BaseClass::has_name()) { std::pair<unsigned, bool> result = get_id_from_part_name(BaseClass::name, "SURFACE_"); return result.second; } return false; } private: SidesetSplitter<EntityId, Topology> sidesetSplitter; }; template <typename EntityId, typename Topology> class Sidesets : public EntityGroup<EntityId, SidesetData<EntityId, Topology>> { public: using BaseClass = EntityGroup<EntityId, SidesetData<EntityId, Topology>>; Sidesets() : BaseClass("SIDESET", "SURFACE_", {"BLOCK_", "NODELIST_", "ASSEMBLY_"}) {} void set_error_handler(ErrorHandler errorHandler) override { BaseClass::set_error_handler(errorHandler); for (SidesetData<EntityId, Topology> &sidesetData : BaseClass::m_groupDataVec) { sidesetData.set_error_handler(errorHandler); } } void finalize_parse(const std::vector<ElementData<EntityId, Topology>> &elementData) { BaseClass::finalize_parse(); for (SidesetData<EntityId, Topology> &sidesetData : BaseClass::m_groupDataVec) { sidesetData.split(elementData); } } }; template <typename EntityId, typename Topology> struct TextMeshData { unsigned spatialDim; std::vector<ElementData<EntityId, Topology>> elementDataVec; PartIdMapping partIds; std::set<EntityId> nodeIds; Coordinates<EntityId> coords; Sidesets<EntityId, Topology> sidesets; Nodesets<EntityId> nodesets; Assemblies<EntityId> assemblies; TextMeshData() : spatialDim(0) {} void add_element(const ElementData<EntityId, Topology> &elem) { elementDataVec.push_back(elem); for (const EntityId &nodeId : elem.nodeIds) { nodeIds.insert(nodeId); associate_node_with_proc(nodeId, elem.proc); } } const std::set<EntityId> &nodes_on_proc(int proc) const { auto it = m_nodesOnProc.find(proc); return it != m_nodesOnProc.end() ? it->second : m_emptyNodes; } unsigned num_nodes_on_proc(int proc) const { auto it = m_nodesOnProc.find(proc); return it != m_nodesOnProc.end() ? it->second.size() : 0; } const std::set<int> &procs_for_node(const EntityId nodeId) const { auto it = m_procsForNode.find(nodeId); return it != m_procsForNode.end() ? it->second : m_emptyProcs; } private: void associate_node_with_proc(const EntityId nodeId, int proc) { m_procsForNode[nodeId].insert(proc); m_nodesOnProc[proc].insert(nodeId); } std::unordered_map<EntityId, std::set<int>> m_procsForNode; std::unordered_map<int, std::set<EntityId>> m_nodesOnProc; std::set<int> m_emptyProcs; std::set<EntityId> m_emptyNodes; }; class TextMeshLexer { public: TextMeshLexer() : m_currentIndex(0), m_token(""), m_isNumber(false) {} void set_input_string(const std::string &input) { m_input = input; m_currentIndex = 0; read_next_token(); } int get_int() { read_next_token(); return std::stoi(m_oldToken); } unsigned get_unsigned() { read_next_token(); return std::stoul(m_oldToken); } std::string get_string() { read_next_token(); return make_upper_case(m_oldToken); } void get_newline() { read_next_token(); } bool has_token() const { return m_token != ""; } bool has_newline() const { return m_token == "\n"; } bool has_number() const { return has_token() && m_isNumber; } bool has_string() const { return has_token() && !has_number() && !has_newline(); } private: void read_next_token() { m_oldToken = m_token; if (char_is_newline()) { m_isNumber = false; m_token = "\n"; m_currentIndex++; return; } m_token = ""; m_isNumber = true; while (has_more_input()) { if (char_is_whitespace()) { m_currentIndex++; continue; } if (char_is_comma()) { m_currentIndex++; break; } if (char_is_newline()) { break; } m_isNumber &= char_is_digit(); m_token += current_char(); m_currentIndex++; } } bool has_more_input() { return m_currentIndex < m_input.size(); } bool char_is_whitespace() { return current_char() == ' '; } bool char_is_comma() { return current_char() == ','; } bool char_is_newline() { return current_char() == '\n'; } bool char_is_digit() { return std::isdigit(static_cast<unsigned char>(current_char())); } char current_char() { return m_input[m_currentIndex]; } std::string make_upper_case(std::string str) { std::transform(str.begin(), str.end(), str.begin(), ::toupper); return str; } std::string m_input; unsigned m_currentIndex; std::string m_oldToken; std::string m_token; bool m_isNumber; }; template <typename EntityId> class SidesetParser { public: SidesetParser() : m_splitType(NO_SPLIT) { ErrorHandler errorHandler = [](const std::ostringstream &errmsg) { default_error_handler(errmsg); }; set_error_handler(errorHandler); } void set_error_handler(ErrorHandler errorHandler) { m_errorHandler = errorHandler; } std::string get_name() { return m_name; } const std::vector<std::pair<EntityId, int>> &get_sideset_data() { return m_elemSidePairs; } SplitType get_split_type() { return m_splitType; } void parse(const std::string &parseData) { auto options = get_tokens(parseData, ";"); for (const auto &option : options) { parse_option_group(option); } } private: void parse_option(std::string optionName, const std::string &optionValue) { convert_to_lower_case(optionName); if (optionName == "name") { parse_name(optionValue); } else if (optionName == "data") { parse_element_side_pairs(optionValue); } else if (optionName == "split") { parse_split_type(optionValue); } else { std::ostringstream errmsg; errmsg << "Unrecognized sideset option: " << optionName; m_errorHandler(errmsg); } } void parse_option_group(const std::string &option) { if (!option.empty()) { auto optionTokens = get_tokens(option, "="); if (optionTokens.size() != 2) { std::ostringstream errmsg; errmsg << "Unrecognized sideset option: " << option; m_errorHandler(errmsg); } parse_option(optionTokens[0], optionTokens[1]); } } void parse_name(const std::string &data) { m_name = data; } void parse_element_side_pairs(const std::string &data) { auto sidesetData = get_tokens(data, ","); if (sidesetData.size() % 2 != 0) { std::ostringstream errmsg; errmsg << "Unmatched element/ordinal pairs in sideset data: " << data; m_errorHandler(errmsg); } for (unsigned i = 0; i < sidesetData.size(); i += 2) { EntityId elem = std::stoull(sidesetData[i]); int side = std::stoi(sidesetData[i + 1]); if (side <= 0) { std::ostringstream errmsg; errmsg << "Invalid element/ordinal pair {" << sidesetData[i] << "," << sidesetData[i + 1] << "}"; m_errorHandler(errmsg); } m_elemSidePairs.push_back(std::make_pair(elem, side)); } } void parse_split_type(std::string splitName) { convert_to_lower_case(splitName); if (splitName == "none") { m_splitType = NO_SPLIT; } else if (splitName == "block") { m_splitType = ELEMENT_BLOCK; } else if (splitName == "topology") { m_splitType = TOPOLOGY; } else { std::ostringstream errmsg; errmsg << "Unrecognized sideset split type: " << splitName; m_errorHandler(errmsg); } } std::vector<std::pair<EntityId, int>> m_elemSidePairs; std::string m_name; SplitType m_splitType; ErrorHandler m_errorHandler; }; template <typename EntityId> class NodesetParser { public: NodesetParser() { ErrorHandler errorHandler = [](const std::ostringstream &errmsg) { default_error_handler(errmsg); }; set_error_handler(errorHandler); } void set_error_handler(ErrorHandler errorHandler) { m_errorHandler = errorHandler; } std::string get_name() { return m_name; } const std::vector<EntityId> &get_nodeset_data() { return m_nodeList; } void parse(const std::string &parseData) { auto options = get_tokens(parseData, ";"); for (const auto &option : options) { parse_option_group(option); } } private: void parse_option(std::string optionName, const std::string &optionValue) { convert_to_lower_case(optionName); if (optionName == "name") { parse_name(optionValue); } else if (optionName == "data") { parse_node_data(optionValue); } else { std::ostringstream errmsg; errmsg << "Unrecognized nodeset option: " << optionName; m_errorHandler(errmsg); } } void parse_option_group(const std::string &option) { if (!option.empty()) { auto optionTokens = get_tokens(option, "="); if (optionTokens.size() != 2) { std::ostringstream errmsg; errmsg << "Unrecognized nodeset option: " << option; m_errorHandler(errmsg); } parse_option(optionTokens[0], optionTokens[1]); } } void parse_name(const std::string &data) { m_name = data; } void parse_node_data(const std::string &data) { auto nodesetData = get_tokens(data, ","); for (const std::string &nodeString : nodesetData) { if (!is_number(nodeString)) { std::ostringstream errmsg; errmsg << "Urecognized nodeset node id: " << nodeString; m_errorHandler(errmsg); } EntityId node = std::stoull(nodeString); m_nodeList.push_back(node); } } std::vector<EntityId> m_nodeList; std::string m_name; ErrorHandler m_errorHandler; }; class AssemblyParser { public: AssemblyParser() : m_assemblyType(INVALID_ASSEMBLY) { ErrorHandler errorHandler = [](const std::ostringstream &errmsg) { default_error_handler(errmsg); }; set_error_handler(errorHandler); } void set_error_handler(ErrorHandler errorHandler) { m_errorHandler = errorHandler; } std::string get_name() { return m_name; } AssemblyType get_assembly_type() const { return m_assemblyType; } const std::vector<std::string> &get_assembly_data() { return m_members; } void parse(const std::string &parseData) { auto options = get_tokens(parseData, ";"); for (const auto &option : options) { parse_option_group(option); } } private: void parse_option(std::string optionName, const std::string &optionValue) { convert_to_lower_case(optionName); if (optionName == "name") { parse_name(optionValue); } else if (optionName == "type") { parse_assembly_type(optionValue); } else if (optionName == "member") { parse_assembly_members(optionValue); } else { std::ostringstream errmsg; errmsg << "Unrecognized assembly option: " << optionName; m_errorHandler(errmsg); } } void parse_option_group(const std::string &option) { if (!option.empty()) { auto optionTokens = get_tokens(option, "="); if (optionTokens.size() != 2) { std::ostringstream errmsg; errmsg << "Unrecognized assembly option: " << option; m_errorHandler(errmsg); } parse_option(optionTokens[0], optionTokens[1]); } } void parse_name(const std::string &data) { m_name = data; } void parse_assembly_type(std::string type) { convert_to_lower_case(type); if (type == "assembly") { m_assemblyType = ASSEMBLY; } else if (type == "block") { m_assemblyType = BLOCK; } else if (type == "sideset") { m_assemblyType = SIDESET; } else if (type == "nodeset") { m_assemblyType = NODESET; } else { std::ostringstream errmsg; errmsg << "Unrecognized assembly type: " << type; m_errorHandler(errmsg); } } void parse_assembly_members(const std::string &data) { std::vector<std::string> assemblyData = get_tokens(data, ","); for (std::string &member : assemblyData) { convert_to_upper_case(member); } m_members = assemblyData; } std::vector<std::string> m_members; std::string m_name; AssemblyType m_assemblyType; ErrorHandler m_errorHandler; }; template <typename EntityId, typename Topology> class TextMeshOptionParser { private: static constexpr int INVALID_DIMENSION = -1; static constexpr int DEFAULT_DIMENSION = 3; enum ParsedOptions { PARSED_NONE = 0, PARSED_DIMENSION = 1L << 0, PARSED_COORDINATES = 1L << 1, PARSED_SIDESET = 1L << 2, PARSED_NODESET = 1L << 3, PARSED_ASSEMBLY = 1L << 4 }; public: TextMeshOptionParser(TextMeshData<EntityId, Topology> &data, unsigned enforcedDimension) : m_parsedOptionMask(PARSED_NONE), m_parsedDimension(INVALID_DIMENSION), m_constructorEnforcedDimension(enforcedDimension), m_data(data) { } TextMeshOptionParser(TextMeshData<EntityId, Topology> &data) : m_parsedOptionMask(PARSED_NONE), m_parsedDimension(INVALID_DIMENSION), m_constructorEnforcedDimension(INVALID_DIMENSION), m_data(data) { } void set_error_handler(ErrorHandler errorHandler) { m_errorHandler = errorHandler; } std::string get_mesh_connectivity_description() const { return m_meshConnectivityDescription; } void initialize_parse(const std::string &parameters) { if (!parameters.empty()) { std::vector<std::string> optionGroups = get_tokens(parameters, "|"); parse_options(optionGroups); m_meshConnectivityDescription = optionGroups[0]; } validate_dimension(); set_dimension(); } void finalize_parse() { set_coordinates(); m_data.partIds.finalize_parse(); m_data.sidesets.finalize_parse(m_data.elementDataVec); m_data.nodesets.finalize_parse(); m_data.assemblies.finalize_parse(); validate_sidesets(); validate_nodesets(); validate_assemblies(); } private: bool parsed_dimension_provided() { return m_parsedOptionMask & PARSED_DIMENSION; } bool enforced_dimension_provided() { return m_constructorEnforcedDimension != INVALID_DIMENSION; } void validate_dimension() { if (enforced_dimension_provided()) { if (parsed_dimension_provided() && m_constructorEnforcedDimension != m_parsedDimension) { std::ostringstream errmsg; errmsg << "Error! An enforced dimension of " << m_constructorEnforcedDimension << " was provided but does not match the parsed value of " << m_parsedDimension << "."; m_errorHandler(errmsg); } } } void set_dimension() { if (enforced_dimension_provided()) { m_data.spatialDim = m_constructorEnforcedDimension; } else if (parsed_dimension_provided()) { m_data.spatialDim = m_parsedDimension; } else { m_data.spatialDim = DEFAULT_DIMENSION; } } void parse_dimension_option(const std::vector<std::string> &option) { if (parsed_dimension_provided()) { std::ostringstream errmsg; errmsg << "Spatial dimension has already been parsed! Check syntax."; m_errorHandler(errmsg); } if (option.size() == 2) { m_parsedDimension = std::stoull(option[1]); if (m_parsedDimension != 2 && m_parsedDimension != 3) { std::ostringstream errmsg; errmsg << "Error! Parsed spatial dimension (" << m_parsedDimension << " not defined to be 2 or 3."; m_errorHandler(errmsg); } m_parsedOptionMask |= PARSED_DIMENSION; } else { std::ostringstream errmsg; errmsg << "Error! Invalid spatial dimension syntax."; m_errorHandler(errmsg); } } void deallocate_raw_coordinates() { std::vector<double> swapVectorForDeallocation; m_rawCoordinates.swap(swapVectorForDeallocation); } void set_coordinates() { if (parsed_coordinates_provided()) { m_data.coords.set_coordinate_data(m_data.spatialDim, m_data.nodeIds, m_rawCoordinates); deallocate_raw_coordinates(); } } bool parsed_coordinates_provided() { return m_parsedOptionMask & PARSED_COORDINATES; } void parse_coordinates_option(const std::vector<std::string> &coordinatesOptionGroup) { if (parsed_coordinates_provided()) { std::ostringstream errmsg; errmsg << "Coordinates have already been parsed! Check syntax."; m_errorHandler(errmsg); } if (coordinatesOptionGroup.size() > 1) { const std::vector<std::string> &coordinateTokens = get_tokens(coordinatesOptionGroup[1], ","); m_rawCoordinates.reserve(coordinateTokens.size()); for (const auto &token : coordinateTokens) { double coord = std::stod(token); m_rawCoordinates.push_back(coord); } m_parsedOptionMask |= PARSED_COORDINATES; } } template <typename DataType> void check_name_collision_with_entity_sets(const EntityGroupData<EntityId, DataType> &groupData, const std::string &entityType, const std::set<std::string> &entitySetNames) { std::string groupName = groupData.name; convert_to_upper_case(groupName); if (entitySetNames.count(groupName) > 0) { std::ostringstream errmsg; errmsg << "Error! " << groupData.type << " with id: " << groupData.id << " and name: " << groupData.name << " is referencing " << entityType << " with same name."; m_errorHandler(errmsg); } } template <typename SrcDataGroup, typename DestDataGroup> void check_name_collision_with_group(const SrcDataGroup &srcGroup, const DestDataGroup &destGroup) { std::set<std::string> groupNames = transform_to_set(destGroup.get_part_names()); for (const auto &srcGroupData : srcGroup.get_group_data()) { check_name_collision_with_entity_sets(srcGroupData, destGroup.get_group_type(), groupNames); } } void check_sideset_element_reference() { for (const SidesetData<EntityId, Topology> &sidesetData : m_data.sidesets.get_group_data()) { for (const std::pair<EntityId, int> &elemSidePair : sidesetData.data) { EntityId id = elemSidePair.first; if (!std::binary_search(m_data.elementDataVec.begin(), m_data.elementDataVec.end(), id)) { std::ostringstream errmsg; errmsg << "Error! Sideset with id: " << sidesetData.id << " and name: " << sidesetData.name << " has reference to invalid element '" << id << "'."; m_errorHandler(errmsg); } } } } void check_sideset_name_collision() { check_name_collision_with_group(m_data.sidesets, m_data.partIds); check_name_collision_with_group(m_data.sidesets, m_data.nodesets); check_name_collision_with_group(m_data.sidesets, m_data.assemblies); } void validate_sidesets() { check_sideset_element_reference(); check_sideset_name_collision(); } void check_nodeset_node_reference() { for (const NodesetData<EntityId> &nodesetData : m_data.nodesets.get_group_data()) { for (const EntityId nodeId : nodesetData.data) { if (m_data.nodeIds.count(nodeId) == 0) { std::ostringstream errmsg; errmsg << "Error! Nodeset with id: " << nodesetData.id << " and name: " << nodesetData.name << " has reference to invalid node '" << nodeId << "'."; m_errorHandler(errmsg); } } } } void check_nodeset_name_collision() { check_name_collision_with_group(m_data.nodesets, m_data.partIds); check_name_collision_with_group(m_data.nodesets, m_data.sidesets); check_name_collision_with_group(m_data.nodesets, m_data.assemblies); } void validate_nodesets() { check_nodeset_node_reference(); check_nodeset_name_collision(); } template <typename T> void check_assembly_member_reference_in_group(const AssemblyData<EntityId> &assemblyData, const T &group) { for (const std::string &entry : assemblyData.data) { if (!group.is_registered(entry)) { std::ostringstream errmsg; errmsg << "Error! Assembly with id: " << assemblyData.id << " and name: " << assemblyData.name << " has reference to invalid " << group.get_group_type() << " '" << entry << "'."; m_errorHandler(errmsg); } } } void check_assembly_member_reference() { for (const AssemblyData<EntityId> &assemblyData : m_data.assemblies.get_group_data()) { const AssemblyType assemblyType = assemblyData.get_assembly_type(); switch (assemblyType) { case AssemblyType::BLOCK: check_assembly_member_reference_in_group(assemblyData, m_data.partIds); break; case AssemblyType::SIDESET: check_assembly_member_reference_in_group(assemblyData, m_data.sidesets); break; case AssemblyType::NODESET: check_assembly_member_reference_in_group(assemblyData, m_data.nodesets); break; case AssemblyType::ASSEMBLY: check_assembly_member_reference_in_group(assemblyData, m_data.assemblies); break; default: std::ostringstream errmsg; errmsg << "Error! Assembly with id: " << assemblyData.id << " and name: " << assemblyData.name << " does not have a valid assembly type '" << assemblyType << "'."; m_errorHandler(errmsg); } } } void check_assembly_name_collision() { check_name_collision_with_group(m_data.assemblies, m_data.partIds); check_name_collision_with_group(m_data.assemblies, m_data.sidesets); check_name_collision_with_group(m_data.assemblies, m_data.nodesets); } void check_assembly_cyclic_dependency() { for (const std::string &assembly : m_data.assemblies.get_part_names()) { if (m_data.assemblies.is_cyclic(assembly)) { std::ostringstream errmsg; errmsg << "Error! Assembly with name: '" << assembly << "' has a cyclic dependency."; m_errorHandler(errmsg); } } } void validate_assemblies() { check_assembly_member_reference(); check_assembly_name_collision(); check_assembly_cyclic_dependency(); } void parse_sideset_option(const std::vector<std::string> &sidesetOptionGroup) { if (sidesetOptionGroup.size() > 1) { SidesetParser<EntityId> parser; parser.set_error_handler(m_errorHandler); parser.parse(sidesetOptionGroup[1]); SidesetData<EntityId, Topology> *sideset = m_data.sidesets.add_group_data(parser.get_name(), parser.get_sideset_data()); sideset->set_split_type(parser.get_split_type()); m_parsedOptionMask |= PARSED_SIDESET; } } void parse_nodeset_option(const std::vector<std::string> &nodesetOptionGroup) { if (nodesetOptionGroup.size() > 1) { NodesetParser<EntityId> parser; parser.set_error_handler(m_errorHandler); parser.parse(nodesetOptionGroup[1]); m_data.nodesets.add_group_data(parser.get_name(), parser.get_nodeset_data()); m_parsedOptionMask |= PARSED_NODESET; } } void parse_assembly_option(const std::vector<std::string> &assemblyOptionGroup) { if (assemblyOptionGroup.size() > 1) { AssemblyParser parser; parser.set_error_handler(m_errorHandler); parser.parse(assemblyOptionGroup[1]); AssemblyData<EntityId> *assembly = m_data.assemblies.add_group_data(parser.get_name(), parser.get_assembly_data()); assembly->set_assembly_type(parser.get_assembly_type()); m_parsedOptionMask |= PARSED_ASSEMBLY; } } void print_help_message(std::ostream &out = std::cout) { out << "\nValid Options for TextMesh parameter string:\n" "\tPROC_ID,ELEM_ID,TOPOLOGY,{NODE CONNECTIVITY LIST}[,PART_NAME[,PART_ID]] " "(specifies " "element list .. first " "argument)\n" "\t|coordinates:x_1,y_1[,z_1], x_2,y_2[,z_2], ...., x_n,y_n[,z_n] (specifies " "coordinate data)\n" "\t|sideset:[name=<name>;] data=elem_1,side_1,elem_2,side_2,....,elem_n,side_n; " "[split=<block|topology|none>;] " "(specifies sideset data)\n" "\t|nodeset:[name=<name>;] data=node_1,node_2,....,node_n (specifies nodeset data)\n" "\t|assembly:[name=<name>;] type=<assembly|block|sideset|nodeset>; " "member=member_1,...,member_n (specifies assembly hierarchy)\n" "\t|dimension:spatialDimension (specifies spatial dimension .. default is 3)\n" "\t|help -- show this list\n\n"; } void handle_unrecognized_option(const std::string &optionType) { std::ostringstream errmsg; fmt::print(errmsg, "ERROR: Unrecognized option '{}'. It will be ignored.\n", optionType); m_errorHandler(errmsg); } void parse_options(const std::vector<std::string> &optionGroups) { for (size_t i = 1; i < optionGroups.size(); i++) { std::vector<std::string> optionGroup = get_tokens(optionGroups[i], ":"); std::string optionType = optionGroup[0]; convert_to_lower_case(optionType); if (optionType == "coordinates") { parse_coordinates_option(optionGroup); } else if (optionType == "dimension") { parse_dimension_option(optionGroup); } else if (optionType == "sideset") { parse_sideset_option(optionGroup); } else if (optionType == "nodeset") { parse_nodeset_option(optionGroup); } else if (optionType == "assembly") { parse_assembly_option(optionGroup); } else if (optionType == "help") { print_help_message(); } else { handle_unrecognized_option(optionType); } } } unsigned long m_parsedOptionMask; int m_parsedDimension; int m_constructorEnforcedDimension; std::string m_meshConnectivityDescription; std::vector<double> m_rawCoordinates; ErrorHandler m_errorHandler; TextMeshData<EntityId, Topology> &m_data; }; template <typename EntityId, typename TopologyMapping> class TextMeshParser { private: using Topology = typename TopologyMapping::Topology; public: explicit TextMeshParser(unsigned enforcedDimension) : m_optionParser(m_data, enforcedDimension) { initialize_constructor(); } TextMeshParser() : m_optionParser(m_data) { initialize_constructor(); } TextMeshData<EntityId, Topology> parse(const std::string &meshDescription) { initialize_parse(meshDescription); parse_description(); finalize_parse(); return m_data; } void set_error_handler(ErrorHandler errorHandler) { m_errorHandler = errorHandler; m_data.partIds.set_error_handler(errorHandler); m_data.coords.set_error_handler(errorHandler); m_data.sidesets.set_error_handler(errorHandler); m_data.nodesets.set_error_handler(errorHandler); m_data.assemblies.set_error_handler(errorHandler); m_optionParser.set_error_handler(errorHandler); } private: void initialize_constructor() { ErrorHandler errorHandler = [](const std::ostringstream &errmsg) { default_error_handler(errmsg); }; set_error_handler(errorHandler); m_topologyMapping.initialize_topology_map(); } void initialize_connectivity_parse(const std::string &meshDescription) { m_lexer.set_input_string(meshDescription); m_lineNumber = 1; validate_required_field(m_lexer.has_token()); } void initialize_parse(const std::string &meshDescription) { m_optionParser.initialize_parse(meshDescription); initialize_connectivity_parse(m_optionParser.get_mesh_connectivity_description()); } void finalize_parse() { m_optionParser.finalize_parse(); } void parse_description() { while (m_lexer.has_token()) { ElementData<EntityId, Topology> elemData = parse_element(); m_data.add_element(elemData); validate_no_extra_fields(); parse_newline(); } std::sort(m_data.elementDataVec.begin(), m_data.elementDataVec.end(), ElementDataLess<EntityId, Topology>()); } ElementData<EntityId, Topology> parse_element() { ElementData<EntityId, Topology> elem; elem.proc = parse_proc_id(); elem.identifier = parse_elem_id(); elem.topology = parse_topology(); elem.nodeIds = parse_node_ids(elem.topology); elem.partName = parse_part(elem.topology); return elem; } int parse_proc_id() { validate_required_field(m_lexer.has_number()); return parse_int(); } EntityId parse_elem_id() { validate_required_field(m_lexer.has_number()); return parse_unsigned(); } Topology parse_topology() { validate_required_field(m_lexer.has_string()); std::string topologyName = parse_string(); Topology topology = m_topologyMapping.topology(topologyName); validate_topology(topology, topologyName); return topology; } std::vector<EntityId> parse_node_ids(const Topology &topology) { std::vector<EntityId> nodeIds; while (m_lexer.has_number()) { nodeIds.push_back(parse_unsigned()); } validate_node_count(topology, nodeIds.size()); return nodeIds; } std::string parse_part(const Topology &topology) { std::string partName; if (m_lexer.has_string()) { partName = parse_string(); } else { partName = "block_" + topology.name(); } if (m_lexer.has_number()) { unsigned partId = parse_unsigned(); m_data.partIds.register_part_name_with_id(partName, partId); } else { m_data.partIds.register_part_name(partName); } return partName; } int parse_int() { return m_lexer.get_int(); } unsigned parse_unsigned() { return m_lexer.get_unsigned(); } std::string parse_string() { return m_lexer.get_string(); } void parse_newline() { m_lexer.get_newline(); m_lineNumber++; } void validate_required_field(bool hasNextRequiredField) { if (!hasNextRequiredField) { std::ostringstream errmsg; errmsg << "Error! Each line must contain the following fields (with at least one node): " "Processor, GlobalId, Element Topology, NodeIds. Error on line " << m_lineNumber << "."; m_errorHandler(errmsg); } } void validate_no_extra_fields() { bool requiredCondition = !m_lexer.has_token() || m_lexer.has_newline(); if (!requiredCondition) { std::ostringstream errmsg; errmsg << "Error! Each line should not contain more than the following fields (with at " "least one node): " "Processor, GlobalId, Element Topology, NodeIds, Part Name, PartId. " "Error on line " << m_lineNumber << "."; m_errorHandler(errmsg); } } void validate_topology(const Topology &topology, const std::string &providedName) { if (topology == m_topologyMapping.invalid_topology()) { std::ostringstream errmsg; errmsg << "Error! Topology = >>" << providedName << "<< is invalid from line " << m_lineNumber << "."; m_errorHandler(errmsg); } if (!topology.defined_on_spatial_dimension(m_data.spatialDim)) { std::ostringstream errmsg; errmsg << "Error on input line " << m_lineNumber << ". Topology = " << topology << " is not defined on spatial dimension = " << m_data.spatialDim << " set in parser."; m_errorHandler(errmsg); } } void validate_node_count(const Topology &topology, size_t numNodes) { size_t numTopologyNodes = topology.num_nodes(); if (numNodes != numTopologyNodes) { std::ostringstream errmsg; errmsg << "Error! The input line appears to contain " << numNodes << " nodes, but the topology " << topology << " needs " << numTopologyNodes << " nodes on line " << m_lineNumber << "."; m_errorHandler(errmsg); } } unsigned m_lineNumber = 0; TextMeshData<EntityId, Topology> m_data; TextMeshLexer m_lexer; TopologyMapping m_topologyMapping; ErrorHandler m_errorHandler; TextMeshOptionParser<EntityId, Topology> m_optionParser; }; } // namespace text_mesh } // namespace Iotm
3286f03213958bf2c7d6921662a428f4ccf1df30
dc87786cad39bcce3fe522e2863fa3cab6bd0b37
/Source/Utils/BufferFormat.cpp
6231a31d6ac7efdde1531223d36642b3ec10ddc2
[ "MIT" ]
permissive
Aljenci/ModernGL
dca6234711f057c77884e89786814e01262ef1c3
02aa3518db6ae49742ee33dbfbdcd6e5937a49ea
refs/heads/master
2021-01-22T04:49:29.905307
2017-02-10T17:48:10
2017-02-10T17:48:10
81,587,693
0
0
null
2017-02-10T17:11:38
2017-02-10T17:11:37
null
UTF-8
C++
false
false
1,651
cpp
BufferFormat.cpp
#include "BufferFormat.hpp" #include "Utils/OpenGL.hpp" FormatNode * InvalidFormat = (FormatNode *)(-1); FormatIterator::FormatIterator(const char * str) : ptr(str) { } FormatInfo FormatIterator::info() { FormatInfo info; info.valid = true; info.nodes = 0; info.size = 0; FormatIterator it = FormatIterator(ptr); while (FormatNode * node = it.next()) { if (node == InvalidFormat) { info.valid = false; break; } info.size += node->count * node->size; if (node->type) { ++info.nodes; } } return info; } FormatNode * FormatIterator::next() { node.count = 0; while (true) { char chr = *ptr++; switch (chr) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': node.count = node.count * 10 + chr - '0'; break; case 'f': if (node.count == 0) { node.count = 1; } if (node.count > 4) { return InvalidFormat; } node.type = OpenGL::GL_FLOAT; node.size = 4; return &node; case 'd': if (node.count == 0) { node.count = 1; } if (node.count > 4) { return InvalidFormat; } node.type = OpenGL::GL_DOUBLE; node.size = 8; return &node; case 'i': if (node.count == 0) { node.count = 1; } if (node.count > 4) { return InvalidFormat; } node.type = OpenGL::GL_INT; node.size = 4; return &node; case 'x': if (node.count == 0) { node.count = 1; } node.type = 0; node.size = 1; return &node; case 0: return node.count ? InvalidFormat : 0; default: return InvalidFormat; } } }
b11606a51b6a3fef29295c09c7b870e4b1d3d5e0
b3086689ea407a1b4b57db933eb7c9dae6852902
/include/mpel/core/planner.hpp
bc809b4f510a2d4dd5f25c9d255c84ad17b59f87
[]
no_license
lakshayg/mpel2
6c5d4d8d0ae53db9bc3d2ecbf3832f89fec1cc6b
b807b9cee1da91b57966f2ec7fc3ca998237a7b4
refs/heads/master
2021-04-27T00:09:00.228170
2018-03-02T18:56:24
2018-03-04T04:54:49
123,758,196
0
0
null
null
null
null
UTF-8
C++
false
false
1,003
hpp
planner.hpp
#ifndef MPEL_PLANNER #define MPEL_PLANNER #include "mpel/core/graph_builder.hpp" #include "mpel/core/graph_search.hpp" #include "mpel/core/interpolator.hpp" #include "mpel/core/primitives/graph.hpp" #include "mpel/core/primitives/path.hpp" #include "mpel/core/primitives/problem_definition.hpp" #include "mpel/core/primitives/workspace.hpp" #include <boost/shared_ptr.hpp> namespace mpel { class Planner { public: Planner(GraphBuilder* graph_builder, GraphSearch* graph_search, Interpolator* interpolator); void set_workspace(Workspace& ws); Path solve(const ProblemDefinition& pdef); Graph const& graph() const; Path const& geometric_path() const; private: boost::shared_ptr<GraphBuilder> graph_builder_; boost::shared_ptr<GraphSearch> graph_search_; boost::shared_ptr<Interpolator> interpolator_; Workspace ws_; Graph graph_; Path geometric_path_; Path interpolated_path_; }; } // namespace mpel #endif // MPEL_PLANNER
7e9453eb5c16118328fda808dead1e711307ea58
be596f44528920580e721d5554808bff85ac1883
/Bank/client.cpp
b946447a285a2a44755ef1534ff7cb2631f0df2e
[]
no_license
Mrjarkos/2019_1_d3_prc4_CabuyaAlberto_C-rdenasJavier_RoncancioBrayan
bf98eb521bd06ac53edb0ecf08a2e4886764fccc
00e5ffe1fc1483358cf02ce2803b3c0e9b12af67
refs/heads/master
2022-02-01T05:54:39.654354
2019-04-24T13:36:49
2019-04-24T13:36:49
181,575,180
0
0
null
null
null
null
UTF-8
C++
false
false
3,240
cpp
client.cpp
#include "client.h" #include <QDebug> Client::Client(char* cc,char* contra ) { Cc= cc; Contra= contra; for (int i=0;i<msjzise;i++) { msg[i]='0'; } } void Client::verifyClient(){ fd= open(pipename, O_WRONLY); if (fd<0){ close(fd); strcpy(msg,"No se pudo abrir la comunicación, intente de nuevo"); } else{ string send[2]; send[0]=Cc; send[1]=Contra; string datout= ";"+send[0]+";"+send[1]+";"; printf("string: %s string2 %s", send[0].c_str(),send[1].c_str() ); write(fd,&datout,sizeof(datout)); sleep(1); close(fd); fd= open(pipename, O_RDONLY); if (fd<0){ close(fd); strcpy(msg,"No se pudo abrir la comunicación, intente de nuevo"); } else{ void* resul=new char[msjzise]; read(fd,resul, msjzise); //qDebug()<<"cc:"<<(char *)resul; printf("%s", (char *)resul); strcpy(msg,(char* )resul); string msg2= msg; if(msg2=="Error al inicar sesion"){ confirm=1; } //qDebug()<<"cc:"<<(char *)resul; close(fd); } } } void Client::consulclient(int op){ fd= open(pipenamedata, O_WRONLY); if (fd<0){ close(fd); strcpy(msg,"No se pudo abrir la comunicación, intente de nuevo"); } else{ string datout; switch (op) { case 1:{ string send[2]; send[0]=std::to_string(op); send[1]=Cc; datout= ";"+send[0]+";"+send[1]+";"; write(fd,&datout,sizeof(datout)); //printf("string: %s string2 %s", send[0].c_str(),send[1].c_str() ); sleep(1); close(fd); }break ; case 2:{ string send[4]; send[0]=std::to_string(op); send[1]=idaccount; send[2]= moneyammount; send[3]= Contra; datout= ";"+send[0]+";"+send[1]+";"+send[2]+";"+send[3]+";"; // qDebug()<<"Sending"<<datout.c_str(); //printf("string: %s string2 %s", send[0].c_str(),send[1].c_str() ); write(fd,&datout,sizeof(datout)); sleep(1); close(fd); } break; case 3:{ string send[4]; send[0]=std::to_string(op); send[1]=idaccount; send[2]= moneyammount; send[3]= Contra; datout= ";"+send[0]+";"+send[1]+";"+send[2]+";"+send[3]+";"; //qDebug()<<"Sending"<<datout.c_str(); //printf("string: %s string2 %s", send[0].c_str(),send[1].c_str() ); write(fd,&datout,sizeof(datout)); sleep(1); close(fd); } } fd= open(pipenamedata, O_RDONLY); if (fd<0){ close(fd); strcpy(msg,"No se pudo abrir la comunicación, intente de nuevo"); } else{ void* resul=new char[msjzise]; read(fd,resul, msjzise); //qDebug()<<"cc:"<<(char *)resul; printf("%s", (char *)resul); strcpy(msg,(char* )resul); close(fd); } } }
d49e8180dc2cd6d42fbac37de4cd23608f27b003
c365d25ee2237b3c260198827b33b0253d43eaf4
/codeforces/667-a.cpp
62373fc3f47536c43414b9ea029fb6ecb07d28b8
[]
no_license
germanohn/competitive-programming
fb1249910ce951fe290e9a5be3876d3870ab8aa3
fab9dc0e2998dd395c1b9d6639f8c187cf637669
refs/heads/master
2021-06-12T08:17:52.907705
2021-03-17T19:06:19
2021-03-17T19:06:19
58,595,999
0
0
null
null
null
null
UTF-8
C++
false
false
593
cpp
667-a.cpp
#include <bits/stdc++.h> #define ff first #define ss second #define pb push_back #define mp make_pair #define debug (args...) fprintf (stderr, args) using namespace std; typedef long long ll; typedef pair<int, int> pii; double area, d, h, v, e, E; double eps = 1e-5; double pi = acos (-1); int main () { scanf ("%lf %lf %lf %lf", &d, &h, &v, &e); area = pi * (d/2) * (d/2); E = v * (1 / area); if (e - E > eps) { printf ("NO\n"); } else { double rate = E-e; double ans = h / rate; printf ("YES\n"); printf ("%lf\n", ans); } }
d1aa8ad5fda51e0c581d7f3996bc383990791ed3
edc5b1e0bbfe683f23dd14c811f2da456f5603a1
/include/subsys/Arm.h
9dcc10ade6b75bf230d9487a1ca5aae69408ce66
[ "MIT" ]
permissive
JacksterGamingYT/2019DestinationDeepSpace
fca67d7dbe022ca2289af8bab3091f368e21073e
e863c5b9a7c31e6edd41eb09bb2b33cfde7669d5
refs/heads/master
2020-04-22T19:18:25.859421
2019-02-12T13:49:49
2019-02-12T13:49:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,929
h
Arm.h
/*----------------------------------------------------------------------------*/ /* Copyright (c) 2018 FIRST. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ #pragma once #include "subsys/IMechanism.h" #include <hw/DragonTalon.h> #include <subsys/PlacementHeights.h> class Arm : public IMechanism { public: Arm(std::vector<IDragonMotorController*> motorControllers); void MoveArmPreset(PlacementHeights::PLACEMENT_HEIGHT height, bool cargo, bool flip); void MoveArmSpeed(double speed); void MoveArmAngle(double angle); void MoveExtentionPreset(PlacementHeights::PLACEMENT_HEIGHT height, bool cargo); void MoveExtensionSpeed(double speed); void MoveExtensionInches(double inches); double GetArmRealAngle(); double GetArmTargetAngle(); double GetExtenderRealRotations(); double GetExtenderTargetRotations(); IMechanism::MECHANISM_TYPE GetType() const override; private: enum HATCH_WRIST_PRESETS { HATCH_KEEP_SAME = -1, HATCH_FLOOR, HATCH_LOW, HATCH_MID, HATCH_HIGH, MAX_HATCH_POS }; enum CARGO_WRIST_PRESETS { CARGO_KEEP_SAME = -1, CARGO_FLOOR, CARGO_HP, CARGO_SHIP, CARGO_LOW, CARGO_MID, CARGO_HIGH, MAX_CARGO_POS }; double hatchAngle[MAX_HATCH_POS] = { 1, 2, 3, 4 }; double cargoAngle[MAX_CARGO_POS] = { 1, 2, 3, 4, 5, 6 }; double extenderHatchRots[MAX_HATCH_POS] = { 1, 2, 3, 4 }; double extenderCargoRots[MAX_CARGO_POS] = { 1, 2, 3, 4, 5, 6 }; double m_armTargetAngle; double m_extenderTargetRotations; DragonTalon* m_armMaster; DragonTalon* m_extender; };
f8a3ac8b6abc99da398e71065b15f62dff0a0e26
61343c326fbd76e5bc2c02c700fd6f879deefa39
/Plane.h
fb061c6f11ae9f81ff790d88b99712649bfff692
[]
no_license
mvanmeurs/MatrixOperations
8ccd87d6a04fab9827be433020a750a36997c4bc
6f330946f258d7c95b71ba541da4a567193f80dd
refs/heads/master
2021-09-04T20:02:03.834756
2018-01-22T01:01:28
2018-01-22T01:01:28
112,414,496
0
1
null
null
null
null
UTF-8
C++
false
false
5,742
h
Plane.h
/* Plane.h defines Plane class methods. * Made by Mason VanMeurs * Student at Calvin College in Grand Rapids Michigan * Date:12/2/17 */ #ifndef MATRIXOPERATIONS_PLANE_H #define MATRIXOPERATIONS_PLANE_H #include "Vec.h" #include <cstdlib> #include "cmath" #include "Point.h" using namespace std; template<class Item> class Plane { public: Plane(); Plane(Item, Item, Item, Item); ~Plane(); Item getx() const; Item gety() const; Item getz() const; Vec<Item> getX() const; Vec<Item> getY() const; Vec<Item> getZ() const; Item getMyEqualsTo() const; Vec<Item> getCoefficients() const; void setX(const Item&); void setY(const Item&); void setZ(const Item&); void setEqualsTo(const Item&); void setPlane(const Vec<Item>&, const Point<Item>&); double getCosine(const Plane<Item>&) const; bool operator==(const Plane<Item>&) const; bool operator!=(const Plane<Item>&) const; void scan(); Plane<Item>& operator=(const Plane<Item>&); void WriteToOperator(ostream &out) const; private: Vec<Item> myVec; friend class PlaneTester; }; template<class Item> Plane<Item>::Plane() { myVec.setSize(4); } template<class Item> Plane<Item>::Plane(Item myx, Item myy, Item myz, Item myequals) { myVec.setSize(4); myVec[0] = myx; myVec[1] = myy; myVec[2] = myz; myVec[3] = myequals; } template<class Item> Plane<Item>::~Plane() { myVec.~Vec(); } template<class Item> Item Plane<Item>::getx() const{return myVec[0];} template<class Item> Item Plane<Item>::gety() const{return myVec[1];} template<class Item> Item Plane<Item>::getz() const{return myVec[2];} template<class Item> Vec<Item> Plane<Item>::getX() const{ Vec<Item> result(3); result[0] = myVec[0]; result[1] = result[2] = 0; return result; } template<class Item> Vec<Item> Plane<Item>::getY() const{ Vec<Item> result(3); result[1] = myVec[1]; result[0] = result[2] = 0; return result; } template<class Item> Vec<Item> Plane<Item>::getZ() const{ Vec<Item> result(3); result[2] = myVec[2]; result[0] = result[1] = 0; return result; } template<class Item> Item Plane<Item>::getMyEqualsTo() const{return myVec[3];} template<class Item> Vec<Item> Plane<Item>::getCoefficients() const{ Vec<Item> result(3); result[0] = myVec[0]; result[1] = myVec[1]; result[2] = myVec[2]; return result; } template<class Item> void Plane<Item>::setX(const Item& setX){ myVec[0] = setX; } template<class Item> void Plane<Item>::setY(const Item& setY){ myVec[1] = setY; } template<class Item> void Plane<Item>::setZ(const Item& setZ){ myVec[2] = setZ; } template<class Item> void Plane<Item>::setEqualsTo(const Item& setequals){ myVec[3] = setequals; } template<class Item> void Plane<Item>::setPlane(const Vec<Item>& normalVec, const Point<Item>& point){ for(unsigned i = 0 ; i < normalVec.getSize() ; i++){ myVec[i] = normalVec[i]; } setEqualsTo(normalVec.getDotProduct(point.getVector())); } template<class Item> double Plane<Item>::getCosine(const Plane<Item>& rhs) const{ Vec<Item> lhs(3); for(unsigned i = 0 ; i < 3 ; i++){ lhs[i] = myVec[i]; } return (lhs.getDotProduct(rhs.getCoefficients()))/((lhs.getMagnitude())*(rhs.getCoefficients().getMagnitude())); } template<class Item> bool Plane<Item>::operator==(const Plane<Item>& rhs) const{ if(myVec == rhs.myVec){return true;} else{return false;} } template<class Item> bool Plane<Item>::operator!=(const Plane<Item>& rhs) const{ if(myVec == rhs.myVec){return false;} else{return true;} } template<class Item> Plane<Item>& Plane<Item>::operator=(const Plane<Item>& rhs){ if(myVec == rhs.myVec){return *this;} for(int i = 0 ; i<4 ; i++){ myVec[i] = rhs.myVec[i]; } return *this; } template<class Item> void Plane<Item>::scan(){ cout << "Please enter the coefficients for your plane:" << endl; double scan; for(unsigned i = 0 ; i < 3 ; i++){ cin >> scan; myVec[i] = scan; } cout << "Please enter what your Plane is equal to:" << endl; cin >> scan; myVec[3] = scan; } template<class Item> void Plane<Item>::WriteToOperator(ostream &out) const{ //if all values are zero if(myVec[0] == 0 && myVec[1] == 0 && myVec[2] == 0 && myVec[3] == 0){ out << "All real numbers are solutions" << flush; } else{ //is x coefficient negative if(myVec[0] < 0 && myVec[0] != 0){out << "-" << flush;}\ //if the coefficient isn't 1 if(abs(myVec[0]) != 1 && myVec[0] != 0){ out << abs(myVec[0]) << flush; } //is x not zero if(myVec[0] != 0){out << "X " << flush;} //is y coefficient negative if(myVec[1] < 0 && myVec[1] != 0){out << "- " << flush;} else if(myVec[1] != 0){out << "+ " << flush;} //if the coefficient isn't 1 if(abs(myVec[1]) != 1 && myVec[1] != 0){ out << abs(myVec[1]) << flush; } //is y not zero if(myVec[1] != 0){out << "Y " << flush;} //is z coefficient negative if(myVec[2] < 0 && myVec[2] != 0){out << "- " << flush;} else if(myVec[2] != 0){out << "+ " << flush;} //if the coefficient isn't 1 if(abs(myVec[2]) != 1 && myVec[2] != 0){ out << abs(myVec[2]) << flush; } //is z not zero if(myVec[2] != 0){out << "Z " << flush;} out << "= " << flush; out << myVec[3] << flush; } } template<class Item> ostream& operator<<(ostream& out, const Plane<Item>& plane){ plane.WriteToOperator(out); return out; } #endif //MATRIXOPERATIONS_PLANE_H
80ea184189903dc2ddf37a6fbc17dcded84820fc
b240383bfe38f94a7753293aca1a2d8ee225a856
/Final/Dataset/B2016_Z2_Z4/student9589.cpp
28cbe77b019b0bbef1d37df3e90d30c142b1ba9d
[ "MIT" ]
permissive
Team-PyRated/PyRated
2daa9866e45c75814c24fe073b8be321822f3e4c
1df171c8a5a98977b7a96ee298a288314d1b1b96
refs/heads/main
2023-06-22T08:27:53.615611
2021-07-17T18:44:37
2021-07-17T18:44:37
354,628,313
0
0
null
null
null
null
UTF-8
C++
false
false
4,462
cpp
student9589.cpp
/*B 16/17, Zadaća 2, Zadatak 4 NAPOMENA: i javni ATo-vi su dio postavke Autotestovi by Ivona Ivkovic. Sva pitanja, sugestije i prijave gresaka saljite na mail: iivkovic2@etf.unsa.ba */ #include <iostream> #include <new> #include <algorithm> #include <vector> #include <string> #include <cstring> #include <stdexcept> int PotencijalniKrivci (char **& matrica, std::vector<std::string> imena) { try { matrica=nullptr; matrica=new char*[imena.size()]; } catch (std::bad_alloc) { delete[] matrica; throw; } try { for(int i=0; i<imena.size(); i++) { matrica[i]=new char[imena[i].size()+1]; std::strcpy(matrica[i],imena[i].c_str()); } return imena.size(); } catch (std::bad_alloc) { for(int i=0; i<sizeof(matrica); i++) { delete[] matrica[i]; } delete[] matrica; throw; } } int OdbaciOptuzbu (char **& matrica, int n, std::string ime) { int ima(0); for (int i=0; i<n; i++) { if(std::strcmp(matrica[i], ime.c_str())==0) { delete[] matrica[i]; matrica[i]=nullptr; ima++; } } if(!ima) throw std::domain_error ("Osoba sa imenom "+ime+" nije bila optuzena"); else if (ima>10) { char ** novamat(nullptr); int vel=n-ima; try{ novamat=new char *[vel]; } catch (std::bad_alloc) { delete[] novamat; } try { int j(0); for (int i=0; i<n; i++) { if (matrica[i] != nullptr) { novamat[j]= new char [sizeof(matrica[i]+1)]; for (int k=0; k<=sizeof(matrica[i]); k++) { novamat[j][k]=matrica[i][k]; } j++; } } for (int i=0; i<n; i++) { delete[] matrica[i]; } delete[] matrica; matrica=novamat; return vel; } catch (std::bad_alloc) { for (int i=0; i<vel; i++) { delete[] novamat[i]; } delete[] novamat; } } return n; } int DodajOptuzbu (char **&matrica, int n, std::string ime) { int ubaceno(0); char *ime_niz(nullptr); ime_niz=new char[ime.length()+1]; std::strcpy (ime_niz, ime.c_str()); for (int i=0; i<n; i++) { if (matrica[i] != nullptr) continue; else { matrica[i]=ime_niz; ubaceno++; } if (ubaceno) break; } if (!ubaceno) { int vel=n+1; char ** novamat(nullptr); try { novamat=new char*[vel]; } catch (std::bad_alloc) { delete[] novamat; throw; } try { for (int i=0; i<vel; i++) { if (i==vel-1) { novamat[i]=ime_niz; break; } novamat[i]= new char [sizeof(matrica[i])+1]; std::strcpy(novamat[i], matrica[i]); } for (int i=0; i<n; i++) { delete[] matrica[i]; } delete[] matrica; matrica=novamat; return vel; } catch (std::bad_alloc) { for (int i=0; i<vel; i++) { delete[] novamat[i]; } delete[] novamat; throw; } } return n; } void IzlistajOptuzbu (char **matrica, int n) { for (int i=0; i<n; i++) { std::cout << std::endl; if (matrica[i] != nullptr) { char *p=matrica[i]; while (*p != '\0') std::cout << *p++; } } } int main () { int n; char **matrica; std::cout << "Koliko potencijalnih krivaca zelite unijeti?"; std::cin >> n; std::vector <std::string> imena(n); std::cin.ignore(100000, '\n'); std::cout << "\nUnesite potencijalne krivce: "; for (int i=0; i<n; i++) { std::cin >> imena[i]; } try { int unos; std::string ime; n=PotencijalniKrivci(matrica, imena); while (1) { std::cout << "\nOdaberite opciju: 1 za unos novog optuzenog, 2 za brisanje nekog optuzenog 3 za izlistavanje optuzenih, 0 za kraj:"; std::cin >> unos; if (!unos) break; else if (unos==1) { std::cin.ignore (100000000, '\n'); std::cout << "\nUnesite ime novog optuzenog: "; std::getline (std::cin, ime); n=DodajOptuzbu(matrica, n, ime); } else if (unos==2) { std::cin.ignore(10000000, '\n'); std::cout << "\nUnesite ime koje zelite izbaciti: "; std::getline (std::cin, ime); n=OdbaciOptuzbu(matrica, n, ime); } else { IzlistajOptuzbu(matrica, n); } } for (int i=0; i<n; i++) { delete[] matrica[i]; } delete[] matrica; } catch (std::bad_alloc) { for (int i=0; i<n; i++) { delete[] matrica[i]; } delete[] matrica; } catch (std::domain_error izuzetak) { for (int i=0; i<n; i++) { delete[] matrica[i]; } delete[] matrica; std::cout << izuzetak.what() << std::endl; } return 0; }
81cd93a7e7efcb4f23110f817fb9938e45615178
0d0fd5bebda3a6305c3f8d5017b99c0f28c4667e
/800/Vitalityandpie.cpp
da368bc8f65fae2c8a27e5334b440a2323bd2d1e
[]
no_license
manmeet-kaur18/CodeForces_Leetcode
9b7b88daa8ba8ecca48d92a665bf2ac11a437f0a
8c129d6a6d1ffb57e224f573177c443baf835ad6
refs/heads/master
2023-07-13T09:50:42.888171
2021-08-26T05:00:44
2021-08-26T05:00:44
287,578,703
0
0
null
null
null
null
UTF-8
C++
false
false
611
cpp
Vitalityandpie.cpp
#include<bits/stdc++.h> #include<map> #include<string> using namespace std; int main(){ int n; cin>> n; char arr[2*n-2]; for(int i=0;i<(2*n-2);i++){ char y; cin>>y; arr[i]=y; } int cost = 0; map<char,int> m; for(int i=0;i<(2*n-2);i++){ if(i%2 == 0){ if(m.find(arr[i])== m.end()){ m[arr[i]] = 1; } else{ m[arr[i]] += 1; } } else{ if(m.find(tolower(arr[i])) != m.end()){ if(m[tolower(arr[i])]==1){ m.erase(tolower(arr[i])); } else{ m[tolower(arr[i])] -= 1; } } else{ cost+=1; } } } cout<<cost; return 0; }
70f3753ddea37e89acedaec3731b521a4584ec41
e2021e9651b63a6ff9718ba628d3ad9f6b8ae981
/1195/4447788_AC_704MS_4508K.cc
f7462db74ee90c6dd0664172e398e4799e21ca84
[ "Apache-2.0" ]
permissive
fanmengcheng/twilight-poj-solution
36831f1a9b2d8bc020988e0606b240527a381754
3af3f0fb0c5f350cdf6421b943c6df02ee3f2f82
refs/heads/master
2020-04-08T22:36:47.267071
2015-05-26T10:21:03
2015-05-26T10:25:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,417
cc
4447788_AC_704MS_4508K.cc
/********************************************************************** * Online Judge : POJ * Problem Title : Mobile phones * ID : 1195 * Date : 12/2/2008 * Time : 20:49:34 * Computer Name : EVERLASTING-PC ***********************************************************************/ //二维树状数组 #include<iostream> using namespace std; #define MAXC 1024 int C[MAXC+1][MAXC+1]; int cmd,l,r,b,t,a,s,x,y; inline int LowBit(int x) { return x&(-x); } int Sum(int x,int y) { int sum=0; while (x>0) { int t=y; while (t>0) { sum+=C[x][t]; t-=LowBit(t); } x-=LowBit(x); } return sum; } void Modify(int x,int y,int delta,int len) { while (x<=len) { int t=y; while (t<=len) { C[x][t]+=delta; t+=LowBit(t); } x+=LowBit(x); } } bool WorkLoop() { while (1) { if(scanf("%d",&cmd)==-1) { return false; } switch (cmd) { case 0: { memset(C,0,sizeof(C)); scanf("%d",&s); break; } case 1: { scanf("%d%d%d",&x,&y,&a); x++; y++; Modify(x,y,a,s); break; } case 2: { scanf("%d%d%d%d",&l,&b,&r,&t); l++; b++; r++; t++; printf("%d\n",Sum(r,t)-Sum(r,b-1)-Sum(l-1,t)+Sum(l-1,b-1)); break; } case 3: { return true; } } } } int main() { //freopen("in_1195.txt","r",stdin); while (WorkLoop()); return 0; }
9d5482f19d0f537f94dbc57ed14c6babf1bc0b10
f6fca6c43ad746c45c8321541178eb02e2cb555e
/icpp/Source/RuntimeException.cpp
e389ed11bbe5c58bdb4d5fa0877a1a0387c2bac4
[]
no_license
Asakra/alterplast
da271c590b32767953f09266fed1569831aa78cb
682e1c2d2f4246183e9b8284d8cf2dbc14f6e228
refs/heads/master
2023-06-22T04:16:34.924155
2021-07-16T06:20:20
2021-07-16T06:20:20
null
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
6,561
cpp
RuntimeException.cpp
#include "stdafx.h" #include "RuntimeException.h" ////////////////////////////////////////////////////////////////////////// // CRuntimeExceptionClass class (c) artbear 2007-2008 ////////////////////////////////////////////////////////////////////////// // ====================================================================== // // begin of CRuntimeExceptionClass // bool CRuntimeExceptionClass::isExceptionStatus = false; CString CRuntimeExceptionClass::strTextException; CValue* CRuntimeExceptionClass::ExceptionValue = NULL; //CBLModule7* CRuntimeExceptionClass::pMod = NULL; CSafeModulePtr CRuntimeExceptionClass::pMod; int CRuntimeExceptionClass::iRuntimeErrLineNum = 0; CString CRuntimeExceptionClass::m_strModulePath; DWORD CRuntimeExceptionClass::m_nID = 0; bool CRuntimeExceptionClass::m_bStatusOfTryingBlock = false; // флаг, находимся ли в блоке Попытка-Исключение void CRuntimeExceptionClass::Init(void) { ExceptionValue = new CValue; Empty(); } void CRuntimeExceptionClass::Destroy(void) { delete ExceptionValue; } void CRuntimeExceptionClass::Empty(void) { isExceptionStatus = false; strTextException.Empty(); pMod = NULL; iRuntimeErrLineNum = 0; m_strModulePath.Empty(); m_nID = 0; } // запомнить исключение и данные о нем void CRuntimeExceptionClass::SetException(const CString& strExceptionA) { Empty(); // TODO isExceptionStatus = true; strTextException = strExceptionA; } void CRuntimeExceptionClass::SetException(const CString& strExceptionA, CBLModule7* pModA, DWORD m_nIDA, const CString& m_strModulePathA, int iRuntimeErrLineNumA) { // для вызова CBLModule7::OnErrorMessageEx(strGetRuntimeErrDescr, m_nID, m_strModulePath, GetRuntimeErrLineNum()); SetException(strExceptionA); pMod = pModA; m_nID = m_nIDA; m_strModulePath = m_strModulePathA; iRuntimeErrLineNum = iRuntimeErrLineNumA; } // выбросить исключение для пользовательских классов 1C++ void CRuntimeExceptionClass::ThrowException(bool isThrow) { CString strTextException_copy(strTextException); //static CString* p_strTextException_copy = new CString; //static CString& strTextException_copy ( *p_strTextException_copy ); //strTextException_copy = strTextException; CBLModule7* pMod_copy = static_cast<CBLModule7*>(pMod.operator CBLModule*()); // TODO DWORD m_nID_copy = m_nID; CString m_strModulePath_copy( m_strModulePath ); int iRuntimeErrLineNum_copy = iRuntimeErrLineNum; Empty(); if (pMod_copy) { // для каждого класса согласно иерархии создания будет показано отдельное сообщение об ошибке // т.е. если открыты форма Форма1, в ней создан класс КОП1, в нем КОП2, будет показано 3 сообщения // сначала для КОП2, далее КОП1, далее Форма1 - и двойной щелчок на каждом из сообщений при открытом Конфигураторе вызовет переход на соответствующий файл в Конфигураторе // if (!GetStatusOfTryingBlock() && !IsInsideTryingBlock()) { pMod_copy->OnErrorMessageEx(strTextException_copy, m_nID_copy, m_strModulePath_copy, iRuntimeErrLineNum_copy); } ::RuntimeError(strTextException_copy) ; } else { if (isThrow) ::RuntimeError(strTextException_copy) ; else ::ShowMsg(strTextException_copy, mmExclamation); } } // выбросить исключение для пользовательских классов 1C++ void CRuntimeExceptionClass::IfNeedExceptionThenThrowException(void) { if (IsNeedException()) ThrowException(); } // выбросить исключение для пользовательских классов 1C++ void CRuntimeExceptionClass::ThrowException(const CString& strException) { SetException(strException); ThrowException(); } // выбросить исключение, запомнив переданный объект. Сообщение об ошибке будет пустое void CRuntimeExceptionClass::RuntimeError(const CValue& param) { Empty(); *ExceptionValue = param; ::RuntimeError(""); } // выбросить исключение, запомнив переданный объект. Сообщение об ошибке будет равно указанному void CRuntimeExceptionClass::RuntimeError(const CValue& param, const CString& strNewTextException) { Empty(); *ExceptionValue = param; ::RuntimeError(strNewTextException); } // получить ранее сохраненный объект-исключение void CRuntimeExceptionClass::GetException(CValue & rValue) { rValue = *ExceptionValue; ExceptionValue->Reset(); } // получить флаг, находимся ли в блоке Попытка-Исключение void CRuntimeExceptionClass::SaveStatusOfTryingBlock(void) { m_bStatusOfTryingBlock = IsInsideTryingBlock(); // флаг, находимся ли в блоке Попытка-Исключение } bool CRuntimeExceptionClass::GetStatusOfTryingBlock(void) { return m_bStatusOfTryingBlock; } // проверить, не находимся ли мы в блоке Попытка-Исключение bool CRuntimeExceptionClass::IsInsideTryingBlock(void) { CBLModule* pCurModule = CBLModule::GetExecutedModule(); if (!pCurModule) return false; if (!pCurModule->pIntInfo) return false; CExecutedModule* pExecutedModule = pCurModule->pIntInfo->pExecutedModule; if (!pExecutedModule) return false; // это разведал АльФ - огромное ему спасибо bool bRetInsideTryingBlock = (pExecutedModule->m_DWordArray2.GetSize() > pExecutedModule->val_23); // для классов - особая обработка, т.к. у них использованные выше параметры всегда нулевые CBLContext* pCont = CBLModuleWrapper::GetContextFromModule(pCurModule); if (pCont && !bRetInsideTryingBlock && IS_KINDOF_CComponentClass(pCont)) { bRetInsideTryingBlock = m_bStatusOfTryingBlock; } return bRetInsideTryingBlock; } // // end of CRuntimeExceptionClass // ======================================================================
809f4ffe72df88c8e18f51a01f4f426febe811dd
4ea4c266ca596699ccd964e4d55dce0168ff2246
/tucsenApp/src/tucsen.cpp
5f16bbbb6e0c45d545e51c3fbdf4ca4a990f0048
[]
no_license
ZRen86/ADTucsen
25d61fba02a63d86f8ec038cd3500473c9f5272d
1eb5567e71a32d75caa811967152f9bf53917844
refs/heads/master
2022-01-10T14:12:22.663928
2019-06-22T16:22:40
2019-06-22T16:22:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
30,769
cpp
tucsen.cpp
/* This is a driver for the TUcsen Dhyana 900D camera. It should work for all * Tucsen USB3 cameras that use the TUCAM api. * * Author: David Vine * Date : 28 October 2017 * * Based on Mark Rivers PointGrey driver. */ #include <stdio.h> #include <string.h> #include <unistd.h> #include <epicsEvent.h> #include <epicsTime.h> #include <epicsThread.h> #include <iocsh.h> #include <epicsString.h> #include <epicsExit.h> #include <epicsExport.h> #include <TUCamApi.h> #include <ADDriver.h> #define DRIVER_VERSION 0 #define DRIVER_REVISION 2 #define DRIVER_MODIFICATION 0 #define TucsenBusString "T_BUS" #define TucsenProductIDString "T_PRODUCT_ID" #define TucsenDriverVersionString "T_DRIVER_VERSION" #define TucsenTransferRateString "T_TRANSER_RATE" #define TucsenFrameFormatString "T_FRAME_FORMAT" #define TucsenBinningModeString "T_BIN_MODE" #define TucsenImageModeString "T_IMG_MODE" #define TucsenFanGearString "T_FAN_GEAR" static const int frameFormats[3] = { 0x10, 0x11, 0x12 }; static const char* driverName = "tucsen"; static int TUCAMInitialized = 0; /* Main driver class inherited from areaDetector ADDriver class */ class tucsen : public ADDriver { public: tucsen( const char* portName, const char* cameraId, int traceMask, int maxBuffers, size_t maxMemory, int priority, int stackSize); /* Virtual methods to override from ADDrive */ virtual asynStatus writeInt32( asynUser *pasynUser, epicsInt32 value); virtual asynStatus writeFloat64( asynUser *pasynUser, epicsFloat64 value); /* These should be private but must be called from C */ void imageGrabTask(); void shutdown(); void tempTask(); protected: int TucsenBus; #define FIRST_TUCSEN_PARAM TucsenBus int TucsenProductID; int TucsenDriverVersion; int TucsenTransferRate; int TucsenBinMode; int TucsenFanGear; int TucsenImageMode; int TucsenFrameFormat; #define LAST_TUCSEN_PARAM TucsenFrameFormat private: /* Local methods to this class */ asynStatus grabImage(); asynStatus startCapture(); asynStatus stopCapture(); asynStatus connectCamera(); asynStatus disconnectCamera(); /* camera property control functions */ asynStatus getCamInfo(int nID, char* sBuf, int &val); asynStatus setCamInfo(int param, int nID, int dtype); asynStatus setSerialNumber(); asynStatus setProperty(int nID, double value); asynStatus setCapability(int property, int value); asynStatus getCapability(int property, int& value); /* Data */ const char* cameraId_; int exiting_; TUCAM_INIT apiHandle_; TUCAM_OPEN camHandle_; TUCAM_FRAME frameHandle_; TUCAM_TRIGGER_ATTR triggerHandle_; epicsEventId startEventId_; NDArray *pRaw_; }; #define NUM_TUCSEN_PARAMS ((int)(&LAST_TUCSEN_PARAM-&FIRST_TUCSEN_PARAM+1)) /* Configuration function to configure one camera * * This function needs to be called once for each camera used by the IOC. A * call to this function instantiates one object of the Tucsen class. * \param[in] portName asyn port to assign to the camera * \param[in] cameraId The camera serial number * \param[in] traceMask the initial value of asynTraceMask * if set to 0 or 1 then asynTraceMask will be set to * ASYN_TRACE_ERROR. * if set to 0x21 ( ASYN_TRACE_WARNING | ASYN_TRACE_ERROR) then each * call will be traced during initialization * \param[in] maxBuffers Maximum number of NDArray objects (image buffers) this * driver is allowed to allocate. * 0 = unlimited * \param[in] maxMemory Maximum memort (in bytes) that this driver is allowed * to allocate. * 0=unlimited * \param[in] priority The epics thread priority for this driver. 0= asyn * default. * \param[in] stackSize The size of the stack of the EPICS port thread. 0=use * asyn default. */ extern "C" int tucsenConfig(const char *portName, const char* cameraId, int traceMask, int maxBuffers, size_t maxMemory, int priority, int stackSize) { new tucsen( portName, cameraId, traceMask, maxBuffers, maxMemory, priority, stackSize); return asynSuccess; } static void c_shutdown(void *arg) { tucsen *t = (tucsen *)arg; t->shutdown(); } static void imageGrabTaskC(void *drvPvt) { tucsen *t = (tucsen *)drvPvt; t->imageGrabTask(); } static void tempReadTaskC(void *drvPvt) { tucsen *t = (tucsen *)drvPvt; t->tempTask(); } /* Constructor for the Tucsen class */ tucsen::tucsen(const char *portName, const char* cameraId, int traceMask, int maxBuffers, size_t maxMemory, int priority, int stackSize) : ADDriver( portName, 1, NUM_TUCSEN_PARAMS, maxBuffers, maxMemory, asynEnumMask, asynEnumMask, ASYN_CANBLOCK | ASYN_MULTIDEVICE, 1, priority, stackSize), cameraId_(cameraId), exiting_(0), pRaw_(NULL) { static const char *functionName = "tucsen"; asynStatus status; /* traceMask = ASYN_TRACE_ERROR || ASYN_TRACEIO_DRIVER; pasynTrace->setTraceMask(pasynUserSelf, traceMask); */ createParam(TucsenBusString, asynParamOctet, &TucsenBus); createParam(TucsenProductIDString, asynParamFloat64, &TucsenProductID); createParam(TucsenDriverVersionString, asynParamOctet, &TucsenDriverVersion); createParam(TucsenTransferRateString, asynParamFloat64, &TucsenTransferRate); createParam(TucsenBinningModeString, asynParamInt32, &TucsenBinMode); createParam(TucsenFanGearString, asynParamInt32, &TucsenFanGear); createParam(TucsenImageModeString, asynParamInt32, &TucsenImageMode); createParam(TucsenFrameFormatString, asynParamInt32, &TucsenFrameFormat); /* Set initial values for some parameters */ setIntegerParam(NDDataType, NDUInt16); setIntegerParam(NDColorMode, NDColorModeMono); setIntegerParam(NDArraySizeZ, 0); setIntegerParam(ADMinX, 0); setIntegerParam(ADMinY, 0); setStringParam(ADStringToServer, "<not used by driver>"); setStringParam(ADStringFromServer, "<not used by driver>"); setStringParam(ADManufacturer, "Tucsen"); setIntegerParam(ADMaxSizeX, 2048); setIntegerParam(ADMaxSizeY, 2044); setIntegerParam(NDArraySizeX, 2048); setIntegerParam(NDArraySizeY, 2048); setIntegerParam(NDArraySize, 2*2048*2044); setStringParam(ADManufacturer, "Tucsen"); status = connectCamera(); if (status) { asynPrint(pasynUserSelf, ASYN_TRACE_ERROR, "%s:%s: camera connection failed (%d)\n", driverName, functionName, status); report(stdout, 1); return; } startEventId_ = epicsEventCreate(epicsEventEmpty); /* Launch image read task */ epicsThreadCreate("TucsenImageReadTask", epicsThreadPriorityMedium, epicsThreadGetStackSize(epicsThreadStackMedium), imageGrabTaskC, this); /* Launch temp task */ epicsThreadCreate("TucsenTempReadTask", epicsThreadPriorityMedium, epicsThreadGetStackSize(epicsThreadStackMedium), tempReadTaskC, this); /* Launch shutdown task */ epicsAtExit(c_shutdown, this); return; } void tucsen::shutdown(void) { exiting_=1; if (camHandle_.hIdxTUCam != NULL){ disconnectCamera(); } TUCAMInitialized--; if(TUCAMInitialized==0){ TUCAM_Api_Uninit(); } } asynStatus tucsen::connectCamera() { static const char* functionName = "connectCamera"; int tucStatus; asynStatus status; // Init API char szPath[1024] = {0}; getcwd(szPath, 1024); apiHandle_.pstrConfigPath = szPath; apiHandle_.uiCamCount = 0; tucStatus = TUCAM_Api_Init(&apiHandle_); if (tucStatus!=TUCAMRET_SUCCESS){ asynPrint(pasynUserSelf, ASYN_TRACE_ERROR, "%s:%s: TUCAM API init failed (%d)\n", driverName, functionName, tucStatus); return asynError; } if (apiHandle_.uiCamCount<1){ asynPrint(pasynUserSelf, ASYN_TRACE_ERROR, "%s:%s: no camera detected (%d)\n", driverName, functionName, tucStatus); return asynError; } else { asynPrint(pasynUserSelf, ASYN_TRACEIO_DRIVER, "%s:%s: Detected %d cameras\n", driverName, functionName, apiHandle_.uiCamCount); } TUCAMInitialized++; // Connect to each camera and match serial number to cameraId_ char cSN[TUSN_SIZE] = {0}; TUCAM_REG_RW regRW; regRW.nRegType = TUREG_SN; regRW.pBuf = &cSN[0]; regRW.nBufSize = TUSN_SIZE; char* compResult = NULL; if (strlen(cameraId_)==1){ camHandle_.hIdxTUCam = NULL; camHandle_.uiIdxOpen = std::stoi(cameraId_); } else { for (int camCnt=0; camCnt<apiHandle_.uiCamCount; camCnt++){ if (TUCAMInitialized==0){ apiHandle_.pstrConfigPath = szPath; apiHandle_.uiCamCount = 0; tucStatus = TUCAM_Api_Init(&apiHandle_); if (tucStatus!=TUCAMRET_SUCCESS){ asynPrint(pasynUserSelf, ASYN_TRACE_ERROR, "%s:%s: TUCAM API init failed (%d)\n", driverName, functionName, tucStatus); return asynError; } if (apiHandle_.uiCamCount<1){ asynPrint(pasynUserSelf, ASYN_TRACE_ERROR, "%s:%s: no camera detected (%d)\n", driverName, functionName, tucStatus); return asynError; } else { asynPrint(pasynUserSelf, ASYN_TRACEIO_DRIVER, "%s:%s: Detected %d cameras\n", driverName, functionName, apiHandle_.uiCamCount); } TUCAMInitialized++; } // Init camera camHandle_.hIdxTUCam = NULL; camHandle_.uiIdxOpen = camCnt; tucStatus = TUCAM_Dev_Open(&camHandle_); if (tucStatus!=TUCAMRET_SUCCESS){ asynPrint(pasynUserSelf, ASYN_TRACE_ERROR, "%s:%s: open camera device failed (%d)\n", driverName, functionName, tucStatus); return asynError; } tucStatus = TUCAM_Reg_Read(camHandle_.hIdxTUCam, regRW); if (tucStatus==TUCAMRET_SUCCESS){ compResult = strstr(cSN, cameraId_); if (compResult != NULL){ break; } else { asynPrint(pasynUserSelf, ASYN_TRACEIO_DRIVER, "%s:%s: Camera (%d, %s) does not match requested serial number (%s)\n", driverName, functionName, camCnt, cSN, cameraId_); } } asynPrint(pasynUserSelf, ASYN_TRACEIO_DRIVER, "%s:%s: Closing camera (%d)\n", driverName, functionName, camCnt, cSN, cameraId_); if (camHandle_.hIdxTUCam != NULL){ tucStatus = TUCAM_Dev_Close(camHandle_.hIdxTUCam); } TUCAMInitialized--; if(TUCAMInitialized==0){ TUCAM_Api_Uninit(); } } if (compResult==NULL){ asynPrint(pasynUserSelf, ASYN_TRACE_ERROR, "%s:%s: No camera with serial %s found!\nSet cameraId=\"\" to connect to first camera\n", driverName, functionName, cameraId_); return asynError; } } if (camHandle_.hIdxTUCam==NULL){ tucStatus = TUCAM_Dev_Open(&camHandle_); } if (tucStatus!=TUCAMRET_SUCCESS){ asynPrint(pasynUserSelf, ASYN_TRACE_ERROR, "%s:%s: open camera device failed (%d)\n", driverName, functionName, tucStatus); return asynError; } status = setCamInfo(TucsenBus, TUIDI_BUS, 0); status = setCamInfo(TucsenProductID, TUIDI_PRODUCT, 1); status = setCamInfo(ADSDKVersion, TUIDI_VERSION_API, 0); status = setCamInfo(ADFirmwareVersion, TUIDI_VERSION_FRMW, 0); status = setCamInfo(ADModel, TUIDI_CAMERA_MODEL, 0); status = setCamInfo(TucsenDriverVersion, TUIDI_VERSION_DRIVER, 0); status = setSerialNumber(); return status; } asynStatus tucsen::disconnectCamera(void){ static const char* functionName = "disconnectCamera"; int tucStatus; int acquiring; asynStatus status; // check if acquiring status = getIntegerParam(ADAcquire, &acquiring); // if necessary stop acquiring if (status==asynSuccess && acquiring){ tucStatus = TUCAM_Cap_Stop(camHandle_.hIdxTUCam); if (tucStatus!=TUCAMRET_SUCCESS){ asynPrint(pasynUserSelf, ASYN_TRACE_ERROR, "%s:%s: unable to stop acquisition (%d)\n", driverName, functionName, tucStatus); } } // release buffer tucStatus = TUCAM_Buf_Release(camHandle_.hIdxTUCam); if (tucStatus!=TUCAMRET_SUCCESS){ asynPrint(pasynUserSelf, ASYN_TRACE_ERROR, "%s:%s: unable to release camera buffer (%d)\n", driverName, functionName, tucStatus); } tucStatus = TUCAM_Dev_Close(camHandle_.hIdxTUCam); if (tucStatus!=TUCAMRET_SUCCESS){ asynPrint(pasynUserSelf, ASYN_TRACE_ERROR, "%s:%s: unable close camera (%d)\n", driverName, functionName, tucStatus); } return asynSuccess; } void tucsen::imageGrabTask(void) { static const char* functionName = "imageGrabTask"; asynStatus status = asynSuccess; int tucStatus; int imageCounter; int numImages, numImagesCounter; int imageMode; int arrayCallbacks; epicsTimeStamp startTime; int acquire; lock(); while(1){ /* Is acquisition active? */ getIntegerParam(ADAcquire, &acquire); /* If we are nit acquiring wait for a semaphore that is given when * acquisition is started */ if(!acquire){ setIntegerParam(ADStatus, ADStatusIdle); callParamCallbacks(); asynPrint(pasynUserSelf, ASYN_TRACE_FLOW, "%s:%s: waiting for acquisition to start\n", driverName, functionName); unlock(); epicsEventWait(startEventId_); // SEQUENCE or STANDARD? tucStatus = TUCAM_Cap_Start(camHandle_.hIdxTUCam, TUCCM_SEQUENCE); if (tucStatus!=TUCAMRET_SUCCESS){ asynPrint(pasynUserSelf, ASYN_TRACE_ERROR, "%s:%s: Failed to start image capture (%d)\n", driverName, functionName, tucStatus); } lock(); asynPrint(pasynUserSelf, ASYN_TRACE_FLOW, "%s:%s: acquisition started\n", driverName, functionName); setIntegerParam(ADNumImagesCounter, 0); setIntegerParam(ADAcquire, 1); } /* Get the current time */ epicsTimeGetCurrent(&startTime); /* We are now waiting for an image */ setIntegerParam(ADStatus, ADStatusWaiting); callParamCallbacks(); status = grabImage(); if (status==asynError){ // Release the allocated NDArray if (pRaw_) pRaw_->release(); pRaw_ = NULL; continue; } getIntegerParam(NDArrayCounter, &imageCounter); getIntegerParam(ADNumImages, &numImages); getIntegerParam(ADNumImagesCounter, &numImagesCounter); getIntegerParam(ADImageMode, &imageMode); getIntegerParam(NDArrayCallbacks, &arrayCallbacks); imageCounter++; numImagesCounter++; setIntegerParam(NDArrayCounter, imageCounter); setIntegerParam(ADNumImagesCounter, numImagesCounter); if(arrayCallbacks){ doCallbacksGenericPointer(pRaw_, NDArrayData, 0); } if (pRaw_) pRaw_->release(); pRaw_ = NULL; if ((imageMode==ADImageSingle) || ((imageMode==ADImageMultiple) && (numImagesCounter>numImages))){ status = stopCapture(); } callParamCallbacks(); } } asynStatus tucsen::grabImage() { static const char* functionName = "grabImage"; asynStatus status = asynSuccess; int tucStatus; int header, offset; int nCols, nRows, stride; int bitDepth, pixelFormat, channels, pixelBytes; int index, dataSize; int tDataSize; NDDataType_t dataType; NDColorMode_t colorMode; int numColors; int pixelSize; size_t dims[3]; int nDims; int count; unlock(); tucStatus = TUCAM_Buf_WaitForFrame(camHandle_.hIdxTUCam, &frameHandle_); if (tucStatus!= TUCAMRET_SUCCESS){ asynPrint(pasynUserSelf, ASYN_TRACE_ERROR, "%s:%s: Failed to wait for buffer (%d)\n", driverName, functionName, tucStatus); } lock(); setIntegerParam(ADStatus, ADStatusReadout); callParamCallbacks(); header = frameHandle_.usHeader; offset = frameHandle_.usOffset; // Width & height are array dimensions nCols = frameHandle_.usWidth; nRows = frameHandle_.usHeight; // Not sure what this is "Frame image width step"? stride =frameHandle_.uiWidthStep; // Pixel bit depth bitDepth = frameHandle_.ucDepth; // Image format pixelFormat = frameHandle_.ucFormat; // Number of channels channels = frameHandle_.ucChannels; // Not sure what this is "Frame image data byte"? pixelBytes = frameHandle_.ucElemBytes; // Frame image serial number? index = frameHandle_.uiIndex; // Frame image data size tDataSize = frameHandle_.uiImgSize; /* There is zero documentation on what the formats mean * Most of the below is gleaned through trial and error */ if (pixelFormat==16){ // Raw data - no filtering applied dataType = NDUInt16; colorMode = NDColorModeMono; numColors = 1; pixelSize = 2; } else if (pixelFormat==17){ if (bitDepth==1){ dataType=NDUInt8; pixelSize = 1; } else if (bitDepth==2) { dataType=NDUInt16; pixelSize = 2; } if (channels==1){ colorMode = NDColorModeMono; numColors = 1; } else if (channels==3){ colorMode = NDColorModeRGB1; numColors = 3; } } else if (pixelFormat==18){ dataType=NDUInt8; pixelSize = 1; colorMode = NDColorModeRGB1; numColors = 3; } else { asynPrint(pasynUserSelf, ASYN_TRACE_ERROR, "%s:%s: Unsupported pixel format %d\n", driverName, functionName, pixelFormat); return asynError; } if (numColors==1){ nDims = 2; dims[0] = nCols; dims[1] = nRows; } else { nDims = 3; dims[0] = 3; dims[1] = nCols; dims[2] = nRows; } dataSize = dims[0]*dims[1]*pixelSize; if (nDims==3) dataSize *= dims[2]; if (dataSize != tDataSize){ asynPrint(pasynUserSelf, ASYN_TRACE_ERROR, "%s:%s: data size mismatch: calculated=%d, reported=%d\n", driverName, functionName, dataSize, tDataSize); return asynError; } setIntegerParam(NDArraySizeX, nCols); setIntegerParam(NDArraySizeY, nRows); setIntegerParam(NDArraySize, (int)dataSize); setIntegerParam(NDDataType, dataType); setIntegerParam(NDColorMode, colorMode); pRaw_ = pNDArrayPool->alloc(nDims, dims, dataType, 0, NULL); if(!pRaw_){ // No valid buffer so we need to abort setIntegerParam(ADStatus, ADStatusAborting); callParamCallbacks(); asynPrint(pasynUserSelf, ASYN_TRACE_ERROR, "%s:%s [%s] ERROR: Serious problem: not enough buffers left. Aborting acquisition!\n", driverName, functionName, portName); setIntegerParam(ADAcquire, 0); } memcpy(pRaw_->pData, frameHandle_.pBuffer+offset, dataSize); getIntegerParam(NDArrayCounter, &count); pRaw_->uniqueId = count; updateTimeStamp(&pRaw_->epicsTS); pRaw_->timeStamp = pRaw_->epicsTS.secPastEpoch+pRaw_->epicsTS.nsec/1e9; getAttributes(pRaw_->pAttributeList); setIntegerParam(ADStatus, ADStatusReadout); callParamCallbacks(); pRaw_->pAttributeList->add("ColorMode", "Color mode", NDAttrInt32, &colorMode); return status; } /* Sets an int32 parameter */ asynStatus tucsen::writeInt32( asynUser *pasynUser, epicsInt32 value) { static const char* functionName = "writeInt32"; const char* paramName; asynStatus status = asynSuccess; int tucStatus; int function = pasynUser->reason; getParamName(function, &paramName); status = setIntegerParam(function, value); if (function==ADAcquire){ if (value){ status = startCapture(); } else { status = stopCapture(); } } else if ((function==ADTriggerMode) || (function==ADNumImages) || (function==ADNumExposures)){ //status = setTrigger(); } else if (function==TucsenFrameFormat){ frameHandle_.ucFormatGet = frameFormats[value]; frameHandle_.uiRsdSize = 1; frameHandle_.pBuffer = NULL; tucStatus = TUCAM_Buf_Release(camHandle_.hIdxTUCam); tucStatus = TUCAM_Buf_Alloc(camHandle_.hIdxTUCam, &frameHandle_); } else if (function==TucsenBinMode){ if ((value==0)||(value==1)){ status = setCapability(TUIDC_RESOLUTION, value); } frameHandle_.pBuffer = NULL; tucStatus = TUCAM_Buf_Release(camHandle_.hIdxTUCam); tucStatus = TUCAM_Buf_Alloc(camHandle_.hIdxTUCam, &frameHandle_); } else if (function==TucsenFanGear){ if ((value>=0)||(value<=6)){ status = setCapability(TUIDC_FAN_GEAR, value); } } else if (function==TucsenImageMode){ status = setCapability(TUIDC_IMGMODESELECT, value); } else { if (function < FIRST_TUCSEN_PARAM){ status = ADDriver::writeInt32(pasynUser, value); } } asynPrint(pasynUserSelf, ASYN_TRACEIO_DRIVER, "%s::%s function=%d, value=%d, status=%d\n", driverName, functionName, function, value, status); callParamCallbacks(); return status; } void tucsen::tempTask(void){ static const char* functionName = "tempTask"; TUCAM_VALUE_INFO valInfo; int tucStatus; double dbVal; lock(); while (!exiting_){ tucStatus = TUCAM_Prop_GetValue(camHandle_.hIdxTUCam, TUIDP_TEMPERATURE, &dbVal); if (tucStatus!=TUCAMRET_SUCCESS){ asynPrint(pasynUserSelf, ASYN_TRACE_ERROR, "%s:%s: failed to read temperature (%d)\n", driverName, functionName, tucStatus); } else { setDoubleParam(ADTemperatureActual, dbVal); } valInfo.nID = TUIDI_TRANSFER_RATE; tucStatus = TUCAM_Dev_GetInfo(camHandle_.hIdxTUCam, &valInfo); if (tucStatus!=TUCAMRET_SUCCESS){ asynPrint(pasynUserSelf, ASYN_TRACE_ERROR, "%s:%s: failed to read transfer rate(%d)\n", driverName, functionName, tucStatus); } else { setDoubleParam(TucsenTransferRate, valInfo.nValue); } callParamCallbacks(); unlock(); epicsThreadSleep(0.5); lock(); } } asynStatus tucsen::writeFloat64(asynUser *pasynUser, epicsFloat64 value) { static const char* functionName = "writeFloat64"; const char* paramName; asynStatus status = asynSuccess; int function = pasynUser->reason; int tucStatus =TUCAMRET_SUCCESS; status = setDoubleParam(function, value); if (function==ADAcquireTime){ tucStatus = setProperty(TUIDP_EXPOSURETM, value); if (tucStatus!=TUCAMRET_SUCCESS){ asynPrint(pasynUserSelf, ASYN_TRACE_ERROR, "%s:%s: failed to set exposure time(%x)\n", driverName, functionName, tucStatus); } } if (function==ADTemperature){ /* Temperature is scaled -50C to 50C->0 to 100 */ value = value+50.0; tucStatus = setProperty(TUIDP_TEMPERATURE, value); if (tucStatus!=TUCAMRET_SUCCESS){ asynPrint(pasynUserSelf, ASYN_TRACE_ERROR, "%s:%s: failed to set temperature(%x)\n", driverName, functionName, tucStatus); } } else { if (function < FIRST_TUCSEN_PARAM){ status = ADDriver::writeFloat64(pasynUser, value); } } callParamCallbacks(); return (asynStatus)status; } asynStatus tucsen::getCamInfo(int nID, char *sBuf, int &val) { static const char* functionName = "getPropertyText"; // Get camera information int tucStatus; TUCAM_VALUE_INFO valInfo; valInfo.pText = sBuf; valInfo.nTextSize = 1024; valInfo.nID = nID; tucStatus = TUCAM_Dev_GetInfo(camHandle_.hIdxTUCam, &valInfo); if (tucStatus==TUCAMRET_SUCCESS){ val = valInfo.nValue; return asynSuccess; } else { asynPrint(pasynUserSelf, ASYN_TRACE_ERROR, "%s:%s: could not get %d\n", driverName, functionName, tucStatus); return asynError; } } asynStatus tucsen::setCamInfo(int param, int nID, int dtype) { static const char* functionName = "setCamInfo"; int tucStatus; TUCAM_VALUE_INFO valInfo; int sSize = 1024; char sInfo[sSize] = {0}; valInfo.pText = sInfo; valInfo.nTextSize = sSize; valInfo.nID = nID; tucStatus = TUCAM_Dev_GetInfo(camHandle_.hIdxTUCam, &valInfo); if (tucStatus==TUCAMRET_SUCCESS){ if (param==TucsenBus){ if (valInfo.nValue==768){ setStringParam(TucsenBus, "USB3.0"); } else{ setStringParam(TucsenBus, "USB2.0"); } } else if (dtype==0){ setStringParam(param, valInfo.pText); } else if (dtype==1){ setDoubleParam(param, valInfo.nValue); } else if (dtype==2){ setIntegerParam(param, valInfo.nValue); } callParamCallbacks(); return asynSuccess; } else { return asynError; } } asynStatus tucsen::setSerialNumber() { static const char* functionName = "setSerialNumber"; int tucStatus; char cSN[TUSN_SIZE] = {0}; TUCAM_REG_RW regRW; regRW.nRegType = TUREG_SN; regRW.pBuf = &cSN[0]; regRW.nBufSize = TUSN_SIZE; tucStatus = TUCAM_Reg_Read(camHandle_.hIdxTUCam, regRW); if (tucStatus==TUCAMRET_SUCCESS){ printf("Camera serial number: %s\n",cSN); setStringParam(ADSerialNumber, cSN); return asynSuccess; } else { return asynError; } } asynStatus tucsen::setProperty(int property, double value){ static const char* functionName = "setProperty"; TUCAM_PROP_ATTR attrProp; int tucStatus; attrProp.nIdxChn = 0; attrProp.idProp = property; tucStatus = TUCAM_Prop_GetAttr(camHandle_.hIdxTUCam, &attrProp); if (tucStatus==TUCAMRET_SUCCESS) { printf("min: %f Max: %f\n", attrProp.dbValMin, attrProp.dbValMax); if(value<attrProp.dbValMin){ value = attrProp.dbValMin; printf("Clipping set min value: %d, %f", property, value); } else if (value>attrProp.dbValMax){ value = attrProp.dbValMax; printf("Clipping set max value: %d, %f", property, value); } } tucStatus = TUCAM_Prop_SetValue(camHandle_.hIdxTUCam, property, value); if (tucStatus!=TUCAMRET_SUCCESS){ asynPrint(pasynUserSelf, ASYN_TRACE_ERROR, "%s:%s unable to set property %d\n", driverName, functionName, property); return asynError; } else { return asynSuccess; } } asynStatus tucsen::setCapability(int property, int val) { static const char* functionName = "setCapability"; int tucStatus; TUCAM_CAPA_ATTR attrCapa; TUCAM_VALUE_TEXT valText; char szRes[64] = {0}; valText.nTextSize = 64; valText.pText = &szRes[0]; attrCapa.idCapa = property; tucStatus = TUCAM_Capa_GetAttr(camHandle_.hIdxTUCam, &attrCapa); if (tucStatus==TUCAMRET_SUCCESS){ int nCnt = attrCapa.nValMax - attrCapa.nValMin; valText.nID = property; for (int i=0; i<nCnt;i++){ valText.dbValue = i; TUCAM_Capa_GetValueText(camHandle_.hIdxTUCam, &valText); printf("%s\n", valText.pText); } } tucStatus = TUCAM_Capa_SetValue(camHandle_.hIdxTUCam, property, val); if (tucStatus!=TUCAMRET_SUCCESS) { asynPrint(pasynUserSelf, ASYN_TRACE_ERROR, "%s:%s unable to set capability %d=%d\n", driverName, functionName, property, val); return asynError; } return asynSuccess; } asynStatus tucsen::getCapability(int property, int& val) { static const char* functionName = "getCapability"; int tucStatus; tucStatus = TUCAM_Capa_GetValue(camHandle_.hIdxTUCam, property, &val); if (tucStatus!=TUCAMRET_SUCCESS) { asynPrint(pasynUserSelf, ASYN_TRACE_ERROR, "%s:%s unable to get capability %d=%d\n", driverName, functionName, property, val); return asynError; } return asynSuccess; } asynStatus tucsen::startCapture() { static const char* functionName = "startCapture"; setIntegerParam(ADNumImagesCounter, 0); setShutter(1); epicsEventSignal(startEventId_); return asynSuccess; } asynStatus tucsen::stopCapture() { static const char* functionName = "stopCapture"; int tucStatus; setShutter(0); tucStatus = TUCAM_Cap_Stop(camHandle_.hIdxTUCam); setIntegerParam(ADAcquire, 0); setIntegerParam(ADStatus, ADStatusIdle); callParamCallbacks(); return asynSuccess; } static const iocshArg configArg0 = {"Port name", iocshArgString}; static const iocshArg configArg1 = {"CameraId", iocshArgString}; static const iocshArg configArg2 = {"traceMask", iocshArgInt}; static const iocshArg configArg3 = {"maxBuffers", iocshArgInt}; static const iocshArg configArg4 = {"maxMemory", iocshArgInt}; static const iocshArg configArg5 = {"priority", iocshArgInt}; static const iocshArg configArg6 = {"stackSize", iocshArgInt}; static const iocshArg * const configArgs [] = {&configArg0, &configArg1, &configArg2, &configArg3, &configArg4, &configArg5, &configArg6}; static const iocshFuncDef configtucsen = {"tucsenConfig", 7, configArgs}; static void configCallFunc(const iocshArgBuf *args) { tucsenConfig(args[0].sval, args[1].sval, args[2].ival, args[3].ival, args[4].ival, args[5].ival, args[6].ival); } static void tucsenRegister(void) { iocshRegister(&configtucsen, configCallFunc); } extern "C" { epicsExportRegistrar(tucsenRegister); }